Distributed Rate Limiting

The problem with multiple Redis nodes

On Redis Cluster (or multiple independent primaries) keys spread across nodes, and a Lua script touching keys on different nodes fails with CROSSSLOT. Force all of a user's keys onto the same shard with hash tags — Redis uses only the content inside {} for slot assignment:

✗ Without hash tag — may land on different shards

key := fmt.Sprintf("rl:tb:%s:curr", userID)

✓ With hash tag — both share slot hash("{user_42}")

key := fmt.Sprintf("rl:tb:{%s}:curr", userID)

Approximate distributed limiting (local counters + sync)

For extreme scale (millions of users, hundreds of app servers), a single Redis node becomes a bottleneck. One approach: each app server keeps a local counter and periodically (every 100 ms or every N requests) syncs to Redis and gets the global count.

Local limit  = global_limit / num_servers   (rough heuristic)
Global sync  = every 100ms

Acceptable error window: one sync interval

This sacrifices exactness for throughput: a user could exceed the global limit by up to num_servers × local_limit during one sync interval. Whether that's acceptable depends on your threat model.

Redis + Sentinel / Cluster failover behavior

  1. The replica may be slightly behind — async replication (see Replication).
  2. Counters on the replica are stale — they undercount recent requests.
  3. For the brief failover window, some over-limit traffic gets through.

For rate limiting (vs. billing) this is usually acceptable. If it isn't, you need synchronous acknowledgment (WAIT) or a different consistency model entirely — a CP system like etcd.