> For the complete documentation index, see [llms.txt](https://blog.byc1999.com/software/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://blog.byc1999.com/software/software/system-design/rate-limiter.md). Agents can also search and read this documentation through its [MCP server](https://blog.byc1999.com/software/~gitbook/mcp).

# Rate Limiter

## Leaky Bucket Algorithm

想像一個底部破洞的水桶，水會以固定的速度 (leak rate) 流出。

類比到 rate limit，leak rate 就是 server 回應的頻率，比如 10 req/sec，待處理的請求會被放在 queue 裡排隊，代處理的請求數量不能超過 bucket size，所以當超過時 server 必須拒絕請求。

#### 參數

* Leak rate
* Bucket size

#### 範例

下面是一個使用 Redis 實作的範例，這裡會用到的資料型態是 hash。由於通常請求是高度併發的，為了避免 race condition，會使用具有 atomic 性質的 LUA script 來撰寫：

```lua
local timestamp_sec = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local leak_rate = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])

local data = redis.call("HMGET", KEYS[1], "level", "last_timestamp_sec")
local level = tonumber(data[1]) or 0
local last_timestamp_sec = tonumber(data[2]) or timestamp_sec

local delta = math.max(timestamp_sec - last_timestamp_sec, 0)
local leaked = delta * leak_rate
local new_level = math.max(level - leaked, 0)

new_level = new_level + cost
if new_level <= capacity then
  redis.call("HSET", KEYS[1], "level", new_level, "last_timestamp_sec", timestamp_sec)
  redis.call("EXPIRE", KEYS[1], 3600)  -- default key ttl: 3600
  return {1, tostring(new_level), tostring(0)}
else
  local excess = new_level - capacity
  local retry_after = 0
  if leak_rate > 0 then
    retry_after = excess / leak_rate
  else
    retry_after = 1e9
  end
  redis.call("EXPIRE", KEYS[1], 3600)  -- default key ttl: 3600
  return {0, tostring(new_level), tostring(retry_after)}
end
```

#### 特色

* 短時間內有大量請求 (burst) 時須排隊，甚至會直接被拒絕。
  * Pros: 因為把 burst 平滑化，所以服務不容易過載。
  * Cons: 晚到的請求須花較長時間等待。
* 適用於服務需要穩定的請求量、不允許 burst 的情況。
* MQ system 就像是一個搭配 priority queue 的 leaky bucket。

## Token Bucket Algorithm

想像一個裝著 tokens 的桶子，每個請求都必須拿到 token，server 才會處理，否則就拒絕。

桶子裡的 token 會以一個固定速度 (refill rate) 增長，長到一個最大值 (bucket size) 後就會停止增長。

每個請求可以有不同的 cost，也就是消耗不同數量的 tokens。

#### 參數

* Refill rate
* Bucket size

#### 範例

下面是一個使用 Redis 實作的範例，這裡會用到的資料型態是 hash：

```lua
local key = KEYS[1]
local cost = tonumber(ARGV[1])
local timestamp_ms = tonumber(ARGV[2])
local capacity = tonumber(ARGV[3])
local refill_rate = tonumber(ARGV[4])

local data = redis.call("HMGET", key, "tokens", "timestamp_ms", "to_add_token_fraction")
local tokens = tonumber(data[1])
local last_timestamp_ms = tonumber(data[2])
local to_add_token_fraction = tonumber(data[3])

if tokens == nil or last_timestamp_ms == nil or to_add_token_fraction == nil then
    tokens = capacity
    to_add_token_fraction = 0
else
    local elapsed_time_ms = timestamp_ms - last_timestamp_ms
    local temp = elapsed_time_ms * refill_rate / 1000 + to_add_token_fraction
    local tokens_to_add = math.floor(temp)

    tokens = math.min(tokens + tokens_to_add, capacity)
    to_add_token_fraction = temp % 1
end

if tokens >= cost then
    tokens = tokens - cost
    redis.call(
        "HSET", key,
        "tokens", tokens,
        "timestamp_ms", timestamp_ms,
        "to_add_token_fraction", to_add_token_fraction
    )
    redis.call("EXPIRE", key, 3600)  -- default key ttl: 3600
    return 1
else
    redis.call(
        "HSET", key,
        "tokens", tokens,
        "timestamp_ms", timestamp_ms,
        "to_add_token_fraction", to_add_token_fraction
    )
    redis.call("EXPIRE", key, 3600)
    return 0
end
```

#### 特色

* 允許 burst，發生 burst 時不須排隊。
  * Pros: 晚到的請求不須花較長時間等待。
  * Cons: 較容易造成服務過載；無法防禦 DoS 攻擊。
* 相對於 leaky bucket，token bucket 更常被用來做 API rate limit，因為通常 API 服務要允許 burst。

## Fixed Window Counter Algorithm

將時間平均切分成固定長度 (window span) 的 windows，並規定每個 window 區間內最多可以處理多少請求 (window capacity)。當區間請求數量超過上限後就拒絕該 window 的後續請求。

#### 參數

* Window span（單位通常為秒或分鐘）
* Window capacity

#### 特色

在 window 與 window 間的邊界，最多可能會有 window capacity 兩倍的請求數量（所有請求都擠在前一個 window 的最後，和後一個 window 的開頭）。

## Sliding Window Log Algorithm

每次收到請求時，都 log 這個請求抵達的時間，同時計算最近若干時間 (window span) 已處理幾個請求，若數量沒有超過上限 (window capacity)，則拒絕新請求。

由於實務上 log 通常會定時用檔案儲存，但每次數 log 時都去讀檔案有點太慢了，所以通常會將最近的 log 存一份在 memory 裡。

#### 參數

* Window span（單位通常為秒或分鐘）
* Window capacity

#### 範例

下面是一個使用 Redis 實作的範例，這裡會用到的資料型態是 sorted set：

```lua
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])

local min_time = now - window

redis.call("ZREMRANGEBYSCORE", key, 0, min_time)

local count = redis.call("ZCARD", key)
if count < limit then
  redis.call("ZADD", key, now, now)
  return 1
else
  return 0
end
```

#### 特色

時間複雜度較高，因為每次收到請求時都要把上次 window 裡過舊的 log 移除，並數 queue 裡有幾條 log。

## Sliding Window Counter Algorithm

$$
weight = (1 - x%) \times previousWindowReqs + currentWindowReqs
$$

其中 x% 代表「目前 window 已經過了幾 % 的時間」。假設 window size 為每分鐘一個 window，那如果現在是 o 點 o 分三十秒，那 x% 就是 50%。

如果 $weight + 1 \leq windowCapacity$，則接受請求，否則拒絕。

#### 參數

* Window span（單位通常為秒或分鐘）
* Window capacity

#### 特色

這個做法在 fixed window counter algorithm 與 sliding window log algorithm 間取得了平衡，不會有最多兩倍 capacity 的流量，時間複雜度也不會太高。不過其實計算 weight 的公式只能用來估算，因為前一個 window span 的請求分佈狀況不一定是（通常不是）均勻的。

## 參考資料

* <https://www.youtube.com/watch?v=mQCJJqUfn9Y>
