Message queues and delivery guarantees: idempotency, ordering, dead-letter queues

A message queue lets one part of a system hand work to another without waiting for it. It is one of the most useful tools in a design, and one of the easiest to get subtly wrong: messages can arrive twice, arrive out of order, or turn out to be impossible to process. This lesson covers how queues work, what delivery guarantees they offer, and the three habits that make a queue safe: idempotent consumers, deliberate ordering and dead-letter queues. Section 2 contrasts queue brokers with log brokers such as Kafka, which has its own lesson.

1. Why Use a Queue

A producer puts messages on a queue. A broker (SQS, RabbitMQ and others) stores them. A consumer takes messages and processes them. The producer does not wait for the consumer.

  • Decoupling: the producer does not need the consumer to be up, fast or even known.
  • Load leveling: a spike is stored in the queue and worked off at the pace the consumers can handle.
  • Asynchronous work: a user need not wait for slow jobs such as sending email, resizing images or generating a report.
  • Retries: a failed job stays in the queue and can be tried again.
  • Independent scaling: add consumers when the queue grows.

The costs: the caller does not get an immediate result, the system becomes eventually consistent, there is one more component to run, and it brings new problems: duplicate messages, ordering and messages that cannot be processed. Use a queue when the work can wait. Do not use one when the caller needs the answer now.

There are two shapes. In a queue (point to point), each message goes to one consumer, and several consumers share the work. In publish-subscribe (a topic), each message goes to every subscriber, and each subscriber has its own copy of the stream. A common pattern combines them: a topic fans out to several queues, one per service.

1.1 Example: Sizing Around a Spike

An order service puts one message per order on a queue. Normal load is 500 orders per second. A flash sale sends 10,000 per second for 10 minutes. Workers handle 2,000 per second.

  • Backlog after the spike: (10,000 − 2,000) × 600 s = 4.8 million messages waiting.
  • Drain time: after the spike, new orders arrive at 500 per second, so the net drain rate is 2,000 − 500 = 1,500 per second. 4.8 million ÷ 1,500 = 3,200 seconds, about 53 minutes. Customers wait up to an hour for confirmation.
  • Workers needed: if each message takes 200 ms, the workers must handle 2,000 × 0.2 = 400 messages at the same time (Little's law). To drain the backlog in 10 minutes instead, the workers would need to handle 4.8 million ÷ 600 + 500 = 8,500 per second, more than 4 times as many.

The queue protected the database from 10,000 writes per second, but it only moved the delay. Decide how old a message may get, and size the workers for it.

2. How a Consumer Reads

A consumer gets messages from a broker in one of two ways. A queue broker (SQS, RabbitMQ) hands a message to a consumer and deletes it after the ack. A log broker (Kafka, Redpanda, Kinesis) keeps the messages, and the consumer reads them by position. The broker only records how far each consumer has read.

2.1 Queue Brokers: Receive, Process, Ack

  1. The consumer receives a message. The broker hides it from other consumers but does not delete it.
  2. The consumer processes it.
  3. The consumer acknowledges (acks) it, and the broker deletes it.

If the consumer crashes or is too slow and no ack arrives, the broker makes the message visible again and another consumer gets it. In Amazon SQS this hiding time is the visibility timeout (30 seconds by default). Set it longer than the longest processing time, or a slow but healthy consumer will have its message handed to a second one. For long jobs, extend the timeout while you work (a heartbeat) instead of setting one very large value.

Consumers usually receive messages in batches (SQS returns up to 10) to save calls. Ack each message on its own, so one failure does not make the whole batch run again.

The queue may also have size limits (SQS allows 256 KB per message). For large payloads, store the file in object storage and send only a reference, as in the storage lesson.

2.2 Log Brokers: Read by Offset

A log broker appends every message to the end of a partition (called a shard in Kinesis), an ordered log, and numbers it with an offset (0, 1, 2 and so on). Reading does not delete anything. For each consumer group, the broker stores a committed offset per partition: the position of the next message that group will read. (Kafka keeps it in an internal topic.) The consumer tells the broker when to move it forward, and to "ack" is to commit that offset. After a crash or restart, the group continues from the stored offset. Messages stay until the retention period ends (for example 7 days). Because they stay, every group reads all messages with its own offset, and a group can replay old messages by moving its offset back.

Example: a partition holds offsets 0 to 9, and the group has committed 6. The consumer processes 6, 7 and 8, then crashes before committing. After the restart it begins at 6 again and sees 6, 7 and 8 a second time. That is at-least-once delivery. Committing before processing would lose them instead, which is at-most-once. Commit after the work, in batches, and make the consumer idempotent, as in section 4.

Two consequences matter in an interview. First, parallelism is limited by partitions: within one group each partition is read by one consumer, so 12 partitions keep at most 12 consumers busy and a 13th sits idle. Second, there is no per-message ack, so one message that keeps failing at offset 40 blocks everything behind it in that partition. The usual fix is to publish it to a retry or dead-letter topic and commit past it, which is the pattern of section 6 built by hand. The Kafka lesson covers brokers, replication and consumer groups in detail.

3. Delivery Guarantees

What does the system promise about how many times a message is processed?

Guarantee How Risk Use for
At most once Ack before processing, no retries A crash after the ack loses the message Metrics, logs, anything you can lose
At least once Ack after processing, retry on failure A crash after processing but before the ack causes a duplicate Most systems. Pair it with idempotent consumers
Exactly once At least once, plus the consumer ignores duplicates The duplicate check must be correct and must survive crashes Payments, inventory, anything where a duplicate hurts

True exactly-once delivery over a network is not possible. Consider the consumer that charges a card and then crashes before sending the ack. The broker cannot know whether the work was done. It must either redeliver (a possible duplicate) or drop the message (a possible loss). Without extra coordination, there is no third choice. So "exactly once" in practice means at-least-once delivery plus idempotent processing, which has the same effect. (Some systems, such as Kafka, offer transactions that give exactly-once inside their own boundaries, but not for side effects in other systems.)

The default answer for almost every design: at-least-once delivery, and make every consumer idempotent.

4. Idempotency

An operation is idempotent if doing it twice has the same result as doing it once. Setting a status to PAID is idempotent. Adding $10 to a balance is not.

  • Make the operation naturally idempotent. Use "set" instead of "increment" where you can. UPDATE orders SET status = 'PAID' WHERE id = ? is safe to repeat.
  • Record the message ID. Each message carries a unique ID. The consumer stores processed IDs in a table with a unique constraint, in the same transaction as the change. A duplicate fails the insert and is skipped.
  • Use conditional updates. UPDATE ... WHERE status = 'PENDING' or a version check changes nothing on the second run.
  • Pass an idempotency key to external services. A card charge sent with the order ID as the key is charged once, even if you send it three times. Payment APIs support this.
@Transactional
public void handle(PaymentMessage m) {
    int first = jdbc.update(
        "INSERT INTO processed_messages(message_id) VALUES (?) ON CONFLICT DO NOTHING",
        m.messageId());
    if (first == 0) return;                   // duplicate: do nothing, then ack

    jdbc.update("UPDATE orders SET status = 'PAID' WHERE id = ?", m.orderId());
}   // both changes commit together. Ack the message only after this returns

Why the same transaction? If the ID were saved first and the work failed, the retry would be skipped and the work lost. If the work were done first and the ID saved separately, a crash in between would allow a duplicate. One transaction makes them succeed or fail together. Delete old IDs after a retention period longer than the longest possible redelivery.

Duplicates can also come from the producer. A send that times out is retried, but the first attempt may have succeeded. Give each message a unique ID when it is created. Some brokers deduplicate for you: SQS FIFO queues drop messages with the same deduplication ID sent within 5 minutes.

5. Ordering

A queue seems to keep order, but that holds only for one consumer. With several consumers working in parallel, message 2 can finish before message 1. Retries make it worse: a failed message returns to the queue after later messages were processed.

  • Most work does not need order. Sending 1,000 independent emails does not care. Do not pay for order you do not need.
  • Order within a key (the usual answer). All messages for one order, user or account must be handled in order, but different keys can be handled in parallel. Give each message a partition key (the order ID). The broker sends all messages with the same key to the same partition, and one consumer reads each partition in sequence. Kafka partitions and SQS FIFO message groups work this way, and it is the same hash-to-partition idea as in the sharding lesson.
  • Global order means one consumer for the whole queue. It is simple and slow, limited to the speed of one worker.
  • Make consumers tolerate disorder. Put a version or sequence number on each message. If a message arrives with an older version than the stored one, ignore it. The consumer can then work with a plain parallel queue.

Strict order has a price. If message 5 in a partition keeps failing and you must keep order, everything behind it waits (head-of-line blocking). Either block, or accept moving the failing message aside and processing the rest out of order.

6. Failures, Retries and Dead-Letter Queues

Some messages cannot be processed: a bad format, a missing record, a bug. Such a message, which fails every time, is called a poison message. If you retry it forever, it wastes capacity, and in an ordered queue it blocks everything behind it. Handle failures in three steps:

  1. Retry transient failures, such as a timeout or a busy database, with exponential backoff and jitter (wait 1 s, then 2 s, 4 s, each with a random offset). Do not retry instantly, or you add load to a struggling system.
  2. Do not retry permanent failures, such as a malformed message. Retrying cannot fix them. Send them straight to the next step.
  3. Move to a dead-letter queue (DLQ) after a maximum number of attempts (for example 5). A DLQ is a separate queue that holds messages that could not be processed. In SQS, a redrive policy with a maxReceiveCount does this automatically.
flowchart LR
    P["Producer"] --> Q["Main queue"]
    Q --> C["Consumers"]
    C -- "ack on success" --> X["Message deleted"]
    C -- "failure: retry with backoff" --> Q
    Q -- "too many attempts" --> D["Dead-letter queue"]
    D --> A["Alert and inspect"]

Read the diagram from left to right. The producer adds a message to the main queue, and a consumer takes it. If processing succeeds, the consumer acks and the message is deleted. If it fails, the message goes back to the queue and is tried again after a growing delay. When the number of attempts passes the limit, the broker moves the message to the dead-letter queue, and an alert tells a person to look at it.

A DLQ is only useful if you act on it:

  • Alert when anything lands in it, or when it grows.
  • Keep messages long enough to investigate (set its retention longer than the main queue's).
  • Inspect, fix the cause, and redrive: move the messages back to the main queue after the bug is fixed. Redrive is only safe because consumers are idempotent.
  • Store the reason, such as the error and the number of attempts, with each message.

7. Operating a Queue

  • Watch the age of the oldest message, not only the queue depth. A depth of 10,000 can be fine or terrible, depending on the processing rate. Age tells you how late the work is. On a log broker the same signal is consumer lag: the latest offset minus the group's committed offset.
  • Autoscale consumers on queue depth or age.
  • Apply backpressure. If producers can outrun consumers for long, bound the queue and slow or reject producers. An unbounded queue turns a slow consumer into a growing delay, and in the end into lost data when old messages expire.
  • Use delay, expiry and priority when needed. Most brokers can delay a message (SQS up to 15 minutes) and expire messages that are too old to be useful. For priorities, the simplest way is a separate queue per priority, with more workers on the urgent one.
  • Plan for a queue outage. Use a managed broker with replication, and decide what the producer does if the queue is unavailable (retry, buffer locally, or fail the request). The outbox pattern in the distributed transactions lesson solves the case where a database write and a message send must both happen.

Choosing a broker: SQS for a simple managed queue, RabbitMQ for flexible routing and priorities, SNS or Google Pub/Sub for fan-out, and Kafka when you need very high throughput, long retention and the ability to replay (see the Kafka lesson).

8. Common Pitfalls

  • Assuming exactly-once delivery. Design for at-least-once, and make consumers idempotent.
  • Acking, or committing an offset, before processing, which loses the message if the consumer crashes.
  • Treating a log broker like a queue: adding more consumers than partitions, or expecting per-message retries and a built-in dead-letter queue.
  • A visibility timeout shorter than the processing time, so two consumers do the same job.
  • Recording the message ID outside the transaction of the work.
  • Assuming a queue preserves order with several consumers or retries.
  • Retrying forever, with no limit and no dead-letter queue.
  • A DLQ nobody watches. It becomes a place where data quietly disappears.
  • Retrying without backoff, which turns a small failure into an overload.
  • Using a queue when the caller needs the result now.

9. Interview Questions This Lesson Prepares You For

  • When would you use a message queue? To decouple services, absorb spikes, run slow work asynchronously, and retry failures. Not when the caller needs an immediate answer.
  • What is the difference between a queue broker like SQS and a log broker like Kafka? A queue deletes a message after the ack and shares messages among consumers. A log keeps messages for a retention period, tracks one offset per consumer group per partition, lets every group read everything, and allows replay. Choose a queue for tasks, and a log for event streams, replay and very high throughput.
  • Explain at-most-once, at-least-once and exactly-once delivery. At-most-once can lose messages. At-least-once never loses but can duplicate. True exactly-once is not possible over a network, so use at-least-once with idempotent consumers.
  • How do you make a consumer idempotent? Use naturally repeatable operations, or store each message ID in the same transaction as the work and skip duplicates. Pass idempotency keys to external APIs.
  • How do you keep order in a queue? Give messages a partition key, so that all messages for one entity go to one partition and one consumer. Global order needs one consumer, so use it only if you must. Or add version numbers and ignore stale messages.
  • What is a dead-letter queue? A queue for messages that failed after the maximum number of retries. You alert on it, investigate, fix the bug, and redrive the messages. It keeps a poison message from blocking the queue.
  • A message was processed twice although nothing failed. How is that possible? The consumer took longer than the visibility timeout, so the broker handed the message to a second consumer. Set the timeout above the processing time, extend it for long jobs, and make processing idempotent anyway.
  • Your queue has a backlog of 5 million messages. What do you do? Check the age of the oldest message and the processing rate. Scale up consumers, find out whether processing slowed down, and consider shedding or deprioritizing less important messages. Then prevent a repeat with autoscaling and backpressure.