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.

Intermediate 4 min readLesson 10 of 20

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.

publishProducersAPI serversQueue / topicdurable bufferConsumer 1Consumer 2

Why use a queue

BenefitExample
DecouplingThe order service doesn't need to know about the email, analytics and warehouse services
Load levellingA flash sale produces 50k orders/minute; workers drain them at their own pace
ResilienceIf the email provider is down, messages wait and are retried later
Faster responsesReturn "accepted" immediately; do the slow work in the background
Fan-outOne event, many independent subscribers

Two models: queues vs logs

Message queue (RabbitMQ, SQS)
  • 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
Log / stream (Kafka, Kinesis, Pulsar)
  • 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.

P0P1P2012345012301234
Topic 'orders' with 3 partitions; each consumer group keeps its own offset per partition.

Delivery guarantees

GuaranteeMeaningHow
At most onceMay be lost, never duplicatedAck before processing
At least onceNever lost, may be duplicatedAck after processing; redeliver on failure — the common default
Exactly onceEach message's effect happens onceOnly within closed systems (Kafka transactions) or with idempotent processing
Idempotent consumer
@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 succeeds

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).

Key takeaways
  • 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.