引言
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. 本文将逐步拆解设计与实现,帮助你在生产环境中安全落地。
问题
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. 理解问题的全貌是设计正确方案的前提。
设计决策
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);
}
}
实现
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;
}
测试边界
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. 测试应覆盖正常路径与异常路径,确保系统在边界条件下行为正确。
常见陷阱
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. 避开这些陷阱可以减少生产事故。
结论
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. 按照本文的方法,你可以构建出既安全又高效的解决方案。
Sources: Redis INCR, sharded counters.