What is Django's performance with database connection pooling?
Answer
Advanced Django database performance and connection management: CONN_MAX_AGE: Django closes and reopens DB connections by default for each request. Set CONN_MAX_AGE for persistent connections: DATABASES = {"default": {"CONN_MAX_AGE": 60, "CONN_HEALTH_CHECKS": True}}. Each thread maintains a persistent connection for up to 60 seconds. Dramatically reduces connection overhead (PostgreSQL connection setup takes ~50-100ms). PgBouncer (connection pooler): between Django and PostgreSQL. Manages a pool of real DB connections shared across many app threads. Modes: session (one connection per client session), transaction (one connection per transaction — best), statement. Configure: DATABASE_URL = "postgresql://user:pass@pgbouncer:5432/mydb". django-db-geventpool: for async/gevent applications. Read replicas: route read queries to replicas, writes to primary. Use database router: class ReadWriteRouter: def db_for_read(self, model, **hints): return "replica" def db_for_write(self, model, **hints): return "primary" DATABASE_ROUTERS = ["myapp.routers.ReadWriteRouter"]. Queryset: Article.objects.using("replica").filter(...). Monitoring queries in production: enable log_min_duration_statement = 100 in PostgreSQL to log slow queries. Use pg_stat_statements to identify most time-consuming queries. Raw SQL for complex queries: Article.objects.raw("SELECT a.*, COUNT(c.id) as comment_count FROM articles a LEFT JOIN comments c ON c.article_id = a.id WHERE a.is_published = true GROUP BY a.id ORDER BY comment_count DESC LIMIT 10"). Indexed fields: add db_index=True or Meta.indexes on frequently filtered/sorted fields.
Previous
What is Django's caching strategies and cache invalidation?
Next
What are Django custom template tags and filters?
More Django Questions
View all →- Advanced What is Django's select_for_update and database locking?
- Advanced What is Django's database optimization with query analysis?
- Advanced What is Django's transaction management in depth?
- Advanced What is Django's deployment best practices?
- Advanced What is Django's caching strategies and cache invalidation?