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;
}
댓글 0