Skip to content

Aggregate counts without one hot writer

11 min reading

Derive shard/aggregation trade-offs and define the observable count guarantee

Page details

System Design · Operate the system

11 min reading · 24 min with practice

Sources

Published · Last edited:

Prerequisite: Recover across regions and restore data. For basics, use the independent System Design foundations.

More
20px

Hypothetical scenario. Northwind’s seller dashboard needs product-view counts. A popular product concentrates increments on one key. Maya accepts an approximate display; Dev suggests using that same count to enforce a limited promotion allowance. Priya asks whether those decisions permit the same uncertainty.

Dev: “Both features need a number of events.”

Maya: “Define the event and the decision before choosing how to distribute the count.”

Build a counter contract covering qualification, duplicate handling and read semantics. Separate a responsive display from an authoritative admission decision. The selected counter stress workload is a new exercise, not the original catalogue or reservation ledger.

Which event qualifies for this count?

A view might mean an HTTP request, a rendered product, a session seeing the product or a unique authenticated viewer. These are different populations. Retries, refreshes and bots change the relationship between them. Northwind chooses accepted display events for this example and records which events qualify.

The seller dashboard can accept an explicitly delayed aggregate if that meets its product contract. A scarce promotion allowance cannot safely use an arbitrarily delayed total as if it were current authority. One derived counter can support reporting while a separate guarded decision governs allocation. Reusing a convenient number for both silently changes the safety argument.

Also decide whether corrections are possible. Duplicate removal, invalid-event filtering and deletion obligations may revise the aggregate. A monotonic display count and a corrected accounting total may therefore need distinct definitions. The interface should not promise exact uniqueness when the accepted event stream does not establish it.

An atomic increment still has one hot owner

Redis provides an integer increment operation for a key. That can avoid a read-modify-write race at the selected server, but it does not divide one key’s work across independent owners automatically. More shards help different keys. A single popular product still concentrates its increments unless the data model deliberately splits that aggregate.

Northwind proposes several component counters per product, with each qualifying event assigned to one component. Writers spread increments across them; a reader obtains the components and combines them. The representation distributes write work by increasing read and coordination work. It must define how events keep their assignment across retries and migration.

Distribute increments and compose the readQualifying events choose one stable component counter. Three illustrated components receive updates independently. A reporting reader sums their observed values, with an explicit freshness and completeness contract. That sum is not automatically a transactional admission decision.Qualifying eventsStable assignmentComponent AComponent BComponent CObserved sumDeclared contract
Write distribution buys capacity with a more expensive and nuanced read.

Separate a distributed sum from allocation authority

Hypothetical scenario. Three increment components reduce one hot writer, but a report reading them at different instants may combine values that never existed together. A point-in-time total requires a snapshot or another declared observation protocol; eventual component convergence alone is a weaker statement.

Separate a distributed sum from allocation authority — selected design evidence
QuantityEvidence neededAppropriate use
Eventual countDeduplicated component updatesLag-tolerant reporting
Snapshot sumCoherent component boundaryDeclared point-in-time report
Remaining rightsConserved allocation authorityExclusive grants
The observation protocol determines what the sum means; atomic component updates do not supply it.The observation protocol determines what the sum means; atomic component updates do not supply it. Deduplicated events to Count components: qualified increments; Count components to Report snapshot: declared observation boundary.DeduplicatedeventsCount componentsReport snapshotqualified incrementsdeclared observation boundary
The observation protocol determines what the sum means; atomic component updates do not supply it. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

Delivery identity matters independently from atomic increment. Replaying the same qualifying event twice can inflate every correctly atomic counter. Bind the increment to the event's admitted identity or rebuild from a deduplicated source under an explicit rule. Retain window and event-time interpretation if late events can change earlier totals.

A dashboard count may tolerate lag while an inventory grant cannot. Do not grant exclusive units by reading a sum of independently changing components and then incrementing one. Escrow can allocate bounded local rights under a different protocol, but requires conserving those rights across transfer, loss and restart. The reporting counter is not that protocol.

Work the component arithmetic

Hypothetical worked example. Select nine hundred qualifying events per second for one hot product and three components. Under an assumed exactly even assignment, each receives 900 ÷ 3 = 300 increments per second. This is an idealized distribution; random assignment produces variation and a poor key choice can preserve the hotspot.

Choose observed component values of 120, 90 and 110. The reporting sum is 120 + 90 + 110 = 320. A reader now needs three component observations instead of one logical counter read. At a selected fifty dashboard reads per second, that is 50 × 3 = 150 logical component reads per second, before retries and caching.

Suppose the newest component values are actually 125, 94 and 111, while the reader saw the earlier values. The newer sum is 125 + 94 + 111 = 330, a difference of 330 − 320 = 10 events. These selected values illustrate lag; they do not establish a general maximum error without a bound on propagation and event rates.

Repeated delivery can inflate a perfectly atomic counter

If a worker increments a component and loses its reply, another delivery may increment again. Each individual increment can be atomic while the logical event is counted twice. Stable event identity and a protected transition are required where the definition counts logical events once.

One option retains processed event identities with the aggregate transition in an appropriate authoritative boundary. Another derives aggregates from retained accepted events and rebuilds them under a defined replay contract. Both have storage, retention and recovery costs. An ephemeral deduplication cache cannot promise indefinite recognition of old replayed events.

Routing an event to another component on retry introduces a further trap. Per-component deduplication can miss the repeated identity if the first attempt used a different component. Preserve assignment or enforce identity across the full operation boundary. Resharding must account for in-flight attempts and retained history, not only new traffic.

An exact sum requires an observation argument

Reading components sequentially does not automatically obtain a snapshot of one instant. With transfers, resets or corrections, a combined observation can include incompatible stages. Even with only positive independent increments, the reader must explain which freshness and completeness promise it offers rather than casually labeling the result current.

A materialized total can make dashboard reads cheaper, but it adds another projection with its own progress and duplicate behavior. A cached total adds another age boundary. Connect both to the source evidence and backlog ledger developed earlier. A cache hit on a total does not prove every qualifying event has been processed.

A minute’s count can change after the minute ends

Hypothetical scenario. Define a product-view report for the event-time interval [12:00:00,12:01:00). Event time is when the view was recorded at its source; processing time is when the aggregation handles it. Retain event identity, product, event timestamp and schema generation. Suppose the initial result contains events E1 and E2, so its unique count is two.

Selected late-event and replay policy
Arrival evidenceActionPublished result
E2 delivered againRecognize retained identityRevision 1 remains count 2
E3 at 12:00:50; watermark 12:01:10Accept within retained lateness horizonRevision 2 replaces count with 3
E4 at 12:00:55; watermark 12:01:31Send to correction stream after cleanupKeep count 3 pending separate correction

Choose thirty seconds of allowed lateness, giving a cleanup horizon of 12:01:00 + 30 seconds = 12:01:30. A watermark expresses the processor’s event-time progress; it does not prove no earlier event can arrive. Revision 2 is a replacement keyed by product and window, not three additional events. Adding both emitted totals would produce 2 + 3 = 5 instead of three unique views.

Flink’s window documentation explains retained state for allowed lateness, late firings and side outputs. This exercise adds explicit identity deduplication and a revision-aware sink; a window operator alone does not establish either. Keep source positions, deduplication state and aggregate progress in a compatible recovery boundary. Replay after that state expires needs a new complete rebuild generation or retained identity evidence. Route older corrections deliberately rather than claiming that a closed display total is permanently complete.

In the wild: a command specifies a bounded operation

Redis’s INCR documentation defines the integer-key operation. It supplies a concrete building block, not an application-level promise about unique views, distributed snapshots or surviving every failure. The aggregation policy must establish those properties separately.

The dashboard becomes an allocation authority

Hypothetical failure scenario. A promotion permits a bounded number of accepted claims. Several workers read a delayed dashboard total, each sees remaining allowance and each accepts another claim. The reporting aggregate remains internally understandable, yet the promotion limit is exceeded.

Move the scarce-rights decision to an enforcing boundary. A centralized conditional transition is one possibility. Deliberately allocated rights across owners are another, with a proof that their combined grants cannot exceed the total. A periodically summed display counter is insufficient merely because its arithmetic is correct.

Use partitioned aggregates for the right obligation

Use this design when one aggregate is a measured write bottleneck and its reporting contract tolerates the composed-read behavior. Measure the added fan-out, hot-component variation and recovery work. Do not add components merely because a reference diagram shows them; each makes read completeness and migration harder.

For exact business accounting, retain the accepted operation evidence and state the reconciliation policy. A fast approximate dashboard can remain valuable alongside that authority. Keep their labels and API meanings distinct so later consumers do not accidentally turn an estimate into permission.

Challenge the proposed mechanism

A counter shows one remaining unit to two regions. May both allocate it and repair the sum later?

Reveal the design reasoning

No, if the invariant forbids double allocation. Use a conditional authority or conserved preallocated rights with a transfer protocol. Reconciliation after two incompatible grants cannot make the original decisions safe.

Decision and reconsideration: Keep aggregates as evidence for their declared use. Select a separate rights protocol when the number becomes an allocation decision.

Defend the aggregate

  1. Does adding owners split one unchanged hot Redis key?

    Inspect the data model

    No. The application must partition the aggregate into components or change ownership semantics. Ordinary key partitioning distributes different keys.

  2. An increment is atomic but its reply is lost. Is repeated delivery harmless?

    Protect the logical event

    Not for an additive counter. A second increment can count the same event again. Use identity and an effect boundary or a replayable aggregation contract.

  3. Can a delayed reporting total authorize the last promotion claim?

    Locate scarce-rights enforcement

    No without an additional bounded-allocation argument. Reporting lag can allow competing claims. Enforce the limit with current authority or deliberately partitioned rights.

The counter adds another operation with its own observation rule. Page 40 brings that rule alongside admission, authorization, deployment and recovery in one production-readiness decision.

Northwind decision log

Define qualifying logical events and stable component assignment.
Declare aggregate observation semantics and retain recovery evidence.
Next, defend the full production plan against combined failures.

Go deeper: aggregate work and partial observations