Edge Cases, Failure Modes and Choosing an Algorithm

Edge Cases and Failure Modes

What to do when Redis is unavailable

OptionBehaviorWhen to use
Fail openAllow all requests when Redis is downBetter UX, risk of abuse during the outage
Fail closedReject all requests when Redis is downProtects 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-After header: 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

AlgorithmMemoryAccuracyBurstComplexityBest for
Fixed WindowO(1)Moderate — 2× burst at boundaryYeslowInternal services, coarse limits
Sliding Window LogO(limit)ExactNo extramediumLow-volume, high-accuracy (payments)
Sliding Window CounterO(1)High — ≤0.003% errorNo extramediumHigh-scale APIs
Token BucketO(1)HighConfigurablemediumUser-facing APIs with burst tolerance
Leaky BucketO(1)HighSmoothedmediumProtecting 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.