Edge Cases, Failure Modes and Choosing an Algorithm
Edge Cases and Failure Modes
What to do when Redis is unavailable
| Option | Behavior | When to use |
|---|---|---|
| Fail open | Allow all requests when Redis is down | Better UX, risk of abuse during the outage |
| Fail closed | Reject all requests when Redis is down | Protects downstream, hurts legitimate users |
func (tb *TokenBucket) Allow(ctx context.Context, userID string) (bool, int64, error) {
allowed, remaining, err := tb.allow(ctx, userID)
if err != nil {
// Fail open: log the error, allow the request
log.Printf("rate limiter redis error: %v — failing open", err)
return true, -1, nil
}
return allowed, remaining, nil
}A third option: circuit breaker with local fallback. When Redis fails, switch to a per-process fixed-window counter. Crude, but it limits blast radius.
Rate limit headers
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 42
X-RateLimit-Reset: 1718534400 # unix timestamp when the window resets
Retry-After: 30 # seconds to wait (on 429 response)func WriteRateLimitHeaders(w http.ResponseWriter, limit, remaining int64, reset time.Time) {
w.Header().Set("X-RateLimit-Limit", strconv.FormatInt(limit, 10))
w.Header().Set("X-RateLimit-Remaining", strconv.FormatInt(remaining, 10))
w.Header().Set("X-RateLimit-Reset", strconv.FormatInt(reset.Unix(), 10))
}
func WriteRetryAfter(w http.ResponseWriter, retryAfter time.Duration) {
w.Header().Set("Retry-After", strconv.Itoa(int(retryAfter.Seconds())))
w.WriteHeader(http.StatusTooManyRequests)
}The thundering herd on window reset
Every user who hit the limit in window N will retry simultaneously at window N+1's start — because X-RateLimit-Reset handed them all the same synchronization point. That creates a spike at every window boundary.
- Jitter the
Retry-Afterheader:reset + rand(0, window/10). - Use a sliding window — no shared reset boundary.
- Use token bucket — blocked users aren't all waiting for the same moment.
Key expiry and the counter-resurrection bug
T=0s: User sends 100 requests. Key "rl:fw:user_42:0" = 100. TTL set to 60s.
T=59s: User sends 1 request. Key = 101 (over limit, rejected). TTL refreshed to 60s.
T=118s: Key expires.
T=119s: User sends 100 more requests — fresh window.Choosing an Algorithm
| Algorithm | Memory | Accuracy | Burst | Complexity | Best for |
|---|---|---|---|---|---|
| Fixed Window | O(1) | Moderate — 2× burst at boundary | Yes | low | Internal services, coarse limits |
| Sliding Window Log | O(limit) | Exact | No extra | medium | Low-volume, high-accuracy (payments) |
| Sliding Window Counter | O(1) | High — ≤0.003% error | No extra | medium | High-scale APIs |
| Token Bucket | O(1) | High | Configurable | medium | User-facing APIs with burst tolerance |
| Leaky Bucket | O(1) | High | Smoothed | medium | Protecting downstream services |
Default recommendation:Token bucket for user-facing APIs (burst tolerance is user-friendly), sliding window counter when you need O(1) memory with near-exact accuracy, leaky bucket when the thing behind the limiter needs a steady input rate.