I would like to add a hook to Python's Tornado web server such that I can execute some async cleanup function whenever the server is going down for whatever reason.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below, I'll explain how to add a shutdown hook to a Tornado web server that executes an asynchronous cleanup function whenever the server is shutting down, regardless of the reason (e.g., Ctrl+C/SIGINT, SIGTERM from a process manager like systemd, or programmatic shutdown). This approach works for Tornado 6+ (which has good integration with Python's asyncio), and assumes Python 3.7+ for modern async features.
Key Concepts
Tornado's IOLoop and asyncio Integration: Tornado's IOLoop can run on top of Python's asyncio event loop. This allows us to use asyncio features like signal handlers and tasks for async operations.
Shutdown Triggers: We'll handle common shutdown signals (SIGINT and SIGTERM) using asyncio's signal handlers. These are safer than raw signal.signal() because they integrate directly with the event loop.
Async Cleanup: Your cleanup function can be an async def coroutine (e.g., to close database connections, flush queues, or send notifications asynchronously).
Graceful Shutdown: We'll stop the HTTPServer (to prevent new connections) before running cleanup, then stop the event loop. You can add a grace period if needed (e.g., to wait for in-flight requests).
Limitations: This handles signals and programmatic stops, but not unhandled exceptions crashing the process (for that, wrap your app in try/except). It doesn't handle Windows well (asyncio signal handlers are Unix-only; use signal.signal() as a fallback if needed).
Step-by-Step Implementation
Here's a complete example of a Tornado application with an async shutdown hook.
python
import asyncio
import signal
import tornado.ioloop
import tornado.web
from tornado.httpserver import HTTPServer
# Your async cleanup function (this can do anything async, e.g., close DB connections)
async def async_cleanup():
print("Starting async cleanup...")
# Simulate async work (e.g., await closing resources)
await asyncio.sleep(1) # Replace with real async operations
print("Async cleanup complete!")
# Example Tornado handler
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, Tornado!")
# Async shutdown coroutine
async def shutdown(server: HTTPServer, grace_period: float = 5.0):
print("Shutdown initiated...")
# Stop accepting new connections
server.stop()
print("Stopped accepting new connections.")
# Optional: Wait a grace period for existing requests to finish
await asyncio.sleep(grace_period)
# Run your async cleanup
await async_cleanup()
# Stop the event loop
asyncio.get_event_loop().stop()
print("Event loop stopped.")
# Signal handler (regular function, not async)
def signal_handler(server: HTTPServer):
# Schedule the async shutdown as a task on the event loop
asyncio.create_task(shutdown(server))
# Main async entrypoint
async def main():
# Set up Tornado app
app = tornado.web.Application([
(r"/", MainHandler),
])
# Create HTTPServer
server = HTTPServer(app)
server.bind(8888)
server.start() # Starts the server (use num_processes=0 for single-process)
print("Tornado server started on port 8888")
# Get the asyncio loop (Tornado integrates with it)
loop = asyncio.get_event_loop()
# Add signal handlers (Unix-only; for Windows, use signal.signal() below)
loop.add_signal_handler(signal.SIGINT, signal_handler, server)
loop.add_signal_handler(signal.SIGTERM, signal_handler, server)
# For Windows compatibility (or as fallback), you can add:
# import signal
# signal.signal(signal.SIGINT, lambda sig, frame: signal_handler(server))
# signal.signal(signal.SIGTERM, lambda sig, frame: signal_handler(server))
# Run the loop forever (until stopped)
await loop.create_future() # This keeps it running indefinitely
if __name__ == "__main__":
# Run the async main function
asyncio.run(main())
How It Works
Starting the Server:
The main() coroutine sets up the Tornado Application and HTTPServer.
It binds to a port and starts listening.
Signal handlers are registered to catch SIGINT (e.g., Ctrl+C) and SIGTERM (e.g., kill command).
Shutdown Trigger:
When a signal is received, signal_handler() is called synchronously (as required by signal handlers).
It schedules the shutdown() coroutine as an asyncio.Task on the event loop using asyncio.create_task(). This ensures the async cleanup runs without blocking the signal handler.
Shutdown Process:
shutdown() stops the HTTPServer (closes listening sockets, no new connections).
Optionally waits a grace period (e.g., 5 seconds) for ongoing requests to complete.
Awaits your async_cleanup() function.
Finally, stops the event loop with loop.stop().
Programmatic Shutdown:
If you want to trigger shutdown programmatically (e.g., from within a handler or another part of your code), you can call asyncio.create_task(shutdown(server)) directly.
Testing It
Run the script: python your_script.py.
Visit http://localhost:8888/ in a browser to see "Hello, Tornado!".
Press Ctrl+C in the terminal: You'll see shutdown messages, the async cleanup running, and the server stopping cleanly.
Alternatively, find the process ID and run kill <pid> to simulate SIGTERM.
Customizations and Edge Cases
Graceful Request Handling: If you need to wait for all active requests to finish, you can track them manually (e.g., using a counter in your handlers) or use Tornado's wait_for_requests if you subclass HTTPServer. For simplicity, the example uses a fixed timeout.
Multiple Processes: If you set server.start(num_processes>1), each process needs its own signal handlers. Tornado handles forking, but test carefully.
Error Handling: Wrap sensitive parts in try/except inside async_cleanup() to avoid shutdown hangs. If cleanup fails, you can log it and proceed with loop.stop().
Windows Support: loop.add_signal_handler doesn't work on Windows. Use signal.signal() as shown in the code comment. Note that Windows doesn't support SIGTERM natively.
Logging: Replace print() with proper logging (e.g., logging.info) for production.
Tornado Versions <6: If you're on an older Tornado, use tornado.ioloop.IOLoop.current().add_callback_from_signal() instead of asyncio.create_task(). The pattern is similar but less async-friendly.
Unclean Shutdowns: For crashes due to unhandled exceptions, use sys.excepthook or wrap asyncio.run(main()) in a try-finally to run sync cleanup (but async cleanup won't work here).
This setup ensures your async cleanup runs reliably on shutdown. If you provide more details about your app (e.g., Tornado version, specific cleanup needs, or multi-process setup), I can refine it further!