Queues and asynchronous design

An email outage that failed a synchronous checkout and did not touch an asynchronous one, the outbox, what queues guarantee, dead letters, and the workflow that is a state machine.

13 min read🏗️ System Design Fundamentals

A queue lets one part of a system say "this needs doing" without waiting for it to be done. That single change — separating the request from the work — is what lets a checkout finish while the confirmation email is still being written, lets a spike of traffic be absorbed rather than rejected, and lets a failing dependency slow one feature down instead of taking every feature down with it.

It is also a change in what "done" means, and most of the design work is about that.

The checkout that waited for everything

A checkout does five things: save the order, reserve stock, send a confirmation email, record analytics, and notify the warehouse. Written synchronously, the customer waits for all five. With each step simulated by its typical duration:

plaintext
synchronous, all healthy:   placed in  213 ms
asynchronous, all healthy:  placed in   24 ms

The asynchronous version does only what the customer must wait for — save the order and reserve the stock — and records an event saying the order was placed. The email, analytics and warehouse notification happen after, driven by that event. The numbers are simply the sums of the simulated steps, so the ratio belongs to this example; the structure is the point.

Now the email provider has an outage, and times out after two seconds:

plaintext
synchronous, email down:    FAILED after 2023 ms (email provider timed out after 2 s)
asynchronous, email down:   placed in   23 ms
events waiting for the email consumer: 2

The synchronous checkout failed a sale because an email could not be sent. The asynchronous one placed the order in the same 23 ms and left two events waiting; the emails go out when the provider recovers.

Look again at the failed synchronous run, because it is worse than it appears. The order was saved and the stock was reserved before the email step threw. The customer was told the checkout failed, so they try again — and now there are two orders and twice the reserved stock. A synchronous chain of side effects that fails halfway leaves exactly this kind of mess, and the idempotency lesson in the distributed systems course is what cleans it up.

What belongs on the synchronous path

The dividing question for each step: does the caller need the result to continue?

stepthe customer needs it now?path
save the orderyes — it is the resultsynchronous
reserve or check stockyes — it decides whether there is an ordersynchronous
take paymentusually yes, or a clear pending statesynchronous, or asynchronous with a status to poll
confirmation emailnoasynchronous
analytics, search indexing, recommendationsnoasynchronous
notify the warehouseno, within minutesasynchronous

Everything in the second half is allowed to be late and must not be lost. That combination is exactly what a durable queue offers.

The event must not be lost either

Moving work to a queue introduces a new failure: the order is saved, and the process crashes before the event is published. Or the event is published and the database transaction rolls back. Writing to a database and a broker are two separate operations, and no transaction spans both.

The standard answer is the transactional outbox: write the event as a row in an outbox table in the same database transaction as the order, and have a separate relay publish outbox rows to the broker. Either the order and its event both commit, or neither does. The relay may publish an event twice after a crash, so consumers must be idempotent — which, because every broker delivers at least once anyway, they had to be regardless.

What a queue guarantees, and what it does not

propertytypicallythe design consequence
deliveryat least onceevery consumer must tolerate duplicates
orderingper partition or group key, not globalchoose the key so events that must be ordered share it — an order id
durabilityonce the broker acknowledgesthe producer must wait for that acknowledgement
latencyusually milliseconds, unbounded under backlognothing that needs an answer in a deadline should depend on it

"Exactly once" appears in broker documentation with careful conditions attached — typically within the broker's own read-process-write loop. A consumer that charges a card or sends an email is outside those conditions and must deduplicate itself.

Backpressure and the backlog

A queue absorbs the difference between how fast work arrives and how fast it is done. That is its value during a spike and its danger during a sustained overload: the backlog grows, the age of the oldest message grows with it, and "late" turns into "too late to matter". The backpressure lesson measures an unbounded queue doing exactly that.

For a design, three decisions:

  • What is the acceptable age of a message for each consumer? Email within minutes; a fraud check within seconds; analytics within hours.
  • How does the system scale consumers, and what limits them — partitions, database connections, a downstream rate limit?
  • What happens past the limit — shed the lowest-value work, pause producers, or alert and let it catch up?

Failures: retry, then dead-letter

A consumer that fails on a message has three options, and a real system uses all three:

  1. Retry, with backoff, for failures that are likely transient: a timeout, a 503.
  2. Dead-letter the message after a limited number of attempts, so one poison message does not block everything behind it. A dead-letter queue is not a bin; it needs an alert, an owner and a way to replay.
  3. Skip with a record, for messages that can never succeed — invalid data from an old producer — so they are visible without being retried forever.

The Kafka course's lesson on retries and dead-letter topics covers blocking and non-blocking retries in detail.

When the workflow is really a state machine

As more steps move to asynchronous processing, a single business operation becomes a chain of events: order placed, payment captured, stock allocated, shipped. Implemented as consumers that each trigger the next, the flow exists nowhere in the code, and "where is order 1041 stuck?" is answered by reading five services' logs.

The better model is an explicit state machine, stored with the entity:

plaintext
PLACED ──payment captured──▶ PAID ──stock allocated──▶ ALLOCATED ──shipped──▶ SHIPPED
   │                           │
   └──payment failed──▶ CANCELLED ◀──allocation failed (refund issued)

Each event handler performs one transition, as a conditional update that names the state it expects:

sql
UPDATE orders SET status = 'PAID'
WHERE id = ? AND status = 'PLACED'

That one WHERE clause does three jobs. A duplicate event affects zero rows, so the transition is idempotent. An event that arrives out of order — "stock allocated" before "payment captured" — affects zero rows instead of skipping a state. And the order's status column is the answer to "where is it stuck", in one query.

Under the hood: why "at least once" is unavoidable, and how a visibility timeout actually redelivers a message

"At least once" is not a design choice a broker makes — it falls out of what acknowledgement means. A consumer processes a message, then tells the broker "done" (an ack). Between "processed" and "acked" there is an unavoidable gap — a crash, a network blip, a slow GC pause — during which the broker does not yet know the message was handled. A broker that wants to guarantee "at least once" must, in that gap, err toward redelivering: if it is unsure whether the consumer finished, it delivers again rather than risk losing the message. The only way to avoid ever redelivering is to risk the opposite failure — ack before processing completes and lose messages on a crash — which is "at most once", a strictly worse guarantee for anything that must not be silently dropped. This is why "exactly once" between two independent systems (a broker and your consumer) is not fully achievable by the broker alone: it can dedupe within its own boundary (Kafka's idempotent producer avoids duplicate writes into the log itself), but it cannot know whether your consumer's side effect — a charged card, a sent email — already happened before a redelivered message arrives.

A visibility timeout is the specific mechanism behind "at least once" in queue-based systems like SQS or RabbitMQ (as opposed to log-based systems like Kafka). When a consumer receives a message, the broker does not delete it — it makes the message temporarily invisible to other consumers for a configured window (the visibility timeout) and waits for an explicit ack (a delete call) within that window. If the ack arrives in time, the message is gone for good. If it does not — the consumer crashed, hung, or is simply still working — the timeout expires and the message becomes visible again, ready to be picked up by any consumer, including the same one. That redelivery is not a bug in the broker; it is the mechanism doing exactly what "at least once" promises. A visibility timeout set shorter than the consumer's real processing time causes the broker to redeliver a message that is, in fact, still being handled — the classic cause of a message processed twice concurrently, and why the timeout should be set comfortably above the slowest realistic processing time, not the typical one.

An idempotency key turns "processed at least once" into "had an effect at most once" — at the application layer, because the broker cannot do it for you. The pattern: the producer attaches a unique key to each logical operation (an order id, a request id — generated once, before the first attempt, so a retry reuses the same key rather than minting a new one); the consumer, before performing the side effect, checks whether that key has already been recorded as done — typically a unique constraint or a conditional write against a small table or cache entry keyed by the idempotency key — and skips the side effect (returning the previously recorded result) if it has. This is precisely the same WHERE status = 'PLACED' conditional-update trick the state machine section above already uses; an idempotency key is that trick generalised to any side effect, not just a state column.

java
Set<String> processedKeys = new HashSet<>();
// the same order id redelivered, then a genuinely different order
String[] deliveries = {"order-41", "order-41", "order-99"};
 
for (String key : deliveries) {
    if (processedKeys.contains(key)) {
        System.out.println("skipped " + key + " (already charged)");
    } else {
        processedKeys.add(key);
        System.out.println("charged " + key);
    }
}

Try it yourself

Decide where the idempotency key comes from, and why it can't come from the consumer

A payment consumer reads "charge card" events off a queue and calls a payment provider's API. The events can be redelivered (visibility timeout, consumer crash and restart). The team debates two designs: (a) the consumer generates a fresh unique key for the payment provider's idempotency-key parameter each time it processes a message, or (b) the key is generated once by the producer and travels inside the event itself. Which is correct, and what specifically breaks with the other one?

Why the key has to be born with the operation, not with an attempt at it

(b) is correct: the idempotency key must identify the logical operation ("charge order 41"), and it must be the same value on every attempt at that operation, including a redelivery — which means it has to be generated once, at the point the operation is first decided on (typically by the producer, when the order is placed), and carried along with the event data itself. Design (a) breaks the entire point: if the consumer mints a new key every time it processes a message, then a redelivered message — which is, by definition, the same logical charge being attempted again — gets a different key each time, and the payment provider's deduplication (which works by rejecting a repeated key) has nothing to catch, because from the provider's point of view every attempt looks like a brand-new charge. This is a realistic mistake, not a contrived one: it is easy to reach for "generate a UUID" inside the consumer without noticing that "inside the consumer, per delivery" is exactly the scope that must NOT vary across redeliveries for idempotency to work at all.

Misconceptions

  • "Exactly-once delivery means a message can never be processed twice." Brokers that advertise "exactly once" scope that guarantee to their own internal boundary (writing to the log, or a read-process-write loop entirely inside the broker's ecosystem) — a consumer's own side effect, outside that boundary, is only protected by whatever idempotency the consumer itself implements.
  • "A visibility timeout expiring and redelivering a message is a failure." It is the mechanism working as designed — the alternative (never redelivering an unacked message) is silent message loss whenever a consumer crashes mid-processing, which is a strictly worse failure mode than an occasional duplicate a well-written consumer already tolerates.

Sources

  • Amazon SQS documentation, "Amazon SQS visibility timeout" — the mechanism a queue-based (non-log) broker uses for at-least-once delivery.
  • Confluent/Apache Kafka documentation, "Exactly-once Semantics" — what Kafka's idempotent producer and transactions actually guarantee, and its boundary.
  • Chris Richardson, Microservices Patterns — the transactional outbox pattern and idempotent consumer pattern.
  • Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns — message delivery guarantees and the idempotent receiver pattern.
Progress is saved on this device and to your account when signed in.