Monday, 22 December 2025

FastAPI Microservices Setup

 Below is a real-world FastAPI microservices setup, explained step by step, and mapped to how companies actually do it in production. I’ll also relate it to Spring Boot microservices, so it’s easy to grasp.


FastAPI Microservices Setup (Production-Ready Guide)

1️⃣ What Is a FastAPI Microservices Architecture?

Instead of one large backend, you create multiple small FastAPI services, each responsible for one business capability.

Example services:

  • Auth Service

  • User Service

  • Notification Service

  • Event / Integration Service

  • Reporting Service

Each service:

  • Has its own codebase

  • Has its own database (recommended)

  • Can be deployed and scaled independently


2️⃣ High-Level Architecture

Frontend (Angular / React / Mobile) ↓ API Gateway ↓ ┌────────┬─────────┬──────────┐ | Auth | Users | Events | FastAPI services |Service | Service | Service | └────────┴─────────┴──────────┘ ↓ Databases / Queues / Caches

3️⃣ Example Microservices Folder Structure

microservices/ │ ├── api-gateway/ │ └── app/ │ └── main.py │ ├── auth-service/ │ └── app/ │ ├── main.py │ └── api/ │ ├── user-service/ │ └── app/ │ ├── main.py │ └── api/ │ ├── event-service/ │ └── app/ │ ├── main.py │ └── api/ │ ├── docker-compose.yml └── README.md

👉 Each service is a separate FastAPI app.


4️⃣ Service-to-Service Communication

Option 1: REST (Most Common)

  • HTTP calls between services

  • Use async HTTP clients (httpx)

User Service → Auth Service

Option 2: Message Queue (Recommended for scale)

  • Kafka / RabbitMQ / AWS SQS

  • Event-driven communication

Event Service → Queue → Notification Service

5️⃣ API Gateway (Very Important)

Companies use:

  • Nginx

  • Kong

  • FastAPI Gateway

Responsibilities:

  • Routing

  • Authentication

  • Rate limiting

  • Logging

Simple FastAPI Gateway Example

@app.api_route("/{path:path}", methods=["GET", "POST"]) async def proxy(path: str, request: Request): async with httpx.AsyncClient() as client: response = await client.request( request.method, f"http://user-service/{path}", headers=request.headers.raw, content=await request.body() ) return Response(response.content)

6️⃣ Authentication Strategy

Central Auth Service (Recommended)

Flow:

  1. User logs in → Auth Service

  2. JWT token issued

  3. Other services validate JWT

Each service:

  • Validates token

  • Does not store auth logic

📌 Same idea as Spring Security + JWT.


7️⃣ Database Strategy

Best practice:

  • One database per service

Examples:

  • Auth Service → PostgreSQL

  • User Service → MongoDB

  • Event Service → NoSQL / Kafka

❌ Avoid shared databases between services.


8️⃣ Async & Performance Setup

Run services using:

Gunicorn + Uvicorn workers

Example:

gunicorn app.main:app -k uvicorn.workers.UvicornWorker -w 4

9️⃣ Docker Setup (Per Service)

Dockerfile (Common for all services)

FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY app app CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

🔟 docker-compose (Local Development)

version: "3.8" services: auth-service: build: ./auth-service ports: - "8001:8000" user-service: build: ./user-service ports: - "8002:8000" event-service: build: ./event-service ports: - "8003:8000"

1️⃣1️⃣ Configuration Management

Use:

  • .env files

  • Environment variables

  • Secrets manager (in prod)

Example:

AUTH_SERVICE_URL=http://auth-service:8000

1️⃣2️⃣ Logging & Monitoring

Production services include:

  • Structured logging

  • Request tracing (request ID)

  • Metrics (Prometheus)

  • Central log aggregation


1️⃣3️⃣ Scaling Strategy

  • Stateless services

  • Horizontal scaling

  • Kubernetes HPA

  • Load balancing via ingress


1️⃣4️⃣ FastAPI vs Spring Boot Microservices

AspectFastAPISpring Boot
Startup timeVery fastSlower
Resource usageLowHigher
AsyncSimpleComplex
Enterprise toolingModerateExcellent

Many companies use:

Spring Boot → Core services FastAPI → Integration & API services

1️⃣5️⃣ Common Mistakes to Avoid

❌ Sharing databases
❌ Tight coupling between services
❌ Missing API gateway
❌ Blocking calls in async routes
❌ No centralized auth


Final Thoughts

FastAPI microservices are:

  • Lightweight

  • Fast

  • Easy to scale

  • Perfect for integration-heavy systems

For someone with your background:

  • Spring Boot → Core business logic

  • FastAPI → Microservices, integrations, ML APIs

This combo is very powerful in modern architectures.

No comments:

Post a Comment