[aryan@dev]
← cd ~/work
Idekavan GroupTechnical Manager & Backend Engineer2025 - 2026

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.

Zero silent autocommit or libpq wire-state corruptions
Replaced worker hard time-limits with PG statement_timeout
CI guard blocking accidental result-backend opt-in
PythonDjangoCelerygeventPostgreSQLRabbitMQ

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:

  1. gevent.Timeout unwinds the stack while the underlying libpq connection is still in PQTRANS_ACTIVE (awaiting the server’s CommandComplete / ReadyForQuery bytes).
  2. Django’s Atomic.__exit__ finally block runs and calls connection.set_autocommit(True) on that ACTIVE connection.
  3. psycopg rejects the call with ProgrammingError, leaving Django’s Python-side connection.autocommit flag stuck at False.
  4. The task’s error handler (or the next with transaction.atomic(): on that greenlet) sees autocommit == False, assumes it is nested inside a healthy transaction, and issues SAVEPOINT on a socket that still has an unread COMMIT reply, triggering OperationalError: 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-limit from 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_timeout per queue/role, sized from observed pg_stat_statements maxima. A server-side QueryCanceled returns cleanly over the wire protocol and leaves libpq in a well-defined INERROR state 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:

  1. With django_celery_results enabled and acks_late = True, a task that failed because PostgreSQL was down entered Celery’s trace_task error handler, which tried to persist the failure state to django_celery_results on the same dead PostgreSQL instance. When on_error raised, Celery’s outer tracer invoked on_error a second time, which raised again and escaped trace_task before apply_target’s completion callback could run. The greenlet died without acknowledging or rejecting the RabbitMQ delivery.
  2. When CELERY_WORKER_DEDUPLICATE_SUCCESSFUL_TASKS = True is combined with acks_late and 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.
  3. On the same -P gevent -c 50 workers, pairing acks_late = True with no max_retries turned 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 before worker_ready fires; mutating global connection registries in worker_ready corrupts active transactions.
  • Never apply Celery’s hard time_limit to gevent pools talking to libpq (and do not rely on soft_time_limit, which gevent’s TaskPool ignores). Bound DB work with PostgreSQL statement_timeout and 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.
Discussion

Comments

Loading…

Leave a note

Comments are moderated before appearing publicly.