Slow at Peak Hours — Query Shape, OOM Kills and Gunicorn Workers That Never Clean Up
A field story about a web app that crawled every day at peak — the three causes hiding behind one complaint — and the read-only checks I now run before anyone says “add more hardware”.
The complaint came in the same way every week.
“The system is slow again. All our users say the same thing. It is fine in the morning and terrible by noon.”
The app was a Django application on a single VM: nginx for TLS, gunicorn behind it, MariaDB underneath. Remote users worked in it during a fixed daily window, late morning to evening. Outside that window, nobody complained.
“Can you give us faster storage? Other clouds are faster.”
I asked one question.
“Which page is slow, and how slow?”
Silence. Then: “Everything. All of it.”
That’s the trap. “Slow at peak” is not one problem. It is a symptom that several different problems share — and if you fix the one you guessed, the complaint does not go away. It just changes shape.
In this case there were three.
What “Slow at Peak Hours” Actually Means
A request is slow when one of these is waiting:
- The network between the user and the server.
- The app worker — no free gunicorn thread to take the request.
- The database — the query itself takes seconds.
The flow is simple:
User → nginx → gunicorn worker → MariaDB → back the same way
Peak hours make every one of these worse at the same time, so they look like one problem. The only way through is to measure each hop on its own, during the real peak, without changing anything first.
Why the Usual Checks Miss It
The usual checks are CPU graphs and “how much RAM is free”. Both lied here.
CPU had headroom most of the day. Free memory looked fine right up until it did not. And the database tables already had around 30 indexes, so “add an index” — the first answer on every forum — was already done, many times over.
Here’s the part that trips people up: the obvious resource was never the bottleneck. Every hardware guess — faster disk, more CPU, more RAM — could be tested and disproved with read-only commands. So I tested them, one at a time.
Cause One: The Users’ Own Last Mile
The first capture ran across a full working day: per-request timing, gunicorn socket backlog, thread states, sar, and a filtered packet capture on port 443.
The server side was quiet:
- gunicorn backlog (
Recv-Q) was 0 in 1,003 of 1,006 samples. - Around 45–58 open connections against 192 thread slots (24 workers × 8 threads).
- Median app response: 26 ms.
- Peak bandwidth: about 15 Mbps.
But 10.3% of incoming SYNs were retransmitted, rising to about 13% at the two daily peaks. Each lost SYN costs the user a second or more before the retry. That is the “slow” they felt — and the server never saw it.
The kernel counters ruled out the server’s own accept queue:
nstat -az TcpExtListenOverflows TcpExtListenDrops TcpExtTCPReqQFullDrop
ListenOverflows and ReqQFullDrop were 0. Then mtr to the worst client addresses showed 0% loss on the provider’s first hops, 0% to a public control address, and 4–5% loss with multi-second latency inside the users’ consumer ISPs.
mtr -rwc 100 203.0.113.44
One middle hop showed 19% “loss” while every hop after it showed 0%. That is ICMP de-prioritisation on a router, not real loss. If later hops are clean, the loss in the middle is a red herring.
You cannot fix someone else’s last mile. You can make each connection cost less. HTTP/2 lets one connection carry many requests, and BBR with the fq qdisc copes better with lossy paths:
listen 443 ssl http2;
sysctl net.ipv4.tcp_congestion_control
Expected output after the change: net.ipv4.tcp_congestion_control = bbr. Plain takeaway: measure the path before you buy a bigger server.
Cause Two: A 50-Second Page and a Query With the Wrong Shape
The second complaint was sharper. A handful of admin pages were slow even with one user on site, on a short, clean network path.
The browser’s DevTools timing told the story: time to first byte of 50 seconds, 15 seconds and 4.3 seconds on three pages, and about 1 ms to download the response. That is 100% server-side.
I sampled the process list as the app’s own database user — no root password needed, because the whole app runs as that user:
mysql -e "SHOW FULL PROCESSLIST" | grep -v Sleep
One query was 63% of the database load: a duplicate check that counted rows over a derived table on a 3.15 million-row table, joined three lookup tables, and grouped by eight columns — one of them a column from a joined table.
The first guess was a missing index. The table already had about 30, including one that covered every filter and group column.
The second guess was storage. I checked the buffer pool counter before and after one run:
mysql -e "SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_reads'"
The number did not move. The query did 0 disk reads. The data was fully in memory. Faster NVMe would have changed nothing.
So I timed the pieces:
- Original query: 50 s.
- Single-statement rewrites: still about 29 s.
- The base aggregation on its own: 1.4 s.
- Two steps — aggregate first into a temp table, then join the lookup names onto the small result: 2.7 s.
The cause was the shape of the query, not the index and not the disk. Grouping by a joined column forces the database to join first and group after, across 1.5 million rows. Aggregate the base table alone, keep only the rows you need, then join the names for display.
The same pattern showed up later in a per-user progress report: one SUM(CASE …) plus five correlated COUNT(*) subqueries, each re-run per output row. It took 3–6 seconds with one user and 15 seconds or more under load. The fix is the same family:
- Replace the five correlated subqueries with one pass of conditional aggregation (
SUM(CASE WHEN … THEN 1 ELSE 0 END)). - Cache the report per user for 30–60 seconds.
- Do not add more indexes. On a table that is written all day, every extra index slows the write path.
This error is not a bug in the database. It is the verification that the query, not the platform, is doing the work.
Cause Three: OOM Kills and Workers That Never Clean Up
The third problem was the one users called “it went down”. The kernel log had the answer:
journalctl -k | grep -i "out of memory"
The OOM killer had taken mariadbd twice in one afternoon, during working hours. MariaDB died, gunicorn returned 502, and the site was down for about a minute until systemd restarted the database.
MariaDB was the victim, not the cause. The box had 126 GB of RAM and a 90 GB InnoDB buffer pool. But gunicorn workers that sat at about 220 MB idle had grown to about 2.2 GB each under load — 24 of them, roughly 53 GB. Each request loaded large result sets into Python. The OOM killer picks the biggest single process, and that was MariaDB.
The memory fixes I recommended were plain settings:
innodb_buffer_pool_sizefrom 90 GB to 64 GB (it can be resized live).tmp_table_sizeandmax_heap_table_sizecapped at 64 MB.- gunicorn
--max-requestslowered so bloated workers are recycled, and--log-level debugremoved.
Later, the RAM was upgraded and the OOM kills stopped. But the process count kept rising — and that led to the most interesting finding.
Count the gunicorn processes two ways:
pgrep -f bin/gunicorn | wc -l
ps aux | grep -c gunicorn
The first gave 40. The second gave 105. There should have been 24 workers plus one master. The gap of 65 was zombies — they have no command line, so pgrep -f cannot see them.
Then group the children of every worker by state:
ps --ppid $(pgrep -d, -f bin/gunicorn) -o stat= | sort | uniq -c
And look at when each batch started:
ps --ppid $(pgrep -d, -f bin/gunicorn) -o ppid,pid,stat,lstart -ww
The children came in batches with an identical start time: one worker had 1 live child and 16 zombies, all born in the same second. Another had 6. Another had 11. Each batch was one run of the app’s image-cropping job. The code forked a pool of child processes per run and never closed or joined them. Dead children became zombies. Hung children stayed alive. Real workers stayed at exactly 24; the “extra” 16 live processes were stuck forks.
The same leak explained a data problem the admins had reported: when a cropping run took long, items went missing (hung forks), and when they re-ran it, items were duplicated (no unique key to stop a second insert).
The fix belongs in the code, in this order:
- Close and join every child process:
with multiprocessing.Pool() as p:or an explicitclose(),join(),terminate(). - Add a unique key on the natural key of the processed rows and use
INSERT … ON DUPLICATE KEY, so a re-run cannot duplicate. - Make the job faster, so no fork runs long enough to hang.
Settings only reduce the damage: a longer --graceful-timeout, a lower --max-requests so workers recycle and take their child piles with them, and a separate gunicorn pool for the admin path. Only the code cleanup and the unique key actually fix it.
What About the Hypervisor?
I checked that too, because “other clouds are faster” deserved an honest answer.
sar -u -f /var/log/sysstat/sa17
CPU steal averaged under 1.1% on seven of eight working days. One day was contended. Weeks later, after the VM grew, steal rose to 10–14% exactly at the daily peaks and the overnight batch window — a real contributor, and the right ask to the virtualisation team is a CPU reservation for that VM.
But even at 0.2% steal, the 50-second page was still 50 seconds. Steal was a contributor, never the cause. Lead with the app, not the hosting.
The Bigger Lesson
Here is the read-only checklist I now run on any “slow at peak” case, in this order:
- Is the user’s path losing packets?
nstat -az TcpExtListenOverflowson the server,mtrto a client address. Clean server counters plus lossy last hops = not your server. - Is the slow part server-side? DevTools time to first byte versus download time.
- Which query is the load? Sample
SHOW FULL PROCESSLISTas the app user during peak. - Is it I/O?
Innodb_buffer_pool_readsbefore and after one run. No change = do not buy storage. - Is it shape or index? Time the base aggregation alone. If it is fast, rewrite; do not add an index.
- Is the OOM killer involved?
journalctl -k | grep -i "out of memory". - Are workers leaking?
pgrep -f bin/gunicorn | wc -lversusps aux | grep -c gunicorn. A gap means zombies. - Is the host stealing CPU?
sar -uacross a full working day, peak hours only.
Absence of high CPU is not health. Every one of these problems ran on a box that looked fine on a dashboard.
What I Tell Every Customer Now
When someone asks for more hardware because the system is slow at peak, I ask one question:
“Which page, how many seconds, and have we proved it is not the query?”
If the answer is a page name, a number and a timing of the base query, they’re in good shape. If the answer is “everything is slow”, we’re not done yet.
I write about the questions I ask in real customer rooms — the ones that change architectures and surface the problems no one else noticed. If you found this useful, drop your email below and I’ll send the next one when it’s ready.
FAQs
Why is my web app slow only at peak hours when CPU looks fine?
Because CPU is rarely the first thing to run out. Look for lost packets on the users’ path, a query whose cost grows with concurrent users, or app workers that bloat or leak under load. Measure each hop separately during the real peak.
Will adding an index fix a slow GROUP BY query?
Not if the table already has a covering index. If the query groups by a column from a joined table, the database must join before it groups. Aggregate the base table first, then join the lookup names onto the small result.
How do I prove a slow MariaDB query is not a disk problem?
Read Innodb_buffer_pool_reads before and after running the query once. If the number does not change, the query read nothing from disk, and faster storage will not help.
Why does the OOM killer kill MariaDB when gunicorn uses the memory?
The OOM killer picks the largest single process. Many gunicorn workers can use more memory in total than MariaDB, but each one alone is smaller, so MariaDB is killed. Recycle workers with --max-requests and keep the buffer pool well below total RAM.
How do I find zombie processes left by gunicorn workers?
Compare pgrep -f bin/gunicorn | wc -l with ps aux | grep -c gunicorn. Zombies have no command line, so only the second count includes them. Then run ps --ppid on the worker PIDs to group children by state and start time.
Is CPU steal time the reason my VM is slow at peak?
It can contribute. Check sar -u across a full working day. If a slow page is still slow when steal is near zero, steal is not the cause, and the fix is in the application.