Innovating
Software
Solutions
fazesoft.com
When traffic scaled from 600 to 4,500 requests per minute during morning operational peaks on one of our client platforms, our p95 API latency climbed from an acceptable 140ms to a painful 840ms. At the same time, transactional emails and webhook dispatches started queuing for up to 14 minutes. Here is the technical post-mortem of how we identified the bottlenecks, restructured connection handling and queue topologies, and brought p95 latency down to 182ms without adding expensive compute instances.
"Scaling web systems is rarely about adding bigger database servers. In production, 80% of latency bottlenecks stem from connection churn, unindexed foreign key table locks, and worker starvation in unsegmented queues."
The stack was typical for a modern web application: a Next.js frontend querying a Python/Django REST Framework backend running on Gunicorn, backed by PostgreSQL on AWS RDS and Redis for Celery worker queues. Everything ran in Docker containers orchestrating under AWS ECS.
Under light traffic, the system performed well. But as active enterprise tenants grew, three distinct failure patterns surfaced simultaneously:
FATAL: remaining connection slots are reserved).pg_stat_statements and Django Debug Toolbar revealed that a single HTTP request executed 87 SQL queries. The ORM was lazily fetching related tenant profile and permission rows in sequential roundtrips.Throwing higher-tier hardware at connection exhaustion or queue starvation only masks poor architecture while inflating cloud bills. We established three architectural constraints before touching any code:
Instead of allowing 64 application processes to maintain open connections to Postgres, we placed PgBouncer in front of the database running in pool_mode = transaction. The trade-off: transaction pooling breaks prepared statements and session-level settings (like SET timezone or advisory locks across transactions). We audited all raw SQL queries and configured Django with DISABLE_SERVER_SIDE_CURSORS = True to ensure clean compatibility.
We banned the monolithic queue model. Workloads were classified by execution profile: urgent.fifo for user-facing transactional events (<500ms SLA), default for asynchronous database syncs (<5s SLA), and bulk.batch for exports, PDF generation, and external syncs (no latency SLA). Each lane received dedicated Celery worker containers.
Arbitrary cache expiration times (e.g., cache.set(key, val, timeout=300)) caused the dreaded "cache stampede": when a key expired on a hot endpoint, 50 concurrent requests simultaneously bypassed cache and slammed the database with identical complex aggregate queries. We switched to write-through invalidation with Redis distributed locks.
Using EXPLAIN (ANALYZE, BUFFERS) on our slowest queries, we discovered that PostgreSQL was running sequential heap scans across a 4.8 million row audit log table. The foreign key tenant_id was indexed, but the query filtered on both tenant_id and created_at in reverse chronological order.
We created a partial composite B-tree index concurrently without locking production writes:
This single index eliminated the sorting buffer spill to disk, reducing query execution time from 320ms down to 4.2ms. Next, we replaced ORM nested queries with pre-aggregated SQL window functions and select_related() / prefetch_related() with explicit Prefetch querysets limiting columns via .only(). Response payload sizes dropped from 1.4MB to 38KB.
A major source of background worker instability was Celery's default behavior. By default, CELERY_WORKER_PREFETCH_MULTIPLIER = 4. If worker A was processing a 30-second export, Celery would still prefetch 4 additional tasks into worker A's local queue buffer, leaving worker B completely idle while urgent tasks waited behind worker A.
We tuned our worker deployment configuration:
Setting prefetch to 1 forced workers to pull only one task at a time, ensuring fast tasks were immediately picked up by any available worker process. Setting max_tasks_per_child = 250 automatically recycled worker processes, resolving intermittent container out-of-memory (OOM) crashes caused by memory fragmentation in Python image processing libraries.
To eliminate cache stampedes on the main dashboard, we implemented a brief Redis mutex lock pattern. When the cache key is missing, only the first worker acquires a 2-second lock to compute the expensive aggregate from PostgreSQL and write the cache. Concurrent requests detect the lock, wait 40ms, and fetch the freshly populated key from Redis rather than recalculating in parallel.
After deploying these changes to production and observing during the following Monday morning peak traffic (4,600 rpm):
A few core principles we enforce across all client engineering projects at FazeSoft:
1. Never share queue workers between I/O tasks and CPU batch jobs. The moment an async task requires more than 2 seconds of execution time, it belongs in an isolated worker pool with its own resource limits.
2. Always inspect generated SQL before signing off on ORM models. ORMs make database interaction convenient, but convenience easily masks Cartesian products and unindexed foreign key lookups. Always run EXPLAIN (ANALYZE, BUFFERS) on endpoints handling list views.
3. Connection pooling belongs at the network boundary, not in application threads. Using a dedicated transaction pooler like PgBouncer allows your API containers to autoscale freely without choking your relational database.
High performance isn't magic. It is the result of measuring bottlenecks with real profilers, understanding how your database executes query plans, and respecting the boundaries between synchronous web threads and asynchronous task workers.