Northwind: Queues and streams: acceptance, effects, and recovery
Outcome. After this lesson, you can separate queue delivery from catalogue publication.
Hypothetical scenario. At Northwind, Promotion traffic creates more email work than Northwind can deliver immediately.
In short. Separate accepted work from completed work. Name delivery, ordering and acknowledgement semantics.
Accepting work and finishing it are different events
Hypothetical scenario. A catalogue update should refresh a search view and notify a seller. Waiting for all downstream work would delay the response, so the application places follow-up work in a queue. The user now needs to know whether the update was accepted, whether processing finished and what happens when a worker fails.
A queue separates the producer's progress from a consumer's progress. It does not remove work or make its effects occur exactly once. A useful design states the acceptance boundary, acknowledgement meanings, backlog limits, retry behavior and how readers observe unfinished processing.
This completes the data module's path from authoritative state through indexes and caches to asynchronous derived work. Later lessons distribute ownership across replicas and partitions, where the same distinctions become even more important.
A buffer does not create service capacity
Buffers can absorb a temporary mismatch between arrivals and processing. If sustained work arrives faster than it can be completed, a queue grows until something changes: demand falls, processing increases, work is discarded or admission is limited. Moving a wait from an HTTP request into a broker does not make it disappear.
Acknowledgements also have a particular scope. The AMQP 1.0 transport specification defines delivery state and settlement between communicating nodes. These mechanisms answer different questions; neither automatically includes an external business effect performed by a consumer.
Define the visible state honestly. An accepted background job can be pending, running, completed or failed under the application's contract. Returning “completed” when only a message was accepted hides uncertainty and makes recovery harder to reason about.
Draw the commit and acknowledgement boundaries
Consider which state change must survive together with the intention to do downstream work. One pattern records the authoritative update and an outbox record in the same local database transaction. A dispatcher later publishes the outbox item and marks its progress. This avoids treating two independent writes as one atomic operation, but the dispatcher can still publish duplicates.
The consumer needs an identity for the intended logical operation. If duplicate delivery must not duplicate the effect, enforce that requirement at the effect boundary. Recording “seen” before applying an effect can lose work; recording it afterward without atomic protection can repeat work after a crash. When the effect is external, inspect that service's supported identity and reconciliation contract.
Worked case: an order-notification service
Hypothetical scenario. An order service must notify a buyer after an order is accepted. The product supports email and an in-application inbox. It requires a durable inbox entry for each accepted notification intent; email is a separately tracked delivery attempt. Provider acceptance is not proof that a person received or read a message.
Keep order acceptance and notification intent in one authoritative transaction using an outbox. A publisher retries moving the intent into the delivery path. The notification service resolves the current recipient and channel policy, then creates a channel-specific operation identity from the intent and channel. It records inbox creation and its deduplication state together where the selected store permits that atomic boundary. Email uses the provider's documented identity and status capabilities; a missing response becomes unresolved rather than automatically failed.
Choose 100 accepted orders per minute. Assume exactly 60 require both channels and 40 require only the inbox. Inbox demand is 60 + 40 = 100 operations per minute; email demand is 60. Total channel operations are 100 + 60 = 160 per minute. The fan-out is therefore not simply the number of orders. If six email operations each require one additional attempt, the email path handles 60 + 6 = 66 attempts while still representing 60 logical notifications.
Now choose a ten-minute email-provider interruption. At 60 new email intents per minute, the backlog grows to 60 × 10 = 600, assuming none completes during that interval. After recovery, suppose the permitted processing budget is 100 successful logical notifications per minute while 60 new ones continue arriving. Net drain is 100 − 60 = 40 per minute, so the illustrative backlog needs 600 ÷ 40 = 15 minutes to clear. This budget is a chosen assumption, not a measured provider quota. Unresolved attempts, retries and rejected requests can make actual completion slower.
Separate channel worker pools and bound their queues so an email outage does not consume the resources needed for inbox creation. Preserve notification age, expiry and recipient-policy checks. A stale promotional message may be discarded under a declared policy; a required order-status message may instead need reconciliation or an alternate authorized channel. Do not silently apply the same expiry rule to both.
A cancellation can race with a prepared send. State whether the notification represents the original accepted event or the latest order status, and recheck the state needed by that contract. A later cancellation does not make an already delivered email disappear. Likewise, updating a preference does not prove that every in-flight provider request has stopped.
Evaluate accepted intents, inbox effects, provider-confirmed outcomes, unresolved attempts, queue age and expired work separately. Alert on the user-relevant lag and recovery capacity, not only broker availability. Reject a synchronous provider call inside order acceptance unless the business deliberately accepts its availability dependency. Reject unlimited retry and an “exactly once delivered” promise that the external channel cannot establish.
Design exercise. The provider returns success, but the worker crashes before recording it. Explain the next transition before continuing. The safe answer depends on the provider's actual operation identity and reconciliation contract: reuse that evidence when available, otherwise retain uncertainty and avoid inventing a universal safe retry. A broker acknowledgement alone cannot resolve an email side effect.
Separate queue delivery from catalogue publication
A Northwind price change creates work that can be accepted now and applied later. Kafka retains a partitioned event log and allows consumers to track their progress. A work queue such as SQS exposes a different delivery lifecycle, while RabbitMQ uses acknowledgement and routing concepts suited to message handling. These mechanisms decide how work reaches a consumer; the catalogue's accepted price version still belongs to the application's state contract.
Suppose, hypothetically, updates arrive at 120 jobs per second while workers finish 100. The excess is 120 − 100 = 20 jobs per second. Over ten minutes, backlog grows by 20 × 600 = 12,000 jobs. Doubling the buffer allows more waiting, but does not change that growth rate. If arrivals later fall to 60 and completion remains 100, the net drain is 100 − 60 = 40 per second, so the same backlog takes 12,000 / 40 = 300 seconds to clear.
A consumer crash exposes a second dimension. Completing a Postgres change and then losing the acknowledgement can cause a delivery to return. Treat the event's stable identity and source version as part of the update decision. A repeated delivery of the same desired version should not create an additional business operation. Visibility timeouts and acknowledgement settings are recovery triggers, not proof that the first attempt had no effect.
Kafka ordering is scoped to a partition, so choose the key to match the order that matters. Product identity can keep one product's changes together while allowing unrelated products to proceed independently. Replaying those events to rebuild a search view should not also resend historical customer notifications. The same record can feed consumers with different permissions and side-effect policies; replay needs an explicit purpose.
Derive the backlog and the recovery time
Hypothetical scenario. Choose an arrival rate of 120 jobs/s and a processing rate of 100 jobs/s, both constant for thirty seconds, with an initially empty queue. The excess rate is 120 − 100 = 20 jobs/s. Backlog grows by 20 × 30 = 600 jobs.
Next, arrivals fall to 60 jobs/s while processing remains 100 jobs/s. Net drain is 100 − 60 = 40 jobs/s. Clearing the 600-job backlog takes 600 ÷ 40 = 15 seconds under these simplified assumptions. Dividing by the full 100 jobs/s would ignore the continuing arrivals.
If each queued payload is exactly 4,000 bytes, those 600 jobs contain 600 × 4,000 = 2,400,000 bytes = 2.4 decimal MB of payload. Broker metadata, replicated copies, delivery state, retention and storage allocation are outside that figure. Message count alone does not establish total memory or disk usage.
For a separate duplicate-delivery example, choose 100 distinct logical jobs delivered 105 times. Five deliveries are additional attempts, not five additional intended jobs. If every attempt consumes a chosen 0.2 seconds of worker time, total attempt work is 105 × 0.2 = 21 worker-seconds, compared with 100 × 0.2 = 20 without those extra attempts. Preventing duplicate business effects does not make duplicate processing free.
These examples assume a constant service rate. Real jobs vary in cost and may compete for dependencies. Model expensive job classes and retries separately; do not promise that adding another worker will linearly increase completed business work.
In the wild: Separate queue delivery from catalogue publication
The primary reference establishes this concrete distinction: aMQP delivery state and settlement govern communication between nodes; external effects need separate coordination.
Ordering and replay need a business meaning
“In order” needs a scope: one queue, one partition, one entity or all events everywhere. Multiple consumers and redelivery can change the order in which effects finish even when messages were originally enqueued in a useful order. The consumer position and the publication order must be considered alongside the application's concurrency and replay policy.
For a catalogue item, an older update should not overwrite a newer state merely because it completed later. A revision or explicit state transition can help distinguish useful work from obsolete work. A timestamp alone is not a universal ordering authority; clocks, concurrent writers and the actual conflict policy matter.
Replay also needs a definition. Reconstructing a derived search view from source events is different from sending historical notification messages to users again. Separate rebuildable state from irreversible external effects and decide which consumers are permitted to replay.
An authoritative event history and a work queue have different purposes. Event sourcing makes a defined history the basis for reconstructing state; an outbox records publication intent alongside another authoritative update. A query projection can be rebuilt only when the retained history and its interpretation are sufficient. Explicitly decide event identity, ordering scope, schema evolution and which side effects must not run during reconstruction.
The worker that crashed after the effect
Hypothetical scenario. A worker sends a seller notification, then crashes before acknowledging the queued job. The broker redelivers it. A second worker sends the same notification again because the system treated delivery identity as irrelevant.
The broker may be behaving exactly as configured. The missing contract lies around the external effect. Where the destination supports an idempotency identity, use and retain it appropriately. Otherwise define how uncertain results are reconciled and whether the effect can safely be repeated; do not claim that an acknowledgement setting alone solves the problem.
A poison message is another recovery case. Repeatedly retrying an invalid job can consume the queue's useful capacity. Bound attempts, preserve enough diagnostic context and define a repair/replay procedure. Moving a message to a dead-letter destination identifies unfinished work; it does not complete the business task.
Queue guarantees that stop too early
“The publisher received a confirm, so the customer was notified.” Publication evidence does not establish the downstream effect.
“Exactly-once delivery makes every workflow exactly once.” Inspect the mechanism's actual scope, including consumer state and external side effects.
“The queue is short, so processing is healthy.” A short queue can coexist with rejected producers, lost work or stuck in-flight jobs. Inspect age, acceptance and outcomes.
“Replay means re-executing every effect.” Rebuilding a projection and repeating an external action require different policies.
Introduce asynchrony for a specific boundary
Use asynchronous work when the caller can accept delayed completion and the system can represent and recover that delay. Define a completion signal, a useful failure state and what happens when a dependency is unavailable for longer than expected.
Do not introduce a broker solely to make a diagram look distributed. It adds acceptance, storage, delivery, observation and operational boundaries. A local transaction or bounded background process may be sufficient for a smaller requirement; evaluate what failure and scale problem the broker actually addresses.
Carry the module's invariants into the next distribution lessons. Authoritative state, derived indexes, caches and queued work each have different freshness and recovery contracts. Distributing them should preserve those meanings rather than replacing them with a vague promise of eventual success.
Limits of this model
The fixed arrival and completion rates exclude bursts, variable job costs and worker failures. Broker delivery semantics do not automatically extend into external systems. Bound retention, replay permissions, retry attempts and poison-message handling according to the business operation rather than assuming one universal queue configuration.
Check yourself: identify unfinished work
Arrivals remain 120 jobs/s while processing remains 100 jobs/s. Will a larger queue clear the backlog?
No. The sustained excess is still twenty jobs/s. More storage changes the time before a limit is reached, not the sign of the demand imbalance.
The source transaction commits but the dispatcher loses its publish confirmation. Can it safely assume the event was not published?
No. Publication may have occurred. Preserve event identity and use a replay/consumer contract that tolerates the resulting uncertainty.
Can a replay that reconstructs item views also resend all historical seller notifications?
Only if that effect is explicitly intended and authorized. Reconstructing a derived view is not permission to repeat external effects. Consumers need separate replay policies.
Northwind decision log
Separate accepted work from completed work.
Name delivery, ordering and acknowledgement semantics.
Bound backlog age before accepting further work.
Go deeper: Separate queue delivery from catalogue publication
- Video lecture: Causality and happens-before — Martin Kleppmann. Distinguish the order a consumer needs from the order messages happen to arrive.
- Book chapter: Kafka in Action, chapter 5: Consumers: Unlocking data — Dylan Scott, Viktor Gamov, Dave Klein. Read Consumers: Unlocking data while considering how to separate queue delivery from catalogue publication.
- Book chapter: RabbitMQ in Depth, chapter 5: Don’t Get Messages; Consume Them — Gavin M. Roy. Read Don’t Get Messages; Consume Them while considering how to separate queue delivery from catalogue publication.
- Primary source: OASIS AMQP Version 1.0: Transport — OASIS AMQP Technical Committee. Bound backlog age before accepting further work.
Related blog: Safe retries after uncertain message handling.