Message Queues
Decouple producers and consumers for durable AI job processing.
In plain words
A queue is a waiting line for jobs. One part of the system adds jobs to the line, other parts take them one by one and mark them done, and nothing gets lost if a worker crashes.
Think of it like…
A post office sorting room. Senders drop parcels in a tray and leave; workers take one parcel at a time, stamp it when delivered, and if a worker disappears mid-delivery the parcel reappears in the tray after a while; a parcel that fails five times goes to a special shelf for a human to inspect.
Where you’ve seen it
A document-processing service receives 10 jobs a second on average; each job (parse, chunk, embed) takes about 6 seconds. Little's law says average work in progress is 10 × 6 = 60 jobs, so at least 60 workers are busy; to keep utilisation near 70% the pool needs about 60 / 0.7 ≈ 86 workers. After an upload burst the queue holds 3,600 messages. With 100 workers the capacity is 100 / 6 = 16.7 jobs a second against 10 arriving, so the backlog drains at 6.7 a second: 3,600 / 6.7 = 540 seconds, about 9 minutes; autoscaling on queue depth (target backlog per worker of 30 messages) adds workers as the line grows. The queue is configured with a visibility timeout of 90 seconds (the p99 job time is 35 seconds, with workers extending the lease every 30 seconds for the rare 3-minute document), maxReceiveCount = 5 before a message goes to the DLQ and long polling to reduce empty receives. Because delivery is at-least-once, the handler is idempotent: it keys writes by (document_id, chunk_index) with an upsert, so processing a message twice leaves the same result. Large payloads aren't stored in the message; the message carries the S3 key (a claim check), since broker message size limits are small (often a few hundred KB, check your broker). Ordering matters only per document, so the producer sets a message group or partition key of document_id, and the team accepts out-of-order processing across documents. The DLQ has an alarm on depth above zero and a runbook: inspect the poison message, fix the bug or the data, and redrive it back. Dashboards show queue depth, age of the oldest message (the number users feel), consumer errors and DLQ count.
Words you’ll hear
- Visibility timeout
- How long a received message stays hidden before it is redelivered if not acknowledged.
- Dead-letter queue
- A holding queue for messages that failed too many times.
- At-least-once delivery
- A guarantee that a message is delivered one or more times, so duplicates can occur.
- Claim check
- Storing a large payload elsewhere and putting only its reference in the message.
Visual diagram
Theory & deep dive
Delivery semantics, acknowledgements and retries
The broker stores each message until a consumer acknowledges it. When a consumer receives a message, the message becomes invisible for the visibility timeout; if the consumer acknowledges in time, the message is deleted, and if it crashes or is too slow, the message reappears and is delivered again. That is at-least-once delivery: duplicates are normal, so handlers must be idempotent (upserts keyed by a natural ID, a processed-messages table, or idempotency keys on downstream calls). Exactly-once processing is achieved by combining at-least-once delivery with idempotent handling, not by the broker alone.
Set the visibility timeout above the p99 processing time (35 seconds in the example, so 90 seconds) and let workers extend the lease with a heartbeat for long jobs; too short causes duplicate processing, too long delays recovery from crashes. Retry with backoff (a delayed re-enqueue or a visibility timeout that grows with the receive count) and a cap: after 5 receives the message moves to the DLQ so a poison message (bad data, a bug) doesn't block the line or burn money. Distinguish transient errors (rate limit, timeout: retry) from permanent errors (invalid document: send to the DLQ or a failure table immediately). Large payloads use a claim check: put the file in object storage and the reference in the message.
Job time p50 6 s, p99 35 s, rare outliers 3 min. Visibility timeout 90 s with a heartbeat every 30 s extending it by another 90 s. A worker that dies is detected within 90 s and its message redelivered; a healthy slow worker keeps its lease.
Scaling consumers, ordering and operating queues
Size consumers with Little's law: workers busy = arrival rate × service time. At 10 jobs a second and 6 seconds each, 60 workers are busy on average; at a 70% utilisation target you need about 86. When a burst leaves 3,600 messages queued and you run 100 workers (capacity 100 / 6 = 16.7 jobs a second against 10 arriving), the backlog drains at 6.7 a second, so 3,600 / 6.7 = 540 seconds. Autoscale workers on backlog per worker or on the age of the oldest message, and put a ceiling on concurrency so the queue doesn't turn into a way to overload a rate-limited provider.
Ordering: standard queues don't guarantee order; FIFO queues, message groups or partition keys (Kafka) preserve order within a key, which is usually all you need (per document or per conversation), at the cost of limiting parallelism per key. Choose the broker by need: SQS for managed simple queues, RabbitMQ for routing and priorities, Kafka for high-throughput logs and replay, Redis Streams for light workloads. Operate with dashboards for depth, oldest-message age, in-flight count, consumer errors and DLQ size; alarm when the DLQ is non-empty and when message age breaches the user-visible SLO; keep a redrive procedure; and apply per-tenant fairness so one customer's 5,000-job upload doesn't starve others (separate queues, weighted scheduling or per-tenant concurrency caps).
Backlog 3,600, arrivals 10/s, capacity 100 workers / 6 s = 16.7/s. Net drain 6.7/s → 3,600 / 6.7 ≈ 540 s ≈ 9 min. Doubling workers to 200 gives capacity 33.3/s, net 23.3/s and drain 155 s, about 2.6 minutes.
How it works, step by step
Step 1 of 41. Define messages and keys
Keep messages small (claim check for large payloads), version the schema and choose an ordering key.
- Include
- idempotency id
When to use it & trade-offs
What it is
A message queue decouples the code that produces work from the code that does it. Producers enqueue messages, the broker stores them durably, and consumers pull them, process them and acknowledge each one; an unacknowledged message becomes visible again after a visibility timeout and is redelivered, which gives at-least-once delivery. Messages that keep failing move to a dead-letter queue (DLQ) after a set number of attempts. Queues smooth bursts, let you scale consumers independently, absorb provider slowness and keep long LLM tasks, embeddings and evaluations off the request path. Products differ: SQS and RabbitMQ are classic queues, Kafka is a partitioned log that consumers read at their own offsets and Redis Streams offer a lighter option.
Why it matters: AI work is slow, bursty and failure-prone: a model call takes seconds, a provider rate-limits at the worst moment and an upload of 5,000 documents arrives at once. Without a queue the web tier holds connections, drops work on restarts and spreads load unpredictably. With one, you get durability, retries, back-pressure visibility (queue depth) and the ability to add workers when the backlog grows. The price is at-least-once semantics, so consumers must be idempotent, and new operational concerns such as poison messages and lag.
When to reach for it
- Document ingestion, chunking and embedding pipelines
- Batch evaluations and long agent runs
- Smoothing bursts before rate-limited provider calls
When to avoid or be careful
- Non-idempotent handlers behind at-least-once delivery
- Retrying poison messages forever
- Large payloads inside messages
Queue and log options
Strengths: Fully managed; DLQ and visibility built in.
Watch out: Limited routing; message size limits.
Strengths: Flexible exchanges; mature.
Watch out: You run and tune the cluster.
Strengths: Partitioned scale; retention; multiple consumers.
Watch out: Operationally heavy; ordering per partition only.
Strengths: Simple; consumer groups.
Watch out: Memory-bound; fewer guarantees than dedicated brokers.
Interview signals & numbers to know
When this topic comes up
- “How would you process 5,000 uploaded documents?”
- At-least-once delivery and idempotency
- Visibility timeout and DLQ
- Scaling workers from the backlog
- Queue fairness across tenants
Benchmarks & rules of thumb
- 60 workers busy
- 10 jobs/s × 6 s each by Little's law (≈ 86 at 70% utilisation)
- 540 s
- time to drain 3,600 messages at a net 6.7 jobs/s
- 90 s
- example visibility timeout above a 35 s p99
Common mistakes & follow-ups
Common interview mistakes
- A visibility timeout shorter than the slowest normal job.
- Alerting on depth alone and missing a few very old messages.
- No per-tenant limits, letting one customer fill the queue.
Likely interviewer follow-ups
- What happens if a worker crashes mid-job?
- How would you preserve ordering per conversation?
- How do you redrive messages from a DLQ safely?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Message Queues with generative AI interview Q&A and hands-on practice.