SteelReed

Search

Search posts, questions…

7. System Design

Message brokers: four problems with request-response and how to choose a broker

Why you need a message broker: four problems synchronous calls can't solve, what it costs you, how an event differs from a response, and how to choose between a database-as-queue, Redis, RabbitMQ, NATS, Pulsar and Kafka.

18 Nov 20269 min readMid

–

1. The problem

Creating an order calls Inventory, Notification and Analytics over HTTP in turn: when Analytics is down, nobody can order. During a sale, tracking events hit 30,000 writes/second against a database that handles 8,000, and it falls over.

2. Key idea

A synchronous call is a phone call: both sides must be free at once. A message broker is a post office: the sender drops the letter and leaves, the receiver picks it up when ready.

Request-response problem How a broker solves it
One message to many services, waiting on each Send once to a topic and move on (asynchronous)
Must know each other; one slow side drags the other (cascading failure) Producers and consumers only know the broker (decoupling); a dead consumer's messages wait
Adding a receiver means changing the producer Add a consumer group that subscribes (fan-out)
Traffic spikes crash the DB The queue absorbs the peak, workers drain at the DB's pace in batches (load levelling)

The price: data matches after a delay (eventual consistency); a message may arrive twice, so consumers must be idempotent; ordering holds only within a partition; messages that always fail need a dead letter queue.

The message schema is an API: changing amount from a number to a string breaks every consumer.

2.1 Which broker?

Filter by delivery guarantee and features first; performance can be bought (nodes, partitions), delivery guarantees are architectural properties.

Broker Use when Don't use when
Database table + SKIP LOCKED internal jobs, outbox, a few thousand jobs/day; same transaction as the data tens of thousands of messages/second
Redis Streams light, short-lived queues, Redis already there you can't lose writes on failover
RabbitMQ task queues, routing, priority, delay long replay (classic/quorum queues)
Kafka event streaming, many teams, replay by offset, CDC you need priority, delay, complex routing
Redis Pub/Sub cache invalidation, realtime UI updates anything that mustn't be lost: an offline subscriber misses it forever

3. In Java

JAVA
// Wrong: dual write. If send fails after commit, nobody learns the order exists.
@Transactional
public void placeOrder(Order order) {
    orders.save(order);
    kafka.send("orders", new OrderPlaced(order.id(), order.total()));
}
 
// Right: transactional outbox. The event is written in the same transaction as the order.
@Transactional
public void placeOrderWithOutbox(Order order) {
    orders.save(order);
    outbox.save(new OutboxEvent("orders", order.id().toString(),
            json(new OrderPlaced(order.id(), order.total()))));
}
// A relay (a poller, or Debezium reading WAL/binlog) pushes the outbox to the broker: at-least-once.
// Consumers store processed event ids (UNIQUE) to skip duplicates.

A database table as a queue: use FOR UPDATE SKIP LOCKED so two workers never take the same job.

Using the database as a queue properly, and the distributed monolith
SQL
WITH next AS (
  SELECT id FROM order_queue
  WHERE status = 'NEW' AND available_at <= now()
  ORDER BY id LIMIT 5
  FOR UPDATE SKIP LOCKED
)
UPDATE order_queue q
SET status = 'IN_PROCESSING', attempts = q.attempts + 1, locked_until = now() + interval '5 minutes'
FROM next WHERE q.id = next.id
RETURNING q.order_no, q.payload;
  • Don't keep the transaction open while calling an external API for 30 seconds: each worker holds a connection and the pool drains. Transaction 1 marks IN_PROCESSING + lease and commits; do the work; transaction 2 marks DONE. A cleanup job returns expired leases to NEW, and after 5 attempts to FAILED.
  • A distributed monolith over a message bus: A publishes a command and waits for B's reply on another topic, and B waits on C. It's as coupled as HTTP, just slower and harder to debug. A broker doesn't create decoupling by itself; correct service boundaries do.
  • Queue capacity: a 30,000/second peak for 10 minutes with workers draining 8,000/second needs room for ~13 million messages and ~27 more minutes to drain.

4. Working with AI

Delegate to AI: producer/consumer code, the outbox table and relay, tests where a consumer receives duplicates.

Check yourself:

  • No save() followed by send() in one method without an outbox.
  • Consumers are idempotent: a processed-event-id table or upsert on a business key.
  • No publish or HTTP call inside a long @Transactional.
  • There's a DLQ and a retry limit.

5. Exercises

Exercise 1: Pick a broker for three systems

(a) A small shop, one Spring Boot + PostgreSQL, emailing after each order, 2,000 orders/day. (b) Behaviour tracking at 200,000 events/second, many teams, 7-day replay. (c) Background jobs with priority (VIP first) and a 15-minute delay. AI proposes Kafka for all three. What do you choose?

Solution to Exercise 1
  • (a) A database table (outbox + SKIP LOCKED): writing the order and the email job in one transaction is the best guarantee you can get; 2,000 orders/day doesn't justify a cluster.
  • (b) Kafka: throughput, 7-day retention for replay, many independent consumer groups, Kafka Connect into the warehouse.
  • (c) RabbitMQ: priority queues and delays (plugin, or TTL + dead letter exchange). Kafka has neither built in; faking them adds needless complexity.
  • "One broker for everything" is only right when the cost of running another system exceeds the cost of the wrong choice.

Exercise 2: Read the incident: an order without an email

Every day ~0.1% of orders get no confirmation email. Logs show a few TimeoutExceptions from kafka.send right after orders.save, inside a @Transactional method. Diagnose and fix.

Solution to Exercise 2
  • Diagnosis: a dual write. send fails (or the failure is swallowed because it's asynchronous) after the order commits, so the event never reaches the broker. Conversely, if send succeeds and the transaction rolls back, there's an email for an order that doesn't exist.
  • Now: a reconciliation job finds orders from the last 24 hours with no event and republishes them.
  • Root fix: a transactional outbox; the email consumer is idempotent on orderId since the relay delivers at-least-once.

Summary

  • Request-response: latencies add up, availabilities multiply.
  • A broker gives asynchrony, decoupling, fan-out and load levelling.
  • In return: eventual consistency, duplicates, ordering only within a partition.
  • Choose by delivery guarantee and features before performance.
  • Writing to the DB and publishing needs an outbox; Redis Pub/Sub isn't a queue.

Next: Part 2: Why Kafka is fast and durable.

Practice interview questions on this topic

All Messaging & Kafka questions →All Microservices questions →

Loading comments…