Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 1

Going distributed: atomic counters, races and store outages

Share one limit between two application instances through Valkey (a Redis-compatible store): watch a read-then-write counter race, fix it with atomic scripts, keep time on the store's clock, and choose and test what happens when the store is down or hangs.

Contentsand lesson path

What you will learn

  • Design a distributed rate limiter with a shared store, atomic updates and an explicit fail-open or fail-closed decision.

01. Why it matters

The limiters from lesson 03 live in one process. Run your API as two instances and each keeps its own buckets, so a client gets twice its limit. The usual fix is a shared store: every instance asks the same Redis-compatible server before admitting a request. Stripe, for example, keeps its token buckets in Redis. A shared store brings three new problems, which this worked example solves one at a time:

  1. Races. Two instances read the same count at the same moment, and both decide there is room.
  2. Partial failure. A process crashes between two commands and leaves a state nobody intended.
  3. Store outages. When the store is down or hangs, requests still need an answer. You decide in advance whether the limiter fails open (admits) or fails closed (rejects).

The task: each free-tier API key may send a burst of 50 requests, then one every 5 seconds. Two application instances with 8 worker threads each must enforce it together, with tested behaviour during a store outage.

02. Set up Valkey and the client

The example uses Valkey, an open-source (BSD-licensed) fork of Redis 7.2 run by the Linux Foundation. It speaks the same protocol, and every command used here works the same way in Redis. The Python client redis (redis-py) talks to both. Tested with Python 3.12.13, redis-py 8.1.0 and the official Valkey 9.0.7 binary for Ubuntu 22.04 (jammy; a noble build exists for 24.04). Everything listens on 127.0.0.1:18479 only.

Terminal: project folder and client library
mkdir shared-limit && cd shared-limit
python3 -m venv .venv && source .venv/bin/activate
python -m pip install -q redis
python -c "import redis, sys; print(sys.version.split()[0], redis.__version__)"
Expected output (your versions may differ)
3.12.13 8.1.0
Terminal: download, verify and start Valkey (Linux x86_64)
V=valkey-9.0.7-jammy-x86_64
curl -fsSLO https://download.valkey.io/releases/$V.tar.gz
curl -fsSLO https://download.valkey.io/releases/$V.tar.gz.sha256
sha256sum -c $V.tar.gz.sha256 && tar xzf $V.tar.gz
export PATH="$PWD/$V/bin:$PATH"
valkey-server --port 18479 --bind 127.0.0.1 --save '' --appendonly no \
  --daemonize yes --pidfile "$PWD/valkey.pid" --logfile "$PWD/valkey.log"
sleep 1 && valkey-cli -p 18479 ping
Expected output
valkey-9.0.7-jammy-x86_64.tar.gz: OK
PONG

03. Step 1: A shared counter that races

Start with the simplest shared design, a fixed window of 50 requests per 60 seconds. Save store.py. connect() builds the limiter's client (step 5 explains its short timeouts). naive_fixed() reads the count, compares it with the limit and writes back count + 1. Ignore atomic_fixed() until step 2.

Python · store.py
"""Fixed-window limits kept in Valkey or Redis: a naive one and an atomic one."""

import redis
from redis.backoff import NoBackoff
from redis.retry import Retry

FIXED_WINDOW = """
local n = redis.call('INCR', KEYS[1])
if n == 1 then
  redis.call('EXPIRE', KEYS[1], ARGV[1])
end
return n
"""


def connect(port: int = 18479, timeout: float = 0.05) -> redis.Redis:
    """A client for the limiter path: short timeouts and no hidden retries."""
    return redis.Redis(host='127.0.0.1', port=port, socket_timeout=timeout,
                       socket_connect_timeout=timeout, retry=Retry(NoBackoff(), 0))


def naive_fixed(r: redis.Redis, key: str, limit: int, window: int) -> bool:
    count = int(r.get(key) or 0)  # 1. read the count
    if count >= limit:
        return False
    r.set(key, count + 1, ex=window)  # 2. write it back; others may have written
    return True


def atomic_fixed(r: redis.Redis, key: str, limit: int, window: int) -> bool:
    # The store runs the whole script as one step. EVAL sends the script text on
    # every call; production code loads it once and calls EVALSHA instead.
    return r.eval(FIXED_WINDOW, 1, key, window) <= limit

Save burst.py, the test harness. It starts two processes, playing two application instances with their own connections; each sends 150 requests for one API key from 8 threads at the same moment. It imports the later modules only in bucket mode.

Python · burst.py
"""Two app instances (processes), 8 threads each, share one API key's limit.

python burst.py naive|atomic|bucket [--policy open|closed|local] [--reset] [--timing]
"""

import argparse
import multiprocessing as mp
import time
from concurrent.futures import ThreadPoolExecutor

from store import atomic_fixed, connect, naive_fixed

INSTANCES, THREADS, PER_INSTANCE = 2, 8, 150
LIMIT, WINDOW = 50, 60  # fixed window: 50 requests per 60 s
CAPACITY, RATE = 50, 0.2  # token bucket: 50 at once, then 1 token every 5 s


def make_decider(r, mode: str, policy: str | None):
    key = f'rl:{mode}:api-key-42'
    if mode == 'naive':
        return (lambda: naive_fixed(r, key, LIMIT, WINDOW)), None
    if mode == 'atomic':
        return (lambda: atomic_fixed(r, key, LIMIT, WINDOW)), None
    from bucket_store import token_bucket  # imported here: you write it in step 3
    if policy is None:
        return (lambda: token_bucket(r, key, CAPACITY, RATE)), None
    from guard import GuardedBucket  # written in step 4
    guard = GuardedBucket(r, CAPACITY, RATE, policy, INSTANCES)
    return (lambda: guard.allow(key)), guard


def instance(mode: str, policy: str | None, start_at: float, results) -> None:
    decide, guard = make_decider(connect(), mode, policy)  # own connections

    def timed(_: int) -> tuple[bool, float]:
        start = time.perf_counter()
        allowed = decide()
        return allowed, time.perf_counter() - start

    time.sleep(max(0.0, start_at - time.time()))  # both instances start together
    with ThreadPoolExecutor(THREADS) as pool:
        outcomes = list(pool.map(timed, range(PER_INSTANCE)))
    admitted = sum(allowed for allowed, _ in outcomes)
    errors = guard.errors if guard else 0
    results.put((admitted, errors, max(seconds for _, seconds in outcomes)))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('mode', choices=['naive', 'atomic', 'bucket'])
    parser.add_argument('--policy', choices=['open', 'closed', 'local'])
    parser.add_argument('--reset', action='store_true', help='delete the key first')
    parser.add_argument('--timing', action='store_true', help='print the slowest call')
    args = parser.parse_args()
    key = f'rl:{args.mode}:api-key-42'
    if args.reset:
        connect().delete(key)

    results = mp.Queue()
    start_at = time.time() + 0.5
    workers = [
        mp.Process(target=instance, args=(args.mode, args.policy, start_at, results))
        for _ in range(INSTANCES)
    ]
    for worker in workers:
        worker.start()
    rows = [results.get() for _ in workers]
    for worker in workers:
        worker.join()

    admitted = sum(row[0] for row in rows)
    errors = sum(row[1] for row in rows)
    label = f'{args.mode}, policy {args.policy}' if args.policy else args.mode
    print(f'{label}: sent {INSTANCES * PER_INSTANCE}, admitted {admitted}, '
          f'store errors {errors}')
    if args.mode != 'bucket':
        print(f'counter in the store: {int(connect().get(key))}')
    if args.timing:
        print(f'slowest decision: {max(row[2] for row in rows):.3f} s')
Terminal
python burst.py naive --reset
Illustrative output (the counter differs between runs; admitted stays far above 50)
naive: sent 300, admitted 300, store errors 0
counter in the store: 38

All 300 requests were admitted against a limit of 50, and 300 increments left a counter of 38 (three runs ended at 38, 39 and 38). This is a lost update: between one GET and its SET, other threads read the same value and write the same "count + 1":

How two increments become one
instance a                    instance b                    value in store
GET rl:naive:... -> 37                                      37
                              GET rl:naive:... -> 37        37
SET rl:naive:... 38                                         38
                              SET rl:naive:... 38           38 (one add lost)

The counter grows more slowly than the requests, never reaches 50, and nothing is rejected. A shared store is necessary but not sufficient (the shared-state lab shows the same race on PostgreSQL): the decision itself must happen inside the store, in one step.

04. Step 2: Make the check and the update one step

INCR adds one and returns the new value in a single command, so no other client can slip in between; compare after incrementing. The counter also needs an expiry so that it disappears when the window ends, and sending INCR and EXPIRE as two calls has a trap. Try it, imagining that the instance crashes after the first command:

Terminal
valkey-cli -p 18479 INCR rl:demo:leak
valkey-cli -p 18479 TTL rl:demo:leak
Expected output
(integer) 1
(integer) -1

A time to live (TTL) of -1 means "no expiry": the key stays until someone deletes it, and once it passes the limit it is rejected for good. The fix is one Lua script for both commands. The Valkey documentation says the server runs a script atomically: while it runs, all other server activity is blocked.

Terminal
valkey-cli -p 18479 EVAL "local n = redis.call('INCR', KEYS[1])
  if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end return n" 1 rl:demo:safe 60
valkey-cli -p 18479 TTL rl:demo:safe
Expected output
(integer) 1
(integer) 60

atomic_fixed() in store.py runs this script, FIXED_WINDOW. Run the same burst through it:

Terminal
python burst.py atomic --reset
Expected output
atomic: sent 300, admitted 50, store errors 0
counter in the store: 300

Exactly 50 of 300 were admitted. The counter reads 300 because rejected requests increment it too, which is harmless since the key expires with its window. Because a script blocks the server, keep scripts short: a sliding log of thousands of timestamps per key makes every other client wait.

05. Step 3: A token bucket on the store's clock

A burst of 50 and then one request every 5 seconds is a token bucket with capacity 50 and a rate of 0.2 tokens per second. Save bucket_store.py. The script reads the tokens and the last update time from a hash, refills, decides and writes back in one atomic step. Two details matter in a fleet:

  • Whose clock? The script asks the store for the time with TIME. If each instance passed its own clock, differences between machines would become wrongly added or missing tokens.
  • When can the key go? PEXPIRE deletes an idle bucket after capacity / rate seconds, 250 here, exactly the time a full refill takes. A deleted bucket and a full bucket give the same answer, so idle keys cost no memory.
Python · bucket_store.py
"""A token bucket kept in Valkey or Redis and updated by one atomic script."""

import redis

TOKEN_BUCKET = """
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local t = redis.call('TIME')  -- the store's clock, the same for every instance
local now = tonumber(t[1]) + tonumber(t[2]) / 1000000
local saved = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(saved[1]) or capacity
local ts = tonumber(saved[2]) or now
tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate)
local allowed = 0
if tokens >= 1 then
  tokens = tokens - 1
  allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000))
return allowed
"""


def token_bucket(r: redis.Redis, key: str, capacity: float, rate: float) -> bool:
    return r.eval(TOKEN_BUCKET, 1, key, capacity, rate) == 1
Terminal: one burst, wait 10 seconds, another burst
python burst.py bucket --reset && sleep 10 && python burst.py bucket
Expected output
bucket: sent 300, admitted 50, store errors 0
bucket: sent 300, admitted 2, store errors 0

The first burst used the 50 tokens. Ten seconds later, 10 × 0.2 = 2 tokens had dripped in, and exactly 2 more requests passed. This is the check the skill's practice task asks for: observed against capacity + rate × elapsed time. On a machine slow enough that a burst lasts over 5 seconds, one more token can arrive during it.

06. Step 4: Decide what happens when the store is down

Now the limiter depends on a server that can fail. Save guard.py. When the store call raises any Redis error (refused, timed out, a read-only replica after a failover, a busy script), GuardedBucket follows a policy chosen in advance: open admits, closed rejects, and local falls back to a LocalBucket holding this instance's share (capacity and rate divided by the number of instances). Every fallback is counted: a limiter that silently stopped limiting is an incident nobody sees.

Python · guard.py
"""What the limiter does when the store cannot answer: a policy chosen in advance."""

import threading
import time

import redis

from bucket_store import token_bucket


class LocalBucket:
    """A per-instance fallback that holds this instance's share of the limit."""

    def __init__(self, capacity: float, rate: float) -> None:
        self.capacity, self.rate = capacity, rate
        self.tokens, self.last = capacity, time.monotonic()
        self.lock = threading.Lock()  # many threads share one instance

    def allow(self) -> bool:
        with self.lock:
            now = time.monotonic()
            gained = (now - self.last) * self.rate
            self.tokens = min(self.capacity, self.tokens + gained)
            self.last = now
            if self.tokens < 1:
                return False
            self.tokens -= 1
            return True


class GuardedBucket:
    def __init__(self, r: redis.Redis, capacity: float, rate: float,
                 policy: str, instances: int) -> None:
        self.r, self.capacity, self.rate = r, capacity, rate
        self.policy = policy  # 'open', 'closed' or 'local'
        self.local = LocalBucket(capacity / instances, rate / instances)
        self.errors = 0
        self.lock = threading.Lock()

    def allow(self, key: str) -> bool:
        try:
            return token_bucket(self.r, key, self.capacity, self.rate)
        except redis.RedisError:  # down, hanging, read-only after failover, busy...
            with self.lock:
                self.errors += 1  # export this as a metric and alert on it
            if self.policy == 'open':
                return True
            if self.policy == 'closed':
                return False
            return self.local.allow()
Terminal: stop the store, then try each policy
valkey-cli -p 18479 shutdown nosave
for p in open closed local; do python burst.py bucket --policy $p; done
Expected output
bucket, policy open: sent 300, admitted 300, store errors 300
bucket, policy closed: sent 300, admitted 0, store errors 300
bucket, policy local: sent 300, admitted 50, store errors 300

Each policy is right somewhere. Fail open keeps the API available and gives up protection during the outage; Stripe's write-up wants requests to keep flowing if its limiter code or Redis fails. Fail closed turns a store outage into an API outage, acceptable only when admitting too much is worse: spending money, sending messages, calling a fragile partner. Local fallback keeps an approximate limit, here 25 per instance. It assumes requests spread evenly and a known instance count; AWS describes dividing a quota by the number of servers and notes that it breaks when a client's traffic reaches only some of them.

07. Step 5: A store that hangs is worse than one that is down

A stopped server refuses connections at once. A stuck or cut-off server answers nothing, and the client waits. Simulate that by pausing the process with SIGSTOP:

Terminal: restart, pause, and run with timing
valkey-server --port 18479 --bind 127.0.0.1 --save '' --appendonly no \
  --daemonize yes --pidfile "$PWD/valkey.pid" --logfile "$PWD/valkey.log"
sleep 1 && kill -STOP "$(cat valkey.pid)"
python burst.py bucket --policy open --timing
python burst.py bucket --policy local --timing
Illustrative output (the counts are exact; the times depend on your machine)
bucket, policy open: sent 300, admitted 300, store errors 300
slowest decision: 0.063 s
bucket, policy local: sent 300, admitted 50, store errors 300
slowest decision: 0.061 s

Most decisions gave up after about 0.05 s, the timeout set in connect() (a busy machine adds scheduling delay), and the policy took over. Now try the library's defaults: save default_client.py and run it while the store is paused (it takes about a minute).

Python · default_client.py
"""How long does a client with the library's default settings wait for the store?"""

import time

import redis

r = redis.Redis(host='127.0.0.1', port=18479)  # default timeouts and retries
start = time.perf_counter()
try:
    r.ping()
    print('PONG')
except redis.RedisError as err:
    print(f'{type(err).__name__}: {err}')
print(f'gave up after {time.perf_counter() - start:.1f} s')
Terminal
python default_client.py
Illustrative output (redis-py 8.1.0; about 4 s when the store is stopped instead)
TimeoutError: Timeout connecting to server
gave up after 59.8 s

redis-py 8.1.0 waits up to 5 seconds per attempt and retries up to 10 times with backoff: reasonable for a cache read, disastrous for a limiter in front of every request. Check your client's defaults, give the limiter path its own short timeout and no hidden retries, and let the policy decide. Then resume and stop the store:

Terminal
kill -CONT "$(cat valkey.pid)"
valkey-cli -p 18479 shutdown nosave
deactivate

08. Check your understanding

Practice check · 3 questions

Shared limits under failure

Three scenarios about crashes, clocks and shares of a limit.

Q1. An older version of the fixed-window limiter sent `INCR` and then, in a separate call, `EXPIRE` when the count was 1. One instance crashed between those two calls while creating the counter for API key `k7`. What happens to `k7` from then on?
Q2. A teammate changes the token-bucket script to use a time passed in by each instance (`time.time()`) instead of `TIME`. Instance B's clock runs 30 seconds behind instance A's, and requests for one key alternate between A and B. What happens?
Q3. A service without a shared store enforces each API key's 600 requests per minute by giving each of its 6 instances a local limit of 100 per minute. A customer's batch client opens one long-lived HTTP/2 connection, and the load balancer keeps that whole connection on one instance. What does the customer see?
Practice only: not graded, not saved, not evidence.

09. Apply it

Now do the skill's practice task with real instances: wrap token_bucket in a small HTTP service (Python's http.server is enough) that answers 200 or 429, start it on two ports, and point concurrent clients at both. Report:

  1. The configured limit and the expected maximum, capacity + rate × test duration, next to the observed number of 200 responses for one key.
  2. The same run with a deliberate race: the naive fixed window, and how far over the limit it went.
  3. The behaviour while the store is stopped and paused, for the policy you chose, with the latency you measured and why the policy fits your API.

10. Review prompt

Without looking back: explain why the naive counter admitted all 300 requests, and why INCR alone is not enough without the expiry in the same step. Say why the token-bucket script reads the store's clock and why its expiry equals the full refill time. Then compare fail open, fail closed and a local fallback, name one API where each fits, and explain why a store that hangs needs a different setting than a store that is down.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check