Sub topic 15
When the limiter's store is down: fail open or fail closed
Prerequisites
This chapter assumes you have read the earlier chapters on distributed state and atomic updates. You should know how a limiter keeps counters or buckets in a shared store such as Redis, and how application servers call that store on every request. You should also be comfortable with Python and basic HTTP status codes.
The problem
A distributed limiter adds a network dependency to every request. The store can fail in several ways:
- The Redis node crashes or is being restarted.
- A network partition separates some application servers from the store.
- The store is up but slow, so calls take longer than the request can afford.
- A failover promotes a replica that has stale or missing counters.
- The store is out of memory and rejects writes.
In each case the limiter cannot answer "is this request allowed?" from its shared state. It must still return an answer. There are two basic policies.
- Fail open means allow the request when the limiter cannot decide. Availability is preferred over protection.
- Fail closed means reject the request when the limiter cannot decide. Protection is preferred over availability.
Neither policy is correct in general. The right choice depends on what the limiter protects and what a wrong decision costs.
When to fail open
Fail open when the limiter exists to improve quality of service, not to enforce a hard rule. Typical cases:
- Protecting a service against accidental overload from well-behaved clients. If the limiter is down, the service usually still handles normal traffic.
- Public read endpoints where an outage of the limiter would otherwise take down the whole product.
- Limits that are a courtesy, such as a generous per-user cap.
The risk is that a limiter outage can coincide with abusive traffic. A failed-open limiter gives an attacker unlimited access exactly when the protection is missing. If the backend behind the limiter cannot survive that traffic, the outage spreads.
When to fail closed
Fail closed when allowing an unchecked request is more harmful than rejecting a legitimate one. Typical cases:
- Login and password reset endpoints, where unlimited attempts enable credential stuffing.
- Endpoints that send SMS or email, or call a paid third-party API, where each request costs real money.
- Quotas with contractual or billing meaning.
- Backends that are known to collapse under unthrottled load.
The risk is that the limiter becomes a single point of failure. A Redis outage then looks like a full outage to your users, even though the application itself is healthy.
Comparing the policies
| Aspect | Fail open | Fail closed |
|---|---|---|
| User impact during outage | Requests keep working | Requests rejected, often including legitimate ones |
| Abuse exposure | Unlimited while the store is down | None beyond the last known state |
| Protects the backend | No | Yes |
| Typical use | General APIs, read traffic | Auth, costly operations, billing |
| Error returned | None | 503 Service Unavailable, not 429 |
A rejected request during an outage is not the client's fault. Return 503, not 429, and include Retry-After if you can estimate recovery. Using 429 would tell well-behaved clients that they sent too many requests and might trigger the wrong back-off behavior or support tickets.
A middle path: local fallback
You rarely have to choose between the two extremes. A common design falls back to an in-process limiter when the shared store is unavailable. Each application server enforces its own limit with a local token bucket from the earlier chapters.
The local limit is less accurate. With N servers, the effective global limit becomes up to N times the per-server limit, unless you divide the global limit by the number of servers. It is still much better than no limit. Choose a conservative local limit, because you do not know how traffic is spread across servers.
The sketch below wraps a shared limiter with a timeout, a local fallback, and a per-route policy. It uses the TokenBucket class from the token bucket chapter for the local fallback.
import time
class TokenBucket:
"""Single-process token bucket. Not thread-safe."""
def __init__(self, capacity, refill_rate):
self.capacity = capacity
self.refill_rate = refill_rate
self.tokens = float(capacity)
self.last = time.monotonic()
def allow(self, cost=1):
now = time.monotonic()
elapsed = now - self.last
self.last = now
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
if self.tokens >= cost:
self.tokens -= cost
return True
return False
class StoreUnavailable(Exception):
pass
class ResilientLimiter:
"""Asks a shared limiter first; on failure applies a configured policy."""
def __init__(self, shared_allow, policy="fallback", local_capacity=5, local_rate=1):
# shared_allow(key) -> bool, raises StoreUnavailable on error or timeout
self.shared_allow = shared_allow
self.policy = policy # "open", "closed", or "fallback"
self.local = TokenBucket(local_capacity, local_rate)
self.degraded_count = 0
def check(self, key):
"""Returns (allowed, degraded)."""
try:
return self.shared_allow(key), False
except StoreUnavailable:
self.degraded_count += 1
if self.policy == "open":
return True, True
if self.policy == "closed":
return False, True
return self.local.allow(), True
def broken_store(key):
raise StoreUnavailable("connection timed out")
limiter = ResilientLimiter(broken_store, policy="fallback", local_capacity=3, local_rate=1)
print([limiter.check("alice") for _ in range(5)])
print("degraded decisions:", limiter.degraded_count)The first three calls are allowed by the local bucket and the last two are rejected. Every result carries degraded=True, so the caller can log it and expose it as a metric.
Timeouts matter more than the policy
A dead store is the easy case, because connections fail fast. A slow store is harder. If each limiter call blocks for 30 seconds, requests pile up, worker threads are exhausted, and the application fails even though your policy says "fail open".
Follow these rules:
- Set a short timeout on the limiter call, usually a few milliseconds to tens of milliseconds. The limiter sits on the hot path, so its budget should be a small fraction of the request budget.
- Set a connection timeout separately from the read timeout.
- Use a circuit breaker. After several consecutive failures, skip the store for a short period and go straight to the failure policy. This avoids paying the timeout on every request, and it gives the store room to recover.
- Probe the store again with a small number of requests before closing the breaker, so a recovering store is not hit by the full traffic at once.
Recovery and the state gap
When the store comes back, its state may be empty or stale. This causes two edge cases.
- Empty counters. After a restart without persistence, every client appears to have a full bucket. Clients that were throttled just before the outage get a fresh burst. Under a token bucket this is bounded by capacity, so the effect is usually acceptable.
- Thundering herd. Clients rejected during a fail-closed outage retry together when it ends. Return a
Retry-Aftervalue with some random jitter, and encourage clients to back off exponentially.
Replication adds another gap. If you read from a replica, or promote one after a failover, recent writes may be missing. Counters can then undercount for a short time. Accept that for approximate limits. For strict quotas, write to the primary and treat a failover as a store failure.
Choosing per route, not per system
One global failure policy is usually the wrong design. Declare the policy next to each limit, as part of the limit policy discussed in earlier chapters.
| Route | Limit purpose | Policy on store failure |
|---|---|---|
| `GET /products` | Overload protection | Fail open |
| `POST /login` | Brute-force defense | Fail closed or local fallback |
| `POST /sms/send` | Cost control | Fail closed |
| `GET /api/search` | Fair use | Local fallback |
Write these choices down and review them with the people who own the affected endpoints. Many teams discover during an outage that nobody decided what the limiter should do.
Observe degraded mode
A limiter that silently fails open is dangerous because nothing looks wrong. Always record degraded decisions.
- Count store errors and timeouts as a separate metric, labeled by policy.
- Alert when the degraded rate is above zero for more than a short period.
- Log the policy applied, not only the error.
- Test the failure path on purpose. Stop the store in a staging environment, or inject faults, and confirm that each route behaves as documented.
Summary
Every distributed limiter needs an explicit answer to "what happens when the store cannot answer?" Fail open favors availability and risks unprotected backends. Fail closed favors protection and turns a store outage into a user-visible outage. A local fallback sits between them and is often the best default. Whichever you pick, bound the call with a short timeout, use a circuit breaker, choose the policy per route, return 503 rather than 429 for system-caused rejections, and monitor degraded decisions.
Exercise
Your service has two endpoints: POST /password-reset, which sends an email, and GET /articles, a cached read endpoint. Redis, which holds your limiter state, goes down. Which failure policy would you choose for each endpoint, what status code would a rejected request receive, and why?
Show answer
For POST /password-reset, use fail closed or a conservative local fallback. Unchecked requests could be used to spam users with emails and abuse the reset flow, and each one has a real cost. For GET /articles, use fail open. The data is cached and cheap to serve, and rejecting readers because of a limiter outage would cause more harm than allowing the extra traffic. Requests rejected because the limiter is unavailable should receive 503 Service Unavailable, ideally with Retry-After, not 429, because the client did not exceed any limit.
Exercise
A limiter is configured to fail open, and the Redis call has no timeout. Redis becomes very slow, and the application stops responding even though the limiter "should" allow everything. What went wrong, and what two changes fix it?
Show answer
The failure policy only runs when the call raises an error. Without a timeout, each request waits on the slow store, so worker threads are exhausted and the application stalls. Fix it by adding a short timeout to the limiter call so a slow store becomes an error, and by adding a circuit breaker so that after repeated failures requests skip the store and go straight to the failure policy.