Background Jobs and Task Queues

Run slow, retryable or scheduled work in worker processes instead of making users wait.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Server-Side Caching with Redis, Transactional Email and Notifications

A request should do the minimum needed to answer the user. Sending emails, generating PDFs, resizing images, calling slow third-party APIs and nightly reports belong in background jobs processed by separate worker processes.

The basic shape

  1. The web process enqueues a job (sendWelcomeEmail, { userId: 42 }) and responds immediately.
  2. A queue stores the job durably. Redis-backed libraries are the common choice: BullMQ (Node), Celery or RQ (Python), Sidekiq (Ruby), Hangfire (.NET). Postgres-backed queues (pg-boss, Graphile Worker, Oban) avoid an extra system.
  3. One or more workers pull jobs, run them and mark them done.

Designing reliable jobs

  • Retries with exponential backoff for transient failures, with a max attempt count.
  • A dead-letter queue (or failed set) for jobs that keep failing, plus alerting on it.
  • Idempotency: jobs can run more than once (a worker crashes after finishing but before acknowledging). Design them so a second run is harmless.
  • Pass ids, not objects: the worker loads fresh data rather than a stale snapshot.
  • Timeouts so a hung job does not block a worker forever.

Scheduling and priorities

Cron-style recurring jobs, delayed jobs ("remind in 24 hours"), separate queues for priorities so bulk exports do not delay password resets, and concurrency limits to protect rate-limited APIs.

Enqueue safely

If you enqueue inside a database transaction that later rolls back, the job runs for data that does not exist. Enqueue after commit, or use a DB-backed queue or the transactional outbox pattern.

You are ready to move on when your app sends email from a worker with retries and a dead-letter view, and you can explain what happens if the worker crashes mid-job.

Key concepts

  • Producers, queues and workers
  • Retries and exponential backoff
  • Dead-letter queues
  • Idempotent jobs
  • Scheduled and delayed jobs
  • Priorities and concurrency limits
  • BullMQ, Celery, Sidekiq
  • Database-backed queues

Mini project

Add a job queue to your API for report generation: enqueue on request, process in a worker with retries, expose job status via an endpoint and show failed jobs in a small admin view.

Check yourself

A job charges a customer and then the worker crashes before acknowledging it. What happens next, and how do you make that safe?

Free resources