CPU at 0% and 502s in a loop: how one blocking lock froze our national CTF platform
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…
On the second day of the online qualifier for the National CTF of Togo, players experienced the 502 Bad Gateway error due to a blocking lock in one of the application's workers. The platform, running on CTFd with additional plugins, was hosted on a server with multiple components, including MariaDB and Redis databases. The issue began around 10:00 UTC on November 7, with the system experiencing increased load and disk usage.
As the day progressed, the system kept resizing the server, cleaning up the root disk, and attempting to resolve the problem by adding more workers, increasing timeout settings, and implementing a micro-cache. However, the root cause remained unresolved.
The deadlock occurred within a gevent worker, where the instancer plugin employed a file lock to serialize changes to the tunnel agent's configuration. This lock was implemented using the flock() system call, which is a blocking call and not cooperative. When two instance requests landed on the same worker, one greenlet would hold the lock and yield during its HTTP call, while another greenlet on the same thread would call flock(), causing the thread to block in the kernel.
As a result, the hub could not resume the first greenlet, leading to a deadlock and preventing any requests from being processed on that worker. This caused every request on that worker to be delayed, along with all the database connections the worker held. The deadlock was only triggered when two instance operations occurred simultaneously in the same worker, which was a common occurrence during the busy Saturday morning.
The bug went unnoticed during unit testing, as it only manifested under heavier load conditions. The aggravating factors included the database exceeding its connection limit and the workers failing to boot due to the frozen workers' connections being held until they were killed. These factors combined to create a restart loop, causing the platform to become unavailable and resulting in 2,301 refused connections.
The issue was resolved by raising the MariaDB max_connections limit and deploying a cooperative lock.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to