Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 95/ 160
05. AI System Design

Async Job Pipelines

Queues and workers for long-running AI tasks with retries and progress tracking.

IntermediateQueues · Workers3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

You give the system a big task and get a ticket; it works on the task in the background and you check the ticket or get a message when it's done.

Think of it like…

A dry-cleaner's counter: you hand in the clothes and get a ticket (job id); the shop processes the queue at its own pace, you can check the status with the ticket, and they text you when it's ready.

Where you’ve seen it

A report generator makes five LLM calls and takes about 90 seconds, longer than the gateway's 30-second limit. POST /jobs returns 202 with job_id; the message goes to a queue; workers run five checkpointed steps (retrieve, outline, draft, review, format) writing each intermediate result to object storage so a retry resumes from the failed step. The client polls GET /jobs/{id} every 2 seconds and shows "step 3 of 5". At peak, 1,200 jobs an hour arrive (0.333 per second); by Little's law 0.333 × 90 s = 30 workers are busy on average, so with a 75% utilisation target the team runs 40 workers. Failed steps retry three times with exponential backoff and jitter; messages that still fail go to a dead-letter queue for inspection; because the queue delivers at least once and about 0.5% of messages are duplicates, every step is idempotent via an idempotency key, and the visibility timeout (5 minutes) is extended by a heartbeat while a step runs.

Words you’ll hear

Job id and status endpoint
A handle returned at submission that clients use to check progress and results.
Idempotency key
A unique key that makes repeated execution of a task produce a single effect.
Dead-letter queue
A holding queue for messages that fail repeatedly, for inspection and replay.
Visibility timeout / heartbeat
How long a claimed message stays hidden from others, extended while work continues.

Visual diagram

Loading interactive diagram

Theory & deep dive

Building blocks and delivery semantics

A typical stack uses an API service that validates the request, writes a job record (id, owner, input reference, status, timestamps) and enqueues a message; a queue (SQS, RabbitMQ, Redis streams, Kafka, Pub/Sub) with separate priority queues for interactive and bulk work; workers (Celery, Temporal, Step Functions, custom consumers) that claim messages; and storage for inputs and results (database for state, object store for large payloads). For multi-step workflows, orchestration engines such as Temporal or Step Functions provide durable state, retries and timers so you don't hand-write them.

Most queues offer at-least-once delivery: a message can be delivered twice (a worker crashes after finishing but before acknowledging, or the visibility timeout expires). So every step must be idempotent: derive an idempotency key from job id and step, check whether the step already has a stored result before running and write results with upserts. Set the visibility timeout longer than the longest expected step and extend it with a heartbeat for long work; otherwise another worker will pick up the same message mid-run. Use timeouts on every LLM and tool call, retries with exponential backoff and jitter for transient errors and a dead-letter queue after the retry limit so poison messages don't loop forever.

Capacity from Little's law

Arrival rate 1,200 jobs/hour = 0.333 jobs/s; duration 90 s; busy workers = 0.333 × 90 = 30. At a 75% target utilisation: 30 ÷ 0.75 = 40 workers. With only 30 workers the system runs at 100% utilisation and queues grow without bound at peak.

Key takeaway: Queue plus workers plus durable state, with idempotent steps, heartbeats, retries and a dead-letter queue.

Progress, concurrency control and user experience

Design the client contract: POST /jobs returns 202 with a job id and a status URL; GET /jobs/{id} returns status (queued, running, succeeded, failed, cancelled), progress (step name and fraction), partial results where meaningful and an error object on failure; a cancel endpoint stops the work and refunds nothing already spent. For fast feedback use SSE or WebSocket updates, or webhooks for system-to-system integration (sign them and retry with backoff). Show estimated time using recent medians per step, and make retries user-visible rather than silent.

Protect providers and budgets with concurrency control: a global or per-tenant semaphore on in-flight LLM calls, a token-bucket rate limiter matched to RPM and TPM quotas and backpressure (stop pulling messages when limits are hit). Use priority queues and per-tenant fairness so one customer's bulk upload doesn't starve others. Put checkpoints between steps (store the outline before drafting) so retries don't repeat expensive calls; cache LLM results by input hash for deterministic reuse. Monitor queue depth and age of oldest message, job duration percentiles, failure and retry rates by step, DLQ size, and cost per job. Test failure paths: kill workers mid-step, deliver duplicates, make the provider return 429 for a minute and confirm jobs complete exactly once in effect.

Retry with a checkpoint

Step 3 (draft) fails after step 2 (outline) stored its result. The retry loads the stored outline instead of calling the model again, so only the failed step's tokens are re-spent. Without checkpoints, one failure at step 5 would repeat all 90 seconds and five model calls.

Key takeaway: Give clients a clear status contract, bound concurrency, add fairness and test failure and duplicate delivery.

How it works, step by step

Step 1 of 4
API service

1. Accept and enqueue

Validate input, store a job record, enqueue a message and return 202 with a job id.

POST /jobs → 202 + job_id
Key numbers at this step
Respond
< 200 ms

When to use it & trade-offs

What it is

An async job pipeline handles long-running AI tasks (generating a report from many LLM calls, parsing and indexing a 300-page document, running an agent for minutes) outside the request-response cycle. The client submits a job and immediately gets 202 Accepted with a job id; a queue holds the work, a pool of workers executes it in steps with retries, timeouts and checkpoints, results go to durable storage and the client learns the outcome by polling, server-sent events or a webhook. Key properties are idempotency (safe to run twice), visibility into progress and bounded concurrency against provider rate limits.

Why it matters: HTTP gateways commonly time out after 30 to 60 seconds, browsers and mobile apps drop connections, and one failed LLM call shouldn't force a user to restart a 90-second job from scratch. Queues smooth traffic bursts, let you scale workers independently of the API, protect downstream providers with controlled concurrency and give users progress feedback instead of a spinner. Without them, long AI tasks fail in ways that are hard to retry and hard to observe.

When to reach for it

  • Document processing, report generation and long agent runs
  • Bulk uploads and scheduled AI workflows
  • Smoothing bursts against provider rate limits

When to avoid or be careful

  • Holding an HTTP request open for minutes
  • Non-idempotent steps with at-least-once delivery
  • Unlimited retries with no dead-letter queue

Request handling styles

Async job pipeline
Best for: Tasks longer than a request timeout or with many steps

Strengths: Resilient, scalable, observable, retryable.

Watch out: More moving parts; eventual results.

Synchronous request
Best for: Short tasks under a few seconds

Strengths: Simple; immediate result.

Watch out: Timeouts and lost work on failure.

Streaming response
Best for: Interactive answers where partial output helps

Strengths: Fast perceived latency.

Watch out: Connection-bound; no durability by itself.

Interview signals & numbers to know

When this topic comes up

  • “The request times out after 30 seconds”
  • “A failure at step 5 restarts everything”
  • Dead-letter queue
  • Visibility timeout
  • Idempotency key

Benchmarks & rules of thumb

0.333 × 90 = 30 -
average busy workers at 1,200 jobs/hour
40 -
workers at a 75% utilisation target
3 -
retry attempts before dead-lettering in the example

Common mistakes & follow-ups

Common interview mistakes

  • Setting the visibility timeout shorter than a step and processing it twice.
  • Retrying immediately without jitter during a provider outage.
  • Charging the user twice because a duplicate message re-ran a paid step.

Likely interviewer follow-ups

  • How would you design long-running report generation with LLMs?
  • How do you make queue consumers idempotent?
  • How do you size the worker pool?
Interview tip: Use Little's law for worker count and name idempotency keys and checkpoints. They show you've handled the failure modes, not just the happy path.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Async Job Pipelines with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Batch Inference
Next topic
Provider Rate Limits