Tutorial

How to Build a Distributed Counter with Redis

Implement an atomic, sharded counter in Redis with INCR, CRDT merge for partitions, and eventual consistency for global aggregation.

On this page

  1. Introduction
  2. The problem
  3. Design decisions
  4. Implementation
  5. Testing the boundary
  6. Common pitfalls
  7. Operational considerations
  8. Conclusion

Introduction

A distributed counter tracks a number across multiple processes: page views, likes, or inventory. A local counter is fast but wrong across instances; a database counter is correct but slow under high write rates. Redis INCR is atomic and fast, but a single key becomes a hot spot. This guide builds a sharded counter that uses INCR for atomicity, spreads writes across shards, and aggregates for reads.

The problem

If each process increments a local counter, the global count is the sum of all locals, which requires a merge step and loses real-time accuracy. If every process increments the same Redis key, the key becomes a hot spot: Redis serializes INCR on a single key, and under high write rates the latency spikes. A sharded counter spreads the writes across multiple keys, so each shard gets a fraction of the load and the increments run in parallel.

Design decisions

The counter has N shards, each a Redis key like counter:0, counter:1, up to counter:N-1. A write picks a shard by hashing the writer ID or a random number modulo N, and increments that shard with INCR. A read aggregates all shards with MGET and sums the values. The total is cached with a short TTL to avoid MGET on every read. For exact real-time counts, skip the cache and MGET on every read; for approximate counts, use the cache.

class DistributedCounter {
  constructor(redis, name, shards = 16) {
    this.redis = redis; this.name = name; this.shards = shards;
  }
  async inc(amount = 1) {
    const shard = Math.floor(Math.random() * this.shards);
    return this.redis.incr(`${this.name}:${shard}`, amount);
  }
}

Implementation

The increment picks a shard randomly or by hashing a context value like the user ID, which distributes writes evenly. The read uses MGET to fetch all shard values in one round trip and sums them. The cached total is stored in a separate key with a TTL of one second, so at most one MGET per second per counter. For counters that need exact values, the cache is skipped. For counters that can tolerate a one-second staleness, the cache reduces read load by the inverse of the TTL.

async get() {
  const cached = await this.redis.get(`${this.name}:total`);
  if (cached) return parseInt(cached);
  const keys = Array.from({ length: this.shards }, (_, i) => `${this.name}:${i}`);
  const values = await this.redis.mget(keys);
  const total = values.reduce((sum, v) => sum + parseInt(v || 0), 0);
  await this.redis.set(`${this.name}:total`, total, 'EX', 1);
  return total;
}

Testing the boundary

Test that a thousand concurrent increments produce a total of one thousand. Test that the shards have roughly equal counts, confirming even distribution. Test that the cached total matches the sum of shards within the TTL window. Test that reads after writes return the updated total. Test that a Redis failure on increment does not crash the caller.

Common pitfalls

Avoid using a single shard; it defeats the purpose of sharding. Avoid too many shards; each shard adds a MGET cost on reads. Avoid caching for too long; stale counts may mislead dashboards or billing. Avoid blocking writes on the counter; if Redis is down, log and continue rather than failing the request. Avoid non-atomic increments; INCR is atomic, but read-modify-write in app code is not.

Operational considerations

Monitor each shard’s commands-per-second and the MGET round-trip latency on reads. A shard that receives a disproportionate share of writes points to a bad hash distribution; switch from random shard selection to a hash of a stable context value like the user ID so the same writer always lands on the same shard. Track the cache hit rate on the cached total key: a low hit rate means the TTL is too short or the read fan-out is too high, and a hit rate near 100% means the TTL could be longer to reduce MGET load further.

On Redis Cluster, MGET cannot cross hash slots. Pin every shard key to the same slot with a hash tag, so {counter}:0, {counter}:1 up to {counter}:N-1 all live in one slot and MGET stays a single-node command. Without the tag, MGET degrades into multiple cluster round trips and the read latency dominates. If the counter must scale beyond a single slot, split the counter namespace into multiple hash-tag groups and aggregate across groups in the application.

Plan capacity by measuring INCR throughput on a single key in your hardware profile. A shard that handles 100k INCR/s gives a 16-shard counter 1.6M increments/s of headroom, but only if the client connection pool and Redis CPU are not the bottleneck. Size the shard count to keep each shard under 60% of its single-key limit so spikes do not saturate one shard. Re-evaluate the count after major traffic changes, not on a fixed calendar.

For failure handling, wrap the INCR call in a circuit breaker that opens after a few consecutive Redis errors and falls back to a local in-memory counter. On Redis recovery, drain the local buffer with a batch INCR and close the breaker. This adds a small undercount during the outage but never blocks the write path. For counters that feed billing or limits where an undercount is unacceptable, write increments to a durable log first and apply them to Redis asynchronously, so a Redis outage does not lose data.

Conclusion

A distributed counter with Redis needs INCR for atomicity, sharding for throughput, and aggregation for reads. Spread writes across shards, sum them with MGET, and cache the total with a short TTL. Test concurrency, distribution, and consistency. The result is a counter that is accurate, fast, and scalable across instances. For counters that only need an approximate cardinality, a HyperLogLog key uses constant memory and a PFADD per event, trading exact counts for a fixed 12 kilobyte footprint regardless of volume.

Sources: Redis INCR, sharded counters.

FAQ

Why shard a counter?
A single Redis key becomes a hot spot under high write rates; sharding spreads writes across keys and reduces contention.
How many shards do I need?
Start with eight or sixteen; add more when you see latency spikes on the counter key. Each shard is a Redis INCR.
How do I handle Redis failure?
Fall back to a local counter and merge on recovery, or accept a small undercount; never block writes on the counter.

Related Examples