Skip to content
tezvyn:
Menu

FastAPI Lifespan: Code Before Startup, After Shutdown

Source: fastapi.tiangolo.comEasyHow cards are made

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.

Interview question

Which task is best suited for FastAPI's lifespan events?

  • a.Loading a large machine learning model into memory.Correct
  • b.Processing the payload of an incoming HTTP POST request.
  • c.Validating user credentials for an API endpoint.
  • d.Recording the execution time for every API request.
Why?

Lifespan events are designed for one-time, application-wide setup and teardown tasks, such as loading a large ML model. Per-request logic like user validation, payload processing, or request logging should use dependencies or middleware instead.

Just read this? Test yourself on what you have been reading.

Read the original → fastapi.tiangolo.com

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on python — each one lists the topics its interview covers.

See open roles