{"id":25762009,"url":"https://github.com/akhil2308/fastapi-large-app-template","last_synced_at":"2026-04-14T19:32:51.071Z","repository":{"id":277224616,"uuid":"931737379","full_name":"akhil2308/fastapi-large-app-template","owner":"akhil2308","description":"🚀 Production-Grade FastAPI Template • JWT Auth • Rate Limiting • Alembic Migrations • Async PostgreSQL (connection pooling) • Async Redis (efficient pooling) • Gunicorn + Uvicorn • Docker • Async Ready • RFC-Compliant API Responses • Enterprise Security Patterns","archived":false,"fork":false,"pushed_at":"2026-02-13T21:06:00.000Z","size":516,"stargazers_count":15,"open_issues_count":1,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-02-13T21:37:33.201Z","etag":null,"topics":["alembic","async-api","connection-pooling","fastapi","fastapi-best-practices","fastapi-boilerplate","fastapi-production-template","fastapi-security","fastapi-sqlalchemy","fastapi-template","jwt-authentication","postgresql","production-ready","python","rate-limiting","redis","sqlalchemy","uv","uvicorn-gunicorn"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/akhil2308.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-02-12T19:16:58.000Z","updated_at":"2026-02-13T15:18:48.000Z","dependencies_parsed_at":"2025-02-12T20:27:41.841Z","dependency_job_id":"f17be55f-bfb0-4a9b-9150-104a9fc36b1e","html_url":"https://github.com/akhil2308/fastapi-large-app-template","commit_stats":null,"previous_names":["akhil2308/fastapi-large-app-template"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/akhil2308/fastapi-large-app-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akhil2308%2Ffastapi-large-app-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akhil2308%2Ffastapi-large-app-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akhil2308%2Ffastapi-large-app-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akhil2308%2Ffastapi-large-app-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/akhil2308","download_url":"https://codeload.github.com/akhil2308/fastapi-large-app-template/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akhil2308%2Ffastapi-large-app-template/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31812968,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-14T18:05:02.291Z","status":"ssl_error","status_checked_at":"2026-04-14T18:05:01.765Z","response_time":153,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["alembic","async-api","connection-pooling","fastapi","fastapi-best-practices","fastapi-boilerplate","fastapi-production-template","fastapi-security","fastapi-sqlalchemy","fastapi-template","jwt-authentication","postgresql","production-ready","python","rate-limiting","redis","sqlalchemy","uv","uvicorn-gunicorn"],"created_at":"2025-02-26T19:27:24.953Z","updated_at":"2026-04-14T19:32:51.063Z","avatar_url":"https://github.com/akhil2308.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FastAPI Large Application Template 🚀\n\n[![FastAPI](https://img.shields.io/badge/FastAPI-005571?style=for-the-badge\u0026logo=fastapi)](https://fastapi.tiangolo.com)\n[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-316192?style=for-the-badge\u0026logo=postgresql\u0026logoColor=white)](https://www.postgresql.org/)\n[![Redis](https://img.shields.io/badge/Redis-DC382D?style=for-the-badge\u0026logo=redis\u0026logoColor=white)](https://redis.io/)\n\nA production-ready FastAPI template designed for building secure, scalable APIs with modern best practices baked in. This template provides a robust foundation for enterprise-grade applications, featuring essential security measures, performance optimizations, and maintainable architecture patterns out of the box.\n\n## Features ✨\n\n- **JWT Authentication** with refresh tokens 🔒\n- **Custom Rate Limiting** per user/service ⏱️\n- **Unified Logging** (UVICORN + GUNICORN) 📝\n- **Redis Connection Pooling** (Async) with fail-open strategy 🧠\n- **PostgreSQL Connection Pooling** (Async) with health checks 🐘\n- **Standardized API Responses** 📦\n- **Alembic for Database Migrations** 🗄️\n- **Modern Package Management with `uv`** ⚡\n- **Production-Ready Error Handling** 🛡️\n- **Docker** + **Gunicorn** + **Uvicorn** Stack 🐳⚡\n- **OpenTelemetry Observability** — metrics, traces, Golden Signals dashboards (Prometheus + Grafana + Tempo) 📊\n\n## Observability 📊\n\nThis template includes a **production-grade OpenTelemetry observability setup** designed for real-world systems:\n\n- Automatic FastAPI instrumentation\n- Distributed tracing with Tempo\n- Golden Signals dashboards in Grafana\n- Prometheus metrics via OpenTelemetry\n- Custom application \u0026 rate-limiter visibility\n\n### Observability Stack\n\n[![OpenTelemetry](https://img.shields.io/badge/OpenTelemetry-FFFFFF?style=for-the-badge\u0026logo=opentelemetry\u0026logoColor=black)](https://opentelemetry.io/)\n[![Prometheus](https://img.shields.io/badge/Prometheus-E6522C?style=for-the-badge\u0026logo=Prometheus\u0026logoColor=white)](https://prometheus.io/)\n[![Grafana](https://img.shields.io/badge/grafana-%23F46800.svg?style=for-the-badge\u0026logo=grafana\u0026logoColor=white)](https://grafana.com/)\n[![Grafana Tempo](https://img.shields.io/badge/Tempo-000000?style=for-the-badge\u0026logo=grafana\u0026logoColor=white)](https://grafana.com/oss/tempo/)\n\n\n👉 **All observability details live here:**\n📄 [docs/OBSERVABILITY.md](docs/OBSERVABILITY.md)\n\n## Tech Stack 🛠️\n\n| Component              | Technology                          |\n|------------------------|-------------------------------------|\n| Framework              | FastAPI 0.111+                      |\n| Database               | PostgreSQL 14+                      |\n| Cache                  | Redis 6+                            |\n| ORM                    | SQLAlchemy 2.0                      |\n| Migrations             | Alembic                             |\n| Authentication         | JWT (OAuth2 Password Bearer)        |\n| Rate Limiting          | Redis-backed Custom Implementation  |\n| Package Manager        | `uv` (fast Python installer)        |\n| Containerization       | Docker                              |\n| Observability          | OpenTelemetry                       |\n\n## Project Structure 🌳\n\nThe repository follows a **modular, domain-oriented structure** designed for large, production-grade FastAPI applications:\n\n- `app/` — Core FastAPI application\n  - Domain modules (`user`, `todo`, `health`)\n  - Core configuration, database, logging\n  - OpenTelemetry observability setup\n  - Alembic migrations\n  - Application entry point (`main.py`)\n\n- `docker/observability/` — Local observability stack\n  - OpenTelemetry Collector\n  - Prometheus\n  - Grafana (pre-provisioned dashboards \u0026 datasources)\n  - Tempo (distributed tracing)\n\n- `docs/` — Documentation \u0026 assets\n  - Observability guide and dashboards\n  - Architecture diagrams and screenshots\n\n- `tests/` — Automated tests\n\n- Root files — `Dockerfile`, `Makefile`, `run.sh`, `pyproject.toml`, `uv.lock`, etc.\n\n---\n\n## Key Implementations 🔑\n\n### Database Pooling Configuration\n\n**PostgreSQL (SQLAlchemy 2.0 + asyncpg):**\n```python\nfrom sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker\n\n# Async PostgreSQL connection pool\nengine = create_async_engine(\n    \"postgresql+asyncpg://user:pass@host:port/dbname\",\n    pool_size=20,          # Persistent connection pool size\n    max_overflow=10,       # Temporary connections beyond pool_size\n    pool_recycle=300,      # Recycle connections every 300s\n    pool_pre_ping=True,    # Validate connections before use\n    future=True            # Enable SQLAlchemy 2.0 behavior\n)\n\n# Async session factory configuration\nAsyncSessionLocal = async_sessionmaker(\n    bind=engine,\n    expire_on_commit=False,  # Prevent attribute expiration on commit\n    autoflush=False,         # Manual flush control\n    class_=AsyncSession      # Use SQLAlchemy's async session class\n)\n```\n\n**Key Features**:\n- 🚀 **Full Async Support**: Non-blocking database operations via asyncpg\n- 🔄 **Connection Recycling**: Prevents stale connections in long-running applications\n- 🩺 **Connection Validation**: Pre-ping checks verify connection health\n- 📈 **Optimized Pooling**: Balances memory usage and concurrent requests\n- ⚡ **SQLAlchemy 2.0**: Future-proof API with explicit transaction control\n\n\n**Redis Connection Pool:**\n```python\nredis = await Redis(\n    host=\"redis.prod.internal\",\n    port=6379,\n    db=0,\n    password=\"securepassword\",\n    socket_connect_timeout=5,    # 5s connection timeout\n    socket_keepalive=True,       # Maintain TCP keepalive\n    retry_on_timeout=True,       # Auto-retry failed operations\n    max_connections=100,         # Max pool size\n    health_check_interval=30     # Validate connections every 30s\n)\n```\n- **Enterprise Features:** TLS support, cluster mode ready\n- **Resiliency:** Automatic retries and health checks\n\n---\n\n### 🔒 Secure Endpoint Example\n\n**Protected Todo Creation:**\n```python\n@router.post(\"/\")\nasync def create_todo(\n    body: TodoCreate,\n    current_user: User = Depends(get_current_user),\n    db: AsyncSession = Depends(get_db)\n):\n    \"\"\"\n    Implements:\n    - JWT Authentication\n    - User-based Rate Limiting\n    - Structured Error Handling\n    - Audit Logging\n    \"\"\"\n    try:\n        # Rate limit check\n        await user_rate_limiter(current_user.user_id, \"todo_write\")\n\n        # Business logic\n        data = await create_todo_service(current_user.user_id, body, db)\n\n        # Standardized success response\n        return {\n            \"status\": \"success\",\n            \"message\": \"Todo created\",\n            \"data\": data\n        }\n\n    except HTTPException as e:\n        # Preserve existing HTTP exceptions\n        raise\n    except Exception as e:\n        # Log full error context\n        logger.error(f\"Todo creation failed: {str(e)}\", exc_info=True)\n        # Return standardized error format\n        raise HTTPException(\n            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n            detail=\"Internal server error\"\n        )\n```\n\n---\n\n### ⏱️ Custom Rate Limiting\n\n**Implementation:**\n```python\nasync def user_rate_limiter(\n    user_id: str,\n    service: str,\n    times: int = 5,\n    seconds: int = 60\n):\n    \"\"\"\n    Redis-backed rate limiter using LUA scripts for atomic operations\n    \"\"\"\n    key = f\"rl:user:{user_id}:{service}\"\n    try:\n        pexpire = await FastAPILimiter.redis.evalsha(\n            FastAPILimiter.lua_sha, 1,\n            key,\n            str(times),\n            str(seconds * 1000)  # Convert to milliseconds\n        )\n        if pexpire != 0:\n            raise HTTPException(\n                status_code=429,\n                detail=f\"Try again in {ceil(pexpire/1000)} seconds\"\n            )\n    except Exception as e:\n        logger.error(f\"Rate limit check failed: {str(e)}\")\n        # Fail-open during Redis outages\n```\n\n**Features:**\n- ✅ User+service specific limits\n- ✅ Atomic Redis operations via LUA scripts\n- ✅ Fail-open circuit breaker pattern\n- ✅ Millisecond precision timeouts\n- ✅ Automatic retry-after calculation\n\n---\n\n### 📝 Unified Logging System\n\n**Configuration:**\n```python\nlogging_config = {\n    \"version\": 1,\n    \"formatters\": {\n        \"standard\": {\n            \"format\": \"[{asctime}] [{process}] [{levelname}] {module}.{funcName}:{lineno} - {message}\",\n            \"datefmt\": \"%Y-%m-%d %H:%M:%S %z\",\n            \"style\": \"{\"\n        }\n    },\n    \"handlers\": {\n        \"console\": {\n            \"class\": \"logging.StreamHandler\",\n            \"formatter\": \"standard\",\n            \"stream\": \"ext://sys.stdout\"\n        }\n    },\n    \"loggers\": {\n        \"\": {\"level\": \"DEBUG\", \"handlers\": [\"console\"], \"propagate\": False},\n        \"uvicorn\": {\"level\": \"INFO\", \"propagate\": False},\n        \"uvicorn.access\": {\"level\": \"INFO\", \"propagate\": False},\n        \"uvicorn.error\": {\"level\": \"INFO\", \"propagate\": False}\n    }\n}\n```\n\n**Log Example:**\n```\n[2024-05-20 14:30:45 +0000] [1234] [INFO] todo.routers.create_todo:52 - Created todo ID:42\n```\n\n**Features:**\n- 📌 Consistent timestamp with timezone\n- 📌 Process ID tracking\n- 📌 Module/function/line number context\n- 📌 Uvicorn log unification\n- 📌 Production-ready INFO level defaults\n\n---\n\n### 📦 Standardized API Response\n\n**Success Response:**\n```json\n{\n  \"status\": \"success\",\n  \"message\": \"Todo created successfully\",\n  \"data\": {\n    \"id\": 42,\n    \"task\": \"Implement rate limiting\"\n  }\n}\n```\n\n**Error Response:**\n```json\n{\n  \"status\": \"error\",\n  \"message\": \"Validation Failed\",\n  \"errors\": [\n    {\n      \"field\": \"task\",\n      \"message\": \"Field required\"\n    }\n  ]\n}\n```\n\n**Implementation:**\n```python\n@app.exception_handler(RequestValidationError)\nasync def validation_handler(request: Request, exc: RequestValidationError):\n    return JSONResponse(\n        status_code=422,\n        content={\n            \"status\": \"error\",\n            \"code\": 422,\n            \"message\": \"Validation Failed\",\n            \"errors\": exc.errors()\n        }\n    )\n\n@app.exception_handler(HTTPException)\nasync def http_handler(request: Request, exc: HTTPException):\n    return JSONResponse(\n        status_code=exc.status_code,\n        content={\n            \"status\": \"error\",\n            \"code\": exc.status_code,\n            \"message\": exc.detail,\n            \"errors\": getattr(exc, \"errors\", None)\n        }\n    )\n```\n\n**Features:**\n- ✅ RFC-compliant error formats\n- ✅ Automatic validation error parsing\n- ✅ Consistent error code mapping\n- ✅ Detailed error context preservation\n\n\n## Getting Started\n\n### Prerequisites\n\n- Python 3.11+\n- PostgreSQL 14+\n- Redis 6+\n- Docker (optional)\n\n---\n\n### Installation\n\n```bash\ngit clone https://github.com/akhil2308/fastapi-large-app-template.git\ncd fastapi-large-app-template\n\n# Install uv (if not already installed)\npip install uv\n\n# Sync dependencies and create virtual environment\n# This installs all packages defined in pyproject.toml\nuv sync --all-extras\n\n# Install Git Hooks\n# This ensures code quality checks run automatically on commit\nuv run pre-commit install\n```\n\n---\n\n## Using Makefile\n\nThis project includes a Makefile with convenient commands. Run `make help` to see all available targets.\n\n```bash\n# Show all available commands\nmake help\n\n# Install dependencies and setup git hooks\nmake install\n\n# Development server\nmake dev\n\n# Production server\nmake prod\n\n# Run tests\nmake test\n\n# Database migrations\nmake migrate\nmake migrate-create MSG=\"your migration message\"\n\n# Code quality\nmake check-env\nmake lint\nmake format\nmake typecheck\n\n# Full CI pipeline\nmake ci\n\n# Clean generated files\nmake clean\n```\n\n---\n\n### Configuration\n\n#### Set environment variables\n\n```bash\ncp .env.example .env\n# Fill in DB, Redis, JWT, and other values\n```\n\n---\n\n## Alembic Commands (Migrations)\n\n**Generate new migration:**\n\n```bash\nuv run alembic -c app/alembic.ini revision --autogenerate -m \"message\"\n```\n\n**Apply migrations:**\n\n```bash\nuv run alembic -c app/alembic.ini upgrade head\n```\n\n---\n\n### Running\n\n**Development:**\n\n```bash\nuv run uvicorn app.main:app --reload --host 0.0.0.0 --port 8000\n```\n\n**Production:**\n\n```bash\n./run.sh  # Starts Gunicorn with Uvicorn workers\n```\n\n---\n\n## Code Standards \u0026 Quality 🛡️\n\nThis project enforces code quality using **Ruff** (linter/formatter) and **Mypy** (static type checker).\n\n### Manual Checks\n\n**1. Linting \u0026 Formatting (Ruff)**\n\n```bash\n# See what code Ruff wants to fix (Dry Run)\nuv run ruff check .\n\n# Actually fix the code (Auto-formatting \u0026 Import sorting)\nuv run ruff check . --fix\nuv run ruff format .\n```\n\n**2. Static Type Checking (Mypy)**\n\n```bash\n# Check for type errors\nuv run mypy .\n```\n\n\u003e **Note:** 🔒 A **pre-commit hook** is configured. When you attempt to `git commit`, these checks will automatically run to ensure no bad code is pushed to the repository.\n\n---\n\n## API Documentation 📚\n\nAccess interactive docs after starting server:\n- **Swagger UI:** `http://localhost:8000/docs`\n- **ReDoc:** `http://localhost:8000/redoc`\n- **OpenAPI:** `http://localhost:8000/openapi.json`\n\n## Contributing\n\nSee [CONTRIBUTORS.txt](CONTRIBUTORS.txt) for contribution guidelines and code of conduct.\n\n## License\n\nThis project is licensed under the MIT License - see [LICENSE](LICENSE) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakhil2308%2Ffastapi-large-app-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fakhil2308%2Ffastapi-large-app-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakhil2308%2Ffastapi-large-app-template/lists"}