Message Queues & Event Streaming
Asynchronous processing with queues and logs — RabbitMQ/SQS vs Kafka, delivery guarantees, idempotency, ordering, dead-letter queues, backpressure, and event-driven architecture.
A message queue lets one component hand work to another asynchronously. The producer drops a message and moves on; consumers process it when they can. Queues decouple services, absorb traffic spikes, and make slow or unreliable work (emails, video encoding, payments to third parties) resilient.
Why use a queue
| Benefit | Example |
|---|---|
| Decoupling | The order service doesn't need to know about the email, analytics and warehouse services |
| Load levelling | A flash sale produces 50k orders/minute; workers drain them at their own pace |
| Resilience | If the email provider is down, messages wait and are retried later |
| Faster responses | Return "accepted" immediately; do the slow work in the background |
| Fan-out | One event, many independent subscribers |
Two models: queues vs logs
- Messages are removed once acknowledged
- Each message goes to one consumer (competing consumers)
- Per-message acks, retries, delays, priorities
- Great for task distribution: jobs, work queues
- An append-only log, kept for days or forever
- Consumers track their own offset; many consumer groups read independently, and can replay
- Ordered within a partition; scales by partitions
- Great for event streaming: activity feeds, CDC, analytics pipelines, event sourcing
Kafka in one picture
A topic is split into partitions; each partition is an ordered, replicated log. Messages with the same key go to the same partition, so they stay in order. Within a consumer group, each partition is consumed by exactly one consumer, so a group can have at most as many active consumers as there are partitions.
Delivery guarantees
| Guarantee | Meaning | How |
|---|---|---|
| At most once | May be lost, never duplicated | Ack before processing |
| At least once | Never lost, may be duplicated | Ack after processing; redeliver on failure — the common default |
| Exactly once | Each message's effect happens once | Only within closed systems (Kafka transactions) or with idempotent processing |
@KafkaListener(topics = "payments")
@Transactional
public void onPayment(PaymentEvent e) {
// Unique constraint on processed_events.event_id makes duplicates fail fast
if (processedRepo.insertIfAbsent(e.id()) == 0) return; // already handled
ledger.credit(e.accountId(), e.amount());
} // offset committed after the DB transaction succeedsdef handle(msg):
event = json.loads(msg.value)
with conn.transaction():
inserted = conn.execute(
"INSERT INTO processed_events (event_id) VALUES (%s) ON CONFLICT DO NOTHING",
(event["id"],),
).rowcount
if inserted == 0:
return # duplicate delivery
credit(conn, event["account_id"], event["amount"])
consumer.commit(msg)await consumer.run({
eachMessage: async ({ message }) => {
const e = JSON.parse(message.value!.toString());
await db.tx(async (t) => {
const r = await t.query(
"INSERT INTO processed_events(event_id) VALUES ($1) ON CONFLICT DO NOTHING", [e.id]);
if (r.rowCount === 0) return; // already processed
await credit(t, e.accountId, e.amount);
});
},
});Ordering
- Queues with competing consumers don't preserve order across consumers.
- Kafka preserves order per partition: key messages by entity (
order_id) so all events for one order are ordered. - Global ordering requires a single partition and a single consumer — which doesn't scale. Usually you only need per-entity order.
Failures, retries and dead letters
- Retry transient failures with exponential backoff (delayed retry queues or topics).
- After N attempts, move the message to a dead-letter queue (DLQ) so one "poison" message doesn't block the rest. Alert on DLQ growth and provide tooling to inspect and replay.
- Set visibility timeouts (SQS) or max poll intervals (Kafka) longer than processing takes, or you'll get duplicate processing.
Backpressure
If producers outpace consumers, the queue grows. Monitor consumer lag (queue depth, or the offset difference in Kafka). Respond by autoscaling consumers, throttling producers, or shedding low-priority work. A queue buys time; it doesn't create capacity.
The dual-write problem and the outbox
A service that writes to its database and publishes an event can fail between the two: the DB has the order, but no "OrderCreated" event is ever sent (or vice versa). The transactional outbox fixes it: write the event into an outbox table in the same DB transaction, and have a relay (or CDC with Debezium) publish outbox rows to the broker.
Event-driven architecture
Services publish events ("OrderPlaced") rather than calling each other directly; others react. It gives loose coupling and easy extension (add a new subscriber without touching the producer), at the cost of harder debugging (use correlation IDs and tracing), eventual consistency, and the need for event schemas with versioning (a schema registry with Avro/Protobuf).
- Queues decouple services, level load and add resilience; responses can return before work finishes.
- Queues (RabbitMQ, SQS) distribute tasks; logs (Kafka) retain ordered, replayable event streams.
- At-least-once delivery is the norm → make consumers idempotent.
- Order is per partition: key by entity.
- Retry with backoff, dead-letter poison messages, monitor lag, and use an outbox for reliable publishing.