tezvyn:

FastAPI Lifespan: Code Before Startup, After Shutdown

AI-drafted, machine-checkedSource: fastapi.tiangolo.combeginner

FastAPI's lifespan events are "open for business" and "closing time" routines that run once before startup and after shutdown. Use them to initialize a DB pool or load a model. The footgun is putting request-specific logic here; it runs once only.

WHY IT EXISTS Some tasks are expensive and only need to be done once when an application starts, not on every single request. For example, connecting to a database or loading a large data file into memory. Lifespan events provide a clean, official way to manage these one-time setup and teardown operations for the entire application.

THE MENTAL MODEL Think of lifespan events as the code that runs to turn the lights on and off in your shop. The startup part happens before you unlock the doors to customers (requests). The shutdown part happens after the last customer has left and you're closing up for the night. This setup and cleanup code is separate from the work you do for each individual customer.

HOW IT WORKS You define an asynchronous function, often using an async with block (an async context manager), and pass it to the FastAPI app instance using the lifespan parameter. The code before the yield statement runs on startup. The application then starts and handles requests. When the application is told to shut down, the code after the yield statement is executed for cleanup. An older, now deprecated, method involved separate @app.on_event("startup") and @app.on_event("shutdown") decorators.

WHEN TO USE IT Use lifespan events for tasks that need to happen once for the entire application's life. Prime examples include: initializing a database connection pool, loading a large machine learning model from disk into memory, setting up a cache client connection like Redis, or connecting to a message broker like RabbitMQ.

WHEN NOT TO USE IT Do not use lifespan events for any logic that is specific to a single incoming request. This includes user authentication, reading request bodies or headers, or any processing that depends on path or query parameters. For per-request logic, use dependencies or middleware instead.

ONE CANONICAL EXAMPLE A common use case is managing a machine learning model. On startup, you would load the large model file from disk into memory. This can take several seconds and you only want to do it once. On shutdown, you might not need to do anything, but the lifespan function provides a place to gracefully release resources if necessary. This avoids the performance hit of loading the model on the first request.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.