medium.com 5 min read Original Source

System Design Interview: How Would You Implement an API Rate Limiter in a Distributed Environment?

Most engineers hear the question and immediately answer:

“Store request counts in Redis.”

That’s not wrong.

But it’s only the beginning.

In a real system design interview, once you mention Redis, the interviewer starts asking tougher questions:

  • What happens when requests hit different servers?
  • Why not store counters in memory?
  • Which rate-limiting algorithm would you choose?
  • How do you handle bursts?
  • What happens when Redis fails?
  • How do you rate limit across regions?
  • Should the API Gateway enforce limits or individual services?

Let’s walk through a realistic interview discussion.

Full story for non-members | E-Books on Java/Microservices/Springboot | Whatsapp Group

Short video explanation at instagram — <>

The Question

Aadvik: Imagine your public API suddenly receives 100,000 requests per second.

Some requests come from legitimate customers.

Others come from bots, scrapers, or abusive clients.

How would you implement rate limiting in a distributed environment?

Priya: Before discussing implementation, I’d like to clarify the goal.

Rate limiting isn’t primarily about blocking users.

It’s about protecting shared resources and ensuring fair usage.

Without rate limiting, a single client could consume capacity that should be available to thousands of other users.

Aadvik: Fair enough.

What’s the simplest implementation?

Priya: A fixed window counter.

For example:

100 requests per minute
100 requests per minute

Every request increments a counter.

Once the counter reaches 100, subsequent requests are rejected.

Aadvik: Sounds simple.

How would you implement that?

Priya: Something like:

counter++;
counter++;

and reject requests when:

100″ data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

counter > 100
counter > 100

within the current minute.

Aadvik: Would that work in production?

Priya: Not in a distributed system.

Aadvik: Why?

Priya: Because requests don’t always hit the same server.

Imagine:

If each server maintains its own counter:

Server 1:

100 requests
100 requests

Server 2:

100 requests
100 requests

Server 3:

100 requests
100 requests

The client has effectively made:

300 requests
300 requests

while every server believes the limit is still:

100 requests
100 requests

The rate limit is no longer accurate.

Shared State

Aadvik: How do we solve that?

Priya: The counters must live in a shared datastore.

Most commonly Redis.

Every request updates the same counter regardless of which server handles it.

Now all instances share a consistent view of usage.

Fixed Window Problems

Aadvik: Great.

Let’s assume:

100 requests per minute
100 requests per minute

using a fixed window.

Any issues?

Priya: Yes.

Boundary problems.

Suppose a user sends:

100 requests at 12:00:59
100 requests at 12:00:59

and then:

100 requests at 12:01:01
100 requests at 12:01:01

They’ve effectively sent:

200 requests
200 requests

within two seconds.

Yet both windows technically respect the limit.

Aadvik: So the limit is correct but still unfair.

Priya: Exactly.

That’s one reason many systems move beyond fixed windows.

Sliding Window

Aadvik: What’s the next improvement?

Priya: Sliding Window.

Instead of measuring usage in discrete windows, we continuously evaluate activity over the last minute.

This removes abrupt boundary effects.

However, it introduces new challenges.

Aadvik: Such as?

Priya: Storage and computation.

To implement an exact sliding window, we need timestamps for every request.

At large scale:

100,000 requests/sec
100,000 requests/sec

that becomes expensive.

Token Bucket

Aadvik: Which algorithm do large systems typically prefer?

Priya: Token Bucket.

It’s one of the most widely used algorithms because it supports bursts while still enforcing long-term limits.

Aadvik: Explain how it works.

Priya: Imagine every client owns a bucket.

Tokens are added continuously.

For example:

10 tokens per second
10 tokens per second

Every request consumes one token.

If the bucket is empty:

Why Is Token Bucket Popular?

Aadvik: Why is this better?

Priya: Because it allows controlled bursts.

Suppose:

Bucket Capacity = 100
Refill Rate = 10/sec
Bucket Capacity = 100
Refill Rate = 10/sec

If a client hasn’t made requests recently, the bucket fills.

When traffic suddenly spikes:

100 requests
100 requests

can be served immediately.

After that, requests are constrained by the refill rate.

This provides a better user experience than abruptly rejecting every burst.

Redis Implementation

Aadvik: How would you implement Token Bucket using Redis?

Priya: Redis gives us two important things:

  1. Shared state
  2. Atomic operations

The bucket state can be stored as:

userId
tokensRemaining
lastRefillTimestamp
userId
tokensRemaining
lastRefillTimestamp

Each request:

  1. Calculates how many tokens should have been added.
  2. Updates the bucket.
  3. Consumes a token.
  4. Accepts or rejects the request.

All within a Lua script.

Aadvik: Why Lua?

Priya: Atomicity.

Without Lua:

Read Bucket
Update Bucket
Write Bucket
Read Bucket
Update Bucket
Write Bucket

can suffer race conditions.

Multiple requests may consume the same token.

Lua ensures the entire operation executes atomically.

The Hot Key Problem

Aadvik: Let’s say one API key generates 50,000 requests per second.

Any concerns?

Priya: Definitely.

Now Redis becomes a bottleneck.

Every request is updating the same key.

This creates a hot key.

The rate limiter itself becomes the scaling bottleneck.

Aadvik: How would you address that?

Priya: Options include:

  • Sharding
  • Local token caches
  • Hierarchical rate limiting
  • Gateway-level enforcement

The exact solution depends on traffic characteristics.

Where Should Rate Limiting Live?

Aadvik: Should every microservice implement rate limiting?

Priya: Usually no.

I prefer enforcing limits at the edge.

The gateway rejects abusive traffic before it reaches internal services.

This saves compute, database connections, and network bandwidth.

Multi-Tenant Limits

Aadvik: Let’s make it more realistic.

Suppose we offer plans.

Free:

100 req/min
100 req/min

Pro:

1000 req/min
1000 req/min

Enterprise:

Unlimited
Unlimited

How would you support that?

Priya: The bucket parameters become configurable.

For example:

Free
Capacity = 100
Refill = 100/min
Pro
Capacity = 1000
Refill = 1000/min
Free
Capacity = 100
Refill = 100/min
Pro
Capacity = 1000
Refill = 1000/min

Different users simply receive different bucket configurations.

The algorithm remains identical.

Redis Failure

Aadvik: What happens when Redis goes down?

Priya: That’s an important operational decision.

We have two options.

Fail Closed

Redis Down
Reject Requests
Redis Down
Reject Requests

Protects the platform.

But impacts availability.

Fail Open

Redis Down
Allow Requests
Redis Down
Allow Requests

Maintains availability.

But risks abuse.

Aadvik: Which would you choose?

Priya: For customer-facing APIs, most businesses prefer fail-open for a short period.

An outage caused by the rate limiter itself is usually worse than temporarily allowing extra traffic.

Multi-Region Challenge

Aadvik: Let’s say we’re running in:

  • US-East
  • Europe
  • Asia

How does rate limiting work now?

Priya: Now we’re balancing consistency against latency.

A globally consistent counter increases latency.

Regional counters improve performance but sacrifice perfect accuracy.

Many systems accept slight inaccuracies in exchange for lower latency.

Lets Conclude

Aadvik: Summarize your design.

Priya:

  1. Enforce limits at the API Gateway.
  2. Use Redis for shared distributed counters.
  3. Prefer Token Bucket for burst handling.
  4. Use Lua scripts for atomic updates.
  5. Support plan-specific bucket configurations.
  6. Monitor for hot keys.
  7. Decide fail-open versus fail-closed behavior.
  8. Consider regional tradeoffs in global deployments.

The goal isn’t preventing users from calling APIs.

The goal is ensuring that every user gets a fair share of platform resources while protecting the system from abuse.

Interview Summary

Most engineers think rate limiting is:

counter++
counter++

In reality, large-scale rate limiting is about:

  • Fairness
  • Distributed state
  • Atomicity
  • Bursty traffic
  • Failure handling
  • Global consistency

The algorithm is only one part of the solution.

The real challenge is making it work reliably across hundreds of servers, millions of users, and multiple regions.

_Liked this deep dive story? If Yes Please 👏 Clap(50) | 📤 Share | _🔔 Follow

Below is a collection of all related stories in one place

List: 15 System Design Interview Scenarios | Curated by Arvind Kumar | Medium
15 System Design Interview Scenarios · 15 System Design Interview Scenarios which are absolute must if you are going…