To control what FastAPI does on receiving a SIGTERM signal, you can use the lifespan event handler or a custom signal handler. Here are two approaches:
1. Using Lifespan Event Handler
The recommended way is to use the lifespan event handler:
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup logic
print("Application is starting up")
yield
# Shutdown logic
print("Application is shutting down")
# Perform cleanup tasks here
app = FastAPI(lifespan=lifespan)
@app.get("/")
async def root():
return {"message": "Hello World"}
This approach allows you to define startup and shutdown logic[7]. The code after the yield statement will be executed when the application receives a SIGTERM signal, allowing you to perform cleanup tasks.
2. Custom Signal Handler
For more fine-grained control, you can implement a custom signal handler:
import signal
import asyncio
from fastapi import FastAPI
app = FastAPI()
async def shutdown(signal, loop):
print(f"Received exit signal {signal.name}...")
tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
[task.cancel() for task in tasks]
await asyncio.gather(*tasks, return_exceptions=True)
loop.stop()
def handle_sigterm():
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGTERM, lambda: asyncio.create_task(shutdown(signal.SIGTERM, loop)))
@app.on_event("startup")
async def startup_event():
handle_sigterm()
@app.get("/")
async def root():
return {"message": "Hello World"}
This approach allows you to define custom behavior when a SIGTERM signal is received[1][4]. The shutdown function cancels all running tasks and stops the event loop.
Important Considerations
-
Process Management: When running FastAPI with Gunicorn or Uvicorn in multi-worker mode, the SIGTERM signal is typically handled by the process manager[3][6].
-
Graceful Shutdown: Ensure your shutdown logic allows for graceful termination of ongoing requests[4].
-
Kubernetes Environment: In a Kubernetes environment, pay attention to how SIGTERM is propagated to your application, especially if using shell scripts as entrypoints[3][10].
-
Testing: Test your signal handling logic thoroughly to ensure it behaves as expected in different scenarios.
Remember that the exact behavior may depend on your deployment setup and the process manager you're using. Always test your signal handling in an environment that closely matches your production setup.