Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 3

Workers, Processes and the Reverse Proxy

Size ASGI worker processes against container CPU limits and configure reverse proxies for TLS termination, Slowloris defence, and trusted forwarded headers.

Contentsand lesson path

On this page

  1. ASGI worker processes and CPU core sizing
  2. The reverse proxy: buffering, security and forwarded headers
  3. Check your understanding
  4. Apply it
  5. Review prompt

Lessons of Service Production Readiness

  1. What Changes Between Your Laptop and Production Concept · 15 min
  2. Workers, Processes and the Reverse Proxy Worked example · 25 min
  3. Health, Readiness and Graceful Shutdown Worked example · 25 min
  4. Configuration That Fails Fast Concept · 15 min
  5. Lab: A Release with Migrations, Smoke Tests and Rollback Lab · 30 min
  6. Check: Production Readiness Review Knowledge check · 8 questions

What you will learn

  • Run the service under a production ASGI server setup with a justified worker and process count, correct forwarded-header handling behind a reverse proxy, and request timeouts and body-size limits.

Prerequisites: Database Schema Migrations

01. ASGI worker processes and CPU core sizing

When you deploy an async Python framework such as FastAPI or Starlette, you need to know how the ASGI server uses CPU cores, or latency rises sharply under load.

An event loop uses one core. Python's asyncio event loop runs its tasks cooperatively in a single operating system thread. With the standard CPython build, the Global Interpreter Lock (GIL) also stops other threads from running Python code at the same time, so one Uvicorn process uses at most about one CPU core for Python work, however many cores the host has. If an incoming request executes a CPU-bound operation (such as JSON parsing, cryptographic hashing, or complex data transformations), the entire event loop is blocked from processing network I/O for concurrent requests until that operation yields control.

To use several cores, run several worker processes. In production this is usually managed by Uvicorn's own process manager (uvicorn main:app --workers 2), by Gunicorn acting as the process manager with the worker class from the separate uvicorn-worker package (uvicorn_worker.UvicornWorker; the old uvicorn.workers module is deprecated and warns on import), or by running multiple single-worker container replicas behind an orchestrator load balancer.

The os.cpu_count() trap in containers. A common production failure comes from start-up scripts that compute the worker count from os.cpu_count(). On dedicated servers, workers = 2 * os.cpu_count() + 1 was a traditional rule of thumb for synchronous WSGI apps. In Kubernetes, AWS ECS or Google Cloud Run, containers run on large shared nodes:

  • What the host shows: A Kubernetes node may have 64 or 128 virtual CPUs.
  • What the container may use: Your Pod spec may set a cgroup limit such as resources.limits.cpu: "2" (2000 millicores).
  • The result: os.cpu_count() reports the host's CPUs, 64 here; it does not read the cgroup quota (neither does os.process_cpu_count(), added in Python 3.13, which only reads the CPU affinity). A start-up script that spawns 64 workers in a container limited to 2 CPUs makes 64 Python processes share 2 CPUs' worth of time per 100 ms period. The container is throttled, context switches multiply, each worker holds its own copy of the app in memory, and latency becomes long and erratic.

Worker sizing rule. Size worker processes from the container's CPU limit, not from the host. For async I/O workloads, start with 1 to 2 workers per allocated core (e.g. 2 workers for a 2-CPU container), check the choice with a load test, and scale out by adding replicas.

02. The reverse proxy: buffering, security and forwarded headers

Application servers such as Uvicorn are built to run your application, not to face every kind of client on the public Internet. Production deployments usually put a reverse proxy such as Nginx, Caddy or Envoy in front of the app.

The reverse proxy has three jobs here.

1. Request buffering and slow clients. In a Slowloris or slow-client attack, an attacker opens hundreds of TCP connections and sends request headers or body bytes very slowly (e.g. 1 byte every 5 to 10 seconds). If Uvicorn directly interfaces with these clients, Python async sockets remain tied up in memory waiting for request completion, eventually exhausting socket file descriptors. A reverse proxy like Nginx absorbs these slow connections: with request buffering (proxy_request_buffering, on by default) it reads the whole header and body into memory or a temporary file and only then sends the complete request to Uvicorn over a fast local connection. That protects the Python workers, not the proxy: the attacker's connections still occupy Nginx connection slots. client_header_timeout limits the time for the whole header, but client_body_timeout applies between two successive reads, so a client that sends one body byte every few seconds is never timed out. Cap what one address can hold with limit_conn and limit_req, and keep worker_connections sized for the load. Response buffering (proxy_buffering) is a separate setting that protects workers from clients that download slowly.

2. Forwarded headers you can trust. The reverse proxy ends the client's connection and opens a new one to Uvicorn, so the application sees the proxy's private IP (such as 10.0.0.5) as the caller, and http as the scheme. Nginx passes the real client details in headers (the X-Forwarded-* headers are a de facto convention; RFC 7239 defines a standard Forwarded header):

  • X-Forwarded-For: the proxy appends the address of the client it received the request from.
  • X-Forwarded-Proto: whether the user connected with https or http.
  • X-Forwarded-Host: the original host the browser asked for.

Forged headers are a security risk. If your application trusts X-Forwarded-For from any incoming socket (for example, configuring Uvicorn with --forwarded-allow-ips="*"), any malicious actor on the Internet can send X-Forwarded-For: 127.0.0.1 or a forged corporate IP to bypass IP-based rate limiting, geo-fencing, or audit logs. Uvicorn must be configured with --proxy-headers and restricted with --forwarded-allow-ips to trust only the specific private CIDR blocks of your upstream reverse proxies (e.g. 10.0.0.0/8,172.16.0.0/12).

Nginx · /etc/nginx/conf.d/api.conf: buffering, per-IP limits and forwarded headers
# /etc/nginx/conf.d/api.conf (included inside the http block)
upstream backend_cluster {
    server 127.0.0.1:8000 max_fails=3 fail_timeout=10s;
    keepalive 32;
}

# Per-client-IP limits, shared by all workers (zones live at http level)
limit_conn_zone $binary_remote_addr zone=per_ip:10m;
limit_req_zone $binary_remote_addr zone=req_per_ip:10m rate=20r/s;

server {
    listen 443 ssl;
    http2 on;  # nginx 1.25.1+; older versions: listen 443 ssl http2;
    server_name api.example.com;

    ssl_certificate /etc/ssl/certs/api.example.com.crt;
    ssl_certificate_key /etc/ssl/private/api.example.com.key;

    # 1. Slow clients. The header must arrive within 12 s in total; the body
    #    timeout applies between two reads, so a client that trickles one byte
    #    every few seconds never hits it. Cap connections and requests per IP.
    client_header_timeout 12s;
    client_body_timeout 12s;
    client_max_body_size 10m;
    limit_conn per_ip 20;
    limit_req zone=req_per_ip burst=40 nodelay;

    # 2. Request buffering (on by default): Nginx reads the whole request body
    #    before calling Python; bodies above the buffer go to a temp file.
    proxy_request_buffering on;
    client_body_buffer_size 128k;

    # 3. Response buffering: Nginx takes the reply quickly and feeds slow
    #    downloads itself, so a slow reader does not hold a Python worker.
    proxy_buffering on;
    proxy_buffers 8 64k;

    location / {
        proxy_pass http://backend_cluster;
        proxy_http_version 1.1;
        proxy_set_header Connection "";

        # 4. Propagate authentic client IP and HTTPS scheme
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

03. Check your understanding

Practice check · 3 questions

Worker classes and proxy body handling

Three questions on running Uvicorn under Gunicorn and behind Nginx.

Q1. Gunicorn should manage Uvicorn workers in a new deployment. Which worker class should it use?
Q2. What does `client_body_timeout 12s` limit in Nginx?
Q3. You set `proxy_request_buffering off` on `/upload` so large files stream straight to the app. What protection does that route lose?
Practice only: not graded, not saved, not evidence.

04. Apply it

Apply these to the service in your skill project:

  • Workers from the container limit: In your container entrypoint script, compute workers using container quota variables (e.g. parsing /sys/fs/cgroup/cpu.max). For a container with 2 CPUs, configure 2 workers: exec uvicorn main:app --workers 2 --host 0.0.0.0 --port 8000, or with Gunicorn and the uvicorn-worker package, exec gunicorn main:app -w 2 -k uvicorn_worker.UvicornWorker -b 0.0.0.0:8000.
  • Restrict forwarded-header CIDRs: do not use --forwarded-allow-ips="*" unless nothing but your proxy can reach the app. List the trusted proxy subnets instead, for example --forwarded-allow-ips="10.0.0.0/8,172.16.0.0/12", so callers outside them cannot forge a client IP.
  • Keep both kinds of buffering on: proxy_request_buffering on; (the default) makes Nginx read slow uploads before Python sees them; proxy_buffering on; lets Nginx absorb slow downloads. Turning request buffering off for streaming uploads removes the slow-client protection, so do it only on the routes that need it.
  • Limit each client address: Add limit_conn and limit_req per IP, because body read timeouts apply between reads and do not stop a client that trickles bytes.
  • Explicit timeouts and size caps: Configure client_max_body_size, client_header_timeout and client_body_timeout at the proxy, so oversized or stalled requests are dropped before they reach a Python worker.

The next lesson covers container health probes, separating liveness from readiness, and handling graceful shutdown with connection draining.

05. Review prompt

Without looking back, explain why an async Python service needs several worker processes to use several cores, and what goes wrong when a container sizes its workers with os.cpu_count(). Contrast trusting X-Forwarded-For only from your proxies with trusting every caller, and explain what request buffering protects in a slow-client attack and what it leaves to limit_conn and limit_req.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check