DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Avoid Cross-Shard Data Movement in Distributed Databases
  • Enhancing Performance With Amazon Elasticache Redis: In-Depth Insights Into Cluster and Non-Cluster Modes
  • Zero Trust for Agents: A New Lens to Secure Agents
  • Don't Adopt Anything Announced at re:Invent for 90 Days

Trending

  • Evals in CI: How to Catch Agent Regressions Before Production Does
  • Why Your AI Agent Works in the Demo and Fails in Production
  • PWA on iOS, Part 4: What Add to Home Screen Really Does
  • Should Developers Switch From SQLite to DuckDB?

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Designing Distributed Counters: A Redis Challenge for Frontend Engineers

Designing Distributed Counters: A Redis Challenge for Frontend Engineers

Learn how to design distributed counters using sharding, CRDTs, leases, and estimates while handling duplicates, stale state, and reconciliation.

By 
Om Shankar Tiwari
·
Nov. 26, 26 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
0 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

We’ll design distributed counters for page views, reactions, live audiences, and unread messages. Each displays a small number while updates arrive across many machines. “There are 8,412 people watching” might mean active connection leases, a periodically refreshed total, or an estimate of distinct identities. The implementation can be perfectly consistent with itself and still answer the wrong question.

These four products need different inputs, expiration rules, and correctness boundaries. We’ll define those rules before choosing sharded counters, mergeable state, or estimates. The designs below show where each approach fits and where coordination is still required.

Before We Design: Three Counter Concepts

  • Atomic update: an operation that prevents concurrent writers from losing each other’s changes. It does not identify duplicate business events.
  • Sharding: distributing updates among several partitions, then combining their contributions for a read.
  • CRDT: a conflict-free replicated data type with defined update and merge rules that let replicas converge. Those rules do not automatically deduplicate incoming events.

Design route and bottlenecks: define the counted unit and retry behavior, distribute writes, then choose read freshness and reconciliation. Watch hot keys, the cost of reading every shard, duplicate-tracking state, and heartbeat traffic for live audiences.

Write the Counting Contract in One Sentence

For a page-view counter: “Count every accepted view event once.” For reactions: “Count distinct users whose latest accepted state is active.” For presence: “Count sessions whose leases have not expired.” For unread messages: “Count eligible messages after this user’s read position.” Each sentence gives you a different underlying collection.

Product value Underlying state Common mistake
Page views Accepted events with stable IDs Counting a retransmission as a new view
Reactions Membership keyed by user and item Applying repeated “like” commands repeatedly
Live audience Unexpired session or identity leases Assuming a crashed browser sends “leave”
Unread badge Read cursor plus eligible message history Decrementing once per device independently
Unique visitors A set or cardinality estimator Adding regional unique counts with overlap


Then define the time boundary. Is the number current as of the last aggregate refresh? Does it converge after all events arrive? Must a read immediately reflect the user’s own action? “Exact” needs a qualification: exact over which accepted events, and at what point in their propagation?

An Atomic Increment Solves Only the Local Race

A naïve read-modify-write loses concurrent increments: two workers read 100, both write 101. A database statement such as UPDATE counters SET value = value + 1 WHERE id = ... avoids that particular lost-update pattern. PostgreSQL’s concurrency semantics explain how competing updates interact (PostgreSQL: isolation). 

But consider a worker that successfully increments and loses the response. If it retries the same increment, the database correctly performs a second increment. Atomicity protects concurrent execution; business-event identity protects repeated execution. You usually need both.

A proposed event API might accept POST /items/42/view-events with event_id, an authenticated scope, and an event timestamp. The service stores a durable uniqueness key before or alongside the count change. A repeated ID with different content is a conflict, not a new event.

Simply changing the method to PUT does not make “increment by one” safe to retry. Idempotence concerns the intended effect of repeating the same operation. A resource assignment such as “set my reaction to active” is naturally easier to make idempotent than an unqualified increment command (HTTP: idempotent methods). 

For reactions, the authoritative record can be (item_id, user_id, active, version). A transaction changes the membership state and emits a count-adjustment event only when the state actually changes. This supports an active reaction being set again without increasing the total.

Shard a Hot Counter By Writes, Not Just By Item

If a viral item receives most of the updates, hashing by item ID still sends all of those updates to one location. Split that item’s counter into several independently updated shards and sum them for a read. Firestore documents this pattern and its read-cost tradeoff: more shards reduce write contention but increase the work required to read a total. A slower roll-up reduces read cost while introducing staleness (Firestore: distributed counters). 

In a proposed event-based design, choose the shard from a stable hash of the event ID. Retries reach the same deduplication boundary. Randomly choosing a new shard on each attempt complicates deduplication unless a separate global event registry already guarantees uniqueness.

Suppose a hypothetical item receives 40,000 events per second. With 64 shards and uniform distribution, the average is 625 writes per second per shard. If a direct total read visits all 64 shards and the API receives 10,000 reads per second, that implies 640,000 shard reads per second before caching. The write optimization has created a read problem.

A roll-up refreshed once a second can answer most display reads cheaply. Return count, as_of, and a freshness state. During an aggregation outage, a previously known count with a visible timestamp is more informative than a stale number presented as current.

A sum of individually read shards is not automatically a snapshot. Updates can land while the shards are being fetched. For a display total, that may be acceptable. For a cutoff-sensitive result, aggregate through a defined watermark or use a transactional snapshot that covers the required state.

CRDTs Solve a Particular Merge Problem

A grow-only counter, or G-counter, can store one nondecreasing component per writer. Each writer increments its own component. Merge takes the component-wise maximum; the value is the sum of components. Repeated and reordered exchanges of the same state converge because maximum is associative, commutative, and idempotent (Shapiro et al.: CRDTs). 

Writer A advances the A component from eight to ten while writer B advances the B component from four to seven. Component-wise maximum merges the states into ten and seven, totaling seventeen.

The replicas exchange cumulative owned state. They do not add every received message to the total.

In the worked example, both replicas initially know [A: 8, B: 4]. A accepts two new increments and records [10, 4]. B accepts three and records [8, 7]. Exchanging states yields [10, 7] at both replicas, totaling 17. Exchanging the same states again leaves the result unchanged.

Contrast that with adding the two local totals, 14 and 15. That produces 29 because both totals already include the same earlier work. The component identities are what distinguish new information from information already observed.

A positive-negative counter uses two grow-only structures: one for increments, one for decrements. Its visible value is the sum of positive components minus the sum of negative components. Libraries such as Akka provide G-counter and PN-counter data types along with replication and durability options. Their data type alone is not a guarantee that acknowledged updates survive loss of every relevant replica (Akka: distributed data). 

Python
 
# Teaching example for a fixed set of durable writer identities.
def merge_components(left, right):
    writers = left.keys() | right.keys()
    return {w: max(left.get(w, 0), right.get(w, 0)) for w in writers}

def pn_value(positive, negative):
    return sum(positive.values()) - sum(negative.values())


The code illustrates a merge, not a complete production counter. Only the owner may advance a component. A restarted writer must preserve its identity and cumulative state, or introduce a safe new identity without discarding prior contributions. Two active processes cannot independently claim ownership of the same component.

Business retries remain separate. If a client submits one event twice and the owner increments its component twice, the CRDT faithfully preserves both increments. Merge idempotence prevents repeated replication of the same state from changing the result; it does not deduplicate repeated user intent.

Metadata also grows with writer identities. Creating a component for every short-lived browser is a poor fit for long-lived aggregate counters. One proposed arrangement gives stable aggregation workers ownership and sends client events to them. More advanced handoff-counter designs transfer contributions so that transient participants do not permanently enlarge the state; that requires a proven handoff protocol, not casually deleting retired components (Almeida and Baquero: handoff counters). 

Presence Needs Leases Because Departure Is Unreliable

A browser can vanish without sending an exit event. A phone sleeps, a process crashes, or a network disappears. Increment-on-connect and decrement-on-disconnect therefore need a recovery mechanism; otherwise it accumulates ghost viewers.

The proposed presence model assigns a session ID and a renewable lease. A heartbeat updates its expiry using the lease owner’s clock. The active-session index counts leases whose expiry is still in the future. A close signal may remove a session early, but expiry handles missing closes.

Browser sessions renew leases every fifteen seconds. A lease owner maintains expiry times; a crashed browser disappears after a forty-five-second lease runs out. The published count includes its freshness timestamp.

The audience value is exact over the current lease model, not a perfect observation of who is physically looking at the screen.

With illustrative 15-second heartbeats and 45-second leases, a crashed session can remain counted until its lease expires, plus any delay in refreshing the published aggregate. Shorter leases detect disappearance sooner but are more sensitive to delayed heartbeats. Define that tradeoff in the product’s freshness contract.

A sorted set keyed by session ID and scored by expiry can support counting scores above the current time and cleaning older entries. Alternatively, use individual expiring keys with a maintained index. Redis TTLs apply to keys, so expiring a whole set does not expire its members independently (Redis: expiration semantics). 

Be explicit about sessions versus people. A user watching on a laptop and a phone creates two sessions. Distinct-person presence requires a user-level rule that combines those leases. For anonymous visitors, a cookie-based identity has different semantics from a verified account.

Lease migration adds another boundary. If a reconnect creates a lease on a new owner before the old owner’s lease disappears, a sum of owner totals can count the session twice. An ownership epoch or a deduplicated overlapping migration can prevent that. If a partition prevents renewal, expiry may exclude a user who still has the page open; the lease model deliberately treats lack of contact as absence after a deadline.

An Unread Badge Is Usually a Query Over a Cursor

For an ordered conversation, maintain the user’s highest acknowledged read position. Repeated read receipts for the same position are harmless; receipts from two devices combine by taking the greatest accepted position, provided the product defines “read through position” that way.

It is tempting to calculate latest_sequence - read_sequence. That works only when sequence differences correspond exactly to eligible unread messages. Deletions, hidden messages, gaps, and messages the user cannot access break that assumption. A more faithful implementation counts eligible records after the cursor or maintains a projection with those rules.

Do not reduce the badge once per device for the same message. The state belongs to the user’s reading contract. Permissions and membership changes also affect the eligible population, so an unread aggregate needs a reconciliation path when those rules change.

Approximation Is Another Explicit Contract

Distinct visitors require deduplication by identity; adding totals from overlapping regions overcounts. HyperLogLog estimates set cardinality and supports merging observations. Redis documents a standard error of about 0.81% and memory use of up to 12 KB for its implementation. This is an estimate, not an exact counter or a hard error bound on every result (Redis: HyperLogLog). 

A count-min sketch addresses estimated frequencies, while a Bloom filter addresses membership checks with possible false positives. Neither supplies an exact live count. Select the structure from the question, and describe the resulting uncertainty in the API and interface.

Likewise, a convergent counter does not by itself enforce “never go below zero” or “never accept more than this quota.” Two partitioned writers can independently admit operations that violate a global limit. A bounded system needs coordination or a protocol that allocates transferable rights. A display statistic can tolerate different guarantees from an admission decision.

Make Reconciliation Part of the Service

For event counts, keep enough accepted history to recompute an aggregate or verify samples. For reactions, compare the total with active membership. For presence, inspect expired leases and owner migrations. For unread badges, compare the projection with eligible history and read positions.

Monitor aggregation lag, duplicate rates, missing owner state, oldest pending event, and the age of the published result. Push refreshed values through WebSockets or server-sent events at a bounded cadence; coalesce a burst of mutations instead of broadcasting every increment to every viewer.

The right counter is often a small derived view over much richer state. Defining that state clearly makes retries, partitions, cleanup, and recovery understandable. An integer without that definition is easy to display and difficult to trust.

Redis (company) Shard (database architecture) Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Avoid Cross-Shard Data Movement in Distributed Databases
  • Enhancing Performance With Amazon Elasticache Redis: In-Depth Insights Into Cluster and Non-Cluster Modes
  • Zero Trust for Agents: A New Lens to Secure Agents
  • Don't Adopt Anything Announced at re:Invent for 90 Days

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook