upstream api_backend { zone api_backend 64k; resolver 127.0.0.11 valid=2s ipv6=off; server api1:8080 resolve max_fails=1 fail_timeout=2s; server api2:8080 resolve max_fails=1 fail_timeout=2s; } server { listen 8080; # Leave a small margin so the API returns its documented JSON 413 at 10 MiB. client_max_body_size 11m; client_body_timeout 20s; proxy_connect_timeout 1s; proxy_send_timeout 20s; proxy_read_timeout 20s; error_page 502 504 = @upstream_unavailable; location / { proxy_pass http://api_backend; 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_set_header X-Request-Id $request_id; proxy_intercept_errors on; # Retry GET/HEAD on a failed backend. Nginx never replays a POST after # its request has been sent unless `non_idempotent` is enabled; uploads # therefore remain single-shot, while message retries stay client-led. proxy_next_upstream error timeout http_502 http_503 http_504; proxy_next_upstream_tries 2; proxy_next_upstream_timeout 5s; } # Keep the public API error contract when all upstreams are unavailable. location @upstream_unavailable { default_type application/json; add_header X-Request-Id $request_id always; add_header X-Instance-Id "lb" always; return 503 '{"error":{"code":"unavailable","message":"API upstream unavailable","request_id":"$request_id"}}'; } }