Skip to content

Commit b7487ad

Browse files
committed
feat: chapter 10
1 parent 6d9d5d7 commit b7487ad

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

docs/.vitepress/config.mts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ export default defineConfig({
8181
{ "text": "设计 Twitter", "link": "/grokking/chapter-7" },
8282
{ "text": "设计 YouTube 或 Netflix", "link": "/grokking/chapter-8" },
8383
{ "text": "设计自动完成建议", "link": "/grokking/chapter-9" },
84-
// { "text": "设计 API 速率限制器", "link": "/grokking/chapter-10" },
84+
{ "text": "设计 API 速率限制器", "link": "/grokking/chapter-10" },
8585
// { "text": "设计 Twitter 搜索", "link": "/grokking/chapter-11" },
8686
// { "text": "设计网络爬虫", "link": "/grokking/chapter-12" },
8787
// { "text": "设计 Facebook 的新闻订阅", "link": "/grokking/chapter-13" },

docs/grokking/chapter-10.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,28 @@
6767
限流器将负责决定由API服务器处理的请求以及应予拒绝的请求。当新请求到达时,Web服务器首先会询问限流器该请求是被允许还是应当被限流。如果请求未被限流,则会将其传递给API服务器。
6868

6969
![图10-2](/grokking/f10-2.png)
70+
71+
## 8. 基本系统设计与算法
72+
以下是一个示例场景:我们希望为每位用户限制每分钟的请求数。在这种情况下,对于每个唯一用户,我们需要维护一个计数器(表示该用户已发出的请求数)以及一个时间戳(表示开始计数的时间)。我们可以使用哈希表来实现,其中“键”(key)是用户ID(UserID),而“值”(value)是一个包含计数(Count)和起始时间(Epoch Time)的结构。
73+
74+
假设我们的限流器允许每位用户每分钟最多3次请求。当新请求到来时,限流器将执行以下步骤:
75+
1. 如果哈希表中不存在该`UserID`
76+
- 插入此`UserID`记录
77+
-`Count`设为1
78+
-`StartTime`设为当前时间(归一化到分钟级别)
79+
- 允许该请求通过
80+
81+
2. 否则(如果哈希表中已存在该`UserID`记录):
82+
- 如果 `CurrentTime – StartTime >= 1 min`
83+
-`StartTime`重置为当前时间
84+
-`Count`设为1
85+
- 允许该请求通过
86+
87+
- 如果 `CurrentTime - StartTime < 1 min` 且:
88+
-`Count < 3` 时:
89+
-`Count`加1
90+
- 允许该请求通过
91+
-`Count >= 3` 时:
92+
- 拒绝该请求
93+
94+
![图10-3](/grokking/f10-3.png)

0 commit comments

Comments
 (0)