API レート制限(DDoS 防御)
:LiTarget: 何のために?
無防備だと 429 連発でサービス停止 or 課金爆発。
:LiSparkle: どう実装する?
KV / Redis でカウンター。超過時 429 + Retry-After。
:LiCode: コード例
// Cloudflare KV版
async function checkRateLimit(key: string, limit = 60, windowSec = 60) {
const now = Math.floor(Date.now() / 1000);
const bucket = `rl:${key}:${Math.floor(now / windowSec)}`;
const cur = parseInt((await KV.get(bucket)) ?? '0', 10);
if (cur >= limit) return { ok: false, retryAfter: windowSec - (now % windowSec) };
await KV.put(bucket, String(cur + 1), { expirationTtl: windowSec * 2 });
return { ok: true };
}