AI Hints
Home›System Design Tutorial›Shortener Design and More
System Design · Lesson 95 of 120

Rate Limiter Service

A shared limiter.

⏱ 2 min read▶ Video at 1:54:55🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Earlier, we built a token bucket in one process. But Shoply has twenty API servers. If each keeps its own count, a user could get twenty times their limit. The limiter needs a shared memory.

Rate Limiter Service
From the video: Rate Limiter Service
  • Twenty API servers
  • Separate counts don't work
  • Share the state

A shared limiter

The usual design puts the counters in Redis. When a request arrives, the gateway runs a small atomic script in Redis, that refills and takes a token in one step. If a token was available, the request goes on. If not, the gateway answers four two nine straight away.

  1. Request
  2. Gateway
  3. Atomic Redis script
  4. Token? Continue
  5. No token: 429
A shared limiter
From the video: A shared limiter

Design details

A few details matter. The update must be atomic, or two servers could take the last token at the same time. Keys should expire, so idle users don't use memory. If Redis is unreachable, decide whether to fail open, allowing traffic, or fail closed. And put limits in config, so they change without deploys.

keyvalue
Atomicrefill + take in one step
Expiring keysidle users cost nothing
Redis downfail open or closed?
Configchange limits live

Summary

A shared rate limiter keeps counters in Redis, updated atomically, so every server sees the same limit. Next, a bigger case study. A chat app.

Key takeaways
  • Counters in Redis
  • Atomic updates
  • Choose fail open or closed
Next up: Chat App: Requirements — messages in real time