← Building blocks

Move slow work off the request

Decoupling & async workfundamental

A request takes seconds because it does everything inline.

Say it like this

The upload request only needs to be durable, not finished, so the API writes a job row, returns 202 with a status URL, and a worker pool does the transcoding while the client polls or gets a push.

Basic solution

Return quickly (202 Accepted) and do the heavy part in a worker; expose status for the client to poll or push a notification when done.

CelerySidekiqBullMQTemporal

Accept now, finish later

The API writes the job and returns 202 in milliseconds. Workers pull jobs under a lease and update the status row, which the client polls or is pushed.

How it works

  1. The request handler validates the input and authorises the caller, then writes a job record to the database with status queued and a fresh job id. It also puts the job id (just the id, not the payload) onto a queue for workers to pick up.
  2. It returns 202 Accepted within a few milliseconds, carrying the job id and a status URL in the body or a Location header. The client now has a handle it can ask about later.
  3. A worker pool takes job ids from the queue. Each worker marks its job running and takes a lease on it (a timestamp until which this worker owns the job), does the slow work such as transcoding, and finally writes status done or failed plus a pointer to the output.
  4. The client finds out by polling GET /jobs/{id} with growing intervals, by subscribing over a WebSocket or server-sent events, or by receiving a push notification when the status changes. All three read or are driven by the same job row.
  5. If a worker dies mid-job, its lease expires and a sweeper or another worker reclaims the job and runs it again. That rerun is why every job must be safe to execute twice: write outputs under a key derived from the job id and skip steps whose output already exists.

What stays on the request

  • Only the parts the user needs an answer to right now: validation, authorisation, and the durable write that proves the request was accepted. Everything else becomes a job.

Worked example

Video upload on the streaming platform

  • 500K uploads/day ≈ 6/s average, 20/s at peak. Transcoding one 10-minute video takes ~5 minutes of CPU across all renditions.
  • Inline would hold an HTTP connection for 5 minutes and need 20 × 300 s = 6,000 concurrent requests at peak. Nobody does that.
  • With workers: the API call is a metadata insert and an enqueue, ~10 ms. Worker demand is 6 jobs/s × 300 s = 1,800 concurrent jobs average, so ~2,000 worker slots with headroom, scaled on queue depth.
  • Queue depth tells you the backlog in seconds: 5,000 queued jobs ÷ 6 completions/s ≈ 14 minutes of wait. That number drives autoscaling and the "ready in about N minutes" message.
  • Status polling at one request per 10 s per waiting upload is 500 req/s at peak, cheap because it is a single-row read, cheaper still with a push on completion.

Variants and when each wins

Poll a status endpoint

  • The client asks GET /jobs/{id} every few seconds with backoff until the status is terminal. It wins as the simplest option that works everywhere; it costs a little traffic and adds up to one polling interval to the moment the client learns the job is done.

Push on completion

  • The worker publishes a job-finished event, and a WebSocket, server-sent events stream or mobile push delivers it to the client instantly. It wins for anything a user is actively waiting on; it needs the real-time plumbing and a fallback poll for clients that missed the push.

Callback / webhook

  • The job calls a URL the client registered when it finishes. It wins for machine clients and third-party integrations, where nobody is polling; it needs request signing and retries.

Workflow engine

  • A durable workflow (Temporal, Step Functions) records each step of a multi-step job (probe, split, encode, package) and retries only the step that failed. It wins once a job has more than two or three steps, because a plain job row cannot express partial progress.

Default to a job table plus polling for the first version, add push for anything a user waits on, and move to a workflow engine once a job has more than two or three steps.

Failure modes

Lost job after a crash

  • A job stays queued or running forever. It happens because the worker took the message from the queue and then crashed, and nothing noticed that the job never finished. Use a visibility timeout or a lease that the worker renews with a heartbeat, plus a sweeper that requeues jobs whose lease has expired.

Duplicate execution

  • Two sets of renditions exist for one video, or an email is sent twice. It happens because the lease expired while the first worker was still working, so a second worker started the same job. Make the job idempotent: write results under a deterministic key derived from the job id, and check the job's status before any side effect.

Status the client never sees

  • The upload finished but the UI still says processing. It happens because the worker updated the job row but the push notification was lost, or the client had stopped polling. Combine push with a fallback poll, and keep a terminal state in the row that the client can always read back.

Backlog grows without bound

  • Wait time climbs from minutes to hours. It happens because producers are enqueuing faster than workers complete, and nobody is watching the queue. Alert on the age of the oldest job, autoscale workers on queue depth, and shed or defer low-priority jobs when the backlog is too long.

Hot job starves others

  • A four-hour video occupies a worker while a hundred short clips wait behind it. It happens because one first-in-first-out queue holds jobs of every size. Separate lanes by expected duration or priority, and split large jobs into chunks so no single job holds a worker for hours.

Interviewer follow-ups

Answer out loud before you open each one.

Why return 202 instead of holding the request open until the work is done?

An open connection ties up a server slot, a load balancer slot and the client for the whole job, and a network blip loses the result. 202 plus a status resource makes the work durable and lets both sides retry independently.

How does the client know when it is done?

Poll the status URL with exponential backoff, or subscribe for a push over WebSocket, SSE or mobile push. Keep the poll as a fallback: pushes get lost, and a client that reconnects just reads the status row.

What if the worker crashes halfway through?

The lease or visibility timeout expires and another worker reclaims the job. Because that reruns the job, every step must be idempotent: write outputs under a deterministic key and skip steps whose output already exists.

How do you size the worker pool?

Average arrival rate times average job duration gives concurrent jobs in steady state; add headroom for peaks and scale on queue depth or oldest-job age. For the video example that is 6/s × 300 s ≈ 1,800 slots.

Connections

Built on
DAG of tasks
Pairs with
Decouple producer from consumer · Make retries safe · Park poison messages · Keep urgent work ahead of bulk work · Process uploads in parallel · Push to the browser in real time
Pulls against
Never wait forever
Used in
Video Streaming Platform (YouTube / Netflix) · Notification System

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingAPI, Worker poolCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon AuroraJobs tableAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon SQSJob queuePub/Sub, Cloud TasksService Bus queues, Queue StorageRabbitMQ, ActiveMQ