How to Make Idempotent Replays Skip Rate Limiting in NestJS
Imagine you're using @nestjs/throttler and @nestjs/idempotency together. Everything works fine until you notice something: replaying an idempotent request still consumes your rate-limit quota. That's a problem. A clie
Imagine you're using @nestjs/throttler and @nestjs/idempotency together.
Everything works fine until you notice something: replaying an idempotent request still consumes your rate-limit quota.
That's a problem.
A client sends a request with an Idempotency-Key. The server processes it successfully and stores the result. Later, the client retries the same request because it didn't receive the original response.
The whole point of idempotency is to return the previous result without executing the handler again. So why should a replay consume another rate-limit slot?
Let's look at why this happens and how to fix it without implementing your own rate-limiting algorithm.
Why does this happen?
The important thing to understand is NestJS request lifecycle.
Guards run before interceptors.
A simplified request flow looks like this:
Incoming Request
|
v
Guards
|
v
Global Interceptors
|
v
Route Interceptors
|
v
Controller
|
v
Handler
Now consider our setup:
-
ThrottlerGuardis registered globally usingAPP_GUARD. -
IdempotencyInterceptoris registered globally by@nestjs/idempotency.
When a replay arrives, the global rate limiter runs first. At this point, the idempotency interceptor hasn't had a chance to inspect the request.
The request consumes quota, and only afterward does the idempotency interceptor recognize the replay and return the stored response.
We need to change that execution order logically, without breaking the global rate-limiting setup.
The idea: Defer rate-limit enforcement
Instead of enforcing rate limits globally for every request, we'll introduce a way to defer enforcement for specific routes.
The idea is simple:
- Mark a route that needs deferred rate limiting.
- Make the global rate-limit guard skip that route.
- Move the actual rate-limit enforcement into a route-level interceptor.
- Let the idempotency interceptor decide whether the request should continue.
The key is that a replay never reaches the route-level interceptor.
Let's implement it.
1. Create a decorator to mark deferred routes
First, we need a custom decorator that adds metadata to a route.
// deferred-rate-limit.decorator.ts
import { SetMetadata } from '@nestjs/common';
export const DEFERRED_RATE_LIMIT_KEY = 'app:deferred-rate-limit';
export function DeferredRateLimit(): MethodDecorator {
return SetMetadata(DEFERRED_RATE_LIMIT_KEY, true);
}
This decorator doesn't perform any rate limiting. It simply tells our global guard that enforcement for this route should happen later.
2. Update the global rate-limit guard
Now we extend our existing throttler guard.
Instead of completely replacing ThrottlerGuard, we keep the original implementation and add one small condition.
// deferred-rate-limit.guard.ts
export class DeferredRateLimitGuard extends RedisThrottlerGuard {
override async canActivate(context: ExecutionContext): Promise<boolean> {
const deferred = this.reflector.getAllAndOverride<boolean>(
DEFERRED_RATE_LIMIT_KEY,
[context.getHandler(), context.getClass()],
);
if (deferred) {
return true;
}
return super.canActivate(context);
}
}
That's it.
For normal routes, everything works exactly as before.
For routes marked with @DeferredRateLimit(), the global guard returns true without calling the throttler.
Important: We're not disabling rate limiting. We're only moving its enforcement to another point in the request lifecycle.
3. Enforce the rate limit inside an interceptor
Next, we create an interceptor responsible for enforcing the deferred rate limit.
// deferred-rate-limit.interceptor.ts
@Injectable()
export class DeferredRateLimitInterceptor implements NestInterceptor {
constructor(
private readonly throttlerGuard: RedisThrottlerGuard,
) {}
intercept(
context: ExecutionContext,
next: CallHandler,
): Promise<Observable<unknown>> {
return this.throttlerGuard
.canActivate(context)
.then(() => next.handle());
}
}
Notice something important here.
We're not implementing another rate-limiting algorithm.
We're reusing the existing RedisThrottlerGuard and calling its canActivate() method directly.
This means we still use the same:
- Redis storage.
- Throttling policies.
- Key generation.
-
@Throttle()metadata. - Rate-limit headers and throttling exceptions.
We're only changing when the existing rate limiter runs.
4. Make the guard injectable
Since the interceptor needs an instance of RedisThrottlerGuard, we expose it through a shared module.
// throttler-enforcement.module.ts
@Module({
imports: [throttlerModule],
providers: [RedisThrottlerGuard],
exports: [RedisThrottlerGuard],
})
export class ThrottlerEnforcementModule {}
The feature module imports this module, so the interceptor can use the existing throttler configuration and storage.
Keep this infrastructure inside your shared throttling layer instead of duplicating it in feature modules.
5. Apply everything to an endpoint
Now we can combine the decorators.
@Post('challenge')
@DeferredRateLimit()
@Throttle({ short: { limit: 2, ttl: seconds(120) } })
@UseInterceptors(DeferredRateLimitInterceptor)
@Idempotent(challengeIdempotentOptions)
requestChallenge(@Body() body: ChallengeRequestBody) {
return this.enrollmentsService.requestChallenge(body.phoneNumber);
}
The order of the interceptors is what makes this work.
With the global idempotency interceptor wrapping the route-level interceptor, the request flow becomes:
Incoming Request
|
v
Global Guards
|
| Deferred route? Skip throttling.
|
v
Global IdempotencyInterceptor
|
| Acquire idempotency key
|
+---- Completed replay?
| |
| v
| Return stored response
| (No rate-limit check)
|
+---- Key already in use?
| |
| v
| Return 409 Conflict
| (No rate-limit check)
|
v
Route-level Interceptor
|
v
Rate-limit enforcement
|
v
Controller Handler
For a new request, the idempotency interceptor acquires the key and continues down the interceptor chain. That's when our route-level interceptor enforces the rate limit.
For a completed replay, the idempotency interceptor returns the stored response without calling the next interceptor.
The same applies to an in-flight duplicate: the idempotency package rejects it before the deferred rate limiter gets executed.
That's exactly what we want.
6. Don't forget to test the actual quota
One important detail: don't verify this behavior only by checking that the handler wasn't executed.
The handler might be skipped while the rate limiter still consumes quota.
A better approach is to inspect the actual rate-limit counters in Redis.
For example:
const before = await hitCount(tracker, 'short');
const replay = await postChallenge(app, {
key: existingKey,
tracker,
});
const after = await hitCount(tracker, 'short');
expect(replay.status).toBe(202);
expect(replay.headers['idempotent-replayed']).toBe('true');
expect(after).toBe(before);
Also test an in-flight duplicate and, even more importantly, a replay when the client's rate-limit quota is already exhausted.
That last scenario proves the behavior we're trying to achieve: an existing idempotent operation can be replayed even when a new request from the same client would receive 429 Too Many Requests.
A few things worth remembering
There are a couple of details you shouldn't overlook:
Don't skip rate limiting just because a request contains an Idempotency-Key header. A new request can have a perfectly valid idempotency key too. The idempotency layer must decide whether the request is a replay or a new operation.
Keep the original @Throttle() metadata. There's no reason to duplicate limits or maintain a separate rate-limiting implementation.
Be careful with interceptor registration order. The global idempotency interceptor must wrap the route-level deferred interceptor. Otherwise, the rate limiter might run before the idempotency decision.
A deferred route must always have a downstream enforcement mechanism. If you add @DeferredRateLimit() but forget @UseInterceptors(DeferredRateLimitInterceptor), that route won't be rate-limited.
The interesting part of this solution isn't writing another rate limiter. It's understanding how NestJS Guards and Interceptors interact.
By skipping the global guard for selected routes and reusing the existing throttler inside a route-level interceptor, we can make idempotent replays bypass rate-limit enforcement without sacrificing the original throttling policies.
A small change in execution order, but an important improvement when building reliable APIs with NestJS.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.