Owning Stream Cancellation with a Shared Abort Signal
Hello, stream builder! ⏱️ This Stream Lab backend already preserves a deterministic buffered NDJSON sample and several established API routes. This lesson adds a paced live operation whose HTTP response owns cancellation for every stream stage involved.
The core model is:
One HTTP operation creates one AbortController, and its exact AbortSignal travels to every component that must stop together.
When a client disconnects, a deadline expires, or shutdown is requested, the server should stop waiting, producing observations, and writing toward a response that no longer has an owner. The fixed live helper can invoke GET /api/lab/live, cancel an active request, and reveal complete or partial response observations. The backend owns the behavior.
Trace One Signal Through the Live Operation
A completed live request follows this path:
The router recognizes GET /api/lab/live and calls sendLive().
sendLive() validates the query controls before writing headers.
It creates one response-owned AbortController.
Its exact signal goes to the paced source and promise-based pipeline().
A premature response close, deadline, or optional shutdown signal can abort that controller.
The shared signal interrupts delays, prevents further records, and tears down the connected stream stages.
A normal response follows a different path: it finishes writing, cleans up its resources, and does not become a cancellation merely because the response later closes.
text
running├─ finish → finished (cleanup; a later close is ignored)└─ close before finish, deadline, or shutdown → aborted (shared signal)
The existing buffered sample remains the deterministic baseline:
Shell
curl -i "http://127.0.0.1:3001/api/lab/sample"
It returns 200, uses an application/x-ndjson content type, and includes the three fixture records. The live route adds paced production and operation-owned cancellation without replacing that baseline.
Create Deterministic Live Observations
The paced source needs stable observations so a given numeric index always maps to the same record. That makes complete output predictable and partial output meaningful.
In backend/src/streams/observation-source.ts, the first region keeps the existing generated-source setup and defines a separate cycle for live observations.
TypeScript
import { Readable } from "node:stream";import type { Observation as GeneratedObservation } from "../domain/observation.js";const GENERATED_SITES = ["harbor", "orchard", "ridge"] as const;const LIVE_SITES = ["harbor", "orchard", "ridge"] as const;const generatedObservationForIndex = (index: number): GeneratedObservation => ({ id: `generated-${String(index + 1).padStart(6, "0")}`, temperatureC: 16 + ((index * 7) % 50) / 10, site: GENERATED_SITES[index % GENERATED_SITES.length]!,});
GeneratedObservation is aliased because this file also declares a local Observation interface for live records.
The generated source and the live source use separate deterministic factories, even though their site cycles contain the same values.
The non-null assertion after indexed array access is required because noUncheckedIndexedAccess is enabled. The modulo operation guarantees a valid index.
The next region of backend/src/streams/observation-source.ts defines the live record contract and implements the deterministic factory.
ObservationReadable remains a pull-driven source for the established generated route; it is not repurposed as the paced live source.
Each generated observation is serialized as JSON followed by \n, producing newline-delimited JSON.
When push() returns false, _read() returns and waits for Node to request more data.
Omitting highWaterMark preserves Node’s defaults by passing {} rather than explicitly providing a value.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Produce Paced NDJSON That Can Stop While Waiting
Cancellation must be observed both before a record is produced and during a configured delay. Checking only once at source startup would allow a source to continue after the operation has been cancelled.
backend/src/streams/paced-source.ts defines the caller-provided options and the async generator that produces one NDJSON line at a time.
import { Readable } from "node:stream";import { setTimeout as delay } from "node:timers/promises";import { observationForIndex } from "./observation-source.js";export interface PacedSourceOptions { records: number; delayMs: number; signal: AbortSignal; highWaterMark?: number;}async function* pacedObservationLines( options: PacedSourceOptions,): AsyncGenerator<string> { for (let index = 0; index < options.records; index += 1) { if (options.signal.aborted) throw options.signal.reason; if (options.delayMs > 0) { await delay(options.delayMs, undefined, { signal: options.signal }); } yield `${JSON.stringify(observationForIndex(index))}\n`; }}
signal is required in PacedSourceOptions; the source does not create another controller because that would split the operation’s cancellation boundary.
The signal.aborted check runs before every candidate record, preventing a record from being produced after cancellation between yields.
delay() comes from node:timers/promises. Passing the same signal causes a pending positive delay to reject when the operation aborts.
A delayMs value of 0 skips timer creation and yields immediately, while retaining the pre-record cancellation check.
The final region of backend/src/streams/paced-source.ts turns the generator into a Node readable stream.
The same controller.signal is passed to both the paced source and pipeline().
The abort occurs while the source is configured to produce many delayed records, so it checks an in-progress operation rather than only startup cancellation.
Promise-based pipeline() rejects with an AbortError.
Both the source and destination are destroyed, proving that teardown reaches both ends of the connection.
Make the Response Operation Own Cancellation
The source knows how to honor a signal, but it should not decide whether a client disconnected, a deadline expired, or shutdown began. Those decisions belong at the HTTP response boundary.
backend/src/http/response-abort.ts defines the inputs for one response operation, creates its controller, and preserves the first cancellation reason.
OperationAbortOptions makes response ownership explicit: the controller factory receives the response lifecycle, deadline, and optional shutdown signal.
The guarded abort() function is idempotent. If disconnect, deadline, and shutdown race, the first reason remains the signal’s reason.
The deadline uses a DOMException named "TimeoutError" so a server-enforced deadline has a distinct reason.
deadline.unref() ensures an otherwise idle process is not kept alive solely by this operation timer.
didFinish becomes true only in the finish handler. A close event aborts until then, including after end() begins but before all bytes flush.
The remainder of backend/src/http/response-abort.ts cleans up resources, handles normal completion, and forwards shutdown cancellation.
cleanup() clears the deadline and detaches every listener installed for this one operation.
finish represents normal response completion, so its handler cleans up without calling abort().
The controller’s own abort event also triggers cleanup, covering deadline, disconnect, and shutdown through one resource-release path.
An optional shutdown signal is handled in two cases: an already-aborted signal calls onShutdown() immediately, while a future abort registers a one-time listener.
onShutdown() forwards shutdownSignal.reason when it exists and otherwise uses the specified AbortError fallback.
Validate Stream Controls Before Committing Headers
Convert Validation Failures Into Client Responses
The application boundary must recognize HttpError before falling back to a generic 500.
backend/src/app.ts creates the HTTP server and handles rejected routing work.
route() is asynchronous, so .catch(...) handles rejected route promises at the application boundary.
headersSent is checked first. Once streaming headers or body bytes have been committed, the server destroys the response rather than attempting to send a replacement JSON error.
A pre-header HttpError becomes the established structured client error through sendError().
Other failures still become the generic 500 INTERNAL_ERROR response, preserving visibility for unexpected backend failures.
Stream the Live Response With One Shared Signal
backend/src/routes/live.ts is the convergence point for validation, response ownership, paced production, and pipeline teardown.
The first region parses every control before writing a success response and then creates the response-owned controller.
new URL() parses the request URL while providing the route path as a fallback.
records is bounded from 1 through 10_000, delayMs from 0 through 1_000, and deadlineMs from 25 through 60_000.
All validation occurs before writeHead(), allowing invalid values to reach the application’s JSON error path.
Exactly one controller is created for this response operation.
Successful live responses advertise NDJSON and the abortable-live-stream mode.
Application shutdown uses a caller-owned controller. Add shutdownSignal?: AbortSignal to both AppDependencies and RouterDependencies; createApp() already forwards dependencies to route() through its spread. Dispatch the live route with sendLive(response, request.url, deps.shutdownSignal).
The application owner supplies the signal and aborts it when shutdown begins:
const shutdown = new AbortController();const server = createApp({ database, samplePath, shutdownSignal: shutdown.signal });// In the application's shutdown handler:shutdown.abort(new DOMException("Application shutdown requested.", "AbortError"));
The remainder of backend/src/routes/live.ts connects the source and response with the controller’s exact signal.
Its content type is application/x-ndjson; charset=utf-8.
Its x-stream-lab-mode header is abortable-live-stream.
It emits three deterministic, newline-delimited live observations.
A request such as ?records=0 is invalid because the inclusive minimum is 1. It does not begin streaming: integerParam() throws before response headers are committed, and the application returns the established JSON client-error envelope instead of a 500.
A cancellation or deadline can still leave observations visible at the client because bytes that were already sent cannot be unsent. The backend guarantee is that the shared operation signal stops future source production, interrupts an active delay, and tears down the pipeline.
Recap
A cancellable live stream is an operation, not merely a readable source.
observationForIndex() creates stable live records for repeatable output.
createPacedObservationSource() produces paced NDJSON and honors a caller-provided signal before records and during delays.
createOperationAbortController() turns premature response close, deadline expiry, and optional shutdown into one cancellation boundary while treating finish as normal completion.
sendLive() validates controls before headers and passes the controller’s exact signal to both the source and pipeline().
The router exposes /api/lab/live while preserving existing GET, 404, and 405 behavior.
The application returns structured validation errors before streaming begins and preserves unexpected failures as server errors.
Keep this model in view: the HTTP response operation owns one signal, and every stage that must stop together receives that same signal.
A streaming response cannot safely be replaced by a JSON error after headers or body bytes have been sent. The live route therefore validates all controls first.
backend/src/http/query.ts defines the bounded integer parser used for live controls and existing integer-query callers.
import { HttpError } from "./errors.js";export interface IntegerParamOptions { defaultValue: number; min: number; max: number;}export const integerParam = ( url: URL, name: string, options: IntegerParamOptions,): number => { const raw = url.searchParams.get(name); if (raw === null) return options.defaultValue; if (!/^-?\d+$/.test(raw)) { throw new HttpError( 400, "INVALID_QUERY_PARAMETER", `${name} must be an integer between ${options.min} and ${options.max}.`, ); } const value = Number(raw); if ( !Number.isSafeInteger(value) || value < options.min || value > options.max ) { throw new HttpError( 400, "INVALID_QUERY_PARAMETER", `${name} must be an integer between ${options.min} and ${options.max}.`, ); } return value;};
An absent parameter uses defaultValue; a supplied invalid parameter throws instead.
The regular expression accepts integer text with an optional negative sign and rejects decimals, exponent notation, whitespace-only input, and arbitrary text.
Number.isSafeInteger() rejects numeric text that JavaScript can convert but cannot represent safely as an integer.
Bounds are inclusive, and every invalid path produces the same established HttpError status, code, and message format.
The rest of backend/src/http/query.ts retains the existing optional helpers for routes whose controls are not necessarily integers.
export const optionalNumberParam = ( url: URL, key: string, options: { min: number; max: number },): number | undefined => { const raw = url.searchParams.get(key); if (raw === null) return undefined; const normalized = raw.trim(); const parsed = Number(normalized); if ( normalized.length === 0 || !Number.isFinite(parsed) || parsed < options.min || parsed > options.max ) { throw new HttpError( 400, "INVALID_QUERY", `${key} must be a number between ${options.min} and ${options.max}.`, ); } return parsed;};export const optionalStringParam = ( url: URL, key: string, maxLength = 64,): string | undefined => { const raw = url.searchParams.get(key); if (raw === null) return undefined; const normalized = raw.trim(); if (normalized.length === 0 || normalized.length > maxLength) { throw new HttpError( 400, "INVALID_QUERY", `${key} must contain between 1 and ${maxLength} characters.`, ); } return normalized;};
optionalNumberParam() intentionally accepts finite decimal values within its bounds.
optionalStringParam() trims supplied text and requires a non-empty value within the maximum length.
The live route specifically chooses integerParam() because record counts and millisecond controls must be whole numbers.
Keeping these helpers intact preserves validation behavior for established routes.
The HttpError class in backend/src/http/errors.ts carries the client-facing information needed by the application boundary.
export class HttpError extends Error { constructor(public readonly status: number, public readonly code: string, message: string) { super(message); }}
HttpError extends Error, so it naturally travels through rejected asynchronous route handling.
status and code distinguish expected client validation failures from unexpected backend failures.
Query parsing throws this typed error instead of writing to the response directly.
The established error helper in backend/src/http/response.ts creates the JSON envelope.
import { HttpError } from "./errors.js";export interface IntegerParamOptions { defaultValue: number; min: number; max: number;}export const integerParam = ( url: URL, name: string, options: IntegerParamOptions,): number => { const raw = url.searchParams.get(name); if (raw === null) return options.defaultValue; if (!/^-?\d+$/.test(raw)) { throw new HttpError( 400, "INVALID_QUERY_PARAMETER", `${name} must be an integer between ${options.min} and ${options.max}.`, ); } const value = Number(raw); if ( !Number.isSafeInteger(value) || value < options.min || value > options.max ) { throw new HttpError( 400, "INVALID_QUERY_PARAMETER", `${name} must be an integer between ${options.min} and ${options.max}.`, ); } return value;};
TypeScript
export const optionalNumberParam = ( url: URL, key: string, options: { min: number; max: number },): number | undefined => { const raw = url.searchParams.get(key); if (raw === null) return undefined; const normalized = raw.trim(); const parsed = Number(normalized); if ( normalized.length === 0 || !Number.isFinite(parsed) || parsed < options.min || parsed > options.max ) { throw new HttpError( 400, "INVALID_QUERY", `${key} must be a number between ${options.min} and ${options.max}.`, ); } return parsed;};export const optionalStringParam = ( url: URL, key: string, maxLength = 64,): string | undefined => { const raw = url.searchParams.get(key); if (raw === null) return undefined; const normalized = raw.trim(); if (normalized.length === 0 || normalized.length > maxLength) { throw new HttpError( 400, "INVALID_QUERY", `${key} must contain between 1 and ${maxLength} characters.`, ); } return normalized;};
TypeScript
export class HttpError extends Error { constructor(public readonly status: number, public readonly code: string, message: string) { super(message); }}