This is Go implement algorithms about ratelimiter.
The package can be installed as a Go module.
go get github.com/augustus281/ratelimiter
- Imagine a bucket that holds tokens.
- The bucket has a maximum capacity of tokens.
- Tokens are added to the bucket at a fixed rate (e.g., 10 tokens per second).
- When a request arrives, it must obtain a token from the bucket to proceed.
- If there are enough tokens, the request is allowed and tokens are removed.
- If there aren't enough tokens, the request is dropped.
- Imagine a bucket with a small hole in the bottom.
- Requests enter the bucket from the top.
- The bucket processes ("leaks") requests at a constant rate through the hole.
- If the bucket is full, new requests are discarded.
- Time is divided into fixed windows (e.g., 1-minute intervals).
- Each window has a counter that starts at zero.
- New requests increment the counter for the current window.
- If the counter exceeds the limit, requests are denied until the next window.
- Keep a log of request timestamps.
- When a new request comes in, remove all entries older than the window size.
- Count the remaining entries.
- If the count is less than the limit, allow the request and add its timestamp to the log.
- If the count exceeds the limit, request is denied.
- Keep track of request count for the current and previous window.
- Calculate the weighted sum of requests based on the overlap with the sliding window.
- If the weighted sum is less than the limit, allow the request.