Three Silent Failure Modes of Celery -P gevent + Django + PostgreSQL
Why prefork instincts break under greenlets: boot-time DB registry races, hard time_limit poisoning libpq wire state, and DB-backed result stores wedging acks_late workers on primary restarts.
Most teams reach for Celery’s -P gevent pool as a drop-in memory optimization for I/O-bound workloads. Instead of paying 300-500 MB per preforked Django process, a single worker pod runs 50 concurrent greenlets on one heap.
The problem is that Django’s ORM, psycopg/libpq, Kombu, and django_celery_results were all designed around process-level isolation. Under cooperative greenlet scheduling, three assumptions that hold under prefork break in production. We hit all three on a high-throughput Django, PostgreSQL, and RabbitMQ backend.
1. The worker_ready connection registry swap
Symptom
Right after a worker pod booted under heavy queue backlog, tasks failed inside with transaction.atomic(): with:
TransactionManagementError: select_for_update cannot be used outside of a transaction
Worse, any task inside atomic() that did not call select_for_update() did not raise at all; it silently committed partial writes in autocommit mode.
Cause
A common Celery + gevent pattern installs a worker_ready signal handler that resets django.db.connections._connections (swapping the thread-local storage to a greenlet-aware local or clearing stale boot-time wrappers). The assumption is that worker_ready fires before any task executes.
Under -P gevent, that assumption is false. Kombu’s Consumer.consume() issues basic.consume across the worker’s queues and begins dispatching incoming deliveries into greenlets while it is still waiting for the final queue’s consume-ok frame. worker_ready fires only after consume() returns.
Kombu Consumer.consume()
├─ queue A: basic.consume → consume-ok → broker delivers task T1
│ └─ greenlet G1 enters transaction.atomic()
│ (holds wrapper W1, autocommit=False)
├─ queue B: basic.consume → consume-ok
└─ returns → fires worker_ready
└─ handler replaces django.db.connections._connections
└─ G1's next ORM query creates brand-new
wrapper W2 (autocommit=True!)
Greenlet G1 opened its BEGIN on connection wrapper W1, then worker_ready swapped the registry out from under it. The next query inside the same with transaction.atomic(): block looked up connections['default'], got a fresh wrapper W2 in autocommit mode, and ran outside the transaction.
Fix and invariant
We removed the worker_ready DB registry swap completely. With gevent.monkey.patch_all() applied before Django imports, Python’s threading.local is already greenlet-local; replacing _connections after boot only introduces a race window.
Unit tests calling task functions directly never exercise Kombu’s startup order, so we added a regression test that boots an actual celery -P gevent subprocess against a pre-populated queue and verifies connection identity stays invariant across atomic() blocks during startup.
2. Hard --time-limit poisoning libpq sockets (and ignored --soft-time-limit)
Symptom
Under transient database latency spikes, webhook-processing tasks failed in cascades with two PostgreSQL errors on subsequent queries in the same greenlet:
ProgrammingError: set_autocommit cannot be used inside a transaction
OperationalError: another command is already in progress
Cause
Under prefork, --time-limit sends SIGKILL to the child process. The OS closes the process’s file descriptors, PostgreSQL rolls back the open transaction, and the next task starts on a clean process and socket.
Under gevent, there is no child process to kill. Celery enforces time_limit by injecting gevent.Timeout (which inherits from BaseException, not Exception) into the parked greenlet. If that greenlet is yielded inside libpq waiting for a COMMIT response:
gevent.Timeoutunwinds the stack while the underlyinglibpqconnection is still inPQTRANS_ACTIVE(awaiting the server’sCommandComplete/ReadyForQuerybytes).- Django’s
Atomic.__exit__finallyblock runs and callsconnection.set_autocommit(True)on thatACTIVEconnection. psycopgrejects the call withProgrammingError, leaving Django’s Python-sideconnection.autocommitflag stuck atFalse.- The task’s error handler (or the next
with transaction.atomic():on that greenlet) seesautocommit == False, assumes it is nested inside a healthy transaction, and issuesSAVEPOINTon a socket that still has an unreadCOMMITreply, triggeringOperationalError: another command is already in progress.
The usual reaction is to switch to --soft-time-limit so the task can catch SoftTimeLimitExceeded and exit cleanly. That does not work under gevent: Celery’s gevent TaskPool.on_apply silently ignores soft_timeout because it is never wired up.
Fix and invariant
- Strip every worker-level and decorator-level hard
--time-limitfrom gevent queues. Do not use cooperative greenlet exceptions to abort blocking C-extension wire protocols. - Move execution budgets to the server side by enforcing PostgreSQL
statement_timeoutper queue/role, sized from observedpg_stat_statementsmaxima. A server-sideQueryCanceledreturns cleanly over the wire protocol and leaveslibpqin a well-definedINERRORstate that Django rolls back cleanly. - In webhook handlers, check
connection.is_usable()on database errors and explicitly close/discard poisoned connections before deferring retries.
3. DB-backed result store wedging acks_late workers on primary restarts
Symptom
After a routine 3-minute PostgreSQL primary restart, Celery workers did not recover when the database came back. In-flight tasks sat unacknowledged in RabbitMQ for 30 minutes until RabbitMQ hit consumer_timeout, closed the channel with PRECONDITION_FAILED, and crashed the worker pods.
On queues where results were ignored but CELERY_WORKER_DEDUPLICATE_SUCCESSFUL_TASKS = True was enabled, redelivered tasks after the DB outage were silently acknowledged without executing their body.
Cause
Three Celery behaviors collided during the database outage:
- With
django_celery_resultsenabled andacks_late = True, a task that failed because PostgreSQL was down entered Celery’strace_taskerror handler, which tried to persist the failure state todjango_celery_resultson the same dead PostgreSQL instance. Whenon_errorraised, Celery’s outer tracer invokedon_errora second time, which raised again and escapedtrace_taskbeforeapply_target’s completion callback could run. The greenlet died without acknowledging or rejecting the RabbitMQ delivery. - When
CELERY_WORKER_DEDUPLICATE_SUCCESSFUL_TASKS = Trueis combined withacks_lateand a result backend that throws or is unreachable during redelivery checks, Celery’s redelivery path can short-circuit execution and ack the message without running the task body. - On the same
-P gevent -c 50workers, pairingacks_late = Truewith nomax_retriesturned a single OOM-inducing payload into a 50-task poison-pill redelivery cascade: every pod restart pulled the same unacked poison pill back into 50 concurrent greenlets.
Fix and invariant
Do not depend on the primary database to record that the primary database failed. We set CELERY_TASK_IGNORE_RESULT = True globally and set CELERY_WORKER_DEDUPLICATE_SUCCESSFUL_TASKS = False.
To keep that rule from regressing, we added a CI test (test_celery_result_backend.py) that introspects every registered Celery task at import time and fails the build if any task sets ignore_result=False without an explicitly allowlisted reader:
# Simplified CI invariant: no task silently re-enables DB result writes
def test_no_unexpected_task_result_storage():
app.autodiscover_tasks(force=True)
offenders = [
name
for name, task in app.tasks.items()
if not name.startswith("celery.")
and not getattr(task, "ignore_result", True)
and name not in EXPLICIT_RESULT_READERS
]
assert offenders == [], f"Tasks storing unused results: {offenders}"
Takeaways
- Under
-P gevent, Kombu dispatches tasks beforeworker_readyfires; mutating global connection registries inworker_readycorrupts active transactions. - Never apply Celery’s hard
time_limitto gevent pools talking tolibpq(and do not rely onsoft_time_limit, which gevent’sTaskPoolignores). Bound DB work with PostgreSQLstatement_timeoutand HTTP work with explicit transport timeouts. - A result backend sharing fate with your primary database turns transient DB restarts into 30-minute RabbitMQ channel wedges when combined with
acks_late. Disable result storage by default and guard it in CI.
Comments