Protect system from DDoS or abnormal user requests.
# Basics
# Fixed Window
Reset Counter
# Slide Window
Multiple Window
# Leaky Bucket
Buffer requests in a queue
# Token Bucket
Buffer tokens in a queue, request try to get token
# Requirements
# Functional Requirements
- limit number of requests
- error on single server / cluster
# Non-functional requirements
- Highly available
- Performance
# Estimation
# Memory Estimation
Key:{LastTime,CurrentTokenCount}
Key={service}:{resource}:{uid}
Let’s assume we are keeping all of the data in a hash-table. Let’s say we have a structure of key-value pair. The key would be the hash value of user ID, and the value would be a structure of count and startTime, e.g., UserId {Count, StartTime}
Now, let’s assume ‘UserID’ takes 8 bytes and 2 bytes for ‘Count,’ which can count up to 65k, which is sufficient for our use case. Although the end time will need 4 bytes, we can store only the minute and second parts. The hour part is not necessary if we are not considering a window of an hour. Now, it will take 2 bytes. So, we need a total of 12 bytes to store a user’s data.
Now, if our hash-table has an overhead of 20 bytes for each record and we need to track 1 million users at any time, the total memory we need would be :
# Domain Model
# Single Server
Persistence: DB
# Service In Cluster
Availability: Multiple Rate Limiter Instances, DB Cluster
Performance: Cache, In-Mem DB
Lock: Lock-free Redis, Distributed Lock
# Practical
Redis+lua分布式限流器 固定窗口法
Redis+lua分布式限流器 令牌桶法
1 | |