Course contentsShow
← Node.js
Lesson 1433 of 1,98013. Error Handling and Resilient SystemsFree lesson

Request Cancellation Tokens

You will use abort signals to terminate pending operations when a client disconnects or a timeout expires.

In this lesson, you will learn how to prevent wasted server resources by proactively terminating asynchronous operations when a client disconnects or a timeout expires.

The Problem of Orphaned Work

In a distributed system, a client might abandon a request long before your server finishes processing it. For example, if a user navigates away from a page or closes their browser, your server might still be churning through a complex database query or a heavy calculation. If you don't stop this "orphaned" work, you waste CPU cycles, memory, and database connections—eventually creating a bottleneck that impacts other healthy requests.

Using Abort Signals

Node.js uses the AbortController API to bridge this gap. An AbortController creates an AbortSignal, which acts as a "cancellation token." You pass this signal into your asynchronous operations (like fetch, database queries, or file reads). If the controller triggers an abort(), the operation receives a signal to stop immediately and throw a CanceledError.

Practical Implementation

When handling an incoming HTTP request, you can link the request's lifecycle to your operations:

// Inside your request handler
const controller = new AbortController();
const { signal } = controller;

// Listen for client disconnects
req.on('close', () => controller.abort());

try {
  // Pass the signal to an async task
  const data = await heavyDatabaseQuery({ signal });
  res.send(data);
} catch (err) {
  if (err.name === 'AbortError') {
    console.log('Request cancelled by client; stopping work.');
  } else {
    // Handle actual operational errors
    next(err);
  }
}

By connecting the req.on('close') event to your AbortController, you ensure that the moment the socket closes, your server ceases the heavy task. This keeps your system resilient, ensuring that your resources are always reserved for active, interested clients rather than abandoned tasks. This pattern is essential for high-throughput services where "zombie" processes can quickly degrade performance and inflate infrastructure costs.

Key Takeaway: Use AbortController to propagate cancellation signals through your promise chains, allowing your system to immediately halt resource-heavy tasks when a client is no longer waiting for a response.