一個要收費的 API,每個請求進來至少要回答四個問題:這是誰、他的 key 還有效嗎、他現在是不是打太快、這次要不要算錢。這篇照請求經過的順序,用 FastAPI 一段一段寫出來:發 key、驗 key、按客戶限流、記用量,最後是月底怎麼把用量交給計費系統。
程式在 FastAPI 0.162、Python 3.14 上跑過,資料庫的部分用 PostgreSQL 的 SQL 示意。
先決定格式,因為格式會影響後面每一步。我用的是這樣:
acme_live_ea5957e1_44702c1d40b36d4f7ecb68ba7425e34a
└──┬────┘ └──┬───┘ └──────────────┬───────────────┘
前綴 key_id secret
# keys.py
import hashlib
import re
import secrets
KEY_PREFIX = "acme_live"
KEY_PATTERN = re.compile(rf"{KEY_PREFIX}_([0-9a-f]{{8}})_([0-9a-f]{{32}})")
def hash_secret(secret: str) -> str:
return hashlib.sha256(secret.encode()).hexdigest()
def new_api_key() -> tuple[str, str, str]:
"""回傳 (完整 key, key_id, secret_hash)。完整 key 只給客戶看這一次,不進資料庫"""
key_id = secrets.token_hex(4) # 8 個字元,不是秘密,拿來查資料庫和在後台辨認
secret = secrets.token_hex(16) # 128 bits 隨機
full_key = f"{KEY_PREFIX}_{key_id}_{secret}"
return full_key, key_id, hash_secret(secret)
為什麼不直接用 UUID 當 key?可以,但 UUID 沒有 key_id 和 secret 的分界,查資料庫時只能拿整把 key(或它的雜湊)當索引,後台也只能顯示一段看不出意義的字串。拆開之後,key_id 可以明碼存、明碼顯示,secret 只存雜湊。
固定格式還有一個好處:用一條正規表示式就能先擋掉格式不對的東西,不用為了一個亂打的字串查資料庫。GitHub 的 token 格式更進一步,最後還帶一段檢查碼,打錯一個字元在本地就能判斷出來。
create table api_keys (
key_id text primary key,
customer_id bigint not null references customers (id),
secret_hash text not null,
created_at timestamptz not null default now(),
expires_at timestamptz,
revoked_at timestamptz
);
完整的 key 只在建立當下回傳給客戶一次,之後誰都拿不回來,弄丟就只能換一把新的。資料庫外洩時,攻擊者拿到的是 key_id 和 SHA-256,沒辦法拿去呼叫你的 API。
存密碼要用 bcrypt、Argon2 這種刻意很慢的雜湊,那為什麼 API key 用 SHA-256 就好?因為密碼是人想的,熵很低,慢雜湊是為了讓暴力猜測變貴;這裡的 secret 是 128 bits 隨機,本來就猜不到。反過來說,API key 每個請求都要驗一次,bcrypt 一次幾十到上百毫秒,等於每個請求白白多花這段時間。
如果想再多一層,可以把 sha256(secret) 換成 hmac.new(server_pepper, secret, "sha256"),pepper 放在環境變數不放資料庫。這樣只拿到資料庫的人,連「驗證自己猜的 key 對不對」都做不到。
換 key(rotation)的做法是發一把新的,同時給舊的設一個 expires_at,例如 24 小時後。客戶有一天的時間把新 key 部署出去,舊 key 才失效。
FastAPI 的 fastapi.security 有現成的 HTTPBearer 可以讀 Authorization: Bearer ...。我會把 auto_error 關掉,自己決定沒帶 key 時回什麼:
# app.py(節錄)
import hmac
import time
from dataclasses import dataclass
from fastapi import Depends, FastAPI, HTTPException, Request, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from keys import KEY_PATTERN, hash_secret
@dataclass
class KeyRecord:
customer_id: int
secret_hash: str
revoked: bool
requests_per_second: float
burst: int
KEY_CACHE_SECONDS = 30
_key_cache: dict[str, tuple[float, KeyRecord]] = {}
async def find_key(key_id: str) -> KeyRecord | None:
now = time.monotonic()
cached = _key_cache.get(key_id)
if cached and now - cached[0] < KEY_CACHE_SECONDS:
return cached[1]
record = await fetch_key_from_db(key_id) # SELECT ... FROM api_keys JOIN plans ... WHERE key_id = $1
if record is not None:
_key_cache[key_id] = (now, record)
return record
bearer = HTTPBearer(auto_error=False)
def unauthorized(code: str) -> HTTPException:
return HTTPException(status_code=401, detail=code, headers={"WWW-Authenticate": "Bearer"})
async def current_key(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Security(bearer),
) -> KeyRecord:
if credentials is None:
raise unauthorized("missing_api_key")
match = KEY_PATTERN.fullmatch(credentials.credentials)
if match is None:
raise unauthorized("invalid_api_key") # 格式不對,不查資料庫
key_id, secret = match.groups()
record = await find_key(key_id)
if record is None or record.revoked or not hmac.compare_digest(record.secret_hash, hash_secret(secret)):
raise unauthorized("invalid_api_key")
request.state.customer_id = record.customer_id # 第五節記用量時會用到
return record
這段裡每個選擇都有原因:
hmac.compare_digest 而不是 ==。 == 比字串時,遇到第一個不同的字元就停,理論上可以從回應時間推出前面對了幾個字元。compare_digest 不會因為遇到不同的字元就提早結束比較。WWW-Authenticate: Bearer。 HTTP 規範要求 401 回應帶這個標頭,有些用戶端函式庫也靠它判斷要怎麼重新認證。三種情況都回 401。沒帶 key 回 missing_api_key,格式不對或 key 不存在都回 invalid_api_key。前者幾乎都是客戶忘了設定,分開回比較好查;後者對呼叫方來說處理方式一樣,都是換一把正確的 key。
限流要按客戶,不是按 IP,也不是按 key。一個客戶可能從幾十台機器打你,也可能發了好幾把 key;反過來,好幾個客戶也可能躲在同一個公司出口 IP 後面。
用 token bucket:每個客戶一個桶,桶的容量是允許的突發量,以固定速率補 token,每個請求拿一個,拿不到就 429。
import math
@dataclass
class TokenBucket:
capacity: float
refill_per_second: float
tokens: float
updated_at: float
def take(self, now: float) -> float:
"""拿一個 token。拿到回 0,拿不到回還要等幾秒"""
elapsed = now - self.updated_at
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_per_second)
self.updated_at = now
if self.tokens >= 1:
self.tokens -= 1
return 0.0
return (1 - self.tokens) / self.refill_per_second
_buckets: dict[int, TokenBucket] = {}
async def rate_limited_key(key: KeyRecord = Depends(current_key)) -> KeyRecord:
now = time.monotonic()
bucket = _buckets.get(key.customer_id)
if bucket is None:
bucket = TokenBucket(key.burst, key.requests_per_second, key.burst, now)
_buckets[key.customer_id] = bucket
wait_seconds = bucket.take(now)
if wait_seconds > 0:
raise HTTPException(
status_code=429,
detail="rate_limited",
headers={"Retry-After": str(math.ceil(wait_seconds))},
)
return key
路由這樣用:
@app.post("/v1/generate")
async def generate(payload: dict, key: KeyRecord = Depends(rate_limited_key)):
...
或者整個 router 一起套:APIRouter(prefix="/v1", dependencies=[Depends(rate_limited_key)])。FastAPI 在同一個請求裡會快取依賴的結果,路由函式裡再 Depends(current_key) 也不會驗第二次。
一個客戶每秒 2 次、突發 3 次,連打 5 次的結果:
# 狀態 Retry-After body
0 422 - {"detail": "bad_input"}
1 200 - {"ok": true, "customer": 42}
2 200 - {"ok": true, "customer": 42}
3 429 1 {"detail": "rate_limited"}
4 429 1 {"detail": "rate_limited"}
第 0 次故意送壞掉的 body,一樣用掉一個 token。限流數的是「嘗試」,這是對的:它的目的是保護伺服器,壞請求也會吃資源。
這段有幾個容易踩的地方:
async def。 FastAPI 會把一般的 def 依賴丟到執行緒池裡跑,兩個請求就可能同時改同一個桶,讀到同一個 tokens 值,各扣一次卻只扣到一個。寫成 async def 而且裡面沒有 await,它就在 event loop 上一口氣跑完,不會被別的請求插隊。uvicorn --workers 4 或 gunicorn 開 4 個 worker,每個行程各自限流,客戶實際能打到的是 4 倍。可以把每個行程的速率除以 worker 數,或者把桶搬到 Redis,用一段 Lua script 原子地做「補 token、扣一個」。前者簡單但流量分布不均時會擋錯人,後者準但每個請求多一趟網路。限流數嘗試,計費數成功。客戶送了格式錯誤的請求、或者你的伺服器自己出了 500,都不該收他錢。所以要等回應出來、知道狀態碼之後才記。這裡用 middleware 拿到回應的狀態碼,再決定要不要記:
from collections import Counter
usage_by_minute: Counter[tuple[int, int]] = Counter()
@app.middleware("http")
async def record_usage(request: Request, call_next):
response = await call_next(request)
customer_id = getattr(request.state, "customer_id", None)
if customer_id is not None and response.status_code < 400:
minute = int(time.time() // 60) * 60
usage_by_minute[(customer_id, minute)] += 1
return response
request.state 底下其實是 ASGI scope 裡的同一個 dict,所以第三節在依賴裡設的 customer_id,這裡的 middleware 讀得到。被 401、429 擋下的請求根本沒設,或狀態碼大於等於 400,都不會被記。
每個請求寫一次資料庫太貴,所以先在記憶體裡按「客戶 × 分鐘」累加,每 60 秒批次寫一次:
create table usage_minutes (
customer_id bigint not null,
minute timestamptz not null,
count bigint not null,
primary key (customer_id, minute)
);
import asyncio
from contextlib import asynccontextmanager
UPSERT_USAGE = """
insert into usage_minutes (customer_id, minute, count)
values ($1, to_timestamp($2), $3)
on conflict (customer_id, minute) do update set count = usage_minutes.count + excluded.count
"""
async def flush_usage() -> None:
global usage_by_minute
batch, usage_by_minute = usage_by_minute, Counter()
if not batch:
return
rows = [(customer_id, minute, count) for (customer_id, minute), count in batch.items()]
try:
await db_pool.executemany(UPSERT_USAGE, rows) # asyncpg
except Exception:
usage_by_minute.update(batch) # 寫失敗就放回去,下一輪再試
raise
async def flush_forever() -> None:
while True:
await asyncio.sleep(60)
try:
await flush_usage()
except Exception:
logger.exception("flush usage failed")
@asynccontextmanager
async def lifespan(app: FastAPI):
task = asyncio.create_task(flush_forever())
yield
task.cancel()
await flush_usage() # 關機前把最後一批寫掉
app = FastAPI(lifespan=lifespan)
幾個設計上的取捨:
clear()。 batch, usage_by_minute = usage_by_minute, Counter() 在 event loop 上是一步完成的,寫資料庫這段時間進來的請求記到新的 Counter,不會被一起清掉。on conflict ... do update set count = count + excluded.count。 多台伺服器、多個 worker 寫同一個客戶同一分鐘,彼此加總,不會互相覆蓋。kill -9 或記憶體不足被系統砍掉時,記憶體裡還沒寫進資料庫的用量都會不見,也就永遠不會被計費。平常大約是最近一分鐘的量,但如果資料庫已經連續寫失敗好幾輪,放回 Counter 的用量會越積越多,丟的就不只一分鐘。這是批次寫入的代價,要嘛接受,要嘛縮短間隔、並且在寫入連續失敗時發警報。還有一個細節:middleware 拿到 response 時,串流回應(StreamingResponse)的 body 可能還沒送完。如果你在意「客戶中途斷線的串流要不要收錢」,要改寫成純 ASGI middleware,攔 http.response.body 的最後一個訊息。
帳期結束後,把每個客戶的用量加總:
select customer_id, sum(count) as quantity
from usage_minutes
where minute >= $1 and minute < $2
group by customer_id;
送去計費系統之前,先記一筆「這個客戶這個帳期已經送過了」:
create table usage_reports (
customer_id bigint not null,
period_start date not null,
quantity bigint not null,
sent_at timestamptz,
primary key (customer_id, period_start)
);
以 Stripe 的 Billing Meter 為例,一個客戶一個帳期送一筆 meter event:
import stripe
stripe.billing.MeterEvent.create(
event_name="api_requests",
payload={"stripe_customer_id": customer.stripe_customer_id, "value": str(quantity)},
identifier=f"usage-{customer.id}-{period_start:%Y-%m}",
timestamp=int(period_end.timestamp()) - 1,
)
identifier 讓 Stripe 擋掉短時間內的重送,Stripe 寫的去重保證是至少 24 小時。超過這段時間就不能假設重送還會被擋下,所以要靠自己的 usage_reports:送之前先寫一列,成功後填 sent_at,結算程式重跑時跳過已經送過的。timestamp 要落在那個帳期裡。沒填的話預設是送出當下,帳期結束後才送,就會被算進下一期。Stripe 只收 35 天內的時間戳,所以結算不能拖太久。invoice.created 時把草稿的自動定案時間往後延。客戶的帳期如果跟著 Stripe 訂閱走,period_start、period_end 要從訂閱資料拿,不能直接用日曆月。
上面這套,key 的發放和撤銷、限流、用量彙總、送 Stripe 和對帳,都要自己寫、自己維護。UsageRail 的 FastAPI 中介軟體是一個 ASGI middleware,在路由執行前檢查 key、限流和額度。一般的回應在送完時計數,SSE 則是在串流開始時先計一次,結束時再加上 track() 記的單位數。key 一樣只存 SHA-256 雜湊,完整 key 只在建立時顯示一次;SDK 在行程裡保存一份同步過來的 key 清單,所以已知的 key 不用每次連網路。2xx、3xx 算計費,4xx、5xx 和被擋下的請求不算;用量每 60 秒送一次,帳期結束後送進你自己的 Stripe 帳號,記在客戶的發票上。
import os
from fastapi import FastAPI, Request
from usagerail.fastapi import UsageRailMiddleware
app = FastAPI()
app.add_middleware(
UsageRailMiddleware,
app_key=os.environ["USAGERAIL_APP_KEY"],
auth="api-key",
)
@app.post("/v1/generate")
async def generate(request: Request):
result = await run_model(await request.json())
request.state.usagerail.track(result.tokens) # 選用:按 token 數計費,而不是按請求數
return result.body
它讀 Authorization: Bearer,沒有的話讀 x-api-key。如果你的 API 已經有自己的帳號或 key,也可以傳 auth="custom" 和一個 consumer 函式,只用它的限流和計費。各個選項和限制寫在 FastAPI 的 API key 與用量計費設定裡。
我在做 UsageRail,最後這一節講的是我們自己的產品;前面六節不依賴它,但都是節錄,要接進自己的專案,還得補上資料庫查詢、連線池和結算排程。