title: Can a http server detect that a client has cancelled their request?
body: <p>My web app must process and serve a lot of data to display certain pages.  Sometimes, the user closes or refreshes a page while the server is still busy processing it.  This means the server will continue to process data for several minutes only to send it to a client who is no longer listening.</p>
  
  <p>Is it possible to detect that the connection has been broken, and react to it?</p>
  
  <p>In this particular project, we're using Django and NginX, or Apache.  I assumed this is possible because the Django development server appears to react to cancelled requests by printing Broken Pipe exceptions.  I'd love to have it raise an exception that my application code could catch.  <a href="https://stackoverflow.com/questions/299679/java-servlet-how-to-detect-browser-closing">It appears JSP can do this</a>.  <a href="http://nodejs.org/api.html#request-connection-156" rel="noreferrer">So can node.js</a> <a href="http://nodejs.org/api.html#event:-&#39;end&#39;-187" rel="noreferrer">here</a>.</p>
  
  <p>Alternatively, I could register an unload event handler on the page in question, have it do a synchronous XHR requesting that the previous request from this user be cancelled, and do some kind of inter-process communication to make it so.  Perhaps if the slower data processing were handed to another process that I could more easily identify and kill, without killing the responding process...</p>