Database connection timeout with Django CONN_MAX_AGE
0 reputation · 10 Feb 2026, 23:51 UTC
0 reputation · 10 Feb 2026, 23:51 UTC
Determine the optimal CONN_MAX_AGE setting that minimizes latency spikes when Django serves a high volume of concurrent requests.
CONN_MAX_AGE for production but offers no specific value, leaving the choice to the deployment environment.CONN_MAX_AGE value produces the lowest maximum latency when handling 500 concurrent requests on PostgreSQL?CONN_MAX_AGE superior to a dynamic connection‑pooling approach for mitigating latency spikes?34775 reputation · 11 Feb 2026, 09:44 UTC
For a deployment handling ~500 concurrent requests, set CONN_MAX_AGE to a moderate value that keeps the number of idle DB connections roughly equal to your Django worker count (e.g., 10–30 seconds). This limits latency spikes caused by connection‑creation overhead while avoiding exhaustion of PostgreSQL’s max_connections.
CONN_MAX_AGE is 0, meaning each request opens and closes a new connection.CONN_MAX_AGE enables persistent connections that are reused until the specified age elapses.When CONN_MAX_AGE is too low (0), every request pays the connection‑setup cost, raising latency. When it is too high, idle connections accumulate; if the total (active + idle) approaches PostgreSQL’s max_connections, new requests block waiting for a free slot, producing latency spikes. A moderate age lets connections be reused for the burst of requests from each worker, then released before they idle long enough to threaten the connection limit.
--workers or uvicorn workers).max_connections setting (SHOW max_connections;).CONN_MAX_AGE in the range 10–30 seconds. Start with 20 seconds and monitor.max_connections, lower CONN_MAX_AGE; if connection‑setup latency dominates, raise it slightly.To refine the recommendation, please confirm your actual Django worker count and the PostgreSQL max_connections value. If the worker count is a significant fraction of max_connections, a lower CONN_MAX_AGE (e.g., ≤ 10 s) may be needed; otherwise the 10–30 s range is appropriate.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.