worker_processes auto; pid /tmp/nginx.pid; events { worker_connections 1024; } http { access_log /dev/stdout; error_log /dev/stderr warn; # Docker embedded DNS. "api" resolves to every running replica of the Compose service; # with "resolve" below nginx re-reads the set every 2 s, so stopped/scaled replicas leave and join the pool. resolver 127.0.0.11 valid=2s ipv6=off; resolver_timeout 2s; log_format upstream '$remote_addr "$request" $status upstream=$upstream_addr ' 'upstream_status=$upstream_status rt=$request_time'; upstream api { zone api_upstream 64k; # Round robin, no ip_hash/sticky: any replica serves any session from PostgreSQL. server api:8080 resolve max_fails=1 fail_timeout=5s; keepalive 32; # Shorter than uvicorn's keep-alive (5 s), so nginx never reuses a connection the API is closing. keepalive_timeout 4s; } server { listen 8080; access_log /dev/stdout upstream; client_max_body_size 1m; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 1s; proxy_send_timeout 10s; proxy_read_timeout 10s; # Not-yet-sent requests and idempotent methods go to the next replica on a dead backend. # Non-idempotent POSTs (users, chats, sessions) are never replayed by the LB. proxy_next_upstream error timeout http_502 http_504; proxy_next_upstream_tries 3; proxy_next_upstream_timeout 5s; location = /lb/health { access_log off; default_type application/json; return 200 '{"status":"ok"}'; } # Message POST carries a mandatory Idempotency-Key, so replaying it on another replica is safe. location ~ ^/api/v1/chats/[^/]+/messages$ { proxy_next_upstream error timeout http_502 http_504 non_idempotent; proxy_pass http://api; } location / { proxy_pass http://api; } } }