To manage how your FastAPI application responds to termination signals like SIGTERM, you can implement a graceful shutdown process. This ensures that resources such as database connections or background tasks are properly closed before the application exits.
Using FastAPI's Lifespan Events:
FastAPI provides a lifespan context manager that allows you to define startup and shutdown events. This is the recommended approach for handling application lifecycle events:
from fastapi import FastAPI
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup code here
yield
# Shutdown code here
app = FastAPI(lifespan=lifespan)
Within the lifespan function, you can include any necessary cleanup operations that should run when the application receives a termination signal.
Handling Termination Signals Directly:
If you need more control over signal handling, such as intercepting SIGTERM directly, you can register a signal handler:
import signal
import asyncio
from fastapi import FastAPI
app = FastAPI()
def handle_exit(sig, frame):
# Perform cleanup operations here
print(f"Received signal {sig}. Cleaning up...")
# Example: Close database connections, stop background tasks, etc.
asyncio.create_task(shutdown())
async def shutdown():
# Perform asynchronous cleanup operations
await asyncio.sleep(1) # Simulate cleanup delay
print("Cleanup complete. Exiting.")
loop.stop()
# Register the signal handler
signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)
@app.get("/")
async def read_root():
return {"message": "Hello, World!"}
In this example, the handle_exit function is called when a SIGTERM or SIGINT signal is received, allowing you to perform necessary cleanup before the application exits.
Considerations:
-
Avoid Overriding Existing Handlers: Be cautious when registering signal handlers, as overriding existing handlers can interfere with the server's ability to shut down properly. For instance, Uvicorn uses SIGTERM to manage worker threads during reloading. Overriding this without proper chaining can cause issues[1].
-
Use Application State: To manage shutdown flags or other state information, consider using FastAPI's application state:
from fastapi import FastAPI
app = FastAPI()
app.state.shutdown_flag = False
@app.on_event("shutdown")
async def shutdown_event():
app.state.shutdown_flag = True
# Perform cleanup operations here
By implementing these strategies, you can control how your FastAPI application responds to termination signals, ensuring a graceful shutdown process.