Why this matters
Anything slow (document processing, video rendering, batch LLM calls, emails, webhooks) shouldn't hold an HTTP request open. Queues absorb bursts, survive restarts and let you scale workers separately from the web tier. Most AI pipelines are queue-driven.
Core ideas
- Producer → queue → worker. The web request enqueues a job and returns
202 Acceptedwith a job ID; a worker processes it; the client polls or is notified. - At-least-once delivery: most queues may deliver a message more than once (a worker crashed after doing the work but before acknowledging). So jobs must be idempotent.
- Visibility timeout / ack: a message is hidden while a worker processes it; if not acknowledged in time, it reappears.
- Retries with backoff for transient failures; a dead-letter queue (DLQ) for messages that keep failing, so they're inspected instead of retried forever.
- Tools: Celery (Python, with Redis or RabbitMQ), RQ/Dramatiq, AWS SQS, Kafka (event streams), managed durable workflow engines for multi-step processes (9.5).
How to do it
@celery_app.task(bind=True, acks_late=True, autoretry_for=(TransientError,),
retry_backoff=True, retry_jitter=True, max_retries=5)
def process_document(self, document_id: str) -> None:
doc = repo.get(document_id)
if doc.status == "done": # idempotency: already processed
return
result = extract(doc) # may raise TransientError
repo.save_result(document_id, result, status="done") # one transaction
acks_late=True: acknowledge only after the work finishes, so a crash causes a redelivery rather than a lost job.- Status check + unique constraints = safe to run twice.
- Store job state in the database so the UI can show progress, and so a restart doesn't lose track.
Never pay twice
For paid external calls (LLMs, OCR, speech-to-text), save the raw response before parsing it, keyed by job and input hash. If parsing fails or the worker crashes, the next attempt reuses the saved response instead of paying again (P1).
Why this way
The request/response cycle is for things that finish in a second or two. Queues make slow work reliable (retries, DLQs), scalable (add workers) and cheap to recover from (resume, don't restart).
Common mistakes
- Non-idempotent jobs that double-charge or double-send on redelivery.
- Infinite retries on a permanent error (bad input), burning money.
- Job state only in memory or in threads inside the web process, lost on restart (a classic MVP shortcut, see D4).
- Passing whole objects into the queue instead of IDs, then processing stale data.
Interview follow-ups
- "Exactly-once delivery?" Practically impossible across systems; get exactly-once effects with at-least-once delivery plus idempotent processing (dedupe keys, unique constraints, upserts) and the outbox pattern for publishing.
- "What's the outbox pattern?" Write the business change and an "event to publish" row in the same transaction; a relay publishes outbox rows to the queue and marks them sent, so you never publish without committing or commit without publishing.
- "Celery or SQS or Kafka?" Celery for Python task queues with a broker you run; SQS for managed, durable queues on AWS; Kafka for high-volume ordered event streams with replay and many consumers.
- "How do you prioritise urgent jobs?" Separate queues per priority with dedicated workers, so a backlog of batch jobs can't starve interactive ones.
Check yourself
Why must queue workers be idempotent?
Because delivery is at-least-once: the same message can arrive twice after a crash or timeout. Without idempotency, side effects (charges, emails, records) happen twice.
What's a dead-letter queue for?
Holding messages that failed after the maximum retries, so they stop consuming resources, can be alerted on, inspected and replayed after a fix.
Build it
Add a Celery (or RQ) worker to your service: POST /documents enqueues processing and returns 202 with an ID; GET /documents/{id} shows status. Kill the worker mid-job and prove the job completes exactly once after restart.