Add django-db-connection-pool to fix PostgreSQL connection exhaustion#1409
Draft
Add django-db-connection-pool to fix PostgreSQL connection exhaustion#1409
Conversation
- Add django-db-connection-pool==1.2.6 to production requirements - Change production DB ENGINE to dj_db_conn_pool.backends.postgresql - Add PRE_PING to POOL_OPTIONS for connection health verification - Reduce MAX_OVERFLOW default from 20 to 5 to prevent connection exhaustion - Update production .env with aligned pool configuration Celery signals for closing DB connections were already in place. Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>
…trics Create core.db.backends.postgresql backend that inherits from both PGDatabaseWrapperMixin (connection pooling) and PrometheusDatabaseWrapper (metrics), preserving Prometheus database monitoring while using SQLAlchemy QueuePool for connection management. Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>
Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] Fix issues with maintaining Django connection to database
Add django-db-connection-pool to fix PostgreSQL connection exhaustion
Mar 17, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
O que esse PR faz?
Resolve o erro
FATAL: sorry, too many clients alreadyem produção adicionando connection pooling via SQLAlchemy QueuePool ao backend de banco de dados.Com 3 workers Gunicorn gevent (1000 connections cada), as conexões ao PostgreSQL eram ilimitadas. Agora são limitadas a
POOL_SIZE(10) + MAX_OVERFLOW(5) = 15por worker, totalizando ~45 conexões máximas.Mudanças:
django-db-connection-pool==1.2.6emrequirements/production.txtcore.db.backends.postgresqlque combina connection pooling (PGDatabaseWrapperMixin) com métricas Prometheus (PrometheusDatabaseWrapper) via MROproduction.pypara usar o backend customizadoPRE_PING: TrueaoPOOL_OPTIONSpara validar conexões antes do usoMAX_OVERFLOWde 20 para 5Já existente (sem alterações):
config/celery_signals.py) já fecham conexões emtask_prerun/task_postrunCONN_MAX_AGE=60eCONN_HEALTH_CHECKS=Truejá configuradosOnde a revisão poderia começar?
core/db/backends/postgresql/base.py— backend customizado (5 linhas efetivas), depoisconfig/settings/production.pylinhas 19-28.Como este poderia ser testado manualmente?
DB_POOL_SIZE,DB_MAX_OVERFLOW,DB_RECYCLEconfiguradasSELECT count(*) FROM pg_stat_activity WHERE datname = 'core';workers × (POOL_SIZE + MAX_OVERFLOW)too many clients alreadyAlgum cenário de contexto que queira dar?
O
POOL_OPTIONSe as variáveis de ambiente (DB_POOL_SIZE,DB_MAX_OVERFLOW,DB_RECYCLE) já existiam no.envs/.production/.djangoe emproduction.py, mas o pacotedjango-db-connection-poolnunca foi instalado — a configuração era dead code.O backend customizado usa herança múltipla para preservar métricas Prometheus:
PGDatabaseWrapperMixinprimeiro no MRO para queget_new_connection()gerencie o pool; quando precisa criar conexões novas, delega paraPrometheusDatabaseWrapperque adiciona tracking.Screenshots
N/A
Quais são tickets relevantes?
N/A
Referências
Original prompt
This section details on the original issue you should resolve
<issue_title>scielo.org com dificuldade de manter up</issue_title>
<issue_description>### Descrição do problema
O log do django está com algumas mensagens em produção como: