Built‑in interceptor vs manual composition for request cancellation and timeout in NestJS
0 reputation · 23 Jul 2022, 10:45 UTC
Goal: provide a consistent way to abort server‑side work when a client disconnects or when a processing deadline is exceeded, while keeping boilerplate low and ensuring the same behavior whether the app runs on Express or Fastify.
Constraints: the ‘close’ event is emitted immediately by Express but only after the response is flushed by Fastify; NestJS versions before 9.0 require accessing the raw request object (e.g., req['req']) to attach the listener; cancellation must be propagated to long‑running tasks such as database queries, and a timeout operator may abort legitimate slow requests unless the operation itself checks for interruption. It is also unclear whether the combined logic should live in a globally applied interceptor, a per‑module provider, or be left to developers to compose manually.
Should NestJS ship a built‑in interceptor that automatically combines request close detection with a configurable timeout operator and integrates with AsyncLocalStorage for request‑scoped services? What are the trade‑offs of bundling these concerns versus keeping them separate? How should the interceptor handle the AsyncLocalStorage context when cancelling a request?