0
0
NestJSframework~10 mins

Timeout interceptor in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Timeout interceptor
Request received
Interceptor starts
Start timer
Call next handler
Wait for response or timeout
Response
Send response
Request ends
The interceptor starts a timer, calls the next handler, waits for response or timeout, then either sends the response or throws a timeout error.
Execution Sample
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { timeout, catchError } from 'rxjs/operators';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(5000),
      catchError(err => throwError(() => new RequestTimeoutException())),
    );
  }
}
This interceptor sets a 5-second timeout on the request handling observable and throws a timeout exception if exceeded.
Execution Table
StepActionTimer StateNext Handler CalledResponse or TimeoutResult
1Request received, interceptor startsTimer not startedNoNoPrepare to start timer
2Start 5-second timerTimer started (5s)NoNoTimer counting down
3Call next.handle() to process requestTimer runningYesNoWaiting for response or timeout
4Response received before timeoutTimer runningYesResponse receivedSend response to client
5Request endsTimer stoppedYesResponse sentComplete request
6OR timeout reached before responseTimer expiredYesTimeout errorThrow RequestTimeoutException
7Request ends with errorTimer stoppedYesError sentComplete request with error
💡 Execution stops when either response is sent or timeout error is thrown.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4 or 6Final
timernot startedstarted (5s countdown)runningstoppedstopped
nextHandlerCalledfalsefalsetruetruetrue
responseReceivedfalsefalsefalsetrue or falsetrue or false
timeoutReachedfalsefalsefalsefalse or truefalse or true
Key Moments - 3 Insights
Why does the interceptor use next.handle().pipe() instead of just calling next.handle()?
Because next.handle() returns an observable, and pipe() allows adding operators like timeout and catchError to control the flow and handle timeout errors as shown in execution_table step 3.
What happens if the response takes longer than 5 seconds?
The timeout operator triggers an error, caught by catchError, which throws a RequestTimeoutException as shown in execution_table steps 6 and 7.
Does the timer stop automatically when the response is received?
Yes, when the response arrives before timeout, the timer stops and the response is sent, as shown in execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the next handler called?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Check the 'Next Handler Called' column in execution_table rows.
According to variable_tracker, what is the state of 'timeoutReached' after step 4?
Atrue
Bfalse
Cundefined
Dnull
💡 Hint
Look at 'timeoutReached' values in variable_tracker after step 4.
If the timeout duration is increased to 10 seconds, how would the execution_table change?
ANext handler would be called twice
BTimer would start after response
CTimeout error would occur later or not at all if response is within 10s
DResponse would be sent immediately
💡 Hint
Consider the 'Timer State' and 'Timeout error' timing in execution_table.
Concept Snapshot
Timeout Interceptor in NestJS:
- Intercepts requests to add a timeout limit
- Uses RxJS operators: timeout() and catchError()
- Throws RequestTimeoutException if exceeded
- Ensures slow requests don't hang forever
- Wraps next.handle() observable with timeout logic
Full Transcript
A Timeout Interceptor in NestJS watches how long a request takes. When a request comes in, the interceptor starts a timer and calls the next handler to process the request. It waits for the response or for the timer to run out. If the response comes before the timer ends, it sends the response back. If the timer runs out first, it throws a timeout error. This helps keep the app responsive by stopping requests that take too long. The interceptor uses RxJS's timeout and catchError operators to manage this flow cleanly.