Skip to content
Web Development

PostgreSQL Performance Tuning for Django at Scale

Ruslan Danelian 7 min read
Copied!
PostgreSQL Performance Tuning for Django at Scale

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.

Key Takeaways
  • 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

📊 Illustration: infographic summarizing Query optimization
Visual guide: 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 typeBest forDjango usage
B-tree (default)Equality, range, orderingdb_index=True, Meta.indexes
GINJSONB, arrays, full-text searchGinIndex from django.contrib.postgres
GiSTGeometric data, ranges, nearest-neighborGistIndex
PartialQueries on a subset, such as active rowsIndex(condition=Q(...))
Covering (INCLUDE)Index-only scans for hot queriesIndex(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.

20x
Smaller than a full
Pro Tip

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 = True in 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 Consultation

Vacuuming and bloat

🎯 Illustration: diagram illustrating Vacuuming and bloat
Visual guide: Vacuuming 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

💡 Illustration: conceptual illustration of Performance checklist
Visual guide: Performance checklist
CheckTargetTool
Top 20 queries by total time reviewedMonthlypg_stat_statements
No N+1 on list viewsConstant query countassertNumQueries, debug toolbar
Foreign keys and filters indexedNo seq scans on large tablesEXPLAIN ANALYZE
Unused indexes removedZero with idx_scan = 0 after 30 dayspg_stat_user_indexes
Connection pooling enabledConnections under 80% of maxPgBouncer, CONN_MAX_AGE
Buffer cache hit ratio99% or higherpg_stat_database
Autovacuum keeping upDead 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.

55%
CPU usage dropped by

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.

PostgreSQL Performance Tuning for Django at Scale infographic (English version)
PostgreSQL Performance Tuning for Django at Scale infographic (versión en español)
PostgreSQL Performance Tuning for Django at Scale infographic (версия на русском)
📌 Save this infographic for quick reference

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.

Ruslan Danelian
Ruslan Danelian

Full-stack developer specializing in Django, AI automation, and Google Ads management. Building production SaaS platforms and custom web applications for businesses across the US.

Read next

Have a project in mind?

Tell me what you need. I'll send you a plan with timeline and fixed price within one business day.

Year-end offer

20% off AI tools & custom CRM

AI chat assistants, DM bots, lead scoring and a CRM built around your business.

Claim 20% off