How a Lock Held During fork() Froze Our Celery Statement Run With 9 Workers Alive and Zero Progress
← Back
November 29, 2026Python8 min read

How a Lock Held During fork() Froze Our Celery Statement Run With 9 Workers Alive and Zero Progress

Published November 29, 20268 min read

06:48 UTC. The finance channel: "Statement run says 61%. It has said 61% since four o'clock. Customers on the 1st-of-month cycle get their PDFs at 08:00 and I have 2,300 of them that don't exist yet."


the scramble

The nightly run fans out one Celery task per account batch, 640 batches of about 40 accounts each, onto a queue with 8 worker slots. Each task renders the PDFs for its batch using a multiprocessing.Pool(4) because the PDF library is CPU-bound. The run starts at 02:00 and normally finishes by 05:30.

I get paged at 06:51. Flower shows 8 tasks in the active list and 247 still in the queue. The workers are all alive, heartbeats are fine, and the broker has no errors. The oldest active task started at 03:52.

First theory, from whoever was on call before me: the broker dropped acks and the tasks are phantom. I check RabbitMQ. The 8 unacked messages are real, the consumer count is 8, nothing is blocked on flow control. Not that.

the hunt

Second theory: a database lock. Statement generation reads a lot and writes one row per account to statements. I look for waiters:

SELECT pid, state, wait_event_type, wait_event, now() - xact_start AS age FROM pg_stat_activity WHERE application_name = 'statement-worker' ORDER BY age DESC; -- 8 rows, all state = 'idle', wait_event = 'ClientRead', age: NULL

Idle, no open transactions. Whatever the workers are doing, they are not waiting on Postgres.

Third theory: memory. A bad batch with a huge account could have swapped the box. free -m shows 11 GB free, no OOM entries in dmesg. CPU is the strange part. top shows the 8 Celery main processes at 0%, and under each one, 4 pool children at 0%. 40 processes, all asleep, all holding memory.

First useful fact: a slow job burns CPU, a stuck one sits at zero. I attach py-spy to one of the children from the oldest task:

$ py-spy dump --pid 48213 Process 48213: python -m celery worker ... Thread 48213 (idle): "MainThread" get (config_cache.py:41) render_statement (statements/render.py:77) _render_one (statements/pool.py:19) worker (multiprocessing/pool.py:125) ...

Line 41 of config_cache.py. I open it.

class ConfigCache: def __init__(self, loader, ttl=30): self._lock = threading.Lock() self._data = {} self._loader = loader threading.Thread(target=self._refresh_loop, daemon=True).start() def get(self, key): with self._lock: # line 41 return self._data[key] def _refresh_loop(self): while True: with self._lock: self._data = self._loader() # ~800 ms HTTP call, lock held time.sleep(30)

That does not look wrong, until you read the refresher. In this version the lock covers the whole load. git blame says someone moved self._loader() inside the with block eight months ago "so readers never see a half-loaded config". So the lock is held for roughly 800 ms of every 30.8 seconds. About 2.6% of the time.

the find

A thread holds that lock in the parent process. The parent calls Pool(4), which forks. In the child, the lock is copied in its locked state, but the thread that owns it does not exist. fork() only carries the calling thread across. Nobody in the child will ever call release(), so the first cache.get() blocks forever.

The numbers fit. Pool(4) forks all four children within a few milliseconds, so one task is either inside the 2.6% window or it is not. Across 640 tasks that predicts about 17 hung tasks per run. Until two weeks ago the refresher ran hourly and the window was 0.02%, roughly one bad run every seven weeks, which we had written off as a broker blip and fixed with a restart. Someone dropped the TTL to 30 seconds for a config-propagation feature and the odds went up 100x. The tasks had no time_limit, so each hung task held its worker slot for good. Eight slots, eight hung tasks, no more progress.

I checked it against the run. 8 hung tasks out of 393 started is 2.0%, close to the predicted 2.6%. I stopped doubting it.

the fix

Immediate: kill the 8 stuck tasks, requeue their batches, and the run finished at 07:36 with the other 247 batches landing clean. PDFs went out 36 minutes before the cutoff.

The permanent fix took two changes. First, stop forking a process that has threads. Python 3.12 even emits a DeprecationWarning for this, which we had silenced in the worker's logging config. Use a spawn context so children start from a clean interpreter:

import multiprocessing as mp def render_batch(account_ids): ctx = mp.get_context("spawn") with ctx.Pool(4) as pool: return pool.map(_render_one, account_ids)

Spawn costs about 400 ms per child to re-import the PDF library. Over 4 children that runs in parallel, so it adds under a second to a task that takes 20 seconds. Children also no longer see the parent's cache at all, so _render_one takes the config it needs as an argument instead of reaching for a global.

Second, shrink the critical section to what it should have been, and give the task a ceiling:

def _refresh_loop(self): while True: fresh = self._loader() # outside the lock with self._lock: self._data = fresh time.sleep(self._ttl) @app.task(soft_time_limit=600, time_limit=660) def build_statements(batch_id): ...

the aftermath

  • Impact: all 8 worker slots stalled for up to 3 hours. 2,300 accounts were at risk of missing the 08:00 delivery and none did.
  • Every Celery task in the repo now has a time_limit. A lint check fails CI on a @app.task without one.
  • Alert on "active tasks older than 2x p99 duration". The queue-depth alert never fired because the queue was moving, just not draining.
  • We re-enabled the fork DeprecationWarning in worker logs. It had been warning us since the upgrade.

fork() copies every lock in whatever state it happened to be in, and only the calling thread survives to use it. We don't fork from threaded processes anymore.

Share this
← All Posts8 min read