Backend
15 min read
Verified

Rate Limit Explained: Algorithms, Redis & NestJS Implementation

Portrait of Jay Patel, Full Stack Developer

Jay Patel

Full Stack Developer

Diagram showing client requests passing through a NestJS rate limit guard, a Redis token bucket check, and ending in either a 200 response or a 429 response.
“A rate limit controls how many requests a client can send to an API in a set time. This guide explains the main algorithms, shows Redis rate limiting, and builds a production ready NestJS setup.”

A rate limit is a rule that caps how many requests a client can send to your API in a fixed time, such as 100 requests per minute. When a client goes over the limit, the server replies with HTTP 429 and refuses extra calls until the window resets. The most reliable way to enforce it in production is a token bucket or sliding window algorithm backed by Redis, added to NestJS through a guard.

This guide is written from the view of a backend developer who has to ship the feature, not just describe it. You will see how each algorithm behaves, why Redis rate limiting is the usual choice once you run more than one server, and how to connect plan limits from a database to a NestJS guard. You will also get a decision table, a before and after comparison, and the error handling you need when clients hit the limit. If you build APIs on Node.js, every part of this applies directly.

429

HTTP status code returned for too many requests

[Source]

4

Core rate limit algorithms compared in this guide

1

Atomic Lua script per request keeps the Redis limiter race free

What Is a Rate Limit in an API?

A rate limit in an API is a rule that sets the maximum number of requests a client may make during a time window. The client can be a user, an API key, an IP address, or a whole company account. Once the client reaches the cap, the server rejects new requests, usually with the 429 Too Many Requests status, and tells the client when to try again. This is the idea behind every API rate limit, from a free public API to a private call between two of your own services.

The terms around this idea get mixed up often. An API limiter is the code or gateway that enforces the rule. An API limit is the number itself, such as 60 requests per minute. A quota is a longer budget, such as 10,000 requests per month. Rate limits protect the short term health of your servers, while quotas protect billing and fair use over weeks.

API Limit Types: Per User, Per IP, and Per Endpoint

Choosing what to count is the first design decision. Each option below suits a different kind of traffic and a different level of trust.

  • Per IP address: Easy to add and works before login, but many people can share one IP behind an office or mobile network.
  • Per user ID or API key: Fair and precise, but it only works after the client is authenticated.
  • Per endpoint: Gives costly routes such as login, search, and report export a tighter limit than the rest of the API.
  • Per tenant: Common in SaaS products, where one customer should never use all the shared capacity.

In practice you mix them. A common setup is a loose per IP limit on every route, then a tighter per user limit on sensitive routes.

Why Is API Throttling Important?

API throttling protects your servers, database, and budget from traffic spikes, abusive clients, and simple coding mistakes. Here are the main problems it prevents.

  • Brute force attacks: Login and password reset routes need tight limits so nobody can try thousands of passwords.
  • Scraping: Limits make bulk data collection slow and costly.
  • Retry storms: A buggy client that retries in a loop can flood your service, and a limit caps the damage.
  • Unfair usage: One heavy client should not starve everyone else.
  • Runaway cost: Each request may cost database time, third party calls, or paid compute.

Many developers use the words throttling and rate limiting as if they mean the same thing, and in daily work they often do. Strictly, throttling in API design means slowing traffic down, for example by queueing or delaying requests, while a rate limit rejects requests above the cap. Many tools, including NestJS, use the name throttler for what is really a rejecting limiter. Both ideas protect the same thing, which is your capacity.

This matters more on Node.js than many people expect. Node runs your JavaScript on one main thread, so a burst of expensive requests, such as password hashing or large JSON parsing, can block everyone else. The guide on how Node.js works internally explains the event loop in plain terms. A limit at the edge keeps that thread free for real users.

How Does Rate Limiting Work?

Rate limiting works by counting each client's requests in a time window and rejecting any request that goes above the set limit.

  1. Identify the client with a key such as user ID, API key, or IP address.
  2. Build a storage key from that identity, the route, and the window.
  3. Read and update the counter, or the token balance, in fast storage.
  4. Compare the result with the limit for that client's plan.
  5. Allow the request, or return 429 with a Retry-After header.

The hard part is step one. If your app sits behind Nginx, a cloud load balancer, or a CDN, the IP address your code sees may belong to the proxy and not the user. Every user then shares one bucket, and the first busy minute blocks your whole customer base.

Rate Limit Response Headers Clients Can Use

A good limiter does not just say no. It tells the client what happened and when to return. Here is a response that does this well.

429-response.http
Plain text
HTTP/1.1 429 Too Many Requests Content-Type: application/json Retry-After: 12 X-RateLimit-Limit: 100 X-RateLimit-Remaining: 0 {"statusCode":429,"message":"Rate limit exceeded. Try again in 12 seconds.","retryAfter":12}

Retry-After is a standard header that tells the client how many seconds to wait. The X-RateLimit-Limit and X-RateLimit-Remaining headers are not formal standards, but most API clients and SDKs know them. A standards draft exists for new RateLimit header names, yet the X- version is still the one you will see most often today.

Common Rate Limiting Algorithms

There are four rate limit algorithms you will meet again and again. Each one trades accuracy, memory use, and burst handling in a different way, so the right pick depends on your traffic.

Fixed Window Algorithm

The fixed window algorithm counts requests inside a fixed slice of time, such as one minute. The key often includes the time slice, for example user:42:2026-11-29T10:05, and the counter resets when the next slice begins. It is very cheap because it needs one number per client.

The weakness is the window edge. If the limit is 100 per minute, a client can send 100 requests at 10:05:59 and another 100 at 10:06:00. That is 200 requests in two seconds, and your limiter allowed all of them. For internal tools this is fine, but for public APIs it can hurt.

Sliding Window Algorithm for Smoother Throttling in API Traffic

The sliding window algorithm fixes the edge problem by looking at the last 60 seconds from now, not at a fixed minute. The exact version, called a sliding window log, stores one timestamp per request in a Redis sorted set. It is accurate but uses more memory as traffic grows.

The cheaper version is the sliding window counter. It keeps two fixed window counts and blends them by how far you are into the current window. If you are 25 percent into the new minute, it counts 75 percent of the previous window plus all of the current one. The result is an estimate, but it is close enough for most throttling in API systems and costs very little memory.

Token Bucket Algorithm for Bursty Traffic

The token bucket algorithm gives each client a bucket that holds a fixed number of tokens. Every request spends one token, and the bucket refills at a steady rate, for example 5 tokens per second. If the bucket is empty, the request is rejected.

This design allows short bursts up to the bucket size, then enforces a steady average rate. Real users click fast, load a page that fires six calls at once, and then go quiet. Token bucket fits that behavior well, which is why it is my default for public APIs.

Leaky Bucket Algorithm for Steady Output

The leaky bucket algorithm puts requests in a queue and releases them at a constant rate, like water dripping from a small hole. If the queue is full, new requests overflow and are dropped. The output is smooth no matter how bursty the input is.

That makes it a strong choice when you protect a weak downstream system, such as an SMS provider or a payment gateway that cannot take bursts. The cost is latency, because queued requests wait their turn. For normal user facing APIs, most teams prefer to reject fast than to make users wait.

Infographic comparing fixed window and token bucket rate limiting, showing how fixed windows allow request bursts at time boundaries while token buckets control bursts through limited capacity and steady token refills.

Redis Rate Limiting Explained

Redis rate limiting stores counters or token balances in Redis so every app instance sees the same numbers. Redis fits this job because it is fast, runs commands atomically, and can expire keys on its own.

Using Redis for rate limiting solves the biggest flaw of in-memory limiters. Imagine three Node.js instances behind a load balancer, each with its own counter. A client with a limit of 100 can now send 300 requests, because each instance only sees one third of the traffic. A shared store removes that gap. Redis, NestJS, and Node.js are core parts of my backend skills, and this pattern is one I reuse on most projects.

Redis Rate Limit With INCR and EXPIRE

The simplest Redis rate limit is a fixed window built from two commands. You increase a counter, and on the first request you set its expiry.

src/rate-limit/fixed-window.ts
TypeScript
typescript const windowId = Math.floor(Date.now() / 60_000); const key = `rl:userId:{windowId}`; const count = await redis.incr(key); if (count === 1) { await redis.expire(key, 60); } const allowed = count <= 100;

This works, but it has a small flaw. If your process crashes between INCR and EXPIRE, the key never expires and slowly wastes memory. On Redis 7 you can send EXPIRE key 60 NX inside a transaction, or move the logic into a Lua script as shown below.

Atomic Token Bucket Script for a Distributed Rate Limiter

A distributed rate limiter needs every check to be atomic, which means no other request can slip in halfway. Redis runs a Lua script as one unit, so it is the cleanest way to do that. This script implements a token bucket and returns three values: allowed, tokens left, and seconds to wait.

src/rate-limit/token-bucket.lua
Plain text
local capacity = tonumber(ARGV[1]) local rate = tonumber(ARGV[2]) local t = redis.call('TIME') local now = t[1] * 1000 + math.floor(t[2] / 1000) local data = redis.call('HMGET', KEYS[1], 'tokens', 'ts') local tokens = tonumber(data[1]) local ts = tonumber(data[2]) if tokens == nil then tokens = capacity ts = now end tokens = math.min(capacity, tokens + ((now - ts) / 1000) * rate) local allowed = 0 local retry = 0 if tokens >= 1 then tokens = tokens - 1 allowed = 1 else retry = math.ceil((1 - tokens) / rate) end redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now) redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate) * 2000) return { allowed, math.floor(tokens), retry }

Notice that the script reads the time from Redis with TIME and does not trust the app server clock. Servers drift by a few milliseconds, and in a cluster of app instances that drift creates unfair results. The PEXPIRE line also cleans up idle clients, so memory stays flat even with millions of users.

Rate Limiting in Microservices

Rate limiting in microservices works best in two layers. The API gateway applies coarse limits per client, and each service adds its own protective limits on expensive routes.

The reason is simple. Services call each other, and one bug can create a retry storm that no gateway ever sees, because the traffic never leaves your network. A service level limit stops that storm at the door of the service being hit. If you are splitting a monolith and need help shaping this layer, it is a normal part of backend development work.

Distributed Rate Limiter Design With Shared Redis

A distributed rate limiter needs one shared state that every instance of every service can reach. Redis is the common choice, and the design rules are short. Use one key per script call, because in Redis Cluster all keys of a script must live in the same hash slot. Add a prefix per service so keys never collide. Keep Redis in the same region as your services, because every request now makes one extra network call.

You also need a plan for when Redis is down. Failing open means you allow traffic when the limiter breaks, so a Redis outage does not become a full API outage. Failing closed means you block traffic, which is safer for login and payment routes. Many teams choose per route, and keep a small in-memory limiter per instance as a backup layer.

Where to enforceGood forWatch out for
API gatewayPer client and per plan limits for all servicesCannot see internal service to service calls
Inside each serviceProtecting costly routes and shared databasesLimits can drift between teams
Both layersPublic APIs with many servicesMore config, so keep limits in one shared place

If your API uses GraphQL, count query cost and not request count, because one request can ask for a huge amount of data. The comparison of REST vs GraphQL shows why this difference matters.

How to Implement Rate Limiting in NestJS

NestJS rate limiting is easiest with the official @nestjs/throttler package, which adds a guard that counts requests per client. For apps that run on many instances, add a Redis store or write a custom guard like the one below.

If you are still choosing a framework, the comparison of NestJS vs Express.js covers the trade-offs. If you start from plain Express, the guide tobuilding a REST API with Node.js and Express is a good base before you add a limiter.

Project Structure for Production Rate Limiting

Keep limiter code in its own module so it is easy to test and reuse. This layout works well in real projects.

project-structure
Plain text
src/ rate-limit/ rate-limit.module.ts redis-rate-limit.guard.ts plans.service.ts token-bucket.lua.ts auth/ users/ app.module.ts

NestJS Rate Limiting With @nestjs/throttler

Start with the official package. It is quick to add and good enough for many apps.

snippet
Shell
bash npm install @nestjs/throttler
src/app.module.ts
TypeScript
import { Module } from '@nestjs/common'; import { APP_GUARD } from '@nestjs/core'; import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'; @Module({ imports: [ ThrottlerModule.forRoot([{ ttl: 60_000, limit: 100 }]), ], providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], }) export class AppModule {}

Older tutorials show ttl in seconds, but current versions expect ttl in milliseconds, so check your version before you copy an old snippet. You can override the limit on a single route with the @Throttle() decorator, and skip it for health checks with @SkipThrottle(). For several instances, the community package @nest-lab/throttler-storage-redis provides a Redis store so all servers share one counter.

Store Rate Limit Plans in a Database

Hard coded limits do not survive real products. Free users, paid users, and internal services all need different numbers, and product teams will want to change them without a deploy. Store the plans in your database and let the guard read them.

migrations/create_rate_limit_plans.sql
SQL
CREATE TABLE rate_limit_plans ( id SERIAL PRIMARY KEY, plan_name VARCHAR(30) UNIQUE NOT NULL, capacity INT NOT NULL, refill_per_second NUMERIC(8,2) NOT NULL ); INSERT INTO rate_limit_plans (plan_name, capacity, refill_per_second) VALUES ('free', 20, 0.5), ('pro', 100, 5), ('internal', 1000, 100);

Do not query this table on every request. Cache each plan in memory for about 60 seconds inside PlansService, so the database sees one read per plan per minute and not one read per call. Public write routes such as posting and commenting, like those in this social media backend API project, are the best places for per plan limits.

Custom Redis Guard With Plan Based Limits

This guard connects everything: the Lua script, the plan from the database, response headers, and safe error handling.

src/rate-limit/redis-rate-limit.guard.ts
TypeScript
import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable, Logger, } from '@nestjs/common'; import Redis from 'ioredis'; import { TOKEN_BUCKET_LUA } from './token-bucket.lua'; import { PlansService } from './plans.service'; @Injectable() export class RedisRateLimitGuard implements CanActivate { private readonly logger = new Logger(RedisRateLimitGuard.name); constructor( private readonly redis: Redis, private readonly plans: PlansService, ) {} async canActivate(context: ExecutionContext): Promise<boolean> { const http = context.switchToHttp(); const req = http.getRequest(); const res = http.getResponse(); const identity = req.user?.id ?? req.ip; const plan = await this.plans.getPlan(req.user?.plan ?? 'free'); const key = `rl:identity:{req.method}:${req.route?.path}`; try { const [allowed, remaining, retryAfter] = (await this.redis.eval( TOKEN_BUCKET_LUA, 1, key, plan.capacity, plan.refillPerSecond, )) as number[]; res.setHeader('X-RateLimit-Limit', plan.capacity); res.setHeader('X-RateLimit-Remaining', remaining); if (!allowed) { res.setHeader('Retry-After', retryAfter); throw new HttpException( { statusCode: 429, message: `Rate limit exceeded. Try again in ${retryAfter} seconds.`, retryAfter, }, HttpStatus.TOO_MANY_REQUESTS, ); } return true; } catch (error) { if (error instanceof HttpException) throw error; this.logger.error(`Limiter failed, allowing request: ${error.message}`); return true; } } }

The catch block is the part many tutorials skip. If Redis fails, the guard logs the error and lets the request through, which is the fail open choice discussed earlier. For a login route you would change that last return true to throw a 503 instead. Here is what changes once the guard is live.

ScenarioBefore (no limiter)After (Redis guard)
Login brute forceAttacker tries passwords as fast as the server answersAttacker gets 429 after the bucket empties
Client retry loopLoop floods the API and the databaseLoop gets 429 and Retry-After tells it to wait
One heavy tenantShared capacity drops for all customersHeavy tenant is capped by its plan
Redis outageNot applicableRequests pass and an error is logged

Express Rate Limit vs NestJS Throttler

If your project is on plain Express, the express-rate-limit package gives you an API limiter with very little code. Version 7 uses the limit option, and the older max name is kept only for backward compatibility. Here is an express rate limit setup with a Redis store.

src/middleware/api-limiter.ts
TypeScript
import rateLimit from 'express-rate-limit'; import { RedisStore } from 'rate-limit-redis'; import Redis from 'ioredis'; const client = new Redis(process.env.REDIS_URL as string); export const apiLimiter = rateLimit({ windowMs: 60_000, limit: 100, standardHeaders: 'draft-7', legacyHeaders: false, store: new RedisStore({ sendCommand: (command: string, ...args: string[]) => client.call(command, ...args) as Promise<any>, }), });
OptionBest forRedis supportControl level
express-rate-limitExpress apps that need a quick limiterThrough rate-limit-redisFixed window with simple options
@nestjs/throttlerNestJS apps with decoratorsThrough a community storage packagePer route and per named limit
Custom Redis guardPlan based, token bucket limitsBuilt inFull control

How to Handle API Rate Limit Exceeded Errors

An API rate limit exceeded error means the client sent too many requests and must wait before trying again. The safest fix is to read the Retry-After header, pause, and retry with exponential backoff and a little random jitter.

You will see many wordings of the same problem. A message like "call to this api have exceeded the rate limit" or "exceeded API rate limit" comes from different providers, but each one maps to HTTP 429. The cause is almost always one of three things: a loop without a delay, many parallel workers sharing one key, or a traffic spike after a deploy.

Handle Exceeded API Rate Limit Errors on the Client

The client code below honors Retry-After when it exists and falls back to exponential backoff when it does not. The random jitter stops many clients from retrying at the same instant.

src/utils/fetch-with-backoff.ts
TypeScript
export async function fetchWithBackoff( url: string, options: RequestInit = {}, maxRetries = 5, ): Promise<Response> { for (let attempt = 0; attempt <= maxRetries; attempt++) { const response = await fetch(url, options); if (response.status !== 429) return response; if (attempt === maxRetries) { throw new Error('API rate limit exceeded after all retries'); } const retryAfter = Number(response.headers.get('Retry-After')); const base = retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 500; const jitter = Math.random() * 250; await new Promise((resolve) => setTimeout(resolve, base + jitter)); } throw new Error('Unreachable'); }

Return Clear Errors From Your API

On the server side, keep the error body the same on every route. Include a message that a human can read, the retryAfter value, and nothing about your internals. Log each 429 with the user ID and route, and send the count to your metrics tool. A sudden spike in 429 responses usually points to an attack or a broken client release, and you want to see it before customers write to support.

Best Practices for API Rate Limiting

These rate limit best practices come from running APIs in production. Use them as a checklist before you ship the limiter to real traffic.

  • Limit by identity first, IP second: User IDs and API keys are fairer than IP addresses, which can be shared.
  • Tighten costly routes: Login, OTP, search, and export endpoints should have their own lower limits.
  • Always send headers:Retry-After and the limit headers let good clients behave well without guessing.
  • Choose fail open or fail closed per route: Decide it on purpose and write it down.
  • Watch the 429 rate: Add a dashboard and an alert so you notice attacks and broken clients quickly.
  • Document your limits: Publish the numbers in your API docs and announce changes before they ship.
  • Load test the limiter: Run a tool such as k6 against staging and confirm that 429 starts at the number you expect.

Early products do not need a complex setup. If you are building an MVP, a fixed window limit on login and signup routes is enough to start, and you can move to a token bucket later. Real time features need the same care. A chat server needs a limit on messages per socket, and the real-time chat application project is a good example of where that rule belongs. You can also browse other backend builds in the work section to see how these pieces fit in complete products.

Frequently asked questions

Topics

  • #NestJS
  • #RateLimiting
  • #Backend Development
  • #Node.js
  • #APIArchitecture
  • #SystemDesign

Found this article helpful?

Like it or share it with someone who would benefit.

Open to freelance & collaborationIndia

Start a project

Let's Build Something Great Together

Have a project, product idea or development challenge? Let's discuss how I can help turn it into a reliable, scalable web application.

~/hire-jay

$

Usually replies within 24 hours

What brings you here?