Backend2025년 7월 22일2분 읽기

Rate Limiting 구현 — Token Bucket과 Sliding Window

YS
YoungSam
조회 1580

Token Bucket 알고리즘

class TokenBucket {
  constructor(private capacity: number, private refillRate: number) {}
  private tokens: number;
  private lastRefill: number;

  async consume(): Promise<boolean> {
    this.refill();
    if (this.tokens > 0) {
      this.tokens--;
      return true;
    }
    return false;
  }
}

Redis Sliding Window

async function rateLimit(key: string, limit: number, window: number) {
  const now = Date.now();
  const pipe = redis.pipeline();
  pipe.zremrangebyscore(key, 0, now - window * 1000);
  pipe.zadd(key, now, `${now}`);
  pipe.zcard(key);
  pipe.expire(key, window);
  const results = await pipe.exec();
  return results[2][1] <= limit;
}
Rate LimitingRedisAPI

댓글 0

아직 댓글이 없습니다.