Course contentsShow
← Node.js
Lesson 557 of 1,9806. Networking and HTTP FundamentalsFree lesson

Request Cancellation Detection

Listen for client-side abort signals to halt expensive database queries in progress.

In this lesson, you will learn how to detect when a client abandons an HTTP request so you can stop wasting server resources on unnecessary database work.

Why Detect Cancellation?

Imagine a user triggers a heavy report generation that takes ten seconds to query your database. If the user navigates away or closes their browser after three seconds, the HTTP connection is severed. By default, your Node.js server might continue processing the entire database query, consuming CPU and memory for a result that no one will ever receive. Detecting this "abort" signal allows you to halt the operation immediately, freeing up your database and server for other users.

Listening for the close Event

In Node.js, the req (request) object is an EventEmitter. When a client drops the connection, the request emits a close event. You can listen for this event to flag a process as "cancelled."

Here is how you can integrate this into a database operation:

app.get('/expensive-report', async (req, res) => {
  let isCancelled = false;

  // Listen for the client disconnecting
  req.on('close', () => {
    isCancelled = true;
    console.log('Client closed the connection; stopping work.');
  });

  // Simulate a database query that checks for cancellation
  const data = await fetchFromDatabase(async (checkStatus) => {
    if (isCancelled) throw new Error('Query aborted by client');
    // ... proceed with database logic
  });

  res.send(data);
});

Strategic Implementation

The key is to create a "cancellation-aware" data fetcher. Because Node.js is non-blocking, simply listening for the close event isn't enough; you must periodically check the isCancelled variable inside your database loops or callback chains.

By checking if the request is still alive before each major chunk of processing, you ensure that your server stops doing expensive work the moment the user is gone. This is a vital practice for maintaining high-performance servers that don't get bogged down by "ghost" requests that no longer have a destination.

Key Takeaway: By listening to the close event on the request object and periodically checking that status during long-running tasks, you prevent wasted server resources on abandoned operations.