Skip to main content
FastAPI allows you to define logic that should run before the application starts receiving requests and after the application shuts down. This is useful for initializing resources, database connections, or cleaning up. The modern approach uses an async context manager with the lifespan parameter:
The lifespan context manager is the recommended approach for handling startup and shutdown events. It provides better structure and error handling.

How It Works

  1. Code before yield runs at startup (before the app starts receiving requests)
  2. The application runs and handles requests
  3. Code after yield runs 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:
The @app.on_event() decorators are deprecated in favor of the lifespan context manager. They will be removed in a future version of FastAPI.

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