Most Django performance problems at scale are database problems. The application code is fine, the servers are fine, and yet pages that took 80 milliseconds with 10,000 rows now take two seconds with 10 million. The good news is that PostgreSQL is extraordinarily tunable, and a systematic approach, measure first, then fix the biggest offenders, routinely cuts query times by 10x or more. This guide covers query optimization, indexing, connection pooling, partitioning, monitoring, and vacuuming for apps serving 10,000 or more daily users.
It pairs with our broader guide to Django site speed optimization, which covers caching and frontend delivery. Here we focus on the database layer.
- Find the slow queries
- Connection pooling
- Vacuuming and bloat
- Real numbers: before and after
Step 1: Find the slow queries
Never tune blind. Enable the pg_stat_statements extension to see the queries that consume the most total time, not just the slowest individual ones. A 5 ms query run 2 million times a day matters more than a 3 second report run once.
SELECT query, calls, round(total_exec_time::numeric, 0) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
Query optimization
EXPLAIN ANALYZE
Run EXPLAIN (ANALYZE, BUFFERS) on a slow query, or use queryset.explain(analyze=True) in Django. Look for sequential scans on large tables, large differences between estimated and actual row counts, and sorts spilling to disk. The plan tells you what to fix.
Killing N+1 queries
The most common Django issue: a list view that triggers one query per row to fetch related objects. Use select_related() for foreign keys and one-to-one fields (a SQL join) and prefetch_related() for many-to-many and reverse relations (a second query). Detect them with django-debug-toolbar in development and with query-count assertions in tests using assertNumQueries.
Fetch less
Use only() or values() when you do not need full model instances, exists() instead of count() > 0, and iterator() for large exports. Avoid loading large text or JSON columns in list views.
A 5 ms query run 2 million times a day matters more than a 3 second report run once.
Indexing
| Index type | Best for | Django usage |
|---|---|---|
| B-tree (default) | Equality, range, ordering | db_index=True, Meta.indexes |
| GIN | JSONB, arrays, full-text search | GinIndex from django.contrib.postgres |
| GiST | Geometric data, ranges, nearest-neighbor | GistIndex |
| Partial | Queries on a subset, such as active rows | Index(condition=Q(...)) |
| Covering (INCLUDE) | Index-only scans for hot queries | Index(include=[...]) |
Index the columns you filter and order by, in the order of selectivity for composite indexes. A partial index such as one on status='open' can be 20x smaller than a full index and much faster to maintain. Remember that every index slows writes and consumes memory, so remove unused ones, which you can identify through pg_stat_user_indexes. For text search needs, see PostgreSQL full-text search vs Elasticsearch, which relies on GIN indexes.
When working on Indexing, pick one measurable goal first, track it weekly, and only scale what the data shows is working.
Connection pooling
PostgreSQL connections are expensive, roughly 5 to 10 MB each and a process per connection. A Django app with many Gunicorn workers can exhaust the server's connection limit quickly.
- CONN_MAX_AGE: set to 60 or so to reuse connections across requests instead of reconnecting each time.
- PgBouncer: a lightweight pooler between Django and PostgreSQL. Use transaction pooling mode for the best multiplexing, and set
DISABLE_SERVER_SIDE_CURSORS = Truein Django when doing so. - Sizing: a good starting point is a pool size around two to three times the number of CPU cores on the database host, far smaller than most people expect.
Partitioning
For tables beyond tens of millions of rows, such as events, logs, or audit trails, partitioning keeps indexes small and makes old data cheap to drop. Range partitioning by date is the most common: monthly partitions let you drop a whole month with DROP TABLE instead of a slow delete. List partitioning suits categorical splits, like tenant or region. Django does not manage partitions natively, so use raw SQL migrations or a library such as django-postgres-extra, and make sure your queries include the partition key so Postgres can prune partitions.
Want expert help with this? Let's make it happen.
Get a Free ConsultationVacuuming and bloat
PostgreSQL's MVCC design leaves dead rows behind after updates and deletes. Autovacuum reclaims them, but defaults are conservative for large, busy tables. Lower autovacuum_vacuum_scale_factor on hot tables (for example to 0.02), watch for bloat using pgstattuple or monitoring queries, and avoid long-running transactions, which block cleanup.
Monitoring
- pg_stat_statements for ongoing query analysis.
- django-debug-toolbar in development to catch query regressions before merge.
- Prometheus with postgres_exporter and Grafana for connections, cache hit ratio, replication lag, and slow queries.
- Alerts on connection saturation, cache hit ratio below 99%, and growing table bloat.
Performance checklist
| Check | Target | Tool |
|---|---|---|
| Top 20 queries by total time reviewed | Monthly | pg_stat_statements |
| No N+1 on list views | Constant query count | assertNumQueries, debug toolbar |
| Foreign keys and filters indexed | No seq scans on large tables | EXPLAIN ANALYZE |
| Unused indexes removed | Zero with idx_scan = 0 after 30 days | pg_stat_user_indexes |
| Connection pooling enabled | Connections under 80% of max | PgBouncer, CONN_MAX_AGE |
| Buffer cache hit ratio | 99% or higher | pg_stat_database |
| Autovacuum keeping up | Dead tuples under 10% | pg_stat_user_tables |
Real numbers: before and after
On a client application with about 12,000 daily users and 40 million rows in its main events table, we applied these steps over two weeks. Fixing N+1 queries on the dashboard cut its query count from 214 to 9. Adding a partial composite index reduced the slowest report from 6.8 seconds to 190 milliseconds. PgBouncer eliminated connection errors during traffic spikes. Median API latency fell from 420 ms to 95 ms, and database CPU usage dropped by 55%, which let the client postpone a planned server upgrade.
Many of these problems stem from age; older codebases accumulate inefficient queries, and our guide to modernizing legacy Django from 2.x to 6.1 shows how to address them as part of an upgrade. For a performance audit of your own application, see our Django performance and modernization service.
Related reading: PostgreSQL Full-Text Search vs Elasticsearch | Django Site Speed Optimization | Modernizing Legacy Django 2.x to 6.1
Is your Django app slowing down as data grows? Explore my Django performance and modernization service or get in touch for a free consultation.



Frequently Asked Questions
How do I find slow queries in a Django app?
Enable pg_stat_statements on PostgreSQL to rank queries by total time, use django-debug-toolbar in development to spot N+1 patterns, and run EXPLAIN ANALYZE on the worst offenders to see why they are slow.
Do I need PgBouncer for Django?
Not for small apps, where CONN_MAX_AGE is enough. Once you run many Gunicorn workers or multiple app servers and approach PostgreSQL's connection limit, PgBouncer becomes very valuable.
When should I partition a PostgreSQL table?
Consider partitioning when a table reaches tens of millions of rows and queries or retention policies naturally align with a key like date. Below that scale, good indexing is usually enough.
Full-stack разработчик, специализирующийся на Django, ИИ-автоматизации и управлении Google Ads. Создаю production SaaS платформы и кастомные веб-приложения для бизнеса по всей территории США.