Handling Request Timeouts

1. Setting Server-Side Timeout Limits

LayerTypical Timeout
Load balancer30-60s
Reverse proxy (nginx)30-60s
Application server15-30s
Database query2-10s
External HTTP call3-10s
Note: Outer layers should have higher timeouts than inner layers to allow graceful 504 responses.

2. Implementing Client Timeout Configuration

Timeout TypePurpose
Connection timeoutTCP handshake (1-5s)
Read timeoutWait for response body chunks (10-30s)
Write timeoutSend request body
Total request timeoutEnd-to-end cap

3. Handling Timeout Errors

StatusCause
408 Request TimeoutClient took too long to send request
504 Gateway TimeoutUpstream service didn't respond
503 + Retry-AfterService overloaded; client should back off

4. Implementing Request Cancellation

MechanismDetection
HTTP/1.1 client disconnectServer detects via socket close
HTTP/2 RST_STREAMCancel single stream without closing connection
AbortController (JS)Client-side fetch cancellation
Cooperative cancellationCheck req.aborted in long handlers

5. Using Timeout Headers

HeaderPurpose
Keep-Alive: timeout=30Persistent connection idle timeout
Prefer: wait=10Client willing to wait 10s for async op
X-Request-Timeout: 5000Custom: client desired timeout (ms)

6. Implementing Graceful Timeout Handling

ActionGoal
Cancel in-flight DB queryFree resources
Release locksAvoid deadlocks
Log with traceIdDebug correlation
Return 504 with detailInform client

7. Setting Database Query Timeouts

DBSetting
PostgreSQLSET statement_timeout = 5000
MySQLSET max_execution_time=5000
MongoDBmaxTimeMS(5000)
JDBCStatement.setQueryTimeout(5)

8. Handling Slow Third-Party Services

PatternBenefit
Aggressive timeout (2-5s)Fail fast
BulkheadIsolate thread pools per dependency
Cache last good responseStale-while-error fallback
Circuit breakerStop calling failing service

9. Implementing Circuit Breaker for Timeouts

StateBehavior
ClosedNormal; track failure rate
OpenReject immediately (no upstream call)
Half-OpenAllow limited probes; succeed → Closed; fail → Open
LibrariesResilience4j (Java), Polly (.NET), opossum (Node)

10. Logging Timeout Events

FieldUse
endpoint, methodIdentify slow operations
duration_msHow long before timeout
upstream_serviceWhich dependency timed out
traceIdCorrelate distributed trace
userId / clientIdAffected callers