Python / Uvicorn Fundamentals Interview Questions
How do you handle graceful shutdown in Uvicorn?
Uvicorn handles OS signals to shut down gracefully - completing in-flight requests before stopping. Understanding this is important for zero-downtime deployments and container orchestration.
# Uvicorn responds to these OS signals: # SIGINT (Ctrl+C) - graceful shutdown # SIGTERM (kill default) - graceful shutdown (Kubernetes uses this) # SIGQUIT - graceful shutdown with core dump # SIGKILL (kill -9) - immediate termination (not catchable) # Kubernetes sends SIGTERM before SIGKILL: # Pod termination sequence: # 1. SIGTERM sent to container # 2. Uvicorn begins graceful shutdown # 3. Completes in-flight requests # 4. SIGKILL sent after terminationGracePeriodSeconds (default 30s) # Programmatic graceful shutdown: import asyncio import signal import uvicorn async def main(): config = uvicorn.Config("main:app", port=8000) server = uvicorn.Server(config) loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, lambda: asyncio.create_task(server.shutdown()) ) await server.serve() asyncio.run(main())
Lifespan shutdown: during graceful shutdown, Uvicorn sends the lifespan.shutdown event to the application before terminating. This is where you should close database connections, flush caches, and clean up resources. Ensure your lifespan shutdown handler completes quickly - a slow shutdown can cause Kubernetes to send SIGKILL prematurely.
More Related questions...