Bird
Raised Fist0
NestJSframework~20 mins

Timeout interceptor in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Timeout Interceptor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a NestJS TimeoutInterceptor times out?
Consider a NestJS TimeoutInterceptor that throws a timeout error if the request takes longer than 3 seconds. What will the client receive if the handler takes 5 seconds to respond?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError, timeout, catchError } from 'rxjs';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(3000),
      catchError(err => {
        if (err.name === 'TimeoutError') {
          return throwError(() => new RequestTimeoutException());
        }
        return throwError(() => err);
      }),
    );
  }
}
AThe client receives an empty response with status 200.
BThe client receives a 408 Request Timeout error.
CThe client waits indefinitely until the handler finishes.
DThe client receives a 500 Internal Server Error.
Attempts:
2 left
💡 Hint
Think about what the RequestTimeoutException does in NestJS.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this TimeoutInterceptor code
Which option contains a syntax error that prevents the TimeoutInterceptor from compiling?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, timeout } from 'rxjs';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(5000)
    );
  }
}
AThe intercept method is missing the return type Observable<any>.
BMissing import of catchError from 'rxjs' causes runtime error.
Ctimeout operator is used without parentheses: timeout instead of timeout().
DThe class is missing the @Injectable decorator.
Attempts:
2 left
💡 Hint
Check how the timeout operator is called in RxJS.
🔧 Debug
advanced
2:30remaining
Why does the TimeoutInterceptor not trigger on slow requests?
A developer wrote this TimeoutInterceptor but it never triggers even when requests take longer than 10 seconds. What is the likely cause?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError, timeout, catchError } from 'rxjs';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    next.handle().pipe(
      timeout(10000),
      catchError(err => {
        if (err.name === 'TimeoutError') {
          return throwError(() => new RequestTimeoutException());
        }
        return throwError(() => err);
      }),
    );
    return next.handle();
  }
}
AThe interceptor returns next.handle() without the pipe, so timeout is never applied.
BThe timeout duration is too long to trigger in tests.
CThe catchError operator is missing a return statement.
DThe interceptor is missing the @Injectable decorator.
Attempts:
2 left
💡 Hint
Check what the intercept method returns.
❓ state_output
advanced
2:00remaining
What is the output when TimeoutInterceptor wraps a fast handler?
Given this TimeoutInterceptor with 2 seconds timeout, and a handler that responds in 1 second, what will the client receive?
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, timeout, catchError } from 'rxjs';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(2000),
      catchError(err => {
        throw err;
      }),
    );
  }
}

// Handler code:
// async function handle() { await new Promise(r => setTimeout(r, 1000)); return { message: 'done' }; }
AThe client receives a 500 Internal Server Error.
BThe client receives a 408 Request Timeout error.
CThe client receives an empty response immediately.
DThe client receives { message: 'done' } after 1 second.
Attempts:
2 left
💡 Hint
The handler finishes before the timeout limit.
🧠 Conceptual
expert
3:00remaining
How does NestJS TimeoutInterceptor integrate with RxJS to handle slow requests?
Which statement best describes how a NestJS TimeoutInterceptor uses RxJS operators to manage request timeouts?
AIt uses the RxJS timeout operator to emit an error if the observable does not emit within the specified time, which is caught and transformed into a NestJS exception.
BIt uses the RxJS delay operator to postpone the response and cancels the request if it takes too long.
CIt uses the RxJS map operator to transform the response into a timeout error if it takes longer than the limit.
DIt uses the RxJS retry operator to repeat the request until it finishes within the timeout period.
Attempts:
2 left
💡 Hint
Think about how timeout errors are generated and handled in RxJS.

Practice

(1/5)
1.

What is the main purpose of a TimeoutInterceptor in a NestJS application?

easy
A. To stop requests that take too long and prevent hanging.
B. To log every request made to the server.
C. To cache responses for faster retrieval.
D. To authenticate users before processing requests.

Solution

  1. Step 1: Understand the role of TimeoutInterceptor

    The TimeoutInterceptor is designed to limit how long a request can take before it is stopped.
  2. Step 2: Compare options with the interceptor's purpose

    Only To stop requests that take too long and prevent hanging. describes stopping long requests to avoid hanging, which matches the interceptor's goal.
  3. Final Answer:

    To stop requests that take too long and prevent hanging. -> Option A
  4. Quick Check:

    TimeoutInterceptor stops long requests = D [OK]
Hint: TimeoutInterceptor stops slow requests to keep app responsive [OK]
Common Mistakes:
  • Confusing timeout with logging or caching
  • Thinking it handles authentication
  • Assuming it speeds up all requests
2.

Which of the following is the correct way to apply a timeout of 5 seconds using RxJS timeout operator inside a NestJS interceptor?

return next.handle().pipe( ... )
easy
A. return next.handle().pipe(timeout(500));
B. return next.handle().pipe(timeout(5));
C. return next.handle().pipe(timeout(5000));
D. return next.handle().pipe(timeout(50));

Solution

  1. Step 1: Understand RxJS timeout parameter

    The timeout operator expects time in milliseconds, so 5 seconds is 5000 ms.
  2. Step 2: Match the correct timeout value

    Only return next.handle().pipe(timeout(5000)); uses 5000 which equals 5 seconds; others use incorrect values.
  3. Final Answer:

    return next.handle().pipe(timeout(5000)); -> Option C
  4. Quick Check:

    Timeout in ms for 5 seconds = 5000 [OK]
Hint: Timeout value is always in milliseconds in RxJS [OK]
Common Mistakes:
  • Using seconds instead of milliseconds
  • Using too small timeout values
  • Forgetting to import timeout operator
3.

Given this TimeoutInterceptor code snippet, what will be the output if the request handler takes 7 seconds to respond?

intercept(context, next) {
  return next.handle().pipe(
    timeout(5000),
    catchError(err => throwError(() => new RequestTimeoutException()))
  );
}
medium
A. The request completes successfully after 7 seconds.
B. The request throws a RequestTimeoutException after 5 seconds.
C. The request throws a generic error immediately.
D. The request never completes or errors.

Solution

  1. Step 1: Analyze timeout duration and handler delay

    The timeout is set to 5000 ms (5 seconds), but the handler takes 7 seconds, which is longer.
  2. Step 2: Understand error handling on timeout

    When timeout triggers, catchError throws a RequestTimeoutException, so the request errors after 5 seconds.
  3. Final Answer:

    The request throws a RequestTimeoutException after 5 seconds. -> Option B
  4. Quick Check:

    Handler > timeout triggers RequestTimeoutException = A [OK]
Hint: Timeout triggers error if handler exceeds set milliseconds [OK]
Common Mistakes:
  • Assuming request completes despite timeout
  • Confusing generic error with RequestTimeoutException
  • Ignoring catchError usage
4.

Identify the error in this TimeoutInterceptor implementation:

intercept(context, next) {
  return next.handle().pipe(
    timeout(3000),
    catchError(err => {
      throw new RequestTimeoutException();
    })
  );
}
medium
A. Using throw inside catchError instead of returning an observable error.
B. Timeout value should be in seconds, not milliseconds.
C. Missing import for RequestTimeoutException.
D. The interceptor must return a Promise, not an Observable.

Solution

  1. Step 1: Check error handling inside catchError

    Inside catchError, throwing an error directly breaks the observable chain; it should return an observable error using throwError.
  2. Step 2: Validate other options

    Timeout is correctly in milliseconds, imports are assumed correct, and interceptors return Observables, so only Using throw inside catchError instead of returning an observable error. is the error.
  3. Final Answer:

    Using throw inside catchError instead of returning an observable error. -> Option A
  4. Quick Check:

    Use throwError() inside catchError, not throw [OK]
Hint: Inside catchError, always return throwError() observable [OK]
Common Mistakes:
  • Throwing error directly inside catchError
  • Confusing milliseconds with seconds
  • Assuming interceptors return Promises
5.

You want to create a TimeoutInterceptor that applies a 3-second timeout globally but allows a specific route to override it with a 10-second timeout. Which approach correctly implements this behavior?

hard
A. Set timeout to 10 seconds globally and manually check route inside interceptor to reduce to 3 seconds if needed.
B. Apply two TimeoutInterceptors globally, one with 3 seconds and one with 10 seconds; the last one wins.
C. Create two separate interceptors and apply the 10-second one only on the specific route without global interceptor.
D. Use a global TimeoutInterceptor with 3 seconds and a custom decorator to set metadata for 10 seconds, then read metadata inside the interceptor to override timeout.

Solution

  1. Step 1: Understand global and route-specific timeout needs

    Global interceptor applies 3 seconds by default; specific routes can override by metadata.
  2. Step 2: Implement override using custom decorator and metadata

    Custom decorator sets timeout metadata on route; interceptor reads it and uses that value if present.
  3. Step 3: Evaluate other options

    Applying multiple global interceptors causes conflicts; setting longer timeout globally and reducing for most routes reverses the logic; creating separate interceptors without a global one loses timeout protection on other routes.
  4. Final Answer:

    Use a global TimeoutInterceptor with 3 seconds and a custom decorator to set metadata for 10 seconds, then read metadata inside the interceptor to override timeout. -> Option D
  5. Quick Check:

    Use metadata + decorator to override global timeout [OK]
Hint: Use custom decorator + metadata to override global interceptor timeout [OK]
Common Mistakes:
  • Applying multiple global interceptors causing conflicts
  • Hardcoding timeout values without metadata
  • Not reading route metadata inside interceptor
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard