Backend
Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
Default Celery configuration loses tasks silently when workers die. This post covers the four settings that make Celery safe under real failure conditions, with the exact configuration from a production FastAPI backend.
- Published
- Reading
- 7 min
- Author
- Fidelis Uwem Joseph
Series · Part 6 of 9FastAPI in Production
- FastAPI Layered Architecture — Routes, Services, and Repositories
- Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
- Alembic Async Migrations and Idempotent Database Seeding in FastAPI
- Stateless OTP Login in FastAPI with JWT and Redis
- Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System
- Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
- Monitoring Celery with Flower — Local Setup and SSH Tunnel for Remote Servers
- Mailpit as a Dev SMTP Catch-All Behind Traefik
- MinIO as a Self-Hosted S3 Backend in Docker
Celery’s default configuration is optimised for throughput, not reliability. A worker that dies mid-task silently drops the message. A task that hangs runs forever. A broker that restarts orphans any in-flight acknowledgements. None of these are theoretical — they happen under real production load.
This post covers the four configuration changes that prevent silent task loss, add a hard execution ceiling, and ensure workers requeue tasks they cannot finish — using the exact settings from a deployed FastAPI backend.
Prerequisites
Celery 5.3 or later with a Redis broker. The examples use a FastAPI backend, but the Celery configuration is framework-independent. Redis must have requirepass set — an unauthenticated Redis broker in production is an open queue anyone can write to.
Background
Celery’s default is early acknowledgement: the message is acknowledged as soon as a worker picks it up. If the worker process dies after the ack but before the task completes, the message is gone. The broker considers it delivered. The task never ran.
This is acceptable for idempotent tasks where occasional loss is expected. It is not acceptable for transactional tasks like email delivery, invoice generation, or file processing where every message must either complete or be retried.
Implementation
1. Core reliability settings
celery_app.conf.update( task_serializer="json", result_serializer="json", accept_content=["json"], result_expires=3600, task_track_started=True,
task_acks_late=True, # ack AFTER task completes, not on pickup task_reject_on_worker_lost=True, # requeue if worker dies mid-task worker_prefetch_multiplier=1, # one task at a time per worker
task_max_retries=3, task_default_retry_delay=10,
task_soft_time_limit=240, # SoftTimeLimitExceeded raised at 4 min task_time_limit=300, # worker killed at 5 min)Each setting addresses a specific failure mode.
task_acks_late=True moves the acknowledgement from message pickup to task completion. The broker holds the message in an unacked state while the worker runs. If the whole worker disappears, the message is redelivered: immediately on RabbitMQ when the connection drops, and on Redis once the visibility timeout expires (one hour by default — more on that below).
task_reject_on_worker_lost=True is the required complement for the more common crash: a single pool process dying while the main worker process survives. Without it, Celery records WorkerLostError and acks the message, so it is never retried. With it, the main process rejects the message with requeue, and another process picks it up straight away.
worker_prefetch_multiplier=1 prevents a worker from reserving multiple messages from the broker when it can only process one at a time. The default is 4. With acks_late, a worker that reserves 4 messages and then dies has 4 un-acked messages that all need re-delivery. Setting prefetch to 1 limits the blast radius to one message per worker death.
2. Time limits
task_soft_time_limit=240, # SoftTimeLimitExceeded raised at 4 min task_time_limit=300, # worker killed at 5 minThe soft limit raises SoftTimeLimitExceeded inside the task’s execution context. A task that catches it can clean up — close file handles, commit partial state, log the timeout — before exiting.
The hard limit (task_time_limit) kills the pool process running the task after 5 minutes, regardless of what it is doing, and the main worker replaces it. The task is recorded as failed with TimeLimitExceeded and, because task_acks_on_failure_or_timeout defaults to True, its message is acknowledged rather than requeued. That is deliberate: a task that hung once will usually hang again, and requeueing it would just occupy another slot. Without a hard limit, a hung network call or infinite loop holds the worker slot forever.
The gap between soft and hard (here, 60 seconds) is the window for cleanup. Set it based on your heaviest cleanup operation.
3. Per-task retry configuration
The global task_max_retries and task_default_retry_delay apply to all tasks, but individual tasks can override both. The email task sets its own values explicitly so they are visible alongside the task logic:
@celery_app.task( bind=True, name="email.send", max_retries=3, default_retry_delay=30, acks_late=True,)def send_email_task(self, to, subject, template_name, context, text_body=None): try: html = render_template(template_name, **context) text = text_body or "Please view this email in an HTML-capable client." _send_sync(to=to, subject=subject, html=html, text=text) return {"sent_to": to, "subject": subject} except Exception as exc: logger.error( "email.send failed (attempt %d/%d): to=%s error=%s", self.request.retries + 1, self.max_retries + 1, to, exc, exc_info=True, ) raise self.retry(exc=exc)bind=True gives the task access to self, which exposes self.request.retries (the current attempt count) and self.retry(exc=exc) (re-raises and re-queues with the configured delay). Logging the attempt count before retrying means Flower and your log aggregator both show the full retry history per task ID.
acks_late=True on the task decorator overrides the global setting for this task specifically — useful when you want acks_early globally for throughput but acks_late for critical tasks only.
4. Redis broker configuration
CELERY_BROKER_URL=redis://:yourpassword@localhost:6379/0CELERY_RESULT_BACKEND=redis://:yourpassword@localhost:6379/1Broker and backend use separate Redis databases (db 0 and db 1). Using the same database works but pollutes the keyspace and makes it impossible to flush task results without also flushing unprocessed messages.
The requirepass option must be set in the Redis configuration and reflected in both URLs. An unauthenticated Redis instance on a shared network accepts task messages from anyone.
redis: image: redis:7-alpine command: redis-server --requirepass ${REDIS_PASSWORD:-password} healthcheck: test: ["CMD-SHELL", "redis-cli -a \"$${REDIS_PASSWORD:-password}\" --no-auth-warning ping | grep -q PONG"] interval: 10s timeout: 5s retries: 5The health check authenticates and then checks for PONG, rather than trusting the exit code. redis-cli exits with status 0 even when the server replies with an error, so a plain redis-cli ping against a password-protected Redis gets NOAUTH Authentication required — and the health check still passes.
Testing
Verify reliability settings are active by inspecting a running worker:
$ celery -A app.workers.celery_app inspect conf | grep -E "acks_late|prefetch|time_limit"
task_acks_late: Truetask_reject_on_worker_lost: Trueworker_prefetch_multiplier: 1task_soft_time_limit: 240task_time_limit: 300Simulate a worker crash mid-task to confirm requeue behaviour:
# In one terminal — watch worker logs$ celery -A app.workers.celery_app worker --loglevel=info --concurrency=1
# In another — queue a slow task, then kill only the pool process running it$ celery -A app.workers.celery_app call email.send \ --args='["test@example.com", "Subject", "welcome.html", {}, null]'$ kill -9 <pid of the ForkPoolWorker-1 process>
# Worker log# [ERROR] Process 'ForkPoolWorker-1' pid:4242 exited with 'signal 9 (SIGKILL)'# [INFO] Received task: email.send[<same-task-id>]The same task ID arriving again confirms task_reject_on_worker_lost requeued it. Killing the main worker process instead tests the other path: on Redis the message comes back only after the visibility timeout, so set a short visibility_timeout in a test environment if you want to watch it happen.
Pitfalls
Production considerations
The result_expires=3600 setting means task results are available for one hour after completion. If nothing reads the result within that window, it is automatically purged from Redis. For fire-and-forget tasks like email delivery, this is the right setting — do not store results indefinitely and bloat your Redis keyspace.
Celery Beat must run as a single instance. Running multiple Beat schedulers against the same broker duplicates every scheduled task. Run it as its own service with exactly one replica — never embedded in the worker with -B when you scale workers — and let restart: unless-stopped bring that one instance back if it dies.
Wrapping up
Four settings — task_acks_late, task_reject_on_worker_lost, worker_prefetch_multiplier, and the time limit pair — close the most common reliability gaps in default Celery deployments. A task that starts now either completes, retries up to the configured limit, is redelivered after a crash, or appears in Flower as a failure. The silent drops are gone.
The next problem is observability: knowing which tasks are retrying, which have hit their retry limit, and what the SMTP error was. That is where Flower and structured logging come in.
Going deeper
Tune the Redis visibility timeout deliberately. On Redis, an unacked
message is restored once broker_transport_options={"visibility_timeout": ...}
expires (3600 seconds by default). It has two jobs that pull in opposite
directions: it must be longer than your longest task, and longer than the
largest countdown/eta you ever schedule, or the message is redelivered
while the first copy is still waiting or running, and the task executes twice.
With a 5-minute hard limit and no long ETAs, 10–15 minutes is a reasonable
value; with ETAs, keep long delays out of Celery and schedule them elsewhere.
Late acks need idempotent tasks. Every setting in this post moves Celery towards at-least-once delivery. The cost is that some tasks run twice. Design for it: idempotency keys for side effects (emails, payments, webhooks), upserts instead of inserts, and “already done?” checks at the start of non-idempotent tasks.
Poison messages. task_reject_on_worker_lost requeues a task that killed
its worker. If the task always kills its worker — it loads a file too big
for memory, say — it loops forever, taking a worker down each time. Guard
against it by recording a delivery count (Redis INCR on the task ID with a
TTL) at task start and refusing to run after N attempts, or by setting a
memory cap (worker_max_memory_per_child) so the task fails cleanly instead
of being OOM-killed.
Split queues by latency. One queue for everything means a burst of slow
report generation delays password-reset emails. Route time-sensitive tasks to
their own queue (task_routes) with dedicated workers, so a backlog in one
class of work can’t starve another.