Picture an online shop. A customer clicks Place order, and the order service then calls five other services, one after another, and waits for each:
- charge the card (2 s)
- update the stock (1 s)
- send the confirmation email (1 s)
- create a shipping label (1 s)
- tell the warehouse (1 s)
The customer stares at a spinner for six seconds. Worse, if the email service is down, the whole order fails, even though the payment worked and nothing is really wrong with the order.
The fix is to stop waiting. The order service saves the order, drops a message saying “order 42 was placed” into a message broker, and replies at once. Email, warehouse and shipping each pick up the message and do their part in their own time.
This article opens the Asynchronous systems thread. If you want the basic idea of sync vs async first, start with synchronous vs asynchronous communication.
What messaging gives you
A message is a small piece of data, usually JSON, that says something happened or asks for something to be done. A producer sends it, a broker (like RabbitMQ or Kafka) stores it safely, and a consumer reads it and does the work.
That middle step buys you three things:
- Services don’t need to be up at the same time. If the email service is down for ten minutes, its messages wait in the broker. When it comes back, it catches up. Nothing is lost.
- Spikes get smoothed out. 1,000 orders arrive in one second, but the warehouse system handles 100 a second. The broker holds the rest, and the warehouse works through them at its own pace.
- One event can trigger many actions. “User signed up” can start a welcome email, a profile setup and an analytics update. Each runs on its own, and if one fails, the others still succeed. The producer doesn’t even need to know who’s listening.
The price: things happen a little later, not instantly, and you now run a broker and must deal with failures you didn’t have before. We’ll get to those.
The three messaging models
All messaging systems follow one of three patterns, and picking the right one is most of the design work.
1. Queue (point-to-point)
Messages wait in a line, and each message goes to exactly one consumer. Add more workers, and they share the work automatically. Once a message is processed, it’s deleted.
Use it for tasks: send this email, resize this image, process this order. You want each one done once, by one worker. Examples: RabbitMQ, Amazon SQS.
2. Pub/sub (publish-subscribe)
A publisher sends a message to a topic, and every subscriber gets its own copy. The publisher doesn’t know or care who’s listening, so you can add a new subscriber without touching it.
Use it for news: “a user signed up”, “a price changed”. Examples: RabbitMQ with a fanout exchange, Google Pub/Sub, Amazon SNS, Redis Pub/Sub.
3. Stream (an append-only log)
Messages are appended to a log and kept for days or weeks, not deleted when read. Each consumer remembers its own position (its offset), so consumers read at their own speed, and any of them can rewind and replay old messages.
Use it for event history and high volume: activity tracking, analytics, feeding many systems from one source. Examples: Apache Kafka, Amazon Kinesis, Redis Streams.
| You want to… | Use a | Why |
|---|---|---|
| process each task once | queue | one worker per message |
| tell several services about an event | pub/sub | everyone gets a copy |
| replay history, or let many consumers read at their own pace | stream | messages are kept, and each reader has its own position |
In code
A RabbitMQ queue in Spring. The producer sends and returns at once; the consumer runs separately:
// Java · Spring AMQP (RabbitMQ)
// producer: in the order service
orderRepository.save(order);
rabbitTemplate.convertAndSend("orders.exchange", "order.created", new OrderCreated(order.getId()));
return ResponseEntity.accepted().build(); // reply now; the rest happens in the background
// consumer: in the email service
@RabbitListener(queues = "email.order-created")
public void onOrderCreated(OrderCreated event) {
emailSender.sendConfirmation(event.orderId());
}
A Kafka stream. Each consumer group gets every message and keeps its own offset, so two teams can read the same topic without getting in each other’s way:
// Java · Spring for Apache Kafka
kafka.send("user-activity", activity.userId(), activity); // key = userId (more on why below)
@KafkaListener(topics = "user-activity", groupId = "analytics")
public void track(UserActivity a) { analytics.record(a); }
@KafkaListener(topics = "user-activity", groupId = "recommendations")
public void learn(UserActivity a) { recommender.update(a); }
Kafka vs RabbitMQ vs Redis
| RabbitMQ / SQS | Kafka | Redis Pub/Sub | |
|---|---|---|---|
| Model | queue (and pub/sub via exchanges) | stream | pub/sub |
| Keeps messages after reading? | no | yes, for a set time | no, not even before |
| Replay | no | yes | no |
| Ordering | per queue, with one consumer | per partition | in order, but only to subscribers online right now |
| Throughput | high | very high | high |
| Running it | moderate | the most work | very easy |
| Great for | background jobs, task routing, priorities | event streams, analytics, many consumers | quick, can-lose-it signals like “clear your local cache” |
Rule of thumb: jobs that must be done once → RabbitMQ or SQS. Events many teams need, or anything you might replay → Kafka. Fire-and-forget signals where losing one is fine → Redis Pub/Sub. Redis Pub/Sub keeps nothing: if a subscriber is offline when a message is published, that subscriber never sees it.
Ordering: the partition key
Kafka splits a topic into partitions so it can spread the work across machines. It keeps messages in order within a partition, but not across partitions.
So if order matters for a user, an account or an order, use that ID as the message key. Every message with the same key goes to the same partition, and stays in order.
Messaging also means a message can arrive twice: brokers usually deliver at least once, so a retry after a lost acknowledgment repeats the message. Every consumer must be safe to run twice (idempotent). We covered this in depth in message delivery semantics.
What breaks, and how to fix it
| What breaks | What you see | The fix |
|---|---|---|
| A consumer is down or too slow | Messages pile up; emails go out hours late | Alert on queue depth or consumer lag, and add consumers. The broker keeps the messages safe meanwhile |
| A poison message | One broken message crashes the consumer, gets redelivered, crashes it again, and blocks everything behind it | Retry a few times, then move it to a dead letter queue (DLQ) to inspect later, and carry on |
| Lost messages | The producer “sent” it, but the broker crashed before saving it | Wait for the broker to confirm: in Kafka, acks=all (the default since Kafka 3.0); in RabbitMQ, publisher confirms and durable queues |
| Out-of-order processing | A withdrawal is processed before the deposit it depends on | Use the same key for related messages (Kafka), or one consumer per queue when order matters (RabbitMQ) |
| Saved to the database, but the message never sent | The order is saved, then the app crashes before publishing, and no email ever goes out | The outbox pattern: save the order and an “outbox” row in one database transaction, and a separate process publishes outbox rows. We cover it in event-driven architecture |
Puzzle 1: the lost email
The message was acknowledged too early. The broker thought the job was done the moment it was handed out.
Acknowledge only after the work succeeds. The broker then keeps the message until the consumer says “done”. If the consumer crashes first, the broker delivers it again to another worker.
In Spring AMQP, the default acknowledgment mode already works this way: it acknowledges after your listener method returns normally, and redelivers if it throws. The trap is code that turns on auto-ack on delivery (autoAck=true in the plain RabbitMQ client) or swallows exceptions. And since a redelivered message might have been half-done, the consumer must be idempotent.
Puzzle 2: the retry that never ends
There are two kinds of failure, and they need different handling:
- Temporary failures (a timeout, the payment gateway is briefly down) might work next time. Retry, with a growing delay.
- Permanent failures (card declined, invalid data) will never work. Retrying is pointless. Record the failure, tell the customer, and move on.
Spring for Apache Kafka has this built in. After a few retries with backoff, the message goes to a dead letter topic:
// Java · retry 3 times with backoff, then send to a dead letter topic
@RetryableTopic(attempts = "3", backoff = @Backoff(delay = 1000, multiplier = 2),
exclude = CardDeclinedException.class) // permanent: don't retry
@KafkaListener(topics = "orders")
public void charge(OrderCreated event) {
payments.charge(event.orderId());
}
@DltHandler
public void failed(OrderCreated event) {
orders.markPaymentFailed(event.orderId()); // handle it, then move on
}
Puzzle 3: half the users got the email
A queue gives each message to one consumer. With two consumers on one queue, RabbitMQ shares the messages between them, so each service sees only about half the sign-ups.
This needs pub/sub, not a queue. Publish to a fanout exchange, and give each service its own queue bound to it: email.user-created and profile.user-created. Now every message is copied into both queues, and each service gets every sign-up. In Kafka, the same fix is giving each service its own consumer group.
Key takeaways
- Messaging lets services work without waiting for each other. The producer sends and moves on; consumers catch up in their own time.
- Queues share tasks out, one message to one worker. Pub/sub copies each event to every subscriber. Streams keep a log anyone can read and replay.
- RabbitMQ or SQS for jobs, Kafka for event streams and replay, Redis Pub/Sub only for signals you can afford to lose.
- Order is only kept within a partition (Kafka) or a queue. Use the entity’s ID as the key.
- Expect duplicates: acknowledge after the work is done, and make consumers idempotent.
- Plan for failure: dead letter queues for poison messages, alerts on lag, and the outbox pattern so a saved record always gets its message.
This opens the Asynchronous systems thread. Next, we’ll build on messaging with event-driven architecture: designing whole systems around events, and the patterns that keep them reliable.
Comments