Search code examples
tornado

How tornado process remote close connection while it is processing handler?


I have read tornado ioloop and relevant modules to understand what tornado would do when a socket is accepted and a request is parsed and processed.

I want to know if it is possible for tornado to stop request processing after the request connection is closed?


I build a test handler, the get method spends 5 seconds for sleeping(time.sleeo(5)).

Then I send some requests to tornado, all requests are set read timeout 3 seconds, I found some close_wait connections on tornado and several minutes later, these connections are closed normally.

I guess the 5 seconds handler is slow down tornado's event loop, when tornado process the second handler, its connection has been closed, if tornado know that, it does not need to do next.


Solution

    1. Don't use time.sleep() in Tornado applications; see this question for why.

    2. When the time-consuming part of your handler is non-blocking, you can define a method on_connection_close() which will be called when the connection closes. From this method you can cancel the ongoing work. You'll have to implement cancellation yourself, for example by setting self.cancelled = True in on_connection_close, then checking this attribute periodically during your ongoing asynchronous work.