AceDevHub
Advanced Node.js Interview QuestionsAdvancedScenario

Node.js · Question 98

How would you implement rate limiting in an Express API?

Direct answer

Apply express-rate-limit or @fastify/rate-limit globally and stricter on auth/waitlist routes — key by IP or userId, return 429 with Retry-After, store counters in Redis for multi-instance deploys.

Scenario: prevent waitlist spam and login brute force on public AceDevHub endpoints (Q79).

  • Global limit — 100 req/min per IP for API.
  • Strict routes — POST /courses/waitlist: 5/hour per IP.
  • Redis store — shared state across API replicas.
  • 429 response — { error: { code: 'RATE_LIMITED' } } + Retry-After.
scenario-rate-limit.mjs
import rateLimit from "express-rate-limit";
import RedisStore from "rate-limit-redis";
import { createClient } from "redis";

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

const apiLimiter = rateLimit({
  windowMs: 60_000,
  max: 100,
  standardHeaders: true,
  legacyHeaders: false,
  store: new RedisStore({ sendCommand: (...args) => redis.sendCommand(args) }),
});

app.use("/", apiLimiter);

app.post("/courses/waitlist", rateLimit({ windowMs: 3_600_000, max: 5 }), handler);