#Possible memory leak on Timeout Interceptor?

2 messages · Page 1 of 1 (latest)

real acorn
#

Hi!

I'm using the Timeout Interceptor from the documentation to manage timeouts on my API.
https://docs.nestjs.com/interceptors

But if I simulate an infinite loop on my controller, I receive the timeout response but the loop continues its execution. This can cause a memory leak on the service. How do you manage your timeouts to avoid this?

timeout.interceptor.ts

import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(5000),
      catchError(err => {
        if (err instanceof TimeoutError) {
          return throwError(() => new RequestTimeoutException());
        }
        return throwError(() => err);
      }),
    );
  };
};```


app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}

@Get()
async getHello(): Promise<string> {
let second = 0;
while (1 + 1 == 2) {
console.log('Waiting...' + second++);
await this.sleep(1000);
}

return this.appService.getHello();

}

async sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}```

formal bluff
#

using a timeout on a infinite loop is not a accurate approach to do this
i would suggest to just timeout for 6000 ms

as this is longer then your interceptor that should stop request taking longer then 5000