Message Queues: Asynchronous Processing, Kafka and Delivery Guarantees
Why work is moved out of the request path, queue versus pub/sub, how Kafka partitions and consumer groups work, at-least-once delivery, idempotent consumers and dead letter queues.
A message queue is a component that accepts messages from one part of a system and holds them until another part is ready to process them. The sender and the receiver do not need to be available at the same time, or work at the same speed.
Queues appear in almost every design in this series: notifications, feeds, video transcoding, payments, tracking. These notes explain what they solve, the two messaging models, how Kafka works internally, and the guarantees that determine how consumers must be written.
The problem: doing everything in the request
Consider an order placement endpoint. After saving the order it also sends a confirmation email, generates an invoice PDF, updates inventory, notifies the warehouse and records analytics, all before responding to the user.
This synchronous design has three weaknesses. The response time is the sum of all the steps, so the user waits several seconds. If any one step fails, for instance the email provider is down, the whole request fails even though the order itself was saved. And during a traffic spike every downstream system receives the full load at once.
The solution: asynchronous processing
Only the essential work is done in the request: validate, save the order, and publish an 'order placed' message. The API responds immediately. Separate consumer services receive the message and perform the email, the invoice, the inventory update and the rest in the background.
- Lower latency: the user waits only for the essential step.
- Decoupling: the order service does not know or care which services react to an order. New consumers can be added without changing it.
- Fault isolation: if the email service is down, messages wait in the queue and are processed when it recovers. The order flow is unaffected.
- Buffering (load levelling): a spike fills the queue instead of overwhelming consumers, which continue at their own steady rate.
- Independent scaling: more consumer instances are added for whichever task is falling behind.
SYNCHRONOUS
Client --> Order API --> save order --> send email --> create invoice --> update inventory --> response
(slow; any failure fails the whole request)
ASYNCHRONOUS
Client --> Order API --> save order --> publish "OrderPlaced" --> response (fast)
|
+-----+------ topic: orders ------+
v v v
Email service Invoice service Inventory service
(each consumes independently, retries on its own)Two messaging models
In the point-to-point model, also called a work queue, each message is delivered to exactly one consumer. Several workers read from the same queue and compete for messages, so the work is shared among them. This fits task distribution: resize this image, send this email. RabbitMQ and SQS are typical examples.
In the publish-subscribe model, a message published to a topic is delivered to every subscriber. Each subscribing service receives its own copy and processes it independently. This fits event notification: an order was placed, and several services need to react. Kafka and cloud pub/sub services follow this model.
How Kafka works
Kafka is a distributed log. A topic is divided into partitions. Each partition is an ordered, append-only sequence of messages, and each message has a position called an offset. Producers append messages; a message with a key always goes to the same partition, chosen by hashing the key. Order is guaranteed within a partition, not across partitions. So if all events for one order must be processed in sequence, the order ID is used as the key.
Consumers are organised into consumer groups. Within a group, each partition is assigned to exactly one consumer, so the group as a whole shares the work, and adding consumers increases throughput up to the number of partitions. Different groups are independent: the email service's group and the analytics group each read every message. In this way Kafka provides both models: work sharing inside a group, publish-subscribe across groups.
Unlike a traditional queue, Kafka does not delete a message when it is consumed. Messages are retained for a configured period, and each group simply tracks its own offset. A consumer can therefore rewind and reprocess old messages, which is valuable after a bug fix or when a new service needs historical events. Partitions are replicated across brokers for durability.
Topic "orders" (key = orderId -> partition = hash(key) mod 3) Partition 0: [o1-created] [o4-created] [o1-paid] [o4-shipped] -> offsets 0,1,2,3 Partition 1: [o2-created] [o2-paid] [o5-created] Partition 2: [o3-created] [o6-created] [o3-paid] Consumer group "email" : consumer A <- P0, P1 consumer B <- P2 Consumer group "analytics" : consumer X <- P0, P1, P2 * Events of one order share a partition, so they are consumed in order. * Each group keeps its own committed offset per partition. * A group can have at most as many active consumers as partitions.
Delivery guarantees
- At-most-once: the message is acknowledged before it is processed. If the consumer crashes during processing, the message is lost. No duplicates, possible loss.
- At-least-once: the message is acknowledged after it is processed. If the consumer crashes after processing but before acknowledging, the message is delivered again. No loss, possible duplicates. This is the default in most systems.
- Exactly-once: each message takes effect once. It is hard to achieve end to end, and in practice it is obtained by combining at-least-once delivery with idempotent processing.
Idempotent consumers
Because at-least-once delivery produces duplicates, consumers must be idempotent: processing the same message twice must have the same effect as processing it once. Otherwise a redelivered 'order placed' message sends two emails or deducts inventory twice.
The common techniques are to record the IDs of processed messages and skip any that have been seen; to use operations that are naturally idempotent, such as 'set status to PAID' in place of 'increment the count'; and to rely on unique constraints so that a duplicate insert is rejected.
async function handle(message) {
const { eventId, orderId } = message.value;
// 1. Have we already processed this event? (SET ... NX is atomic)
const firstTime = await redis.set("processed:" + eventId, "1", "NX", "EX", 86400);
if (!firstTime) return; // duplicate delivery -> skip
// 2. Do the work
await emailService.sendOrderConfirmation(orderId);
// 3. The framework commits the offset only after this function returns.
// A crash before the commit causes redelivery, which step 1 absorbs.
}Retries and the dead letter queue
When processing fails, the message is retried, with exponential backoff so that a struggling dependency is not hammered. Some messages will never succeed: the payload is malformed, or it refers to a record that does not exist. Such a message is called a poison message. If it is retried forever at the head of a partition, it blocks everything behind it.
After a limited number of attempts, the message is moved to a dead letter queue (DLQ). The main flow continues, and the failed messages are kept for inspection. An alert on the DLQ size tells engineers that something needs attention, and after a fix the messages can be replayed.
Ordering, backpressure and monitoring
Global ordering across a whole topic would require a single partition and a single consumer, which does not scale. The practical approach is to require ordering only per entity and to use that entity's ID as the message key.
The most important metric for a queue is consumer lag: how far the consumers are behind the newest message. Growing lag means messages are produced faster than they are consumed, and the response is to add consumers, add partitions, or speed up processing. A queue absorbs bursts, but it cannot fix a consumer that is permanently too slow.
When not to use a queue
A queue adds latency, operational work and eventual consistency. It is the wrong tool when the caller needs the result in order to respond, such as checking a password or validating that stock exists before confirming an order. Use a synchronous call when the answer is needed now, and a queue when the work can happen a moment later.
Interview summary
- Move non-essential work out of the request: asynchronous processing with a queue.
- Benefits: decoupling, buffering of spikes, fault isolation, independent scaling.
- Models: point-to-point for task distribution, publish-subscribe for events.
- Kafka: topics, partitions keyed for ordering, consumer groups for parallelism.
- At-least-once delivery, idempotent consumers, retries with backoff and a dead letter queue.
Summary
A message queue lets the request path do only what is essential and hands the rest to consumers that work independently. Kafka organises messages into partitioned, ordered logs read by consumer groups. Delivery is normally at-least-once, so consumers must be idempotent, and messages that keep failing are moved to a dead letter queue so that they do not block the rest.
Puneet Tiwari
Full Stack Developer
