How-To Guide

How to Build a Rate Limiter in Node.js

Choose a rate-limiting algorithm, implement an atomic Redis token bucket, return correct headers, and test the boundary without blocking legitimate users.

On this page

  1. Introduction
  2. Choose an algorithm
  3. Design the key
  4. Make the counter atomic
  5. Return useful responses
  6. Decide failure behavior
  7. Apply the limit at the right layer
  8. Test the boundary
  9. Common pitfalls
  10. Conclusion

Introduction

A rate limiter protects a service from abusive clients, accidental retry storms, and runaway integrations. It is also a product policy: how many requests a user may make, what happens when the limit is exceeded, and whether the limit is shared across instances. A limiter that increments an in-memory counter in each process is easy to write and wrong as soon as the service scales horizontally.

This tutorial builds a token-bucket limiter for a Node.js API using Redis. It covers algorithm choice, atomicity, key design, response headers, failure behavior, and tests. The examples use TypeScript, but the concepts apply to any runtime.

Choose an algorithm

A fixed-window counter allows N requests per calendar window. It is simple and cheap, but it allows up to 2N requests across a window boundary: a client can send N requests at the end of one minute and N at the start of the next.

A sliding-window log stores timestamps and removes old entries. It is accurate but uses memory proportional to the number of requests. A sliding-window counter approximates the log with a few buckets, trading precision for memory.

A token bucket stores a number of tokens that refills at a steady rate up to a capacity. Each request consumes a token; when the bucket is empty, the request is rejected or queued. It allows short bursts up to the capacity and enforces a long-term average. That behavior fits HTTP APIs well: a user may burst a few requests, but cannot sustain an unbounded rate.

Choose the algorithm from the product requirement, not from the implementation convenience. If the policy says “10 requests per minute,” a fixed window is easier to explain but has the boundary burst. If it says “5 requests per second with a burst of 20,” a token bucket expresses it directly.

Design the key

The key determines who shares a limit. Common choices are an IP address, an authenticated user id, an API key, a tenant, and a route. Combine dimensions when needed, for example rl:user:42:POST:/orders. Including the method and route prevents one expensive endpoint from consuming the limit for a cheap one.

Do not trust a client-supplied identity header. Derive the key from the authenticated session or a validated API key. For IP-based limits, configure the framework’s proxy trust to the exact number of trusted hops; trusting every X-Forwarded-For lets a client choose its own key. If the service runs behind a shared NAT, an IP limit can affect many unrelated users; use it as a coarse abuse control, not a precise user quota.

Keep keys short and bounded. Hash long identifiers if necessary. Avoid putting secrets in keys because Redis keys may appear in monitoring and debugging output.

Make the counter atomic

A read-modify-write sequence in application code races: two requests can both read the same token count and both decide to allow. Redis provides atomic commands, and a Lua script can combine refill and consume in one operation.

-- KEYS[1] = bucket key
-- ARGV[1] = capacity, ARGV[2] = refill tokens per second,
-- ARGV[3] = now in milliseconds, ARGV[4] = requested tokens
local capacity = tonumber(ARGV[1])
local refill = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])

local data = redis.call('HMGET', KEYS[1], 'tokens', 'updated')
local tokens = tonumber(data[1]) or capacity
local updated = tonumber(data[2]) or now

local elapsed = math.max(0, now - updated) / 1000
tokens = math.min(capacity, tokens + elapsed * refill)

local allowed = 0
if tokens >= requested then
  tokens = tokens - requested
  allowed = 1
end

redis.call('HSET', KEYS[1], 'tokens', tokens, 'updated', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / refill * 1000) + 1000)

return { allowed, tokens }

The script returns whether the request is allowed and the remaining tokens. It also sets a TTL so idle buckets expire. Run it with EVAL or EVALSHA through the Redis client. The script must be deterministic and must not read external state; Redis replicates it consistently.

For a simpler fixed-window limiter, INCR plus EXPIRE is atomic enough when the expiry is set on the first increment. The Lua approach is more code but supports token-bucket semantics and returns a meaningful remaining count.

Return useful responses

A rejected request should receive 429 Too Many Requests, a Retry-After header in seconds, and rate-limit headers such as RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset. The exact header names vary by convention; choose one and document it. Do not return 500 for a client quota.

function rateLimitHeaders(tokens: number, capacity: number, retryAfter: number) {
  return {
    'Retry-After': String(Math.max(1, Math.ceil(retryAfter))),
    'RateLimit-Limit': String(capacity),
    'RateLimit-Remaining': String(Math.max(0, Math.floor(tokens))),
  };
}

The body should be small and machine-readable, for example { "error": "rate_limited" }. Do not reveal internal thresholds or other tenants’ usage. Log the key at a sampled rate and include the route and limit, but avoid storing raw IP addresses indefinitely if privacy rules require minimization.

Decide failure behavior

Redis can be unavailable. The limiter must have a documented failure policy. Failing open preserves availability but removes protection during an outage; failing closed protects the resource but can take down the API. Many teams fail open for general traffic and fail closed for sensitive endpoints such as login or password reset.

Add a local fallback limiter only if its semantics are understood: a per-process limit is not the same as the global limit. Monitor Redis errors, limiter latency, and the rejected-request rate. A limiter that adds 50 milliseconds to every request has become a performance problem.

Apply the limit at the right layer

Edge or gateway limits protect the whole system and reject abusive traffic before it reaches application code. Per-route or per-user limits enforce product quotas and cost controls. They are complementary. A gateway IP limit does not replace a per-account quota, and a per-account quota does not stop a distributed attack from many accounts.

Keep health checks and static assets out of the limiter. Apply stricter limits to expensive or unauthenticated operations and looser limits to cheap reads. Rate limiting often pairs with request size limits, timeouts, and load shedding; it controls request rate, not concurrency or payload size.

Test the boundary

Test the exact limit: the Nth request succeeds and the N+1th returns 429 with a positive Retry-After. Test refill by advancing a fake clock or waiting a short interval. Test that different keys do not share a bucket, that an invalid identity fails as expected, and that Redis errors follow the documented policy.

test('allows the limit and rejects the next request', async () => {
  const key = 'test-user';
  for (let i = 0; i < 5; i++) {
    expect(await limiter.consume(key, 1)).toMatchObject({ allowed: true });
  }
  const rejected = await limiter.consume(key, 1);
  expect(rejected.allowed).toBe(false);
  expect(rejected.retryAfterSeconds).toBeGreaterThan(0);
});

Use a real Redis or a test container for the atomic script; mocking Redis can hide a non-atomic implementation. Clean up keys between tests so order does not matter. Add a concurrency test that fires many requests in parallel and asserts the total allowed count does not exceed the capacity.

Common pitfalls

  • Per-process counters. They do not enforce a global limit across instances.
  • Non-atomic read-modify-write. Concurrent requests can exceed the limit.
  • Trusting forwarding headers. A client can spoof its IP and bypass the limit.
  • No TTL. Buckets accumulate forever and leak memory.
  • Limiting only at the application. Abusive traffic still consumes application capacity.
  • No failure policy. A Redis outage either bypasses or breaks every request unpredictably.
  • Returning 500. Clients cannot distinguish a quota from a server bug.

Conclusion

A rate limiter is a policy plus an atomic counter. Choose an algorithm that matches the product requirement, derive the key from trusted identity, keep the counter in a shared store, return correct 429 responses, and decide explicitly what happens when the store is unavailable. Test the boundary and concurrency, not only a single allowed request. The result is a limiter that protects the service without silently blocking legitimate users or becoming a new bottleneck.

Sources: Redis rate limiting pattern, IETF RateLimit headers, OWASP API Security.

FAQ

Should I rate-limit by IP address?
Per-IP limits are easy but punish users behind a shared NAT and are spoofable if proxy headers are trusted incorrectly. Use authenticated user or API-key limits for critical quotas, and keep IP limits as a coarse abuse control.
Why use Redis for rate limiting?
Multiple application instances need a shared counter. Redis provides atomic increments and TTLs, so the limit applies across the fleet rather than per process.
What should happen if Redis is unavailable?
Decide per policy: fail open for low-risk traffic to preserve availability, or fail closed for sensitive endpoints. Log and alert on the failure, and document the choice.

Related Examples