🚀 新規事業

rate-limit-defense

最終更新 2026年05月08日 / 40_新規事業/SCALE_Build/カタログ/基本装備集/rate-limit-defense.md

API レート制限(DDoS 防御)

何のために?

無防備だと 429 連発でサービス停止 or 課金爆発。

どう実装する?

KV / Redis でカウンター。超過時 429 + Retry-After。

コード例

// 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 };
}