File tree Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Original file line number Diff line number Diff line change @@ -81,7 +81,7 @@ export default defineConfig({
81
81
{ "text" : "设计 Twitter" , "link" : "/grokking/chapter-7" } ,
82
82
{ "text" : "设计 YouTube 或 Netflix" , "link" : "/grokking/chapter-8" } ,
83
83
{ "text" : "设计自动完成建议" , "link" : "/grokking/chapter-9" } ,
84
- // { "text": "设计 API 速率限制器", "link": "/grokking/chapter-10" },
84
+ { "text" : "设计 API 速率限制器" , "link" : "/grokking/chapter-10" } ,
85
85
// { "text": "设计 Twitter 搜索", "link": "/grokking/chapter-11" },
86
86
// { "text": "设计网络爬虫", "link": "/grokking/chapter-12" },
87
87
// { "text": "设计 Facebook 的新闻订阅", "link": "/grokking/chapter-13" },
Original file line number Diff line number Diff line change 67
67
限流器将负责决定由API服务器处理的请求以及应予拒绝的请求。当新请求到达时,Web服务器首先会询问限流器该请求是被允许还是应当被限流。如果请求未被限流,则会将其传递给API服务器。
68
68
69
69
![ 图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 )
You can’t perform that action at this time.
0 commit comments