Skip to content

Pattern: Managing Long-Running Tasks

Intermediate 45 min read Part 11 of 18

Split slow work into a fast acknowledgement and background processing: queue jobs, return an ID, run worker pools, retry safely and report progress.

Summary#

Some operations take far longer than a user, a load balancer or an HTTP connection will wait. Examples are encoding a video, generating a report, importing a large CSV, sending a newsletter to a million people, running code against test cases, or training a model. Managing long-running tasks is the pattern of splitting such an operation into two phases.

  1. Immediate acknowledgement. The API validates the request, records a job in a durable store, puts a message on a queue, and returns a job ID within milliseconds, usually with HTTP 202 Accepted.
  2. Background processing. A separate worker pool pulls jobs from the queue, does the work, and records progress and results. The client learns the outcome by polling a status endpoint or by being pushed an update over SSE, a WebSocket, a webhook, an email or a mobile notification.

This buys fast responses, independent scaling of web servers and workers, and isolation of failures. It costs complexity, and the hard parts are all about failure:

  • A job state machine, so everyone agrees whether a job is queued, running, done or failed.
  • Retries with backoff for transient errors, and dead-letter queues for jobs that keep failing.
  • Idempotency, because at-least-once queues deliver some jobs twice.
  • Leases and heartbeats, so a crashed worker's job is picked up again.
  • Backpressure, so a flood of submissions does not grow the queue for ever.
  • Priorities and fairness, so short or urgent jobs are not stuck behind huge ones.
  • Progress reporting, so users see more than a spinner.

The pattern is also easy to overuse. If a task finishes in a second or two, doing it synchronously is simpler and gives clearer backpressure.

Why It Exists#

Start with a page that shows a user's profile. The server runs one indexed query, formats the result and responds in under 100 ms. Now the product asks for a button that produces a PDF of the user's whole year of activity. That means querying several large tables, aggregating millions of rows, rendering charts and laying out a document, which takes about 45 seconds. Done synchronously, several things go wrong at once.

  • Timeouts cut the request off. Every hop between the browser and the code has a timeout. Many load balancers and proxies close idle or slow requests after 30 to 60 seconds. AWS's Application Load Balancer has a default idle timeout of 60 seconds, and Amazon API Gateway REST APIs have a default integration timeout of 29 seconds. Heroku's router ends requests that send no response within 30 seconds, and Cloudflare's proxy returns an error if the origin takes longer than about 100 seconds. A 45-second request works on a developer's laptop and fails in production.
  • The user sees nothing. Even when the request survives, the user stares at a spinner with no idea whether it is working. Many give up, refresh, and start a second copy of the work.
  • Retries multiply the work. Browsers, mobile networking libraries, proxies and API clients retry failed or timed-out requests. A request that times out at 30 seconds after doing 30 seconds of work is often retried and starts again, so the system does the same expensive work two or three times and never finishes.
  • Capacity is wasted holding connections. By Little's law, the number of requests in flight equals the arrival rate times the time each one takes. At 100 report requests per second and 45 seconds each, the web tier holds 4,500 concurrent requests, each with a thread or coroutine, a database connection and memory, all mostly waiting. A burst of report requests then starves the fast profile requests that share the same servers.
  • Failures are coupled. If the PDF renderer crashes or leaks memory, it takes the web server, and every other request on it, down too.
  • Scaling is coupled. Report rendering is CPU-heavy and video encoding may need GPUs, while web serving is mostly input and output. Running both on the same machines means you can scale neither well.

The report is not unusual. Video uploads need transcoding into several resolutions, which takes minutes. A profile photo upload needs resizing, cropping and thumbnails. Bulk operations, such as sending a newsletter to a hundred thousand users, importing a large file or re-indexing a catalogue, take minutes to hours. A social network's post must be written into the precomputed feeds of every follower, which for a popular account means millions of writes. None of these fit inside one HTTP request.

How It Works#

The architecture has five parts, and every system that uses the pattern has some version of each.

  1. The API server validates the request, checks permissions, and decides whether the job can be accepted at all, given quotas and queue depth.
  2. The job store, usually a database table, records each job durably: its ID, type, owner, parameters, state, attempt count, progress and the location of its result. It is the source of truth for "what is happening to my job?".
  3. The queue holds job IDs, or small messages, waiting for a worker. Its job is distribution: handing each job to one worker, redelivering it if the worker dies, and absorbing bursts.
  4. The worker pool pulls jobs, does the work, updates the job store and writes outputs, typically large ones to object storage. Workers scale separately from the API, on hardware suited to the work.
  5. The notification path tells the client what happened: polling a status endpoint, or a push.

The sections below go through each concern in turn. They cover the timeout problem, the async job contract, queues, workers and autoscaling, the state machine, failure handling, backpressure, priorities and mixed workloads, progress reporting, dependencies between jobs, and a worked example.

The synchronous-timeout problem, in depth#

It helps to see exactly where a slow synchronous request breaks, because the interviewer may push on it.

The chain of timeouts. A request passes through the client library, perhaps a CDN or edge proxy, the load balancer, a reverse proxy such as NGINX, an application server, and the database driver. Each has its own timeout, and the shortest one wins. If the client waits 120 seconds but the load balancer waits 60, the request fails at 60 seconds. Worse, the application may keep working on a request whose client has already gone, finishing a report nobody will receive.

Raising timeouts does not fix it. You can raise all of them to ten minutes, but then:

  • A mobile client switching from Wi-Fi to mobile data loses the connection, and the work is lost with it.
  • Deploys must wait up to ten minutes to drain each server, or kill requests in progress.
  • Every slow request holds resources for its full length, so capacity planning becomes capacity guessing.
  • There is still no progress feedback, and no way to resume.

When synchronous is right. The pattern is not "queue everything". If the work reliably takes well under a second or two, a synchronous request is better:

  • The client gets the answer, or the error, directly.
  • Backpressure is automatic. When the system is overloaded, requests slow down or fail, and callers back off. With a queue, overload shows up instead as a quietly growing backlog that nobody notices until jobs are hours late.
  • There are fewer moving parts: no job table, no status endpoint and no worker fleet.

A useful rule is to keep work synchronous if its 99th-percentile duration fits comfortably inside the shortest timeout on the path, with room to spare, and the user is willing to wait for it. Go asynchronous when either condition fails, or when the work must survive the client disconnecting.

The async job pattern#

The contract between client and server has three operations.

Submit. POST /reports with the parameters and an idempotency key, a client-generated unique ID for this request. The server responds within milliseconds:

HTTP/1.1 202 Accepted
Location: /jobs/j_7f3a91
Retry-After: 5
 
{ "jobId": "j_7f3a91", "status": "queued", "statusUrl": "/jobs/j_7f3a91" }

202 Accepted means "I have accepted your request for processing, but it is not done". The Location header points to the status resource, and Retry-After suggests when to poll. If the client submits again with the same idempotency key, because its first attempt timed out, the server returns the same job rather than creating a second one. See Idempotency.

Check status. GET /jobs/j_7f3a91 returns the state, progress, timestamps and, when finished, either the result or a link to it, often a short-lived pre-signed URL to object storage. Clients poll with a sensible interval, such as every 2 seconds at first and backing off to every 10 to 30 seconds for long jobs.

Receive a push instead. For a better experience, the server pushes status changes over SSE or a WebSocket while the user is on the page, sends a webhook to a server-side client, or sends an email or a mobile notification for jobs that take hours. Push is an optimisation. The status endpoint remains the source of truth, so a client that missed a push can always ask. See Pattern: Pushing Realtime Updates.

Enqueueing safely. There is a subtle gap between inserting the job row and putting the message on the queue. If the server crashes after the insert and before the enqueue, the job sits in "queued" for ever. If it enqueues first and then fails to insert, a worker receives a job that does not exist. There are three standard fixes:

  • The outbox pattern: insert the job row and an outbox row in one database transaction, and let a relay publish outbox rows to the queue. See Change Data Capture.
  • Use the database as the queue: workers claim rows from the job table itself, so there is only one write.
  • Sweep for orphans: a periodic sweeper re-enqueues jobs that have been "queued" for longer than expected.

Queues for jobs, in depth#

A job queue differs from an event stream. Each job should go to one worker. Jobs vary from milliseconds to hours, they are acknowledged individually, and a failed job is retried without blocking the others. That favours work queues over partitioned logs.

QueueHow jobs are claimedStrengthsWatch out for
Amazon SQSReceive hides the message for a visibility timeout; delete on success; reappears on timeoutFully managed, scales without limit, built-in DLQ via redrive policyStandard queues are at-least-once and not ordered; FIFO queues have lower throughput
RabbitMQPush to consumers with a prefetch limit; ack or nack per messagePriorities, routing, per-message TTL, dead-letter exchangesThroughput and queue length must be planned; quorum queues for durability
Redis lists or streams, with Sidekiq, BullMQ, Celery or ResqueAtomic move to a processing list, or consumer groups with pending listsVery fast, simple, good libraries with retries, schedules and dashboardsDurability depends on Redis persistence; memory bounds queue size
PostgreSQL or MySQL tableSELECT ... FOR UPDATE SKIP LOCKED claims a row; workers update itOne system to run; the job state and the queue are the same row; transactional enqueuePolling load, and vacuum pressure from churn, at very high rates
KafkaConsumer groups own partitions; offsets commit in orderHuge throughput, replayHead-of-line blocking: a slow job delays its whole partition; parallelism is capped by partitions
Workflow engines: Temporal, AWS Step FunctionsTasks are scheduled by the engine with retries and timersDurable multi-step state, timeouts, retries built inA larger system to learn and run; see Pattern: Multi-Step Processes

Visibility timeouts and leases are the core mechanism. When a worker takes a job, the queue does not delete it. It hides it for a lease period. If the worker acknowledges success before the lease expires, the job is deleted. If the worker crashes, the lease expires, and the job becomes visible again for another worker. Long jobs need a lease longer than their running time, or, better, a worker that extends the lease periodically, which is a heartbeat. SQS calls this ChangeMessageVisibility. Without extension, a job that runs longer than its lease is handed to a second worker while the first is still working, so the same work runs twice.

Why Kafka is an awkward job queue. Kafka assigns each partition to one consumer and tracks progress as a single offset per partition. A job that takes ten minutes blocks every job behind it in that partition, and a job that fails cannot be retried "later" without either blocking the partition or copying it to a retry topic. Kafka works well for uniform, short tasks at enormous volume, such as feed fan-out or indexing events, and as a durable buffer in front of a real job queue. Slack's engineering blog described doing exactly this. It placed Kafka in front of its Redis-based job queue so that bursts were absorbed durably in Kafka, while Redis kept handling job dispatch.

The database as a queue. For moderate volumes, up to perhaps thousands of jobs per second on good hardware, a jobs table with SKIP LOCKED is often the simplest correct design:

-- claim the next job; concurrent workers skip rows locked by others
UPDATE jobs SET state = 'running', worker = $1, lease_until = now() + interval '5 minutes',
               attempts = attempts + 1
WHERE id = (
  SELECT id FROM jobs
  WHERE state IN ('queued', 'retrying') AND run_after <= now()
  ORDER BY priority DESC, run_after
  FOR UPDATE SKIP LOCKED
  LIMIT 1)
RETURNING id, type, params, attempts;
 
-- reaper: jobs whose worker vanished become claimable again
UPDATE jobs SET state = 'retrying', run_after = now()
WHERE state = 'running' AND lease_until < now();

Libraries such as Oban for Elixir, good_job and Solid Queue for Rails, River for Go, and graphile-worker for Node.js use this approach on PostgreSQL. The job state and the queue are the same row, so they can never disagree, and enqueueing can share a transaction with the business write.

Worker pools and autoscaling#

Workers pull, they are not pushed. Each worker asks the queue for a job when it has capacity, so a busy worker never receives more than it can handle. This is the opposite of a load balancer pushing requests, and it gives natural flow control. A worker typically:

  1. Pulls a batch of up to its concurrency limit of jobs, which is the prefetch in RabbitMQ, the max messages in SQS, or the concurrency setting in Sidekiq or Celery.
  2. For each job, checks the job store. If the job is already finished or cancelled, it skips it. Otherwise it marks the job running.
  3. Does the work, heartbeating the lease and writing progress every few seconds.
  4. Writes the result, marks the job succeeded and acknowledges the message, in that order, so a crash between steps leads to a redelivery that finds the job already finished.
  5. On error, classifies the error, schedules a retry or fails the job, and acknowledges or releases the message.

Concurrency per worker depends on the work:

  • CPU-bound jobs, such as rendering or encoding, run about one job per core.
  • I/O-bound jobs, such as calling APIs or sending emails, can run tens or hundreds concurrently per process with async I/O.
  • Memory-heavy jobs, such as large imports, are limited by memory, not cores.

Mixing these types in one pool wastes capacity, which is one reason for separate pools.

Sizing with Little's law. The number of busy workers needed equals the job arrival rate times the average job duration. At 20 report jobs per second averaging 45 seconds, you need 20 × 45 = 900 concurrent job slots. Run them at about 70 to 80% utilisation to absorb variance, which means roughly 1,150 to 1,300 slots. At one job per core that is about 40 machines with 32 cores. If arrivals exceed capacity, the queue grows without bound at the difference. At 25 jobs per second against capacity for 20, the backlog grows by 5 jobs per second, which is 18,000 jobs an hour.

What to autoscale on. CPU is a poor signal for job workers, because a pool can sit at 100% CPU while keeping up perfectly. Better signals:

  • Queue depth per worker: scale out when there are more than N waiting jobs per worker. SQS exposes ApproximateNumberOfMessagesVisible, and KEDA on Kubernetes scales deployments on queue length for SQS, RabbitMQ, Redis, Kafka lag and many other sources.
  • Age of the oldest job: the clearest user-facing signal. If jobs must start within 60 seconds, scale out when the oldest waiting job is 30 seconds old.
  • Predicted demand: scale ahead of known peaks, such as a nightly batch, month-end reports or a product launch.

Autoscaling has lag. A new machine or container takes from tens of seconds to several minutes to start, pull its image and warm up, and GPU nodes are often slower. During that time the backlog grows. Keep a warm minimum, scale out aggressively and in slowly, and use scale-to-zero only for workloads that can tolerate a cold start. Spot or preemptible instances are attractive for workers, at large discounts, because the pattern already tolerates a worker vanishing. The lease expires, and another worker picks the job up. Long jobs on spot capacity should checkpoint, so a preempted job resumes rather than restarts.

Graceful shutdown. When a worker is stopped for a deploy, a scale-in or a spot interruption, it should stop taking new jobs, finish or checkpoint the jobs in progress within a deadline, and release the rest back to the queue. Kubernetes sends SIGTERM and waits for the termination grace period, 30 seconds by default, so jobs longer than that need checkpoints or a longer grace period.

The job state machine#

Every job moves through a small, explicit set of states, and the transitions are guarded so that two workers cannot both move a job forward. A worker that dies mid-job is treated like a retryable error: when its lease expires, the reaper moves the job to Retrying, and after the backoff it returns to Queued for another worker to claim.

Guarded transitions. Each update is a conditional write, such as UPDATE jobs SET state = 'succeeded' WHERE id = $1 AND state = 'running' AND lease_owner = $2. If the row has changed, because the lease expired and another worker took over, the update affects zero rows, and the old worker knows its result is stale. This is optimistic concurrency on the job row. See Concurrency Control and Locking.

Terminal states are final. Succeeded, Failed and Cancelled never change, except by an explicit operator action that creates a new attempt. Clients and dashboards can then cache them.

What a job record holds. A practical schema has these fields:

  • id, type, owner or tenant, and params or a pointer to them.
  • state, priority, attempts and max_attempts.
  • run_after, for delayed retries and scheduled jobs.
  • lease_owner and lease_until.
  • progress as a percentage, plus a stage such as "rendering charts".
  • result_location or error.
  • created_at, started_at and finished_at.
  • idempotency_key, with a unique index.

Keep job records for a retention period, such as 30 days, then archive or delete them. The table otherwise grows for ever.

Cancellation is cooperative. A worker in the middle of encoding a video cannot be stopped from outside safely. The API marks the job Cancelling, and the worker checks for this at each checkpoint, cleans up partial outputs and moves the job to Cancelled. Jobs still waiting in the queue are skipped when a worker sees they were cancelled.

Timeouts on jobs, not just requests. Every job type needs a maximum running time. A worker that exceeds it is presumed stuck, in an infinite loop or a hung network call, and the job is failed or retried. Without one, a stuck job holds a worker slot, and its lease keeps being renewed for ever.

Handling failures: retries, idempotency and dead letters#

Failures in a job system come in three kinds, and each needs a different answer.

1. The worker dies. A crash, an out-of-memory kill, a deploy or a spot preemption stops a worker mid-job. The lease handles this. The worker stops heartbeating, the lease expires after, say, 2 minutes, and the job becomes claimable again. The cost is a delay of one lease period plus a repeat of the lost work, so long jobs should checkpoint, recording "pages 1 to 400 rendered" or "segments 1 to 30 encoded", and resume from the checkpoint.

2. The job hits a transient error. A downstream API returns 503, a database deadlock occurs, or the network times out. Retry with exponential backoff and jitter: wait about 10 s, then 30 s, 90 s, 5 minutes and so on, each with a random factor, up to a maximum number of attempts. Spreading retries out prevents a failing dependency from being hammered by every job at once just as it tries to recover. Respect Retry-After headers from rate-limited APIs.

3. The job can never succeed. The input is malformed, a referenced object was deleted, or a bug crashes the worker on this specific input. Retrying such a poison message for ever wastes capacity and, if it crashes workers, can take the whole pool down, as each worker in turn picks it up and dies. The answer is to:

  • Classify errors. Validation errors, 4xx responses and "not found" are permanent, so fail the job immediately with a clear error. Timeouts and 5xx responses are transient, so retry them.
  • Cap attempts. After, say, 5 attempts, move the job to a dead-letter queue (DLQ): a separate queue, or a dead_lettered state, that nothing processes automatically.
  • Alert on the DLQ. A rising DLQ count is a signal that something is broken. Operators inspect the jobs, fix the bug or data, and redrive them back to the main queue. SQS has a built-in redrive policy and DLQ redrive, and RabbitMQ has dead-letter exchanges.

Idempotency, the price of at-least-once. Every practical queue is at-least-once. A worker may finish a job and crash before acknowledging it. A lease may expire while a slow worker is still working. A network blip may duplicate a message. So every job may run more than once, and the design must make that harmless:

  • Deduplicate submissions with the idempotency key on the job row, through a unique index, so client retries do not create new jobs.
  • Check before working: a worker that receives a job already in Succeeded acknowledges it and does nothing.
  • Make outputs idempotent: write results to a deterministic location, such as reports/<job_id>.pdf, so a second run overwrites the same object rather than creating another. Use upserts rather than inserts.
  • Make side effects idempotent: when a job charges a card, sends an email or calls a partner, pass an idempotency key derived from the job ID, such as job_id + step, to the downstream service. Payment providers such as Stripe accept idempotency keys for this. For email, record "sent" in the job store before acknowledging, and check it before sending.
  • Fence stale workers: a worker whose lease expired must not overwrite the result of the worker that took over. Each claim increments a lease version, or fencing token, and the final write is conditional on the version still matching. See Distributed Locking.

Together these give exactly-once effect on top of at-least-once delivery. Truly exactly-once execution is impossible, because a worker can always crash after doing the work and before recording it. See Delivery Semantics.

Managing queue backpressure#

A queue absorbs bursts, but it also hides overload. If submissions arrive faster than workers can process them for long enough, the queue grows. Jobs wait for hours, users resubmit, which adds more jobs, and the backlog may never drain. Synchronous systems complain loudly when overloaded, but an async system must be designed to push back.

  • Measure the right things: the age of the oldest job and the time from submission to start, by job type, not just queue length. A queue of 10,000 short jobs may be fine, while a queue of 50 four-hour jobs is not.
  • Bound the queue. Set a maximum backlog, per job type and per tenant. When it is exceeded, reject new submissions with 429 Too Many Requests or 503 Service Unavailable and a Retry-After, rather than accepting work you cannot finish in time. Rejecting early is kinder than accepting work and failing it hours later.
  • Admission control per tenant. One customer importing 10 million rows should not delay every other customer's jobs. Give each tenant a quota of queued and running jobs, and queue or reject beyond it. See Rate Limiting.
  • Expire stale jobs. Some jobs lose their value with time. A "preview thumbnail" for an upload the user abandoned an hour ago is worthless. Give such jobs a deadline, and drop them if they have not started by then.
  • Shed low-value work first. Under sustained overload, pause analytics recomputation or re-indexing, and keep user-facing exports running.
  • Protect downstream systems. Scaling workers out without limit can overwhelm the database or third-party APIs they call. Cap total concurrency per dependency, with a semaphore or token bucket shared across the pool, so autoscaling cannot turn into a self-inflicted denial of service.

Priorities and mixed workloads#

Real systems mix very different jobs: password-reset emails that must go out in seconds, report exports that take a minute, nightly re-indexing that takes hours, and bulk imports of any size. Put them all in one first-in, first-out queue, and a burst of bulk jobs makes the password reset wait behind them. This is head-of-line blocking.

Separate queues and pools by class. The simplest and most robust fix is a queue, and usually a worker pool, per class of work, such as "critical", "default" and "bulk", or per job type. Each pool scales on its own signals and can run on suitable hardware, such as GPU nodes for encoding or high-memory nodes for imports. A failure or a backlog in one class does not touch the others.

Priority within a pool. When one pool serves several classes, workers can choose by priority:

  • Strict priority: always take from the highest non-empty queue. This is simple, but it can starve low-priority work for ever under sustained load.
  • Weighted selection: check queues in proportion to weights, for example critical 6, default 3, bulk 1. Sidekiq supports weighted queues like this. Every class makes progress, and higher classes get more of it.
  • Aging: raise a job's effective priority the longer it waits, so nothing waits for ever.
  • Reserved capacity: keep a few workers that only take critical jobs, so a sudden flood of bulk work can never occupy every slot.

Fairness between tenants. Priorities by class do not stop one large customer from filling the "default" queue. Fair schemes give each tenant its own logical queue and serve them round-robin or by weight, so a tenant with 100,000 jobs and a tenant with 3 both make progress. Techniques from network scheduling, such as weighted fair queueing and deficit round robin, apply directly. They are discussed in a deep dive below.

Split big jobs into small ones. Work per job varies wildly. In a news feed, a post by a user with 200 followers means 200 feed writes, while a post by a user with 50 million followers means 50 million. If each post is one job, the celebrity's job occupies one worker for hours, and it is lost or repeated as a whole if that worker dies. The fix is to fan the big job out into chunks. A coordinator job reads the follower list in pages and enqueues one job per 1,000 or 10,000 followers. Chunks run in parallel across the pool, retry independently, and give accurate progress: "3,412 of 5,000 chunks done". The same applies to imports, split by row ranges, to video, split into segments, and to crawls, split by domain or URL batch.

Sometimes the best job is no job. The news-feed reference takes this further. For accounts with a huge number of followers, the system does not fan out on write at all. Followers' feeds are built by merging in those accounts' recent posts at read time, and a flag on the follow relationship marks which follows are not precomputed. The async workers then only fan out for ordinary accounts. Choosing per account between fan-out on write and fan-out on read is a general lesson: rather than one rule for every item, handle the expensive tail differently. See Pattern: Scaling Reads and the news feed case study.

Progress reporting#

Users tolerate waiting much better when they can see that something is happening. Progress reporting has four parts.

What to report. Report a stage, such as "Fetching data", "Rendering charts" or "Uploading", and, where it can be estimated, a fraction of the work done. For chunked jobs, the fraction is completed chunks divided by total chunks. For single long jobs, the worker estimates from its own loop, such as rows processed out of rows total, or seconds encoded out of video length. An ETA can be computed from elapsed time and the fraction. Show it only when the rate is steady, because ETAs that jump around destroy trust.

Where to store it. Write progress to the job record, or to a fast store such as Redis keyed by job ID, throttled to about once per second or every 1%. Writing on every loop iteration turns progress reporting into the main load on the database. For chunked jobs, keep a counter of completed chunks, incremented atomically by each chunk, rather than having a coordinator poll each chunk.

How to deliver it.

  • Polling GET /jobs/:id every 1 to 5 seconds while the page is open is simple and robust, and the response is cheap to serve from Redis.
  • SSE or a WebSocket pushes progress events as they happen, with the job ID as the channel. The worker publishes to the job's channel, and the gateway delivers it to the watching browser.
  • Webhooks notify a customer's server on completion, signed and retried, with the job ID for deduplication.
  • Email or a mobile notification suits jobs that take minutes to hours, sent once at completion with a link to the result.

Streaming partial results. Some jobs can deliver output as they go, rather than only at the end. LLM responses stream tokens over SSE. Search crawls can show the first results, and builds stream their logs. The job is still a job, with an ID, a state and a result, but the client sees useful output from the first second. See the ChatGPT case study.

Orchestrating job dependencies#

Many real tasks are not one job but a graph of them. A video upload must be validated, then transcoded into five resolutions in parallel, then have its thumbnails and captions generated, and only when all are done can it be published. There are three ways to coordinate such steps.

  • Chaining: each job enqueues the next on success. This is simple for linear flows, but the overall state is spread across jobs, and "what stage is this upload in?" needs a query across several records.
  • Fan-out and fan-in with a counter: a parent job records "5 children pending" and enqueues the children. Each child decrements the counter atomically on success, and the child that brings it to zero enqueues the next stage. This needs care with retries, because a retried child must not decrement twice, so record completion per child ID.
  • A workflow engine: Temporal, AWS Step Functions, Apache Airflow for scheduled data pipelines, or Netflix's Conductor. You declare the steps, and the engine handles state, retries per step, timeouts, waiting for signals, and compensation on failure. This is the right tool once a process has more than a few steps, human approval steps or long waits. See Pattern: Multi-Step Processes.

A related need is scheduled and recurring jobs, such as "run this report every Monday at 9:00" or "retry this payment in 3 days". These need a durable scheduler that enqueues jobs when they come due, survives restarts without skipping or doubling runs, and spreads large numbers of jobs due at the same instant. That is the subject of the job scheduler case study.

Worked example: video processing for an upload site#

The problem. Users upload videos averaging 200 MB and 8 minutes long, at a peak of 30 uploads per second. Each video must be transcoded into 5 resolutions, from 240p to 1080p, with thumbnails and an automatic caption track. Users should see progress, and videos should be watchable within a few minutes of upload. There is also a paid tier whose videos must be processed first.

Step 1: the upload and the acknowledgement. The client uploads directly to object storage using a pre-signed URL, so the API never carries video bytes. When the upload completes, the client calls POST /videos/:id/process with an idempotency key. The API inserts a video_jobs row in state queued, together with an outbox row in the same transaction, and returns 202 with the job ID. The relay publishes the outbox row to the queue. See Pattern: Handling Large Blobs.

Step 2: split the work. A coordinator worker probes the file, then splits the video into 10-second segments, 48 per video on average, and enqueues one job per segment and resolution: 48 × 5 = 240 small transcoding jobs per video. Thumbnails and captions are separate jobs on separate queues. The coordinator records pending = 240 in the job row.

Step 3: size the pools. Peak demand is 30 videos per second × 240 = 7,200 segment jobs per second. If each segment takes about 4 CPU-seconds on average across resolutions, that is 7,200 × 4 = 28,800 busy cores. At 75% target utilisation, that is about 38,000 cores, roughly 600 machines of 64 cores at peak. That is a lot of hardware, which is why real platforms lean on hardware encoders. Google, for example, has described custom video transcoding chips for YouTube. The point for the design is that the pool autoscales on age of the oldest segment job, with a target of starting within 20 seconds. It runs mostly on spot capacity, and a lost segment costs only 4 seconds of work.

Step 4: priorities. Paid-tier videos go to a "priority" queue served with weight 4 against "standard" weight 1, and a small reserved pool takes only priority jobs. Bulk re-encoding of the back catalogue, done when a new codec is adopted, runs on a "bulk" queue that gets only spare capacity and pauses when the oldest standard job exceeds 60 seconds.

Step 5: failures. Segment jobs retry up to 3 times with backoff. A segment that fails three times is dead-lettered, and the video moves to failed with a reason, such as "corrupt input at 02:10", which is shown to the user. Worker crashes are handled by 2-minute leases that are extended every 30 seconds. Outputs go to deterministic keys such as videos/<id>/720p/seg_0031.ts, so a repeated segment simply overwrites itself.

Step 6: fan-in and progress. Each segment job, on success, records its completion in a video_segments table keyed by (video, resolution, segment), and atomically decrements pending only if that row was new. Retries therefore cannot double-count. Progress is 1 - pending / 240, pushed to the uploader's browser over SSE every second. When pending reaches zero, the last segment job enqueues a "package and publish" job, which writes the streaming manifests, marks the video ready, and sends a notification.

Result. The upload API answers in milliseconds. A typical video becomes watchable in about 1 to 3 minutes, set mostly by queue wait and the longest segment rather than by total CPU time. A spot-instance reclaim, a corrupt file or a burst of uploads degrades only the affected jobs, and never the upload API.

When to Use It#

  • The work takes longer than a few seconds, or its 99th percentile comes close to any timeout on the request path: media processing, report generation, exports and imports, bulk email, and machine learning inference on large inputs.
  • The work must survive the client going away: the user closes the tab, the phone loses signal, or the caller's request times out.
  • The work needs different hardware or scaling from the web tier: GPUs, high memory, or a large CPU fleet on spot capacity.
  • The load is bursty and the work can wait: a queue lets you size for the average plus a backlog rather than for the peak.
  • One request triggers a lot of downstream work, such as fan-out to followers, webhooks to many subscribers, or re-indexing.
  • Untrusted or risky work must be isolated, such as running user code in a code judge, so it cannot take down the API.
  • In interviews: whenever you see "upload and process", "generate", "export", "import", "send to all", "encode", "crawl" or "run the user's code".

When NOT to Use It#

  • The work is fast. If it reliably completes in well under a second or two, do it synchronously. You keep direct errors, simple code and automatic backpressure.
  • The user cannot proceed without the answer and it can be computed quickly, as with checkout validation, login or a search query. Making these async only adds a polling loop.
  • Strong ordering across all jobs is required. Parallel workers reorder work. If everything must be processed strictly in order, a queue with many workers is the wrong shape. Use a single-writer log per key instead.
  • The process has many steps, long waits and compensation. A pile of hand-chained jobs becomes unmaintainable. Use a workflow engine.
  • Nobody will watch the queue. An async system without metrics on backlog age, failure rates and the DLQ fails silently. If you cannot operate it, keep the work synchronous or use a managed service.

How to Implement It#

  1. Define the job contract: job types, parameters, the result format and location, the maximum running time, and whether the job is safe to run twice. If it is not, make it so.
  2. Create the job store: a table with state, attempts, lease, progress, result and a unique idempotency key.
  3. Implement submit: validate, enforce quotas and backlog limits, insert the job with an outbox row or claim it from the same table, and return 202 with the job ID and status URL.
  4. Choose the queue: a database table with SKIP LOCKED for moderate volume, SQS or RabbitMQ for managed scale, Redis-based libraries for speed and convenience, and a workflow engine for multi-step processes.
  5. Write the worker loop: claim with a lease, check the state, heartbeat, checkpoint, write idempotent output, make a guarded state update, then acknowledge.
  6. Classify errors and set retries: permanent errors fail immediately, and transient errors back off with jitter, up to a cap, then go to the DLQ with an alert.
  7. Separate queues by class, with weighted or reserved capacity for priorities, and per-tenant fairness.
  8. Autoscale on backlog age and depth, with a warm minimum, caps on concurrency per dependency, and graceful shutdown.
  9. Expose status: a status endpoint, plus push over SSE or webhooks, and notifications for long jobs.
  10. Operate it: dashboards for submit rate, backlog age by type, success and failure rates, attempts per job, DLQ size and job duration percentiles. Add runbooks for redrive.

A worker loop in TypeScript, showing the lease, the guarded completion, error classification and the dead letter:

async function workLoop(workerId: string) {
  while (!shuttingDown) {
    const job = await jobs.claim(workerId, { leaseMs: 120_000 });   // SKIP LOCKED or queue receive
    if (!job) { await sleep(500 + Math.random() * 500); continue; }
    const beat = setInterval(() => jobs.extendLease(job.id, job.leaseVersion, 120_000), 30_000);
    try {
      const out = await handlers[job.type](job.params, {
        progress: throttle((p: number, stage: string) => jobs.progress(job.id, p, stage), 1000),
        checkpoint: (c: unknown) => jobs.checkpoint(job.id, job.leaseVersion, c),
        cancelled: () => jobs.isCancelling(job.id),
      });
      const ok = await jobs.complete(job.id, job.leaseVersion, out);  // WHERE lease_version = $v
      if (!ok) log.warn("lost lease, result discarded", job.id);      // a newer attempt owns it
    } catch (err) {
      if (isPermanent(err)) {
        await jobs.fail(job.id, job.leaseVersion, String(err));
      } else if (job.attempts >= job.maxAttempts) {
        await jobs.deadLetter(job.id, job.leaseVersion, String(err));
        metrics.increment("jobs.dead_lettered", { type: job.type });
      } else {
        const delay = Math.min(3_600_000, 10_000 * 3 ** (job.attempts - 1));
        await jobs.retryAt(job.id, job.leaseVersion, Date.now() + delay * (0.5 + Math.random()));
      }
    } finally {
      clearInterval(beat);
    }
  }
}

The leaseVersion is the fencing token. Every claim increments it, and every write by the worker includes it, so a worker that lost its lease, through a long garbage-collection pause or a network partition, cannot overwrite the result of the attempt that replaced it.

TechnologyFits when
PostgreSQL with SKIP LOCKED: Oban, good_job, Solid Queue, River, graphile-workerModerate volume; you want the job state and queue in one transactional store
Sidekiq, BullMQ, Celery, RQ, Resque on RedisFast, simple job processing with retries, schedules and dashboards in Ruby, Node.js or Python
Amazon SQS with Lambda, ECS or EKS workersManaged, effectively unlimited queueing, with visibility timeouts and DLQs
RabbitMQPriorities, routing, per-message TTLs and dead-letter exchanges on your own infrastructure
Google Cloud Tasks, Azure Queue Storage or Service BusManaged task queues on other clouds, with rate limits and scheduled delivery
Kafka in front of workersUniform, high-volume tasks, or a durable buffer ahead of a job queue
Temporal, AWS Step Functions, Netflix ConductorMulti-step workflows with retries per step, timers, signals and compensation
Apache Airflow, Dagster, Argo WorkflowsScheduled data pipelines and DAGs of batch jobs
KEDA on KubernetesAutoscaling workers on queue length or age for many queue types
Kubernetes Jobs, AWS BatchLarge containerised batch jobs and array jobs with retries

Trade-offs#

OptionProsConsPick when
Synchronous processingSimplest; direct errors; natural backpressureTimeouts; held resources; coupled failures and scalingWork reliably takes under a second or two
Async job with pollingSimple client; robust; cacheable statusPoll load; latency up to the intervalMost jobs; a default
Async job with pushInstant updates; no poll loadA realtime tier, or webhook delivery, to runUsers watch the job; partners need callbacks
Database as queueOne store; transactional enqueue; easy inspectionPolling and vacuum load at high ratesUp to thousands of jobs per second
Dedicated queue (SQS, RabbitMQ, Redis)Scale, leases and DLQs built inTwo stores to keep consistent; needs an outboxHigh volume or bursty load
Kafka as job queueHuge throughput; replayHead-of-line blocking; awkward retriesUniform short tasks at massive volume
Workflow engineDurable multi-step state; retries, timers, compensationNew system; learning curve; deterministic code rulesMulti-step, long-running or human-in-the-loop processes
One pool for everythingEfficient packing; simpleHead-of-line blocking; noisy neighboursSmall systems with similar jobs
Pools per class or typeIsolation; right-sized hardware; independent scalingMore pools to manage; idle capacityMixed workloads with different deadlines

Common Pitfalls#

  • Queueing work that should be synchronous, adding latency and hiding overload for jobs that take 50 ms.
  • No idempotency, so redelivered jobs send two emails, charge twice or create duplicate rows.
  • Leases shorter than the job, without heartbeats, so long jobs are handed to a second worker while still running.
  • No fencing, so a stale worker overwrites a newer attempt's result.
  • Retrying everything, including permanent errors, and retrying without backoff or jitter, which hammers a failing dependency.
  • No dead-letter queue, so a poison message crash-loops the whole pool. Or a DLQ that nobody alerts on.
  • Writing the job row and the queue message separately, with no outbox or sweeper, so jobs are orphaned.
  • Autoscaling on CPU rather than backlog age, and scaling workers without a cap on the dependencies they call.
  • One FIFO queue for jobs of very different sizes and urgency, so password resets wait behind bulk imports.
  • Single huge jobs, such as fan-out to millions of followers in one job, that cannot be retried, parallelised or tracked.
  • Writing progress on every iteration, so progress updates become the database's main load.
  • No maximum running time and no cancellation, so stuck jobs hold workers for ever.
  • Keeping job records for ever, until the job table is the largest table in the database.

Real-World Examples#

  • GitHub created Resque, a Redis-backed job queue for Ruby, in 2009, to run its background work, and it inspired a generation of similar libraries such as Sidekiq.
  • Slack has described its job queue, which handles work such as message fan-out, notifications and unfurling links, and how it placed Kafka in front of the Redis-based queue to absorb bursts durably.
  • Uber built Cadence, a workflow engine for long-running, multi-step processes. Its creators later founded Temporal, which is based on the same model.
  • Meta has described FOQS, the Facebook Ordered Queueing Service, a distributed priority queue built on sharded MySQL that supports priorities, delayed delivery and leases for asynchronous work across the company.
  • Netflix has described Cosmos, a media-processing platform that combines workflows and serverless-style functions for encoding and other media tasks, and open-sourced Conductor, a workflow orchestrator.
  • YouTube transcodes every upload into many formats and resolutions in the background, and Google has described custom video-transcoding chips to make it cheaper.
  • Code-judging sites such as LeetCode queue each submission and run it in an isolated sandbox worker, returning results by polling or push.
  • AWS itself exposes the pattern in many APIs. Starting an Athena query, a Glacier retrieval or a Transcribe job returns an ID that you poll, or are notified about, rather than an immediate result.

Case studies that use this pattern#

  • Code Judge: submissions queued to sandboxed workers, with status by polling or push.
  • Job Scheduler: durable scheduling, leases, retries, priorities and at-least-once execution at scale.
  • Video Streaming: segmenting and transcoding uploads in parallel, with fan-in to publish.
  • News Feed: async fan-out workers, with a hybrid of fan-out on write and on read for huge accounts.
  • Web Crawler: URL frontier queues, politeness per domain, retries and dead letters.
  • Notification System: queued sends per channel, retries, priorities and idempotent delivery.
  • File Sync: background chunking, hashing and thumbnail generation.
  • ChatGPT: long inference jobs that stream partial output.
  • Payment System: asynchronous settlement and reconciliation jobs with idempotency keys.

In the Interview#

Deep Dive: Queueing theory for worker poolsShow

A worker pool is a textbook multi-server queue, and a little theory explains behaviour that surprises teams in production.

Little's law, the one formula to remember. For any stable system, the average number of jobs in the system, L, equals the arrival rate λ times the average time each job spends in it, W. So L = λW. It needs no assumptions about distributions. Three uses follow:

  • Workers needed: busy workers = λ × service time. At λ = 50 jobs per second and 12 seconds of work each, 600 workers are busy on average.
  • Backlog to wait time: if 30,000 jobs are waiting and the pool completes 500 per second, a new job waits about 60 seconds.
  • Checking dashboards: if the dashboard shows 1,000 jobs in progress and 100 completions per second, jobs take about 10 seconds. If the measured duration differs, something is being counted wrongly.

Utilisation and the knee of the curve. Define utilisation ρ = λ × service time ÷ c, where c is the number of workers. Queueing theory shows that waiting time stays small while ρ is moderate, and then rises steeply as ρ approaches 1. For a single server with random arrivals and service times, the M/M/1 queue, the average wait is proportional to ρ / (1 − ρ):

  • At 50% utilisation the factor is 1.
  • At 80% it is 4.
  • At 90% it is 9.
  • At 95% it is 19.

Pools with many workers do much better at the same utilisation, because an idle worker is more likely to be available, which is why big pools can safely run hotter than small ones. But the same steep curve appears near 100% for any size of pool. This is why the practical targets are 70 to 85%, not 100%. The last 15% of utilisation buys a large increase in waiting time and makes the system fragile to bursts.

Variance matters as much as the mean. The Pollaczek–Khinchine formula for a single server with general service times says that the average wait grows with the square of the coefficient of variation of service time. A pool whose jobs take 1 second on average, but sometimes 10 minutes, behaves far worse than a pool where every job takes 1 second. That is the mathematical case for separating short and long jobs into different pools, and for splitting big jobs into uniform chunks. Both reduce variance, and so reduce waiting time, without adding a single worker.

Overload is not gradual. When λ × service time exceeds c, there is no steady state. The backlog grows linearly, at the difference between arrival and completion rates, for as long as the overload lasts, and it drains only when arrivals fall below capacity. A 10-minute burst at 120% of capacity leaves a backlog equal to 2 minutes of full capacity, which takes much longer than 2 minutes to drain if arrivals remain at 90% of capacity, because the spare capacity is only 10%: 20 minutes. Teams that size pools for average load are routinely surprised by this asymmetry. Fast growth during the burst is followed by a slow drain afterwards.

Autoscaling as a control loop. An autoscaler measures backlog, decides on a target size and waits for new workers to start. If start-up takes T seconds and the scaler reacts to a backlog that is already growing, the backlog keeps growing for at least T. Scaling on rate of change, or on predicted demand, helps. So does scaling out by a percentage rather than one worker at a time. Scaling in slowly, with a cooldown of several minutes, prevents oscillation, where the pool repeatedly shrinks just before the next burst.

Deep Dive: Leases, zombies and exactly-once effectsShow

The hardest correctness problem in job systems is a worker that thinks it still owns a job when it does not. That is a zombie.

How zombies arise. Worker A claims job J with a 2-minute lease. A then stalls. It might be a 3-minute garbage-collection pause, a host frozen for live migration, a network partition from the queue, or a blocked disk. The lease expires, and worker B claims J and starts again. A wakes up, unaware of any of this, and finishes. Now two workers have done the work, and both try to record the result. If outputs are overwrites of the same deterministic object, this is harmless. If the job sends an email, posts to a ledger or increments a counter, it is a duplicate.

Heartbeats reduce the window but cannot close it. A heartbeat every 30 seconds extends the lease, so a healthy slow job keeps it. But a worker cannot know that its last heartbeat arrived. Clocks on the worker and the queue can disagree, and a pause can strike between checking "do I still own this?" and doing the write. Checking the lease before writing is therefore never enough on its own. The same reasoning appears in Martin Kleppmann's analysis of distributed locks, which argues for fencing tokens rather than trust in timing. See Distributed Locking.

Fencing tokens close it. Each claim increments a monotonically increasing lease version, and every write that matters carries it:

  • The job store accepts complete(J, version 7) only if J's current version is 7. B's claim made it 8, so A's late completion is rejected.
  • Downstream systems that support it check the token as well. A storage write is conditional on the token, and an outbound API call carries idempotency_key = J:step:attempt-independent-id, so a second call is recognised and returns the first result.

The idempotency key for a side effect must not include the attempt number. "Charge for job J" must be the same key on every attempt, or the downstream service cannot recognise a duplicate.

Exactly-once effect, constructed. Put together:

  1. At-least-once execution, from leases and redelivery.
  2. Idempotent or fenced writes for every effect, using deterministic keys, conditional writes and idempotency keys downstream.
  3. Recording completion before acknowledging, so a crash between them causes a harmless redelivery rather than a lost result.

That is all that is achievable, and it is enough. The impossibility of exactly-once execution follows from the classic argument. A worker that crashes after doing the work and before recording it is indistinguishable, to everyone else, from one that crashed before doing the work. So someone must either retry, risking a duplicate, or not retry, risking a loss. Idempotency makes the retry safe.

Effects that cannot be made idempotent. Some actions have no idempotency support, such as a legacy partner API, an SMS gateway without keys, or a physical action like dispensing an item. For these, use a two-phase record. Write "about to send X" with a unique ID before acting, and "sent X" afterwards. On redelivery, if "about to send" exists without "sent", the outcome is uncertain. The job must then query the downstream system, if it can, or escalate to a human or a reconciliation process, rather than guess. Payment systems live with exactly this, which is why they reconcile against the provider's records every day.

Deep Dive: Fair scheduling, priorities and noisy neighboursShow

Choosing which job to run next is a scheduling problem studied for decades in operating systems and networks, and the classic results transfer directly to job queues.

Strict priority starves. If workers always take the highest-priority job available, a sustained stream of high-priority work means low-priority jobs never run. Operating systems solved this with aging: a waiting job's effective priority rises with its wait time, so even the lowest class eventually runs. In a job table this is a sort key such as priority + wait_seconds / 60, so every minute of waiting is worth one priority level.

Weighted fair queueing. The landmark paper by Alan Demers, Srinivasan Keshav and Scott Shenker ("Analysis and Simulation of a Fair Queueing Algorithm", SIGCOMM 1989) shared a link fairly between flows by serving packets in order of their virtual finish time, as if each flow had its own share of the link. Applied to jobs, each tenant or class is a flow with a weight. When choosing the next job, pick the flow that has received the least service relative to its weight. A tenant with weight 2 gets about twice the worker time of a tenant with weight 1, whatever their backlogs, and an idle tenant's share is spread over the busy ones.

Deficit round robin. WFQ needs a sorted structure. Madhavan Shreedhar and George Varghese ("Efficient Fair Queueing Using Deficit Round Robin", SIGCOMM 1995) gave a constant-time approximation. Visit flows in round-robin order, give each a quantum of credit per visit, and let it run jobs while its accumulated credit covers their cost, carrying unused credit to the next round. With job cost measured in expected seconds, DRR shares worker time fairly even when one tenant's jobs are a hundred times longer than another's. Plain round robin over jobs would not.

Making it practical. In a real system:

  • Keep a logical queue per tenant, or per tenant and class: a Redis list per tenant, or a tenant_id column with an index.
  • Keep an active set of tenants with waiting jobs, and run DRR or weighted round robin over that set.
  • Cap concurrency per tenant, so that even with fair selection one tenant cannot occupy every worker with long jobs.
  • Reserve capacity for the critical class, so that fairness between tenants never delays a password reset.

Meta's FOQS is a public example of a shared queue built for priorities at scale. It orders items by priority and a deliver-after time within sharded MySQL tables, with leases that are acknowledged or released, and it serves many teams from one system.

Measuring fairness. Track backlog age and time-to-start per tenant and per class, not just in aggregate. An aggregate "p99 time-to-start of 30 seconds" can hide one tenant whose jobs all wait 20 minutes. The question to ask of any scheduler is: who is waiting longest, and why?

Key Takeaways#

  • Split slow work into two phases: validate, record a job, enqueue it and return 202 with a job ID in milliseconds, then process it in a separate worker pool.
  • Do not queue fast work. If a task reliably finishes in a second or two, synchronous is simpler and gives natural backpressure.
  • Status is a resource: poll GET /jobs/:id, or receive a push via SSE, WebSockets, webhooks or email. The job store, not the push, is the truth.
  • Make enqueueing atomic with the job record, through an outbox, a table-as-queue or a sweeper, so jobs are never orphaned.
  • Workers pull with leases, heartbeat to extend them, checkpoint long work, and shut down gracefully. Size pools with Little's law and autoscale on backlog age.
  • Give jobs an explicit state machine with guarded transitions, final terminal states, maximum run times and cooperative cancellation.
  • Assume at-least-once delivery: idempotency keys on submit, deterministic outputs, idempotent side effects and fencing tokens give exactly-once effect.
  • Retry transient errors with exponential backoff and jitter, fail permanent errors fast, and send exhausted jobs to a dead-letter queue with an alert and a redrive path.
  • Push back under overload: bounded queues, per-tenant quotas, deadlines for stale jobs and caps on concurrency per dependency.
  • Separate workloads by class, use weighted or aged priorities and fair scheduling between tenants, and split huge jobs into chunks, or avoid them, as hybrid feeds do for celebrity accounts.
  • Report progress as stages and fractions, throttled, and move to a workflow engine when jobs become multi-step processes.