Lifespan context manager shutdown timeout configuration
0 reputation · 15 Apr 2024, 07:40 UTC
FastAPI utilizes the lifespan context manager to handle application startup and shutdown logic. This mechanism allows developers to manage resources like database connection pools or HTTP clients across the entire application lifecycle.
While the startup phase is straightforward, the shutdown phase lacks a built-in framework constraint to enforce a maximum execution duration. When the server receives a termination signal, the lifespan shutdown block executes, but there is no native FastAPI configuration to define a timeout or a cancellation policy for these cleanup tasks.
In production environments using ASGI servers like Uvicorn, it remains unclear how to best synchronize the framework's lifespan shutdown with the server's own graceful shutdown timeout to prevent orphaned resources or abrupt process termination.
- Does FastAPI provide a mechanism to enforce a hard timeout for the lifespan shutdown sequence?
- How should the application handle cleanup tasks that exceed the ASGI server's grace period?