InterviewHubPRO
Section Overview
Q42

Question 42 of 60

Part 4: Express, Fastify, APIs & Middleware (36 - 50)

70%
Node.js & Libuv•Part 4: Express, Fastify, APIs & Middleware (36 - 50)

Rate Limiting Middleware with Redis.

In Simple Words: Tracks IP or API key hit count in Redis with a 60-second sliding expiration window. If count exceeds limit, returns HTTP 429 with Retry-After header.

javascript
async function rateLimiter(req, res, next) {
  const ip = req.ip;
  const requests = await redis.incr(ip);
  if (requests === 1) await redis.expire(ip, 60);
  if (requests > 100) {
    return res.status(429).json({ error: 'Too Many Requests', retryAfter: 60 });
  }
  next();
}