# FastAPI Production Stack

> Production FastAPI with Uvicorn, Celery, PostgreSQL, and Redis.

- Category: Full Web Stacks
- Difficulty: advanced
- Components: fastapi, uvicorn, celery, postgresql, redis, nginx
- Tags: fastapi, python, uvicorn, async, production
- Source: https://docker.recipes/full-stacks/fastapi-production

## Overview

FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ that leverages standard Python type hints for automatic API documentation and data validation. Created by Sebastian Ramirez in 2018, FastAPI combines the speed of NodeJS and Go with Python's ease of use, achieving performance comparable to NodeJS thanks to Starlette and Pydantic under the hood. It automatically generates OpenAPI (Swagger) documentation and supports async/await natively, making it ideal for I/O-bound applications that need to handle thousands of concurrent connections.

This production stack combines FastAPI with Uvicorn's ASGI server for async request handling, Celery for distributed task processing, PostgreSQL for ACID-compliant data persistence, Redis for caching and message brokering, and NGINX for reverse proxying and load balancing. The architecture separates concerns effectively: FastAPI handles API requests asynchronously, Celery workers process background jobs like email sending or data processing, PostgreSQL manages complex relational data with full transaction support, Redis provides sub-millisecond caching and serves as Celery's message broker, while NGINX terminates SSL and distributes traffic across multiple FastAPI workers.

This stack is perfect for startups building scalable SaaS platforms, enterprises migrating from Django/Flask to async Python, and teams developing data-intensive applications that need background processing capabilities. The combination delivers production-grade performance with FastAPI's 10,000+ requests per second capability, PostgreSQL's enterprise reliability, and Celery's proven distributed task management, making it suitable for applications ranging from financial APIs to machine learning pipelines that require both real-time responses and heavy background computation.

## Features

- Automatic OpenAPI/Swagger documentation generation from Python type hints with interactive API testing interface
- Async/await native support with Uvicorn ASGI server for handling 10,000+ concurrent connections
- Celery distributed task queue with Redis broker for background job processing and scheduled tasks
- PostgreSQL with asyncpg driver for non-blocking database operations and ACID transaction support
- Redis-powered caching layer with sub-millisecond response times for frequently accessed data
- NGINX reverse proxy with HTTP/2 support and load balancing across multiple FastAPI workers
- Flower web interface for real-time Celery task monitoring and worker management
- Separate Celery Beat scheduler for cron-like periodic task execution

## Use cases

- SaaS platforms requiring user authentication, subscription management, and background email/notification processing
- Financial APIs handling real-time trading data with async PostgreSQL operations and Redis caching for market data
- E-commerce backends processing orders synchronously while handling inventory updates and payment processing asynchronously
- Machine learning platforms serving model predictions via FastAPI while training models in background Celery tasks
- IoT data collection systems ingesting sensor data through FastAPI endpoints and processing analytics in Celery workers
- Content management systems with async file uploads, image processing workflows, and PostgreSQL full-text search
- Multi-tenant applications requiring database-per-tenant isolation with Redis session management and background data synchronization

## Prerequisites

- Minimum 2GB RAM for PostgreSQL database operations and Celery worker processes
- Docker Engine 20.10+ with Docker Compose V2 for proper async networking and health checks
- Available ports 80, 443 (NGINX), and 5555 (Flower) on the host system
- Understanding of Python async/await patterns and SQLAlchemy async sessions
- Familiarity with Celery task decorators and Redis data structure operations
- SSL certificate files if enabling HTTPS termination in NGINX configuration

## docker-compose.yml

```yaml
services:
  postgres:
    image: postgres:15-alpine
    environment:
      - POSTGRES_USER=fastapi
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
      - POSTGRES_DB=fastapi_app
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - fastapi_net

  redis:
    image: redis:7-alpine
    volumes:
      - redis_data:/data
    networks:
      - fastapi_net

  fastapi:
    build:
      context: .
      dockerfile: Dockerfile
    command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4
    environment:
      - DATABASE_URL=postgresql+asyncpg://fastapi:${POSTGRES_PASSWORD}@postgres:5432/fastapi_app
      - REDIS_URL=redis://redis:6379/0
      - SECRET_KEY=${SECRET_KEY}
    depends_on:
      - postgres
      - redis
    networks:
      - fastapi_net

  celery-worker:
    build:
      context: .
      dockerfile: Dockerfile
    command: celery -A app.worker worker -l info
    environment:
      - DATABASE_URL=postgresql+asyncpg://fastapi:${POSTGRES_PASSWORD}@postgres:5432/fastapi_app
      - REDIS_URL=redis://redis:6379/0
      - SECRET_KEY=${SECRET_KEY}
    depends_on:
      - postgres
      - redis
    networks:
      - fastapi_net

  celery-beat:
    build:
      context: .
      dockerfile: Dockerfile
    command: celery -A app.worker beat -l info
    environment:
      - DATABASE_URL=postgresql+asyncpg://fastapi:${POSTGRES_PASSWORD}@postgres:5432/fastapi_app
      - REDIS_URL=redis://redis:6379/0
      - SECRET_KEY=${SECRET_KEY}
    depends_on:
      - postgres
      - redis
    networks:
      - fastapi_net

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - fastapi
    networks:
      - fastapi_net

  flower:
    build:
      context: .
      dockerfile: Dockerfile
    command: celery -A app.worker flower --port=5555
    ports:
      - "5555:5555"
    environment:
      - REDIS_URL=redis://redis:6379/0
    depends_on:
      - celery-worker
    networks:
      - fastapi_net

volumes:
  postgres_data:
  redis_data:

networks:
  fastapi_net:
```

## .env

```bash
# FastAPI Production
POSTGRES_PASSWORD=secure_postgres_password
SECRET_KEY=your_very_long_secret_key_here

# FastAPI at http://localhost
# API docs at http://localhost/docs
# Flower at http://localhost:5555
```

## Usage notes

- FastAPI at http://localhost
- Swagger docs at http://localhost/docs
- ReDoc at http://localhost/redoc
- Flower at http://localhost:5555
- Async PostgreSQL with asyncpg

## Troubleshooting

- asyncpg.exceptions.InvalidCatalogNameError: Ensure PostgreSQL container starts before FastAPI by adding health checks or startup delays
- Celery workers not discovering tasks: Verify PYTHONPATH includes app directory and task modules are properly imported in worker.py
- FastAPI 422 validation errors: Check Pydantic model field types match incoming JSON data structure and required fields
- Redis connection refused in Celery: Confirm Redis container is running and REDIS_URL environment variable uses correct host 'redis' not 'localhost',
- NGINX 502 Bad Gateway: FastAPI container may not be ready; add upstream health checks or increase proxy timeouts in nginx.conf
- PostgreSQL connection pool exhaustion: Increase SQLAlchemy pool_size and max_overflow settings or implement connection pooling with pgbouncer

