Lifespan Context Manager (Recommended)
The modern approach uses an async context manager with thelifespan parameter:
How It Works
- Code before
yieldruns at startup (before the app starts receiving requests) - The application runs and handles requests
- Code after
yieldruns at shutdown (when the app is stopping)
Common Use Cases
Database Connection
Loading ML Models
Redis Connection
Event Decorators (Legacy)
You can also use event decorators, though the lifespan context manager is preferred:Startup Events
Shutdown Events
Multiple Event Handlers
You can define multiple handlers for the same event:Combining Multiple Resources
Error Handling
Using Dependency Injection
Access lifespan resources in route handlers:Testing with Lifespan Events
The
TestClient automatically handles lifespan events, running startup code when entering the context manager and shutdown code when exiting.Best Practices
- Use the lifespan context manager instead of event decorators
- Initialize expensive resources (DB connections, ML models) at startup
- Always clean up resources in the shutdown phase
- Use proper error handling to prevent startup failures
- Log startup and shutdown events for debugging
- Keep startup time reasonable to avoid deployment timeouts
Migration from Events to Lifespan
If you’re using event decorators, here’s how to migrate:See Also
- Custom Middleware - Process requests and responses
- Dependencies - Dependency injection system
- Testing - Testing FastAPI applications