Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 43

Rate Limiting with Token Bucket and Sliding Window

This lesson is built with resources from youtube.com, systemsdesign.cloud and 1 more site.

Hello! Welcome to the next lesson in our module on Distributed Systems Building Blocks.

In our last session, we explored data replication strategies, focusing on how to ensure data remains available and durable in the face of failures. We discussed the trade-offs between leader-follower, multi-leader, and leaderless architectures. Today, we shift our focus from protecting data to protecting the services themselves. How do we ensure our systems remain available and performant when faced with an overwhelming number of requests?

This brings us to our learning outcome for this lesson: Design rate limiting systems using algorithms like token bucket and sliding window log.

For a Staff-level interview at a company like Google or Uber, a superficial understanding of these algorithms isn't sufficient. You are expected to treat this as a complete system design problem. We will therefore dissect the architectural choices, scalability challenges, and fault-tolerance strategies involved in building a robust, distributed rate limiter.

1. Framing the Problem: Requirements and Placement

Before diving into algorithms, a crucial first step in any system design interview is to define the problem's scope and requirements. A rate limiter's primary goal is to protect backend services from being overwhelmed.

Design a Distributed Rate Limiter w/ a Ex-Meta Staff Engineer: System Design Breakdown

To start, let's watch this segment from a video by an ex-Meta Staff Engineer. It does an excellent job of defining what a rate limiter is and establishing the functional and non-functional requirements you'd be expected to clarify in an interview.

Watch from the beginning of the problem discussion at 01:41 to the end of the requirements section at 11:52. Pay close attention to: The distinction between functional requirements (the 'what') and non-functional requirements (the 'how'). The importance of asking about scale (e.g., 1 million requests per second). The key non-functional requirements for a rate limiter: availability over consistency, low latency, and scalability.

As the video highlighted, the core requirements are:

  • Functional:
    1. Identify clients (by user ID, IP, API key).
    2. Limit requests based on configurable rules.
    3. Return a specific error (HTTP 429 Too Many Requests) with informative headers when a limit is exceeded.
  • Non-Functional:
    1. Low Latency: The rate limiting check must be extremely fast to avoid adding noticeable delay to user requests.
    2. Scalability: The system must handle a massive volume of requests.
    3. High Availability: The rate limiter should be fault-tolerant.
    4. Accuracy: The system should enforce limits precisely.

Architectural Placement: Where Does the Rate Limiter Live?

With the requirements set, the next critical decision is where to place the rate limiter in your system's architecture. This choice has significant implications for latency, flexibility, and the information available for making limiting decisions.

High-Level Design: Where should we place the rate limiter?

The article accompanying the video we just watched provides a clear, text-based breakdown of the three main architectural placements. This is a fundamental trade-off discussion.

Read the section titled 'Where should we place the rate limiter?'. As you read, compare the three approaches: In-Process Rate Limiter: Why does this fail in a distributed environment? Dedicated Service Rate Limiter: What is the main drawback of this approach? API Gateway Rate Limiter: Why is this the most common and generally preferred approach for systems at scale?

To summarize the trade-offs:

Placement Pros Cons
In-Process Very low latency (no network calls). No global coordination; inaccurate in a distributed system.
Dedicated Service Global coordination, flexible rules using business logic. Adds significant latency (extra network hop for every request), new single point of failure.
API Gateway (Edge) Global coordination, protects all downstream services, low latency overhead. Limited context (only has access to request headers/info).

For our design, we'll adopt the API Gateway approach. It provides centralized protection without the significant latency penalty of a separate service call for every request, making it the standard for high-performance systems.


2. Core Algorithms: The "How"

Now we arrive at the engine of the rate limiter: the algorithm that decides whether to allow or reject a request. While there are several, your learning outcome specifically calls out Token Bucket and Sliding Window Log. We'll cover these and their common alternatives.

Rate Limiting Algorithms Overview
This image provides a useful visual summary of five common rate limiting algorithms, highlighting the core mechanics of each. Source: Linked to a public post on LinkedIn.

Let's break down the most important ones.

Design a Distributed Rate Limiter w/ a Ex-Meta Staff Engineer: System Design Breakdown

Let's return to the 'Hello Interview' video, which provides a concise comparison of the four most common rate limiting algorithms. This will give you the vocabulary to discuss their trade-offs effectively.

Watch the segment from 22:37 to 30:10. Focus on understanding the pros and cons of each method: Fixed Window Counter: Simple but suffers from the 'boundary effect'. Sliding Window Log: Perfectly accurate but memory-intensive. Sliding Window Counter: A memory-efficient approximation of the sliding window log. Token Bucket: Highly flexible, handling both sustained load and bursts. This is a very popular choice.

Let's focus on the two algorithms from your learning outcome.

Sliding Window Log

This algorithm provides perfect accuracy by tracking the exact timestamp of each request.

  • Mechanism: A log (e.g., a Redis Sorted Set) of timestamps is maintained for each user. When a request arrives:
    1. Remove all timestamps from the log that are older than the time window (e.g., > 60 seconds ago).
    2. Count the remaining timestamps in the log.
    3. If the count is less than the limit, add the new request's timestamp to the log and accept the request. Otherwise, reject it.
  • Pros: It's perfectly accurate and avoids the boundary issues of the fixed window counter.
  • Cons: It can be very memory-intensive, as you need to store a timestamp for every single request within the window for every user.

Token Bucket

This is one of the most widely used algorithms due to its flexibility and efficiency.

Token Bucket Algorithm Diagram
A visual representation of the Token Bucket algorithm. Tokens are added at a constant rate, and each request consumes a token. If the bucket is empty, requests are rejected. Source: GeeksforGeeks.
  • Mechanism: Each user has a "bucket" with two properties:
    1. A burst capacity (the maximum number of tokens the bucket can hold).
    2. A refill rate (how many tokens are added per second).
      When a request arrives, it consumes one token. If the bucket is empty, the request is rejected.
  • Pros: It naturally handles bursts of traffic (up to the bucket's capacity) while enforcing a steady-state rate (the refill rate). It's also very memory-efficient, only requiring two values (current token count, last refill timestamp) per user.
  • Cons: The "read-modify-write" nature of checking and updating the bucket can introduce race conditions in a distributed environment, which we'll address next.

For a deeper dive into these algorithms, including Go code examples which you might find useful, the article "Design a Distributed Scalable API Rate Limiter" by The Algorists is an excellent resource. You can review sections on the Token Bucket (resource LINK, section 3) and Sliding Window Logs (resource LINK, section 6) algorithms.

We will proceed with the Token Bucket algorithm for our design, as it strikes an excellent balance for real-world systems.


3. Designing for Scale: A Distributed Implementation

Now for the Staff+ part of the interview. How do we build a rate limiter that is distributed, scalable, and fault-tolerant?

State Management and Race Conditions

In our distributed API gateway setup, multiple gateway instances serve requests. If each gateway kept its own in-memory token bucket for a user, the rate limit would be enforced inconsistently. We need a centralized data store. Given our low-latency requirement, an in-memory cache like Redis is the perfect choice.

However, this introduces a classic distributed systems problem: race conditions.

Design a Distributed Rate Limiter w/ a Ex-Meta Staff Engineer: System Design Breakdown

This is a critical concept. Watch how the presenter explains the implementation of the Token Bucket algorithm using Redis, identifies the race condition, and presents the solution.

Watch from 30:10 to 35:43. Focus on: The sequence of operations: fetch from Redis, calculate new tokens, check limit, update Redis. The race condition: What happens when two requests read the same token count before either has a chance to write the new count back? The solution: Using Lua scripting to make the entire read-modify-write cycle an atomic operation within Redis.

Handling this race condition correctly is a strong signal in an interview. A naive "get-then-set" approach is flawed. Using locks would serialize requests and kill performance. The correct, high-performance solution is to use atomic operations, which Redis provides via Lua scripts.

Scalability and Fault Tolerance

A single Redis instance can't handle 1 million requests per second; it becomes a bottleneck and a single point of failure. We need to distribute both the load and the data.

Design a Distributed Rate Limiter w/ a Ex-Meta Staff Engineer: System Design Breakdown

Finally, let's address the non-functional requirements of scalability and high availability. This final video segment covers sharding, failover, and latency optimization.

Watch from 39:25 to 49:32. This is packed with Staff-level concepts: Scaling (39:25): How do you partition the data across multiple Redis instances? Note the mention of Redis Cluster as the practical, off-the-shelf solution. Fault Tolerance (42:54): Understand the critical fail-open vs. fail-close trade-off. Why might a social network choose 'fail-close'? How do replicas prevent data loss and downtime? Latency (47:33): What are the key strategies to minimize latency, such as connection pooling and geographic distribution?

This brings all our concepts together into a robust design:

  1. Placement: An API Gateway at the edge of the network.
  2. Algorithm: Token Bucket, for its flexibility and efficiency.
  3. State Store: A distributed Redis cluster to hold the token bucket state.
  4. Scalability: The Redis cluster is sharded (partitioned) by a client identifier (e.g., user_id). This distributes the load. API gateways use consistent hashing (or the Redis Cluster client library) to route to the correct shard.
  5. Concurrency: Lua scripts are used to perform atomic read-modify-write operations on token buckets, preventing race conditions.
  6. Fault Tolerance: Each Redis shard has at least one replica. If a master node fails, a replica is automatically promoted. The system makes a fail-close decision during an outage to protect downstream services from cascading failure.
  7. Performance: Latency is minimized through connection pooling at the gateway and co-locating gateways and their corresponding Redis shards in the same geographic regions.

Conclusion

In this lesson, we designed a distributed rate limiting system, moving from high-level requirements to a detailed, scalable, and fault-tolerant implementation.

Key Takeaways:

  • It's a System Design Problem: A rate limiter isn't just an algorithm; it's a full-fledged distributed system requiring careful architectural choices about placement, state management, and failure modes.
  • Algorithm Trade-offs Matter: The Token Bucket algorithm is often preferred for its balance of efficiency and flexibility in handling bursty traffic. The Sliding Window Log offers perfect accuracy at the cost of higher memory usage.
  • Distribution Creates Challenges: In a distributed environment, you must solve for centralized state (Redis), race conditions (Lua scripting), scalability (sharding), and fault tolerance (replication and failover strategies).
  • Discussing Trade-offs is Key: For a Staff+ role, demonstrating your thought process around choices like API gateway placement, fail-open vs. fail-close, and the pros/cons of different algorithms is more important than arriving at a single "correct" answer.

Preview of the Next Lesson:
We've now seen how Redis can be used as a high-performance, replicated state store for our rate limiter. However, some distributed systems require even stronger guarantees about state consistency, especially when nodes need to agree on a sequence of operations. This is impossible to achieve with basic replication alone. In our next lesson, we will explore this problem and its solution: Explain the purpose of consensus protocols (e.g., Raft, Paxos) in maintaining state.