Fixed Window Algorithm — Complete Time-Based Rate Limiting Guide
In this tutorial, you will learn about Fixed Window Algorithm. We cover key concepts, practical examples, and best practices to help you master this topic.
Fixed window algorithm counts requests within a fixed time interval (e.g., 100 requests per minute). At the end of each interval, the counter resets. It is the simplest Rate Limiting algorithm.
What You'll Learn
You'll learn how fixed window works, its advantages, and the "traffic spike at window boundary" problem.
Why It Matters
Fixed window is easy to implement and understand. It works well for hourly/daily quotas where the boundary spike is acceptable. Many commercial APIs use fixed window for billing.
Real-World Use
A translation API allows 500,000 characters per month. The counter resets on the 1st of each month. This is a fixed window at monthly granularity.
flowchart LR
A[Minute 1: 100 requests] --> B[Counter = 100]
C[Next Request] --> D{Minute boundary?}
D -->|Yes| E[Reset Counter = 1]
D -->|No| F{Counter < 100?}
F -->|Yes| G[Increment Counter]
F -->|No| H[429 Deny]
Implementation
import time
from collections import defaultdict
class FixedWindow:
def __init__(self, limit, window_seconds):
self.limit = limit
self.window_seconds = window_seconds
self.counters = defaultdict(int)
self.window_starts = {}
def is_allowed(self, client_id):
now = int(time.time())
window_start = (now // self.window_seconds) * self.window_seconds
if self.window_starts.get(client_id) != window_start:
self.counters[client_id] = 0
self.window_starts[client_id] = window_start
if self.counters[client_id] >= self.limit:
return False
self.counters[client_id] += 1
return True
limiter = FixedWindow(limit=100, window_seconds=60)
client = "user_123"
for _ in range(101):
print(f"Allowed: {limiter.is_allowed(client)}")
Common Mistakes
| Mistake | Fix | |---------|-----| | Traffic spike at window boundary | Twice the limit at boundary | Use Sliding Window instead | | No memory cleanup | Memory leak over time | Clean up stale client entries | | Integer division for window | Timezone issues | Use UTC timestamps | | Global counter instead of per-client | All clients share a limit | Use per-client counters | | Window misalignment | Different servers have different Windows | Use shared clock (Redis) |
Practice Questions
- What is the boundary problem in fixed window?
- How would you implement a daily limit using fixed window?
- Why might you choose fixed window over sliding window?
- How do you clean up old entries?
- What is the memory usage of fixed window?
Challenge
Implement a fixed window rate limiter with Redis. Support 100 req/min and 10000 req/day. Track remaining requests and reset time.
What's Next
Learn about the sliding window algorithm.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro