Queues and asynchronous work
Why you decouple slow or bursty work with a queue, what at-least-once delivery really means, and how idempotency, retries and backpressure keep it safe.
ConceptCore11 min readUpdated
- 1 architecture diagram
- 2 sequence flows
- 2 code samples
- 5 interviewer follow-ups
- 3 self-checks
On this page14 sectionsHLDLLDSenior depth
Read first: Replication and sharding
- Explain what a queue buys you (decoupling, smoothing bursts, retries) and what it costs.
- Compare at-most-once, at-least-once and effectively-once delivery.
- Make consumers idempotent and retries safe, with backoff and jitter.
- Describe backpressure, dead-letter queues and ordering through partitions.
2 code samples (49 lines), collapsed so the explanation stays in focus.
Some work does not need to finish before you answer the user: sending an email, resizing an image, updating search indexes, charging a card after an order is accepted. A message queue lets the request path record "this needs doing" and return immediately, while separate workers do the job in the background.
- Decoupling. The producer does not need to know who consumes, how many workers exist, or whether they are currently up.
- Burst smoothing. A traffic spike fills the queue instead of crashing the consumer. Workers drain it at their own pace.
- Independent scaling. Add workers when the backlog grows; the API tier is unaffected.
- Retry and isolation. A failing job can be retried without involving the original request, and a slow downstream service stops slowing the user.
- Eventual completion. The user's request succeeded but the work has not happened yet. Your UI and API must be honest about that ("we are sending your receipt").
- Operational complexity. One more system to run, monitor and secure.
- A new failure surface. Messages can be duplicated, delayed, reordered or poisoned.
If the user must see the result immediately, a queue is the wrong tool for that step.
Two designs get called "queues":
- Traditional queue: a message is delivered to one consumer and removed once acknowledged. Good for task distribution. (Many brokers can also fan a message out to several queues through exchanges or topics.)
- Log (such as Kafka-style systems): messages are appended to a partitioned, ordered log and kept according to a retention policy (by time or size, or compacted to the latest value per key). Consumers track their own position, many consumers can read the same data independently, and within the retention window you can replay history. Good for event streams and when several systems need the same events (the logs, streams and Kafka lesson goes inside one).
Pick the queue when you are distributing tasks. Pick the log when events are a source of truth that many consumers read, or when replay matters.
Networks fail between "the worker did the work" and "the queue heard about it". That forces a choice:
- At-most-once. Acknowledge before processing. If the worker dies, the message is lost. Acceptable for low-value telemetry.
- At-least-once. Acknowledge after processing. If the worker dies before acknowledging, the message is delivered again. Nothing is lost, but duplicates happen. This is the usual default.
- Exactly-once. Not something you get from the network alone. Some systems offer it inside their own boundary (Kafka transactions between Kafka topics, for example), but any external side effect, such as sending an email or charging a card, still needs idempotency. What you can achieve end to end is effectively-once: at-least-once delivery combined with consumers that tolerate duplicates.
So the real job is making duplicates harmless. Duplicates also arise when a worker is slow but alive: most brokers hide a message for a visibility timeout or wait for an acknowledgement, and if the worker has not finished by then, the message is handed to another worker.
An operation is idempotent if doing it twice has the same result as doing it once. Setting a value is idempotent. Incrementing a counter is not.
Practical techniques:
- Give each message a unique ID and record processed IDs. A worker that sees an ID it has handled skips it. Store the ID in the same transaction as the side effect where you can.
- Use idempotency keys on API calls (common in payments): the client sends a key, and the server returns the stored result if it sees the same key again. The API design lesson builds one and shows why the key must reach the downstream effect.
- Prefer absolute writes ("set status to shipped") over relative ones ("add one to the count").
A full worked example, with a ledger that decides what a crash means for each kind of message (resend a login code, drop a promotion), is in the notification service case study.
A failed job should be retried, but badly designed retries make outages worse. If a dependency is overloaded and every worker retries instantly, you have built a self-inflicted attack.
- Use exponential backoff: wait 1 s, 2 s, 4 s, and so on up to a cap. A common refinement is full jitter: sleep a random time between zero and the current backoff.
- Add jitter (a random component) so thousands of retries do not land in lockstep.
- Retry only operations that are safe to repeat, and beware retrying at several layers at once: three layers that each try three times multiply one failure into up to 27 calls.
- Cap the number of attempts.
- After that, move the message to a dead-letter queue (DLQ), a holding area for jobs that keep failing, where people or automated tools can inspect them. Alert on DLQ depth and keep a way to redrive messages once the bug is fixed. A single poison message is most damaging in an ordered stream, where it can block everything behind it, or when a broker redelivers it immediately and forever.
Strict global ordering does not scale, because it forces a single sequence through one place. The usual compromise: guarantee order per key. Partition the queue by something like user ID or order ID, so all events for one entity go to the same partition and are processed in order, while different entities proceed in parallel. Order holds only if one consumer handles a partition sequentially: a failed message retried later, or parallel handling inside one partition, can reorder events. This ties back to choosing a good partition key, the same decision as in sharding.
A queue that grows without bound is not resilient, it is a delayed failure. Decide what happens when producers outrun consumers:
- Scale consumers out.
- Bound the queue and reject or slow producers when it is full (backpressure).
- Shed load: drop low-priority work deliberately.
- Monitor queue depth and age of the oldest message, not just throughput.
A classic bug: save an order to the database, then publish an event. If the process dies between the two, the order exists but nobody hears about it (or the reverse). The outbox pattern fixes it: write the event to an outbox table in the same database transaction as the order, and have a separate process publish rows from the outbox to the queue. You get atomicity locally, with at-least-once publishing downstream (the distributed transactions lesson adds the inbox on the receiving side and shows the pair surviving crashes).
The outbox, step by step
Retries are where a queue's resilience is won or lost. The policy has three parts: how long to wait, when to stop, and where the message goes when it stops. The wait grows exponentially and is capped, and it is randomised ("full jitter": a random delay between zero and the ceiling) so that clients that failed together do not retry together.
C# · RetryPolicy
using System;
public sealed class RetryPolicy
{
private readonly int _maxAttempts;
private readonly double _baseMs;
private readonly double _capMs;
private readonly Random _random;
public RetryPolicy(int maxAttempts, TimeSpan baseDelay, TimeSpan maxDelay, Random random)
{
_maxAttempts = maxAttempts;
_baseMs = baseDelay.TotalMilliseconds;
_capMs = maxDelay.TotalMilliseconds;
_random = random;
}
/// <summary>How long to wait before the next try, given the attempt that just failed (1 for the first).
/// Null means stop retrying: send the message to the dead-letter queue.</summary>
public TimeSpan? NextDelay(int failedAttempt)
{
if (failedAttempt >= _maxAttempts) return null;
double ceiling = Math.Min(_capMs, _baseMs * Math.Pow(2, failedAttempt - 1)); // 1s, 2s, 4s, 8s, then capped
return TimeSpan.FromMilliseconds(_random.NextDouble() * ceiling); // anywhere from zero to the ceiling
}
}The random generator is injected so a test can fix it:
C#
using System.Diagnostics;
var policy = new RetryPolicy(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(8), new Random(3));
double[] ceilings = { 1000, 2000, 4000 };
for (int attempt = 1; attempt <= 3; attempt++)
for (int i = 0; i < 500; i++)
{
double delay = policy.NextDelay(attempt).Value.TotalMilliseconds;
Debug.Assert(delay >= 0 && delay <= ceilings[attempt - 1]); // always under the doubling ceiling
}
double sum = 0;
for (int i = 0; i < 2000; i++) sum += policy.NextDelay(3).Value.TotalMilliseconds;
double mean = sum / 2000;
Debug.Assert(mean > 1800 && mean < 2200); // spread over 0 to 4s, so about 2s on average
TimeSpan? afterFifth = policy.NextDelay(5);
Debug.Assert(afterFifth == null); // the fifth failure goes to the dead-letter queue
var patient = new RetryPolicy(12, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(8), new Random(3));
double biggest = 0;
for (int i = 0; i < 500; i++) biggest = Math.Max(biggest, patient.NextDelay(11).Value.TotalMilliseconds);
Debug.Assert(biggest <= 8000); // the cap holds however many attempts have failedThe consumer side is the other half: the same message may arrive again after a retry or a redelivery, so processing must be idempotent. A common way is a table of processed message ids with a unique constraint, inserted in the same transaction as the side effect, so a duplicate fails the insert instead of repeating the work.
Interviewer follow-upL6Can the broker give you exactly-once processing?How to answer
Not end to end in general. Some brokers offer idempotent producers and transactions that give exactly-once effects inside the broker (for example, read, process and write back to the same system). The moment a side effect leaves that system, such as charging a card or sending an email, you are back to at-least-once delivery. Make the effect idempotent with an idempotency key or a deduplication table, and call the result effectively once.
Interviewer follow-upL6Consumers are falling behind and lag keeps growing. What do you do?How to answer
Measure first: consumer lag and the age of the oldest message tell you whether the problem is throughput or a stuck message. Check for a poison message blocking a partition. Then scale consumers (up to the partition count), speed up the handler with batching, defer or shed low-priority work, and apply backpressure or limits to producers. Idempotent handlers make scaling out and retrying safe.
Interviewer follow-upL7You need strict ordering per user and high throughput. How?How to answer
Partition by user ID so one user's messages go to one partition and stay ordered, while different users run in parallel across partitions with one consumer per partition. The costs: a very active user becomes a hot partition, and retries can break order if a failed message is moved aside while later ones proceed. Decide whether a failure should block the partition or be retried elsewhere, and state the consequence for ordering.
Interviewer follow-upL5What is a dead-letter queue for, and what should happen to what lands in it?How to answer
It parks messages that failed after the allowed attempts, so one bad message cannot block the queue or retry forever. It only helps if someone looks: alert on its depth, keep the failure reason and the original payload, and have a tested way to replay messages once the bug or outage is fixed. Replayed messages must be safe to process again, which is the idempotency requirement once more.
Interviewer follow-upL6Why does the retry delay need jitter, not just exponential backoff?How to answer
Without jitter, every client that failed at the same moment retries at the same moments (one, two and four seconds later), so retries arrive as synchronised waves that can knock a recovering service over again. Randomising the delay spreads them out. AWS's widely cited comparison of backoff strategies found that adding jitter cuts contention and total work sharply compared with plain exponential backoff. A retry budget, which caps retries as a share of normal traffic, stops retries from multiplying load during an outage.
Use a queue to take slow, bursty or non-urgent work off the request path. Assume at-least-once delivery, make consumers idempotent, retry with backoff and jitter, route failures to a dead-letter queue, preserve order only per key, and watch queue depth so a backlog never becomes an outage.
Try answering out loud before you reveal each answer.
QuestionWhy must consumers be idempotent when delivery is at-least-once?Reveal answer
A worker can finish the job and die before acknowledging, or run slowly past the visibility timeout, so the message is delivered again. Idempotency makes the repeat safe.
QuestionExponential backoff is not enough on its own. What else belongs in a retry policy?Reveal answer
Jitter so retries do not synchronise, a cap on attempts, a dead-letter queue for messages that keep failing, and care not to multiply retries across several layers.
QuestionWhat problem does the outbox pattern solve?Reveal answer
The dual-write problem: saving to the database and publishing an event cannot be atomic. Write the event to an outbox table in the same transaction and publish from that table.