Background jobs and queues

Moving slow or unreliable work off the request path with Celery, SQS or Redis queues, and making jobs idempotent, retryable and observable.

L2 · Mid-level engineer≈ 5 min read
Key points · the two-minute version
  1. Slow or flaky work leaves the request path. Return 202 with a job ID.
  2. Delivery is at-least-once, so jobs must be idempotent (status checks, unique constraints).
  3. Use acks_late, retries with backoff and jitter, and a dead-letter queue for poison messages.
  4. Keep job state in the database, not in process memory.
  5. Never pay twice: save paid API responses before parsing.
You should be able to
  • Decide what belongs in a background job
  • Design idempotent jobs with retries and dead-letter queues
  • Explain at-least-once delivery and its consequences

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 Accepted with 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.

What comes next

3.7 Async, concurrency and performance.

Build it to remember

Two hands-on projects that exercise this lesson. Pick one, build it end to end, and keep it in your portfolio.

Project 1

PDF processing pipeline

Upload → enqueue → extract text → store results with status polling; kill workers mid-job and prove exactly-once effects.

  • FastAPI
  • Celery
  • Redis
  • Postgres
  • S3/MinIO

Practises Idempotent jobs, retries, DLQ, job state.

Project 2

Webhook delivery service

Deliver signed webhooks to subscriber URLs with exponential retries, a DLQ, replay from the dashboard and per-subscriber rate limits.

  • Node.js
  • BullMQ
  • Redis
  • Postgres

Practises Retries, signing, operability.

Can you answer every check-yourself question out loud without opening the answer?