typescript 43 lines · 6 steps

Deduping in-flight requests in NestJS

A NestJS interceptor that collapses identical concurrent GET requests into a single shared upstream call.

Explained by highlit
1import {
2 CallHandler,
3 ExecutionContext,
4 Injectable,
5 NestInterceptor,
6} from '@nestjs/common';
7import { Request } from 'express';
8import { createHash } from 'crypto';
9import { Observable, from } from 'rxjs';
10import { finalize, shareReplay } from 'rxjs/operators';
11 
12@Injectable()
13export class DedupeInterceptor implements NestInterceptor {
14 private readonly inFlight = new Map<string, Observable<unknown>>();
15 
16 intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
17 const req = context.switchToHttp().getRequest<Request>();
18 
19 if (req.method !== 'GET') {
20 return next.handle();
21 }
22 
23 const key = this.buildKey(req);
24 const existing = this.inFlight.get(key);
25 if (existing) {
26 return existing;
27 }
28 
29 const shared = next.handle().pipe(
30 finalize(() => this.inFlight.delete(key)),
31 shareReplay({ bufferSize: 1, refCount: false }),
32 );
33 
34 this.inFlight.set(key, shared);
35 return shared;
36 }
37 
38 private buildKey(req: Request): string {
39 const userId = (req as Request & { user?: { id?: string } }).user?.id ?? 'anon';
40 const raw = `${userId}:${req.originalUrl}`;
41 return createHash('sha1').update(raw).digest('hex');
42 }
43}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Sharing one Observable across concurrent callers turns N duplicate requests into a single upstream execution.
  2. 2shareReplay with a cleanup finalize keeps the in-flight map self-pruning once the work completes.
  3. 3Scoping the dedupe key to user plus URL prevents leaking one caller's response to another.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react';
 
const cache = new Map();
const inflight = new Map();

Building a stale-while-revalidate hook in React

caching request-deduplication custom-hooks
Advanced 10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) {
	if !w.timer.Stop() {
		select {
		case <-w.timer.C:

Debouncing a stream of events in Go

debounce timers channels
Advanced 7 steps

Share this explainer

Here's the card — post it anywhere.

Deduping in-flight requests in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code