NCTF26 平台 CPU 接近 0%、502 連環出現:一個阻塞鎖如何令多哥全國 CTF 平台癱瘓
CPU at 0% and 502s in a loop: how one blocking lock froze our national CTF platform
作者在 NCTF26 線上資格賽期間發現,CTFd 自製插件中的阻塞式 `fcntl.flock()` 凍結 gevent worker,令平台持續向玩家回傳 502。
Day two of the online qualifier, late morning. Players were getting 502 Bad Gateway, the proxy logged hundreds of failed upstream connections every minute, and the application container kept restarting. The strange part was the CPU: at times the app sat close to 0%. The database was idle too, with about 190 connections doing nothing.
We had already moved the server up twice that weekend. Size was not the problem. This post explains what was.
Context
NCTF26 was the 4th edition of the National CTF of Togo, run by CERT.tg. The online qualifier ran from 6 November 2026, 19:00 UTC, to 7 November, 23:59 UTC (29 hours), with more than 350 registered players and 77 teams that submitted at least once. The platform was CTFd with in-house plugins (20 over the whole edition), including one that starts a container for each team on a separate "arena" server. The public site is still at https://ctf.tg.
The outage described here ran from about 10:00 to 12:50 UTC on 7 November.
The stack, briefly
players ──► CDN ──► nginx ──► gunicorn (gevent workers) ──► CTFd + plugins
│ │
│ ├──► MariaDB
│ └──► Redis
│
└──► instancer plugin ──► tunnel agent admin API
(on the arena server,
reloads routes per instance)
The key detail is the worker model. gunicorn ran gevent workers: one OS thread per worker process, with hundreds of greenlets switching on I/O. That works well as long as nothing blocks the thread. When something does, every request on that worker stops with it.
Timeline (UTC, 6 to 7 November)
| Time | What happened |
|---|---|
| 06/11 19:56 | First report that the platform is slow. Front at 2 vCPU, load 6.39, app at 123% CPU. |
| 06/11 20:29 | Resized to 4 vCPU (3 to 4 minutes of downtime). Pages back to 0.5 s. |
| 07/11 10:02 | Load 7.46 on 4 vCPU, and the root disk at 99%. |
| 07/11 10:09 | Disk cleaned up (down to 39%). The load stays high. |
| 07/11 10:39 | Resized to 8 vCPU. The internal health check drops from 4,282 ms to 17 ms. |
| 07/11 10:56 | Only 4 workers, so only 4 of the 8 cores in use. |
| 07/11 ~11:05 | Workers go from 4 to 8. Container recreated. |
| 07/11 11:21 |
502s for players. WORKER TIMEOUT in the logs. |
| 07/11 11:30 | gunicorn timeout raised to 120 s. |
| 07/11 11:40 | 8-second nginx micro-cache on four public endpoints. |
| 07/11 12:05 | Found an hourly full export running inside the live container. |
| 07/11 12:17 | Backup script changed: no heavy extras during the event. |
| 07/11 12:21 | MariaDB max_connections raised from 151 to 400. |
| 07/11 12:32 |
py-spy dump: frozen workers stuck on the same line, twice in a row. |
| 07/11 12:42 | Cooperative lock deployed. |
| 07/11 12:48 | Reload signal sent to the gunicorn master. |
| 07/11 12:50 | Back to normal: 0 frozen workers, 0 nginx errors over 30 s, scoreboard in 8 to 15 ms. |
The bigger server, the extra workers, the longer timeout and the micro-cache were reasonable, but they treated symptoms. The export and the connection limit were real aggravating factors. The root cause only showed up at 12:32.
What it looked like
- nginx: 600 to 1,400
connect() failedper minute, in bursts, plusupstream prematurely closed connection. - gunicorn:
[CRITICAL] WORKER TIMEOUT, thenShutting down: MasterwithReason: Worker failed to boot, and a container restart count that kept going up. - SQLAlchemy:
QueuePool limit of size 10 overflow 20 reached. - MariaDB:
Too many connections, about 190 connections inSleep, and no slow queries. - The app process: CPU close to 0% at times, plenty of free memory.
I ruled out several hypotheses by measuring them: an accumulation of long-lived event-stream connections, a container health check (there was none), memory pressure, slow SQL (the standings query took 1 ms). None of them matched.
Root cause: a blocking flock() inside a gevent worker
The instancer plugin serialises changes to the tunnel agent's configuration with a file lock. Starting or destroying an instance means: take the lock, rewrite the route config, ask the agent to reload over HTTP, release the lock.
The lock was taken like this (simplified):
import fcntl
class ConfigLock:
def __enter__(self):
self._fh = open(LOCK_PATH, "w")
fcntl.flock(self._fh, fcntl.LOCK_EX) # blocks the OS thread
return self
def __exit__(self, *exc):
fcntl.flock(self._fh, fcntl.LOCK_UN)
self._fh.close()
gevent's monkey patching makes sockets, time.sleep and many other calls cooperative. It does not make fcntl.flock cooperative: it is a plain blocking system call. Here is what happens when two instance requests land on the same worker:
Greenlet A holds the lock and yields during its HTTP call. Greenlet B, on the same thread, calls flock and blocks the thread in the kernel. The hub can never resume A, so A never releases the lock. It is a deadlock inside a single process, and it takes every request on that worker down with it, along with every database connection the worker holds. At the worst moment, 5 of the 8 workers were frozen.
That explains the 0% CPU. Nothing was busy. Everything was waiting.
The bug only appears with two instance operations at the same time in the same worker. Players launching instances in parallel on a busy Saturday morning do exactly that. A unit test never would.
Aggravating factor 1: the database limit we overran ourselves
At about 11:05 I doubled the workers to use the eight new cores. Flask-SQLAlchemy (version 2.5.1 in our stack) gives each worker a MySQL pool of 10 connections plus 20 overflow, so 30 per worker:
workers × (pool_size + max_overflow) = 8 × (10 + 20) = 240
MariaDB max_connections (default) = 151
Frozen workers kept their connections until gunicorn killed them. Replacement workers then could not open their own: Too many connections. Enough workers failing to boot made the gunicorn master give up, the container restarted, and everything started again from a cold cache. Each restart caused another 10 to 30 seconds of connect() failed. Slowness had turned into a restart loop, and the loop was the 502s.
2,301 refused connections had piled up before I raised the limit. That can be done live:
SHOW VARIABLES LIKE 'max_connections';
SHOW STATUS LIKE 'Threads_connected';
SHOW STATUS LIKE 'Max_used_connections';
SET GLOBAL max_connections = 400; -- live, no restart
Then make it permanent in the database service definition (for example --max-connections=400 in the compose command), or the next recreate silently puts it back to 151. Every MariaDB connection is a server thread, so check any pid or thread limit on the database container too.
Aggravating factor 2: an hourly full export in the live container
The backup timer ran every 15 minutes. The SQL dump was fine. But once an hour the script also archived uploads and ran CTFd's full export, which builds a second application instance inside the production container and writes an archive of about 167 MB. During an event, that is CPU, memory and database work on the box that is already struggling, to re-save challenge files that do not change.
The fix was to detect the event window in the backup script and skip the heavy extras while it is open:
# keep the 15-minute SQL dump, skip the heavy extras during the event
now=$(date +%s)
if [ "$now" -ge "$EVENT_START" ] && [ "$now" -le "$EVENT_END" ] && [ "$FORCE_EXTRAS" != "1" ]; then
echo "event in progress: SQL dump only"
run_sql_dump
exit 0
fi
run_sql_dump
run_full_export
The SQL dump holds all competition data. That is what matters during the event.
The tool that settled it: py-spy
Logs showed symptoms. They did not show where the workers were stuck. py-spy can dump the Python stack of a running process without restarting it and without changing the code:
# host PIDs of the processes inside the container
docker top <app-container>
# dump the Python stack of one worker (run on the host, as root)
py-spy dump --pid <host-pid>
I dumped every worker, waited, and dumped them again. The frozen workers showed the same line both times: the flock call in the instancer lock. One frozen stack can be a coincidence. The same stack twice, on several workers, points straight at the cause.
Two notes. py-spy only shows the greenlet that is running; a greenlet parked in network I/O while holding a lock does not appear. To find who holds a file lock, read /proc/locks on the host and match the PID. Also, I did not have pip on the host, so I took the static binary out of the PyPI wheel. That is worth preparing before the event.
The fix: a lock that yields
import fcntl
import time
LOCK_WAIT = 60 # seconds
def acquire(fh):
deadline = time.monotonic() + LOCK_WAIT
while True:
try:
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
return
except BlockingIOError:
if time.monotonic() > deadline:
raise TimeoutError("instancer lock busy")
time.sleep(0.05) # cooperative under gevent: other greenlets run
With LOCK_NB the call returns immediately. The wait happens in time.sleep, which gevent patches, so the hub keeps running: the lock holder gets resumed, finishes its HTTP call and releases the lock. The deadline turns a stuck lock into an error, not a frozen worker.
I ranked the fixes by what the evidence showed: the cooperative lock first (the root cause), then max_connections at 400 and the export suspended during the event (the two aggravating factors, both already in place by 12:21). A reload of the gunicorn master at 12:48 picked up the new code, and two minutes later the platform was healthy.
What went wrong afterwards
The fix worked. The reload caused two more incidents.
Background loops died after the reload. Several plugins run a loop in a single worker: the challenge release schedule, the king-of-the-hill scorer, first-blood announcements, instance cleanup. Each one took a non-blocking file lock once, when the worker started. On a reload, new workers start while the old ones still hold those locks. The new ones give up. Then the old ones exit, and nobody runs the loops anymore. Result: about 40 minutes with no hill points (never compensated) and three challenge releases late. The fix was to retry the lock every 15 seconds:
def singleton_loop(lock_path, tick, body):
while True:
fh = try_lock(lock_path) # LOCK_EX | LOCK_NB, returns None if busy
if fh is None:
time.sleep(15) # another worker owns it, try again later
continue
while True:
body()
time.sleep(tick)
The tunnel agent froze, and the new lock made it visible. From 13:21, instance launches started failing with HTTP 500 and instancer lock busy: 159 errors in 20 minutes. The tunnel agent on the arena server had been running for eight days. Its admin API still answered config reads, but reload and status calls hung until the 15-second timeout. Every launch held the lock while waiting on that reload. Before the fix, this would have frozen workers again. After the fix, it produced clean errors that pointed at the real problem. Restarting the agent fixed it: 31 successful launches and 0 lock errors over the next five minutes. Restarting the agent then left stale registrations on the tunnel server, so HTTPS instances returned 404 until I restarted that too.
What I would do differently
- Load-test with concurrent instance launches. As the first article of this series admits, our load test and our rehearsal stayed on paper. This bug needs two launches at the same moment in the same worker; a load test that includes concurrent instance launches is the kind of test that exposes it.
-
Audit every blocking call in a gevent process.
flock,subprocesscalls, C extensions that block, and network calls with no timeout. Better still: hold the lock only for reading and writing the config, never across the reload HTTP call. -
Size workers and the database together. Write
workers × 30 < max_connectionsas a comment next to both settings. Never change one without the other. - Ship timeouts and micro-caching from day one. The 120-second gunicorn timeout and the 8-second cache on public, non-per-team endpoints (scoreboard, hill state, first bloods) were good changes, made late.
- Keep heavy jobs off the live container during the event. A full export runs before and after, never during.
- Rotate logs and alert on disk at 80%. The disk at 99% that morning was mostly the tunnel server's own log, filled by hill bots reconnecting several times a second, plus leftover Docker build cache from hot rebuilds.
- Restart long-running agents the day before. No eight-day-old service on the critical path.
- Before any reload, list what depends on a lock taken at startup.
Key takeaways
- CPU near 0% with slow requests means something is blocked, not saturated. You find that by diagnosing it. A bigger server does not fix it.
-
Under gevent, one blocking call freezes the whole worker, with every request and database connection it holds.
fcntl.flockis not patched. - Scaling the app scales its database connections. Doubling the workers that morning pushed us past the default limit and turned slowness into a restart loop.
-
Dump live stacks twice.
py-spy dumpon a running worker, repeated, is the fastest way to find the line every worker is stuck on. - Each restart is a new cold start. Restarting over and over keeps the outage going. Measure first, then change one thing.
Wrapping up
The lock was in our own plugin code. CTFd, gunicorn and MariaDB did exactly what they are designed to do. I learned the most from the hour I spent scaling before I measured. It felt like progress, but the data that settled it came from a stack dump.
This is part of the series "NCTF26: running a national CTF", which covers the architecture, the plugins, per-team instances and the on-site final. Writeups, the creator credits and the idea box for the next edition are at https://ctf.tg.
Next in the series: We tried to keep AI agents out of a 24-hour CTF final. Here is what worked, what broke, and what never could
來源:DEV Community · dev.to
