Skip to content

Advanced Concepts · Concept lesson

Messaging: Delivery, Processing, and Durable Handoffs

Design queues and event streams by separating delivery guarantees from business effects, then make retries, ordering, and retention explicit.

Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.

Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.

What you will be able to explain

  • Distinguish a broker's delivery behavior from the effect a consumer commits.
  • Choose queues, logs, or direct calls based on ordering, replay, and load-shaping needs.
  • Design idempotent handlers, poison-message paths, and observable lag budgets.

A durable handoff is not a completed business action

A message broker stores a handoff between independently running components. The sender can finish after the broker accepts the message, even if the receiver is asleep, slow, or temporarily unavailable. This is different from saying the receiver completed the intended business action. Keep three events separate in designs and dashboards: the producer committed a message, the broker delivered it, and the consumer committed its effect. A transport may provide at-least-once delivery while the business effect is effectively once because the handler records a unique event identifier with its update in one database transaction. Conversely, an apparent exactly-once setting does not make an email, payment gateway call, or arbitrary HTTP side effect exactly once. The broker cannot atomically commit with every external system. Naming these boundaries prevents a familiar but dangerous claim: 'the queue guarantees exactly once.' Ask instead which duplication is possible, which data store owns deduplication, and how long that evidence is kept.

A queue is usually chosen to distribute work among competing workers and to absorb bursts; a retained log is useful when several independent readers need the same ordered history or need to replay it. Those are different operating contracts. A queue may remove acknowledged work and hide old state; a log retains records until a retention policy expires them, even after a group reads them. Neither automatically provides global order. Ordering is normally scoped to a partition, key, or single FIFO lane, and adding parallelism can reorder effects. Treat the message as a durable request with explicit identity, schema version, event time, creation time, and trace context. The envelope should say what happened rather than assume that current database state will never change. Avoid placing secrets or unnecessary personal data in long-lived payloads; a broker's persistence and replay features expand the data-retention boundary.

Publish, acknowledge, and commit in the correct order

The producer's hardest gap is between changing its database and publishing the corresponding event. If it updates a row and then crashes before the publish, downstream systems never learn of the change. If it publishes first and then rolls back the database transaction, a consumer can act on a change that never became true. The transactional outbox pattern writes both the business update and an outbox row in the same local transaction. A relay later publishes each row and marks it sent; a crash after publish but before marking can publish it again, so consumers still need idempotency. This is not a distributed transaction with the broker. It makes the database's committed intent durable, then accepts duplicate publication as a recoverable condition. Monitor oldest unsent row age as well as relay errors; a healthy process can still be stuck behind a poison record or stalled credentials.

On consumption, acknowledge only after the effect and deduplication marker commit. A handler can insert `event_id` into a table with a uniqueness constraint and update the business record in the same transaction. If the unique insert conflicts, the event was already applied and the consumer can acknowledge it. If work includes a remote side effect, persist a local state transition first and use an outbox for the next handoff rather than keeping a database transaction open across a network call. For streams, offset commits have the same ordering problem: committing before effects risks loss; committing after effects risks replay. A safe batch commits effects first and advances the offset second, with idempotent effects covering a crash between those steps. Make deduplication retention exceed every plausible redelivery and replay window, or an old replay can become a new charge.

Size the backlog and make the guarantee testable

Imagine an order service that normally receives 80 events per second, but a partner outage causes a 12-minute backlog while workers continue to process 100 per second. During the outage, arrivals contribute 80 × 720 = 57,600 records and processing removes 72,000, so there is no growing backlog if those rates truly hold. But assume the partner outage reduces successful processing to 20 per second: net growth is 60 × 720 = 43,200 records. After recovery, capacity of 140 per second against 80 arrivals drains at 60 per second, taking 43,200 / 60 = 720 seconds, or 12 minutes. This simplified calculation assumes steady rates and no retries; a retry storm can add load exactly when the dependency is weakest. Estimate disk from average serialized size plus broker replication and index overhead, then include retention, burst headroom, and maximum expected lag rather than provisioning only for the average.

A concrete event might be `OrderAccepted` with an immutable order ID, event ID, aggregate version, event timestamp, and schema version. The billing consumer records the ID and creates an invoice intent; it does not blindly issue a new charge every time delivery repeats. A test should deliver the same event twice, crash after the database commit but before acknowledgement, restart, and verify one invoice intent. A second test should send version 9 before version 8 for one order and confirm that the consumer detects the gap rather than silently overwriting newer state. Measure producer publish failures, oldest message age, consumer lag by partition, retry count, duplicate count, dead-letter age, and business completion latency. Broker throughput alone does not demonstrate that orders completed.

Transactional outbox and idempotent consumption
1. Order API

Validates command and starts the database transaction.

2. Orders + outbox

Stores order state and durable event intent atomically.

3. Outbox relay

Publishes and can safely publish again after a crash.

4. Broker

Buffers or retains an event according to its delivery contract.

5. Billing consumer

Deduplicates by event ID and commits a local effect before ack.

  1. Order API → Orders + outbox: one local transaction
  2. Orders + outbox → Outbox relay: poll unsent intent
  3. Outbox relay → Broker: publish; duplicates possible
  4. Broker → Billing consumer: deliver / redeliver
  5. Billing consumer → Broker: ack after commit

Choose the delivery shape, not a fashionable product

A direct synchronous call is often the simplest choice when the caller needs an immediate answer, the dependency is reliably available, and coupling is acceptable. A work queue is a better fit when work can be deferred, spread over workers, or retried independently. A retained stream fits multiple consumers, audit-like replay, and ordered partition history, provided operators can manage retention and consumer progress. A database outbox without a separate broker can be enough at modest scale; polling a table adds latency and database load but reduces moving parts. A broker adds operational obligations: partition planning, access control, upgrades, storage alarms, schema compatibility, and incident ownership. Do not select by peak benchmark numbers alone. Compare end-to-end completion delay, ordering scope, replay needs, consumer count, acceptable message loss, and whether operators can understand the system at 03:00.

Ordering imposes a throughput tradeoff. If all records for an account must be ordered, key them consistently to one partition, accepting that a hot account can bottleneck. If only a subset of operations requires sequence, redesign those operations around aggregate versions or commutative updates rather than forcing every event through one global lane. Batching increases throughput but can increase latency and enlarge the replay unit. Long retention supports recovery and new consumers, but it raises storage cost and privacy exposure. Compaction retains a latest value per key in some logs; it is not a substitute for an audit history or deletion policy. A broker's 'exactly once' mode may constrain producer-consumer topology and transaction boundaries. Document the exact guarantees actually used, including what happens outside that broker transaction.

Recover without turning retries into an outage

Retries are not a universal repair mechanism. A timeout may mean the downstream system did the work but its reply was lost, so an immediate retry can duplicate an effect. Use bounded attempts, exponential backoff with jitter, and a total retry deadline aligned with business value. Classify errors: validation failures are usually permanent; throttling and connection resets may be transient; authorization errors need operator action. A dead-letter destination preserves evidence, but it is not a trash can. Include the original payload, failure class, attempt history, and correlation ID under appropriate data minimization. Provide a controlled replay tool that validates schema, rate limits replay, preserves idempotency keys, and records who initiated it. Replaying a million old messages at live traffic rate can overload a dependency and recreate the incident.

A poison message can block an ordered partition if the consumer refuses to advance. Decide whether to pause the partition, quarantine the record and proceed, or skip only after a domain owner accepts the consequence. Each choice changes ordering and recovery semantics. Alert on age of the oldest unprocessed message, not just queue depth: a shallow queue may still contain one business-critical event that has been stuck for hours. If retries rise, inspect whether retry traffic is competing with fresh traffic; separate retry lanes or a retry budget can protect healthy work. During recovery, scale workers gradually while watching downstream saturation. Validate the fix by injecting duplicate delivery, broker unavailability, consumer restart, and malformed payloads in a controlled environment. A runbook should describe safe replay and the authority to declare a message permanently unprocessable.

When messaging adds more risk than value

Do not introduce a broker merely to make a component diagram look scalable. For a low-volume feature where the user needs a result before the request returns, a synchronous call with a timeout and clear failure response may be easier to reason about. A broker is also a poor fit when message meaning is vague, no team owns consumer lag, or operators cannot safely replay work. If every consumer immediately reads the same mutable database row, an event may add another stale copy without creating useful decoupling. A small database-backed job table can be a reasonable first step if its throughput and locking model are measured. Migrating later is easier when the job has stable identity, explicit state, idempotent handling, and a documented contract.

Messaging is not a replacement for transaction design. It does not make several services update atomically, erase the possibility of partial completion, or remove the need for compensating business actions. Do not put an entire customer profile into every event when an identifier and minimal changed fields suffice. That choice increases exposure in logs, backups, replay storage, and dead-letter tools. For strict sequence, be precise about what must be ordered and how long sequence gaps may remain. For low-latency coordination, asynchronous messaging can make the user experience worse by turning a clear request-response into polling and eventual state. Explicitly decide whether eventual consistency is acceptable to the user and how the product communicates a pending state.

Questions a senior design review should ask

A senior review should start with the domain consequence of duplicate, delayed, missing, or reordered events. Which system is authoritative, what is the event's identity, and where does the idempotency record live? Can the state update and deduplication marker share one transaction? If not, which side effect is repeatable or compensatable? What is the worst acceptable age of the oldest work, how is that converted into an alert, and who owns the alert? Ask whether the delivery guarantee covers a full broker-region loss, a producer crash, a consumer crash, and a database failover; those are not interchangeable failure cases. Ask how schema evolution handles old messages after a deploy and whether a consumer can be rolled back without corrupting newer data.

A review should also challenge the operational math: realistic burst, processing-time distribution, retry amplification, retention days, replication factor, and replay drain time. If the nominal drain rate is 200 per second but the dependency can accept only 60, adding workers can extend the incident. Who can replay dead letters, what approval is needed for financially meaningful events, and how is replay audit logged? Which fields are sensitive, how long do payloads survive in replicas and backups, and can deletion requests reach every copy? Finally, ask what evidence proves correctness: duplicate-delivery tests, crash-window tests, partition rebalancing, and dashboarded business completion. The answer should include a deliberate no-broker alternative and explain why it fails the stated requirement.

Terms in plain language

At-least-once delivery
A broker may redeliver until acknowledgement, so a handler must expect the same message more than once.
Consumer offset
A position in a retained stream that records how far a consumer group has progressed.
Dead-letter queue
A separately managed destination for messages that exhausted a defined retry policy.

Preparing practice controls…

Check your understanding

These checks explain concepts. They do not measure architecture seniority or update readiness.

1. A consumer commits its database update and crashes before acknowledging an at-least-once message. What is the expected safe behavior?
2. Why does an outbox relay still need consumers to be idempotent?

Design independently

Design a notification pipeline that receives account-change events, sends email through a rate-limited provider, and must not send duplicate security alerts after a worker crash. State the delivery contract, event identity, retry policy, privacy boundary, and safe replay behavior.

Hints, not a solution
  • Draw the crash window between provider acceptance and consumer acknowledgement.
  • Separate provider idempotency support from your own database deduplication.
  • Estimate backlog drain using net throughput, then compare it with the alert's useful lifetime.

0 / 20,000 characters · Not saved

Your learning notes

Sign in to save

Marking a lesson read and reviewing an exercise are separate actions. Neither implies mastery. Saved work is account-owned; saves are explicit and do not queue offline.

References and boundaries

Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.

Apache Kafka: Message Delivery Semantics

Primary Kafka documentation describing at-most-once, at-least-once, and transactional processing limits.

AWS Prescriptive Guidance: Transactional outbox pattern

Primary AWS architecture guidance for atomically recording local state and publish intent; not a claim of global exactly-once effects.

Back to curriculum