Rate Limiting Algorithms: A Deep Dive
The Fixed Window Counter
The simplest approach: you allow 100 requests per minute. You use a Redis key user_1:minute_45. The flaw? A user can make 100 requests at 12:45:59, and another 100 requests at 12:46:01. They just hit your server 200 times in 2 seconds, entirely bypassing the spirit of the rate limit. This is the "boundary condition" problem.
The Sliding Window Log
To fix the boundary problem, you track the exact timestamp of every single request in a Redis Sorted Set. When a new request comes in, you delete all timestamps older than 60 seconds, and count what is left. It is perfectly accurate, but terrible for performance and memory, as you have to store thousands of timestamps per user.
The Sliding Window Counter
The industry standard hybrid. You track the total requests in the previous minute and the current minute. You then calculate a weighted average based on how many seconds into the current minute you are. It requires incredibly low memory (just two numbers per user) while almost entirely eliminating the boundary spike problem. This is what Cloudflare uses at scale.