Rate Limiting

Rate limiting is the process of controlling the number of requests a user or client can make to an API within a specified timeframe.

Without it, a single malicious user (or a poorly written loop in a client application) could overwhelm your servers, drain your database connections, and cause a total outage for all other users (a Denial of Service).

[!TIP] ELI5: The Bouncer and the Nightclub Imagine a nightclub (Your API) that can safely hold 500 people. A giant party bus arrives with 2,000 people. If they all rush the door, the club is destroyed. The Bouncer (The Rate Limiter) stands at the door with a clicker. He enforces a strict rule: "Only 10 people from this bus can enter per minute. The rest of you have to wait." The club remains safe and functional.

1. Where to Implement It?

Rate limiters are almost never implemented directly within the application code of a microservice. They are placed at the edge of your network:

If a user exceeds the limit, the server immediately returns an HTTP 429: Too Many Requests response.

2. Rate Limiting Algorithms

There are several standard algorithms used to implement rate limiting, each with different performance and fairness trade-offs. (These are very common interview questions).

1. Token Bucket

The most common and elegant algorithm (used by Amazon and Stripe).

2. Leaky Bucket

3. Fixed Window Counter

4. Sliding Window Log

3. Distributed Rate Limiting (Redis)

If you have 5 API Gateway servers, how do they share the rate limit counter? If User A hits Server 1, and then Server 2, they both need to know the user's current limit.

The solution is an extremely fast, centralized in-memory store like Redis. The API Gateways check Redis before allowing the request through. To avoid the network latency of hitting Redis for every single request, gateways often use complex eventual consistency models or local memory batching.