SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Message Queues
  • Pub/Sub
  • Message Brokers
  • Delivery Semantics
  • Dead Letter Queues
  • Kafka Deep Dive
  • Retries with Backoff
  • RabbitMQ and SQS
  • Event Streaming vs Message Queues
  • Message Ordering
  • Task Queues, Workers and Scheduled Jobs
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Asynchronous Communication

Task Queues, Workers and Scheduled Jobs

Hand slow work to background workers, and run jobs on a timetable.

⏱ 14 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A task queue lets your app hand slow work to background workers, so the user does not have to wait. Scheduled jobs are the same idea, started by a clock instead of by a user.

  • The web app puts a task in the queue and replies at once: "We are on it".
  • A pool of workers takes tasks one by one, does the work, and acknowledges it when done.
  • If a worker fails, the task goes back and is retried. After too many failures it moves to a dead letter queue.

02Concept: What is it?

Some work is too slow or too heavy to do while a user waits: sending emails, resizing photos, making a PDF report, charging a card through a slow partner, or calling an unreliable service. Doing this inside the web request makes pages slow and fragile. A task queue moves this work out of the request.

The pieces are simple. A producer (often your web app) creates a task: a small message that says what to do and with what data. The task waits in a queue held by a broker such as Redis, RabbitMQ or Amazon SQS. A worker is a separate process that pulls tasks, runs them and reports the result.

The task queue pattern
πŸ™‹Userclicks Export
→↓request
πŸ–₯️Web appenqueue + reply
→↓task
πŸ“¬Queuewaiting tasks
→↓pull
βš™οΈWorker 1
βš™οΈWorker 2
The user gets a quick answer. The slow work happens in the background.

The life of one task

StepWhat happensWhy it matters
EnqueueThe producer saves the task in the queueThe user is free to go on straight away
LeaseA worker takes the task, and it is hidden from other workers for a while (a visibility timeout)Two workers do not run the same task at once
RunThe worker does the jobSlow work is off the request path
AcknowledgeOn success the worker tells the queue to delete the taskThe task is finished only after this
RetryOn failure or a lost worker the lease runs out and the task returnsFailures are not lost
Dead letterAfter a set number of failures the task is parkedA poison task cannot block the line
🧠Acknowledge after the work, not before
If a worker acknowledges first and then crashes, the task is lost. If it acknowledges last and then crashes, the task is run again. That is safer, but it means every handler must cope with running twice.

03Real-Life Example

🍡The Restaurant Kitchen
A waiter takes your order and puts the ticket on the rail. They do not cook it. Cooks take tickets one at a time. If it gets busy, the rail fills up, and the manager calls in more cooks. If a cook drops a dish, the ticket goes back on the rail. A ticket that keeps failing, say for an item that is out of stock, is set aside for the manager. Separately, the restaurant also has a timetable: at 5 pm, someone always starts the soup.
Restaurant
Task queue
The waiter taking the order
The producer (web app)
The ticket rail
The queue
Cooks
Workers
A cook takes a ticket and others skip it
A lease or visibility timeout
Ticket is thrown away when the dish is served
Acknowledge
Ticket goes back after a dropped dish
Retry
The manager sets aside a bad ticket
Dead letter queue
Soup starts at 5 pm every day
A scheduled job (cron)
Failure handling
πŸ“¬Task
→↓
βš™οΈWorkerfails
→↓back
πŸ”Retry x3
→↓still failing
πŸͺ¦Dead letter queue

04Why Do We Need It?

⚑Fast responses
The user gets an answer in milliseconds while the slow work runs in the background.
🌊Smooth out spikes
A burst of tasks waits in the queue instead of crashing the system. Workers finish them at their own speed.
πŸ”Reliable work
A failed task is retried. A crashed worker does not lose its task.
πŸ“ˆScale the slow part
Add workers when the queue grows, without touching the web servers.
🧱Isolation
A slow or broken partner service slows only the workers, not the whole site.
⏰Time-based work
Scheduled jobs run reports, clean-ups and reminders without anyone pressing a button.
Do the quick part now, and put the slow part in a queue. Workers do it safely in the background.

05Where Do We Use It?

πŸ“§Emails and notifications
Welcome emails, receipts and push messages are sent by workers.
πŸ–ΌοΈMedia processing
Resize photos, create thumbnails, and convert and transcode videos.
πŸ“„Reports and exports
Build a big CSV or PDF and email a link when it is ready.
πŸ’³Slow partner calls
Call a payment or shipping service that can take seconds and sometimes fails.
🧹Clean-up and batch jobs
Nightly clean-up, data syncs, and re-indexing run on a schedule.
πŸͺWebhook delivery
Send a webhook to a customer with retries when their server is down.

06Types / Parts / How It Works

Pieces of a task queue system

PartJobExamples
ProducerCreates tasksYour web app or an API
Broker / queueStores tasks safely until a worker takes themRedis, RabbitMQ, Amazon SQS
WorkerPulls and runs tasksCelery, Sidekiq, BullMQ, or a function triggered by SQS
Result store (optional)Keeps the outcome or the status of a taskA database or Redis, read by status polling
Dead letter queueParks tasks that kept failingA second queue you can inspect and replay

Worker settings that matter

SettingWhat it meansWhy it matters
ConcurrencyHow many tasks one worker runs at onceToo high overloads a downstream service. Too low wastes the machine.
Visibility timeout / leaseHow long a task is hidden while a worker runs itShorter than the task, and a second worker starts it too. Much longer, and a crash is noticed late.
HeartbeatA message that extends the lease for a long taskLets a long job run without being handed to someone else.
Max attemptsHow many times a task may fail before it is dead-letteredStops a poison task from retrying for ever.
PrioritySome queues or tasks are served firstA password-reset email should not wait behind 10,000 report jobs.
Rate limitA cap on tasks per second to a partnerProtects a service that has its own limits.

Scheduled jobs (cron)

A scheduled job runs at a fixed time or every so often, for example "every night at 02:00". The hard part is not the clock. It is making sure the job runs once, even when many app instances are running.

Run once across many instances
Wrong: every instance has a cron
πŸ–₯️App 1
πŸ–₯️App 2
πŸ–₯️App 3

At 02:00 the job runs 3 times.

Right: one scheduler
⏰Schedulerleader or lock
↓enqueue once
πŸ“¬Queue
↓
βš™οΈOne worker runs it
Duplicate runs Single run
Only one instance may fire the job. A scheduler enqueues one task, and workers do the work.
VisualizerBacklog, workers and the dead letter queueChange the arrival rate, the number of workers and the task time. Turn on the spike, autoscaling and failures. See when the backlog grows, and how a poison task ends up in the dead letter queue.
Tasks waiting in the queue each second (amber). The shaded band is the spike.
Average time a task waited before a worker picked it up, in seconds (so far)
Workers busy (cyan)
0 s30 s60 s
Backlog
0
tasks waiting
Avg wait
0.0 s
before a worker starts
Done
1196
acknowledged
Retried
0
put back in the queue
Dead letters
0
after 3 tries
Healthy: 4 of 4 workers busy and a short queue. Average wait 0.0 s.

Rule of thumb: workers needed = arrival rate x time per task. Normal load needs about 4, and the spike needs about 12. Your fixed fleet of 4 can finish about 20 tasks per second. A simplified model with a simulated clock (no random numbers). The numbers are illustrative.

07How to Use It / Steps / Implementation

Running background work well

  1. 1
    Keep tasks small and self-contained
    Put IDs in the task, not big data. The worker reads fresh data when it runs, so a task that waits is never stale.
  2. 2
    Make handlers idempotent
    A task can run twice (a retry, a lost acknowledgement). Use an idempotency key or check β€œalready done?” before the side effect.
  3. 3
    Acknowledge after success
    Acknowledge only when the work is complete, so a crash returns the task to the queue.
  4. 4
    Set the lease longer than the task
    Or use heartbeats for long jobs. A lease that is too short causes double processing.
  5. 5
    Retry with backoff and a limit
    Retry temporary failures with growing waits, then send the task to a dead letter queue after a few attempts.
  6. 6
    Size workers from the numbers
    Workers needed is about arrival rate x time per task. Add autoscaling on queue depth or on the age of the oldest task.
  7. 7
    Run scheduled jobs once
    Use one scheduler (a managed one, a leader election or a distributed lock) that enqueues the job, and make the job safe to run twice.
  8. 8
    Watch the queue
    Alert on queue depth, the age of the oldest task, failure rate and dead letter count.
Sketch of a worker loop (illustrative pseudocode)
loop:
    task = queue.receive(leaseSeconds = 60)
    if task is empty: continue
    try:
        if alreadyDone(task.id): queue.ack(task); continue    # idempotent
        process(task)
        queue.ack(task)                                      # ack AFTER success
    except TransientError:
        queue.releaseWithDelay(task, backoff(task.attempts))
    except Exception:
        if task.attempts >= MAX_ATTEMPTS: queue.deadLetter(task)
πŸ’‘Tell the user what is going on
For long tasks, return a job ID at once. The client can poll a status endpoint, or you can push the result later (by email, a webhook or a live update).
⚠️Cron pitfalls
Time zones and daylight saving can skip or repeat a run. A job that takes longer than its interval can overlap with the next run. A missed run (the scheduler was down) needs a rule: catch up, or skip. Run schedules in UTC where you can.

08Key Terms to Know

TermMeaning in easy words
Task / jobA small unit of work, stored as a message in a queue
ProducerThe code that puts tasks into the queue
WorkerA separate process that pulls tasks and runs them
Acknowledge (ack)Telling the queue that a task finished, so it can be deleted
Visibility timeout / leaseThe time a taken task stays hidden from other workers
HeartbeatA signal from a worker that extends the lease of a long task
Dead letter queueA parking place for tasks that failed too many times
Poison taskA task that fails every time it is tried
BacklogThe number of tasks waiting in the queue
AutoscalingAdding or removing workers based on load, such as queue depth
CronA schedule format and tool for running jobs at set times

09Pros, Cons and Trade-offs

βœ… Pros
  • Fast replies, since slow work moves out of the request
  • Spikes wait in the queue instead of crashing the system
  • Failed tasks are retried, and nothing is lost
  • Workers scale on their own
  • Scheduled jobs run without human action
⚠️ Cons
  • More parts to run and watch (broker, workers, dead letters)
  • Work is at-least-once, so duplicates must be handled
  • Results arrive later, so the user experience needs care
  • Debugging is harder than a simple function call
  • Ordering is not guaranteed across workers

Trade-offs

ChoiceWe gainWe lose
More workersShorter backlog and waitMore cost, and more pressure on the database or partner
Short leaseCrashes are noticed fastSlow tasks may be run twice at the same time
Long leaseFewer double runsA crashed task waits a long time to return
Many retriesSurvive long blipsA poison task wastes more work before parking
Priority queuesUrgent work goes firstLow-priority work can starve
Cron per instanceSimple to startDuplicate runs when you scale out

10Common Problems and Mistakes

Common mistakes

  1. Non-idempotent handlers. A retry sends the second email or charges the second time.
  2. Acknowledging too early. A crash after the ack loses the task for good.
  3. A lease shorter than the task. Another worker picks up the same task while the first is still running.
  4. Endless retries. A poison task burns capacity and blocks others. Always set a max and a dead letter queue.
  5. Big payloads in the task. Large data in the message is slow and goes stale. Send an ID.
  6. Cron on every instance. The job runs once per instance, not once per schedule.
  7. No monitoring of the queue. A backlog can grow silently for hours.

Things to watch

πŸ“ˆGrowing backlog
Arrivals exceed what workers finish. Check task time, add workers, or find a slow dependency.
πŸͺ¦Dead letter growth
A rising count means a bug or a bad deploy. Inspect, fix, then replay.
πŸ•³οΈLost tasks
Check that tasks are stored durably and acknowledged only after success.
🌍Time zones and DST
A local 02:30 may not exist, or may happen twice, on a clock-change night.

11Real-World Examples

🐍Celery
A widely used task queue for Python, often with Redis or RabbitMQ as the broker.
πŸ’ŽSidekiq
A popular background-job system for Ruby, backed by Redis.
🟩BullMQ
A queue library for Node.js, built on Redis, with retries, delays and priorities.
☁️SQS plus functions
A managed queue that triggers cloud functions, so you do not run workers yourself.
☸️Kubernetes CronJob
Runs a container on a schedule, with settings for overlapping runs and missed starts.
πŸ“¦Workflow engines
Systems like Temporal or Airflow add long-running, multi-step jobs with state on top of the same idea.
πŸ“Note
Product names are examples, and features and defaults change between versions. Check the documentation of the tool you pick.
Mini case: a photo upload
πŸ“·Uploadsaved, reply in 100 ms
→↓enqueue
πŸ“¬Queue
→↓
βš™οΈWorkersthumbnails, scan
→↓failed x3
πŸͺ¦Dead letters
The user sees a result at once. Thumbnails and moderation happen later.

12Related Topics to Read Next

Message Queues→

The queue that holds the tasks until a worker takes them.

Dead Letter Queues→

Where tasks go when they keep failing.

Retries with Backoff→

How a failed task should be retried.

Idempotency→

Makes it safe for a task to run more than once.

Leader Election→

One way to make sure only one instance runs a scheduled job.

Distributed Locks→

Another way to run a scheduled job exactly once across instances.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: producers enqueue tasks, workers pull, run and acknowledge them.
  • βœ”Ack: only after success. Crash means the task returns and runs again.
  • βœ”So: handlers must be idempotent.
  • βœ”Lease: longer than the task, or use heartbeats.
  • βœ”Failures: retry with backoff, then dead letter after a max.
  • βœ”Workers: about arrival rate x task time. Autoscale on queue depth or age.
  • βœ”Cron: one scheduler enqueues, not one cron per instance. Use UTC and guard overlaps.
  • βœ”One line: β€œTake the order now, cook it in the back, and set aside the ticket that keeps burning.”
← Previous
Message Ordering
Next β†’
What is Caching?