設計限流器 (Rate Limiter)

Medium★★★★★Draft

FromSystem Design Interview

Concepts practiced📐 回中信封估算 (Back-of-the-Envelope)⚡ 快取策略 (Caching Strategies)

Convention: read the requirements & constraints first, sketch your own design, then expand the reference to compare.

📚 From the Books

設計限流器 (Rate Limiter)ProblemMediumInfra & Platform

限制每個用戶/IP/API key 在時間窗內的請求數,保護後端不被打爆。難點在分散式環境下的準確計數與一致性

📋 Requirements

🧠 Core Ideas

TIP

演算法選一個(準確度 vs 記憶體 vs 突發容忍),計數狀態放共享存儲(通常 Redis),權衡一致性與效能。

⚖️ Reference Design

演算法比較
  • 固定窗 (Fixed Window):簡單,但窗邊界會放行 2 倍突發。
  • 滑動窗紀錄 (Sliding Log):精準,但每請求存時間戳,記憶體高。
  • 滑動窗計數 (Sliding Window Counter):用前一窗加權估算,準確度與成本折衷,常用
  • 令牌桶 (Token Bucket):容忍突發、平滑限速,雲服務常見。
分散式計數
  • 狀態集中放 Redis(INCR + EXPIRE);多 gateway 共享。
  • 競態:用 Lua script 或 Redis 原子操作避免 read-modify-write race。
  • 取捨:強一致計數成本高,多數場景接受少量超限(最終一致)。

🔑 Takeaways

✍️ My Notes

No notes yet — jot your takeaways or Q&A here.

📖 Further Reading

🔗 Dive Deeper