本文根据educative课程整理的学习笔记,侵删
题目
设计限流服务(限制范围:集群内的某个API),根据用户请求数量来限制用户请求
难度:easy
核心考点:几种限流算法
限流算法的目的就是T时间内控制事件数量不超过N,如果超过N则拒绝;
结论:从限制准确性和存储成本两个角度,我们选用了方案3,带计数器的滑动窗口算法;
1. 朴素计数器
- 维护一个计数器count和起始时间startTime,count表示[startTime … curTime]的请求数;startTime过期后,重新设置startTime,并重置count;
假定一个user限制每分钟请求3次;我需要维护一个hash,key=userID,value={count, startTime};收到一个请求后,rate limiter有如下步骤
`# step 1
if userID not in hash:
hash[userID] = {
1, current_time}
accept req
# step 2
`if userID in hash and current_time - hash[userID].startTime >= 1m