Lifespan of a FastAPI
Let's learn the Lifespan
Lifespan of a FastAPI
What is Lifespan?
In FastAPI, lifespan refers to the period covering the startup and shutdown phases of the application.
It allows you to:
- Run initialization tasks when the app starts.
- Perform cleanup tasks when the app shuts down.
In simple terms,
“lifespan” gives you a structured way to execute code at the very beginning and the very end of the app’s life cycle.
Why Do We Need a Lifespan?
Some typical use cases where lifespan is essential include:
- Initializing and closing database connections
- Connecting and disconnecting from cache servers
- Launching background tasks
- Releasing resources like file handles or network sockets
- Running health checks
As systems grow more complex,
managing startup and shutdown tasks properly becomes critical for stability and reliability.
How to Use Lifespan
In FastAPI, you define lifespan logic using @asynccontextmanager
.
Flow Summary:
- Server starts → execute code before
yield
. - Server is running → handle HTTP requests.
- Server shuts down → execute code after
yield
.
1
2
3
4
5
6
7
8
9
10
11
12
13
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
# Code to run at app startup
print("The app has started!")
yield # FastAPI runs the application here
# Code to run at app shutdown
print("The app is shutting down!")
app = FastAPI(lifespan=lifespan)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(MyDev) D:\02.MyCode\GP-MyReference\11.MyFastAPI>python main.py
INFO: Will watch for changes in these directories: ['D:\\02.MyCode\\GP-MyReference\\11.MyFastAPI']
INFO: Uvicorn running on http://127.0.0.1:9248 (Press CTRL+C to quit)
INFO: Started reloader process [31952] using StatReload
INFO: Started server process [38816]
INFO: Waiting for application startup.
The app has started!
INFO: Application startup complete.
INFO: Shutting down
INFO: Waiting for application shutdown.
The app is shutting down!
INFO: Application shutdown complete.
INFO: Finished server process [38816]
INFO: Stopping reloader process [31952]
(MyDev) D:\02.MyCode\GP-MyReference\11.MyFastAPI>
More Realistic Example
Key Points:
asyncio.create_task()
is used to start an asynchronous background job.- Upon shutdown, the task is gracefully canceled to prevent resource leaks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import asyncio
from contextlib import asynccontextmanager
async def periodic_task():
while True:
logging.info("Running periodic task...")
await asyncio.sleep(5) # Executes every 5 seconds
@asynccontextmanager
async def lifespan(app: FastAPI):
logging.info("Starting app initialization...")
task = asyncio.create_task(periodic_task()) # Launch background task
# The code above yield is executed when the app starts.
# The code below yield is executed when the app shuts down.
yield
logging.info("Preparing for app shutdown...")
task.cancel() # Cancel background task
try:
await task
except asyncio.CancelledError:
logging.info("Background task has been safely canceled.")
app = FastAPI(lifespan=lifespan)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(MyDev) D:\02.MyCode\GP-MyReference\11.MyFastAPI>python main.py
INFO: Will watch for changes in these directories: ['D:\\02.MyCode\\GP-MyReference\\11.MyFastAPI']
INFO: Uvicorn running on http://127.0.0.1:9248 (Press CTRL+C to quit)
INFO: Started reloader process [32624] using StatReload
INFO: Started server process [41176]
INFO: Waiting for application startup.
[INFO] 2025-04-28 17:02:53,703 Starting app initialization...
[INFO] 2025-04-28 17:02:53,703 Running periodic task...
INFO: Application startup complete.
[INFO] 2025-04-28 17:02:58,710 Running periodic task...
[INFO] 2025-04-28 17:03:03,725 Running periodic task...
INFO: Shutting down
INFO: Waiting for application shutdown.
[INFO] 2025-04-28 17:03:07,989 Preparing for app shutdown...
[INFO] 2025-04-28 17:03:07,989 Background task has been safely canceled.
INFO: Application shutdown complete.
INFO: Finished server process [41176]
INFO: Stopping reloader process [32624]
This post is licensed under CC BY 4.0 by the author.