Skip to content

Choose queues, streams and pub-sub

12 min reading

Select consumption, retention and replay semantics for a concrete workflow

Page details

System Design · Move work through time

12 min reading · 25 min with practice

Sources

Published · Last edited:

Prerequisite: Recover jobs under a delivery contract. For basics, use the independent System Design foundations.

More
20px

Hypothetical scenario. Search and activity-view workers share Northwind’s queue. All items are consumed, but each view misses changes that the other worker received. Dev has balanced consumption while accidentally dividing two different responsibilities.

Dev: “No messages remain unprocessed.”

Maya: “Unprocessed by whom? Each view needed its own complete sequence.”

Choose the consumption contract before selecting a product. Distinguish competing work from independent readers and retained history. Carry the repeated-effect protection from page 20 into each responsibility; changing the transport does not remove it.

Who needs a share of work, and who needs every change?

A competing-work queue distributes tasks among consumers that perform the same logical responsibility. Adding workers normally shares that responsibility; it does not mean every worker performs every task. If all search workers update the same protected projection, that distribution can be appropriate.

Publish-subscribe describes distribution to independent subscriptions. Search and an activity projection can each need the same change, with separate progress and failures. Their subscription positions or queues are not interchangeable with the count of worker processes inside one responsibility.

A retained event stream stores a sequence of records under a retention policy and allows consumers to track progress through it. Several independent consumers can read the same retained history. That supports replay and rebuilding where the history and transformation contract are sufficient. Retention is a declared limit, not a promise to remember everything forever.

Keep requested work and recorded facts distinct

A command asks for an action, such as preparing a specific uploaded image. An event records that something happened, such as a product version becoming authoritative. A query asks for information. Transporting all three as messages does not give them identical business meaning.

Replaying a product fact to rebuild a search view differs from replaying a command that sends a customer message. The latter can repeat an external effect unless its contract protects it. A retained transport makes replay possible; the application determines whether a particular replay is meaningful and safe.

Independent subscriptions differ from competing workersA product-change history feeds a search subscription and a separate activity subscription. Search workers compete within the search responsibility. Independent progress allows an activity failure without consuming the search subscription's position.Product changesRetained historySearch subscriptionOwn progressActivity subscriptionOwn progressSearch poolShared workActivity poolShared work
Separate progress for separate effects; shared work within one effect.

Open the partition and consumer-group state

Hypothetical scenario. Choose a Kafka topic partition containing offsets 40, 41 and 42. Each record has a product key, source revision and schema identity. Search and activity projections use different consumer groups, so each group maintains its own progress rather than dividing the two responsibilities between competing workers.

Open the partition and consumer-group state — selected design evidence
Partition recordSearch groupActivity group
offset 40: Q7 rev10next 42next 41
offset 41: Q7 rev11already processednext to process
offset 42: R2 rev3next to processnot yet reached
Two groups read the same retained records while advancing separate progress positions.Two groups read the same retained records while advancing separate progress positions. Partition 0 to Search group: independent fetch + offset; Partition 0 to Activity group: independent fetch + offset.Partition 0Search groupActivity groupindependent fetch + offsetindependent fetch + offset
Two groups read the same retained records while advancing separate progress positions. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

A partition is an ordered sequence within its selected scope, not a global order across the topic. Key choice can keep one product's changes together while making a popular key a bottleneck. Broker replication, retained log bytes and group offsets solve different responsibilities. Committing an offset records progress under the consumer's policy; it is not evidence that an unrelated remote effect committed.

A rebalance can transfer the partition while an old consumer's effect is still in flight. Protect target versions or operation identities even if only one new consumer receives subsequent fetches. Replay also requires the old record schema and interpretation to remain usable. Event-time windows need a declared late-event rule; a log offset alone does not say that all earlier real-world events have arrived.

Primary mechanism reference: Kafka design and transaction scope. Use its implementation scope when evaluating this design.

A consumer position does not preserve its segment

Hypothetical scenario. Open one Kafka partition as a sequence of segment files. Suppose a closed segment contains offsets 40–49 and the active segment currently contains 50–54. The append path extends the active segment; a fetch uses an offset to locate retained records. These selected boundaries illustrate file organization, not Kafka’s configured segment sizes.

Three independent pieces of broker and consumer evidence
StateSelected exampleWhat it establishes
Leader and replicasA leads; B and C replicateWhere partition bytes are copied
Retained segments40–49 closed; 50–54 activeWhich records remain fetchable
Committed group positionSearch next 47; activity next 52Where each group intends to resume

Suppose the selected delete-retention policy makes the first segment eligible and it is removed. The earliest retained offset is now 50. Search’s next position 47 is three offset positions behind that boundary: 50 − 47 = 3, namely 47, 48 and 49 in this contiguous example. Its committed position cannot recover those bytes. Activity can still resume at 52. Search must declare a gap and use a complete rebuild path; silently resetting to 50 changes its coverage.

Kafka’s design documentation separates replication, consumer progress and retention, and describes compaction as a different cleanup policy. Compaction can remove superseded keyed records while preserving surviving offsets. Therefore offset distance is not generally a count of available records, and a compacted topic is not automatically a complete audit history. State whether a projection needs every transition or only sufficient current-state evidence before selecting cleanup.

Derive fan-out and retention

Hypothetical worked example. Preserve the selected two product changes per second. If three independent projections each require every change, logical subscription deliveries are 2 × 3 = 6 per second before retries. A single competing queue carrying two tasks per second does not become six complete projection obligations merely because three different teams attach consumers.

For a retained-history estimate, choose five hundred payload bytes per change. One day contains 24 × 60 × 60 = 86,400 seconds, so raw daily payload is 2 × 500 × 86,400 = 86,400,000 bytes. Seven days retain 7 × 86,400,000 = 604,800,000 payload bytes under the uniform-rate model.

Three copies of that selected retained payload occupy 3 × 604,800,000 = 1,814,400,000 bytes before keys, indexes, batch framing, logs and free space. Consumer delivery traffic and retained broker storage are different quantities. Three subscribers do not necessarily require three separately stored copies of every event inside the broker’s selected storage model.

Retention creates a recovery deadline. If a consumer falls behind beyond the available history, moving its cursor does not reconstruct missing records. A source snapshot plus a compatible change position, or another explicitly complete rebuild path, may be needed.

Order within a defined sequence

A stream may define order within a partition while independent partitions proceed separately. Choosing product identity for partitioning can keep one product’s related records together under the selected producer and consumer protocol. It does not automatically establish one global order across the catalogue.

For a conventional partition-assigned consumer group, choose three partitions and five available consumer instances. At most three instances can own a partition simultaneously in that selected model; two have no partition assignment. Adding instances does not divide one assigned partition’s serial processing into arbitrary parallel work.

That is a consequence of the declared assignment model, not a universal claim about every modern queue or Kafka feature. Some systems offer other consumption contracts. Compare the actual selected feature rather than treating the product name as one immutable messaging abstraction.

Replay needs versioned meaning

A projection rebuild must know how to interpret historical records. A schema change can make an older message unreadable or change how an old field is understood. Retain compatible readers or an explicit migration path; storing bytes is insufficient if the consumer can no longer interpret them correctly.

Replaying events can also reintroduce withdrawn information if deletion and eligibility changes are omitted. Northwind’s search rebuilding contract must preserve the relevant source versions and removals, not merely append every product description ever observed. Recovery should reconstruct the intended current view.

In the wild: Kafka combines retained records and independent readers

Apache Kafka’s introduction describes topics, event storage and consumption. These mechanisms provide a concrete reference for separating retained history from a particular consumer’s progress. The selected version is named so the lesson does not imply an unverified recent feature or universal consumption behavior.

That documentation does not choose Northwind’s retention, partition key or acceptable recovery lag. Those decisions follow the workload, history size and the consequences of unfinished projections. Keep the operation-level delivery contract from Page 20 when applying a retained stream.

When successful delivery reaches the wrong responsibility

Hypothetical failure scenario. Search and activity consumers compete on one work queue. The activity consumer acknowledges a product update after writing its own view. Search never receives that update. The broker did not lose it; the application selected competing delivery for two independent obligations.

Separate the subscriptions or publish explicit per-responsibility tasks, then track each required projection’s progress. Do not “fix” the symptom by disabling acknowledgements and hoping every team eventually sees every redelivery. Repeated uncertain distribution is not a subscription contract.

Select the smallest useful model

Use competing work when interchangeable workers share one obligation. Use independent subscriptions when several effects require the same information. Use retained history when replay or multiple independently paced readers justify its storage and interpretation duties. These properties can coexist in a platform, but they remain separate decisions.

A small durable task table may be sufficient where the workload and recovery needs are modest. A retained stream is not automatically the simpler architecture. Northwind chooses independent search and activity progress, with retained history only where a documented rebuild need justifies it.

The next lesson adds work that becomes due at a time rather than immediately after a product change. Scheduling must preserve logical identity and ownership even when two scheduler instances notice the same due item.

Challenge the proposed mechanism

The old consumer writes after a rebalance and the new consumer has already applied a later version. What prevents regression?

Reveal the design reasoning

Target-side version or operation protection is required. Group assignment can stop new fetches by an old owner without cancelling its existing remote action. Keep processing order and effect order distinct.

Decision and reconsideration: Partition by the required order and skew envelope. Record replay interpretation and effect protection with each group.

Choose who receives the change

  1. Three independent projections require every one of two changes per second. What logical delivery demand follows?

    Count each required responsibility

    Six deliveries per second before retries. Competing workers on one queue do not establish all three independent effects.

  2. A stream retains seven days. Can a consumer always recover after a longer absence?

    Check retained evidence

    No. Required history may be gone. Recovery needs a complete snapshot/change boundary or another supported reconstruction path.

  3. Five instances consume three partitions under the selected exclusive-assignment model. Are all five active owners?

    Respect the assignment unit

    No. At most three simultaneously own partitions in that model. More processes do not automatically parallelize one partition’s required order.

The consumption contract now names which responsibility owes each effect. Page 22 adds time: a scheduled cleanup must create the intended occurrence and prevent an old claimant from continuing after ownership changes.

Northwind decision log

Separate competing workers from independent subscriptions.
Declare history retention, schema interpretation and rebuild evidence together.
Carry logical identity and ownership into time-based scheduling.

Go deeper: history and consumption