Skip to content

Commit

Permalink
feat: chapter 10
Browse files Browse the repository at this point in the history
  • Loading branch information
honkinglin committed Dec 11, 2024
1 parent 6d9d5d7 commit b7487ad
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export default defineConfig({
{ "text": "设计 Twitter", "link": "/grokking/chapter-7" },
{ "text": "设计 YouTube 或 Netflix", "link": "/grokking/chapter-8" },
{ "text": "设计自动完成建议", "link": "/grokking/chapter-9" },
// { "text": "设计 API 速率限制器", "link": "/grokking/chapter-10" },
{ "text": "设计 API 速率限制器", "link": "/grokking/chapter-10" },
// { "text": "设计 Twitter 搜索", "link": "/grokking/chapter-11" },
// { "text": "设计网络爬虫", "link": "/grokking/chapter-12" },
// { "text": "设计 Facebook 的新闻订阅", "link": "/grokking/chapter-13" },
Expand Down
25 changes: 25 additions & 0 deletions docs/grokking/chapter-10.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,28 @@
限流器将负责决定由API服务器处理的请求以及应予拒绝的请求。当新请求到达时,Web服务器首先会询问限流器该请求是被允许还是应当被限流。如果请求未被限流,则会将其传递给API服务器。

![图10-2](/grokking/f10-2.png)

## 8. 基本系统设计与算法
以下是一个示例场景:我们希望为每位用户限制每分钟的请求数。在这种情况下,对于每个唯一用户,我们需要维护一个计数器(表示该用户已发出的请求数)以及一个时间戳(表示开始计数的时间)。我们可以使用哈希表来实现,其中“键”(key)是用户ID(UserID),而“值”(value)是一个包含计数(Count)和起始时间(Epoch Time)的结构。

假设我们的限流器允许每位用户每分钟最多3次请求。当新请求到来时,限流器将执行以下步骤:
1. 如果哈希表中不存在该`UserID`
- 插入此`UserID`记录
-`Count`设为1
-`StartTime`设为当前时间(归一化到分钟级别)
- 允许该请求通过

2. 否则(如果哈希表中已存在该`UserID`记录):
- 如果 `CurrentTime – StartTime >= 1 min`
-`StartTime`重置为当前时间
-`Count`设为1
- 允许该请求通过

- 如果 `CurrentTime - StartTime < 1 min` 且:
-`Count < 3` 时:
-`Count`加1
- 允许该请求通过
-`Count >= 3` 时:
- 拒绝该请求

![图10-3](/grokking/f10-3.png)

0 comments on commit b7487ad

Please sign in to comment.