Performance: Startup and shutdown events
This concept affects the initial server readiness time and graceful shutdown, impacting how fast the app starts serving requests and releases resources.
Jump into concepts and practice - no test required
import asyncio from fastapi import FastAPI app = FastAPI() @app.on_event("startup") async def startup_event(): await asyncio.sleep(0) # Non-blocking placeholder print("App started")
from fastapi import FastAPI app = FastAPI() @app.on_event("startup") def startup_event(): import time time.sleep(5) # Blocking delay print("App started")
| Pattern | Blocking Behavior | Startup Delay | Shutdown Delay | Verdict |
|---|---|---|---|---|
| Blocking synchronous startup code | Blocks event loop | Delays startup by seconds | N/A | [X] Bad |
| Non-blocking async startup code | Non-blocking | Immediate startup | N/A | [OK] Good |
| No resource cleanup on shutdown | N/A | N/A | Prolonged shutdown, leaks | [X] Bad |
| Async resource cleanup on shutdown | Non-blocking | N/A | Fast, clean shutdown | [OK] Good |
@app.on_event("startup") in a FastAPI application?@app.on_event("startup") decorator marks a function to run when the app starts, useful for setup tasks.@app.on_event("shutdown") to run code when the app stops.from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
async def startup_event():
print("Starting app")
@app.on_event("shutdown")
async def shutdown_event():
print("Stopping app")
@app.get("/")
async def read_root():
return {"message": "Hello"}startup_event prints "Starting app" when the app starts, and shutdown_event prints "Stopping app" when the app stops.from fastapi import FastAPI
app = FastAPI()
def shutdown_event():
print("App is stopping")
app.on_event("shutdown", shutdown_event)app.on_event("shutdown", shutdown_event) which incorrectly passes two arguments to on_event; it expects only the event name and returns a decorator to apply to a function.@app.on_event("shutdown") placed above the function definition for clarity and proper registration.from fastapi import FastAPI
app = FastAPI()
db = None
# Option A
@app.on_event("startup")
async def connect_db():
global db
db = "Connected"
@app.on_event("shutdown")
async def close_db():
global db
db = None
# Option B
@app.on_event("startup")
def connect_db():
db = "Connected"
@app.on_event("shutdown")
def close_db():
db = None
# Option C
@app.on_event("startup")
async def connect_db():
db = "Connected"
@app.on_event("shutdown")
async def close_db():
db = None
# Option D
@app.on_event("startup")
async def connect_db():
global db
db = None
@app.on_event("shutdown")
async def close_db():
global db
db = "Connected"db is defined outside functions, to modify it inside functions, global db is needed.global db in both async event handlers, setting db = "Connected" on startup and db = None on shutdown. Versions without global db create local variables. One version reverses the connection and disconnection logic.