Introduction to Lifespan Events in FastAPI

Ng Wai Foong
3 min readMar 21

New implementation for startup and shutdown logic

Photo by Marissa&Eric on Unsplash

By reading this piece, you will learn to implement lifespan events in your FastAPI for startup and shutdown logic. From version 0.93.0 onward, the fastapi module officially supports the lifespan event, which replaces the startup and shutdown events.

startup and shutdown events will be deprecated in the future release.

One main advantage of lifespan event is that all the logic can be implemented in a single function. Also, the code for the startup and shutdown events has to be implemented after the initialization of the FastAPI instance.

The lifespan event simplify the entire process by having only a single function which has to be declared before the FastAPI instantiation.

Let’s proceed to the next section to learn more about the differences.

Old Method

Have a look at the following example server which uses the startup and shutdown events for model initialization:

import random
from fastapi import FastAPI

sentiments = ["positive", "neutral", "negative"]

def fake_answer(text: str):
return random.choice(sentiments)

app = FastAPI()

async def startup_event():
app.state.models = {}
app.state.models["sentiment_analysis"] = fake_answer

async def shutdown_event():

async def predict(text: str = "Hello, world!"):
result = app.state.models["sentiment_analysis"](text)
return {"text": text, "result": result}

The code snippet above performs the following actions:


  • initializes a global variable called sentiment with a list of three elements


  • initializes a state variable called models with a dictionary to the function fake_answer


  • clears all the items in the models variable
  • clears all the items in the sentiments variable

New Method

Ng Wai Foong

Senior AI Engineer@Yoozoo | Content Writer #NLP #datascience #programming #machinelearning | Linkedin: