Messaging Patterns and Delivery Guarantees

Understand queues vs pub/sub, delivery semantics, ordering and the outbox pattern before choosing a broker.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Background Jobs and Task Queues, Transactions, ACID and Isolation

A message broker lets services communicate without calling each other directly. The producer sends a message and moves on; consumers process it when they can. This decouples services in time and load, but introduces new failure modes you must reason about.

Two core patterns

  • Point-to-point queue: each message is handled by exactly one consumer from a pool. Used for distributing work ("process this order").
  • Publish/subscribe: each message goes to every subscriber. Used for broadcasting facts ("OrderPlaced") to billing, email and analytics independently.

Delivery guarantees

  • At-most-once: may lose messages, never duplicates.
  • At-least-once: never loses acknowledged messages, may deliver duplicates. The practical default.
  • Exactly-once is only achievable within specific systems and boundaries; across your whole pipeline you get it by combining at-least-once delivery with idempotent consumers (track processed message ids).

Ordering and failures

Ordering is usually guaranteed only within a queue or partition, not globally. Design so that consumers can handle out-of-order or late messages, for example by carrying versions or timestamps. Poison messages that always fail must go to a dead-letter queue, not loop forever.

The dual-write problem

Writing to your database and publishing to the broker are two separate operations; one can succeed while the other fails. The transactional outbox fixes it: write the event to an outbox table in the same transaction as the business data, and a relay publishes it afterwards. Change data capture (Debezium) is a related technique.

Commands vs events

A command asks for something ("SendInvoice") and has one handler; an event states a fact ("InvoicePaid") and may have many.

You are ready to move on when you can explain at-least-once delivery, write an idempotent consumer and sketch the outbox pattern.

Key concepts

  • Queues vs publish/subscribe
  • At-least-once delivery
  • Idempotent consumers
  • Ordering guarantees
  • Poison messages and DLQs
  • Transactional outbox
  • Change data capture
  • Commands vs events

Mini project

Implement the outbox pattern in your app: write OrderPlaced to an outbox table in the order transaction, relay it to a queue, and build a consumer that ignores duplicates.

Check yourself

Why is 'exactly-once delivery' across services achieved in practice with at-least-once delivery plus idempotency?

Free resources