Discover how to make your app start and stop like a pro, without messy code everywhere!
Why Startup and shutdown events in FastAPI? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a web app that needs to connect to a database and load some settings every time it starts, and close connections cleanly when it stops.
Without special handling, you have to write this setup and cleanup code everywhere, risking mistakes.
Manually managing startup and shutdown tasks is tricky and error-prone.
If you forget to close a database connection, your app can leak resources and crash later.
If you don't load settings properly, your app might behave unpredictably.
FastAPI's startup and shutdown events let you run code exactly when your app starts and stops.
This keeps your setup and cleanup organized, safe, and automatic.
def start_app(): connect_db() load_settings() # but what about shutdown? # scattered cleanup code elsewhere
@app.on_event('startup') async def startup(): await connect_db() load_settings() @app.on_event('shutdown') async def shutdown(): await close_db()
You can ensure your app always prepares and cleans up resources reliably, improving stability and performance.
A chat app connects to a message broker on startup and disconnects on shutdown, preventing lost messages and resource leaks.
Manual resource management is risky and scattered.
Startup and shutdown events centralize setup and cleanup.
This leads to safer, cleaner, and more reliable apps.
Practice
@app.on_event("startup") in a FastAPI application?Solution
Step 1: Understand the startup event role
The@app.on_event("startup")decorator marks a function to run when the app starts, useful for setup tasks.Step 2: Differentiate from other app parts
Handling requests or shutting down are different concerns; startup is specifically for initialization.Final Answer:
To run code when the application starts, like initializing resources. -> Option DQuick Check:
Startup event = run code at app start [OK]
- Confusing startup with request handling
- Thinking startup runs multiple times per request
- Mixing startup with shutdown event
Solution
Step 1: Recall correct decorator for shutdown
The correct decorator is@app.on_event("shutdown")to run code when the app stops.Step 2: Check syntax correctness
Options A, B, and D use incorrect decorator names or syntax.Final Answer:
@app.on_event("shutdown")\ndef cleanup():\n print("Cleaning up") -> Option CQuick Check:
Shutdown event decorator = @app.on_event("shutdown") [OK]
- Using wrong event name like "start" instead of "shutdown"
- Missing @app.on_event decorator
- Using non-existent decorators like @app.shutdown_event
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"}What will be printed when the server starts and then stops?
Solution
Step 1: Identify startup and shutdown prints
Thestartup_eventprints "Starting app" when the app starts, andshutdown_eventprints "Stopping app" when the app stops.Step 2: Understand event timing
These events run once each: startup at launch, shutdown at server stop.Final Answer:
Starting app (on start), Stopping app (on shutdown) -> Option BQuick Check:
Startup prints "Starting app", shutdown prints "Stopping app" [OK]
- Swapping startup and shutdown outputs
- Expecting prints on every request
- Thinking no output occurs without explicit call
from fastapi import FastAPI
app = FastAPI()
def shutdown_event():
print("App is stopping")
app.on_event("shutdown", shutdown_event)What is the problem?
Solution
Step 1: Check decorator usage
The code usesapp.on_event("shutdown", shutdown_event)which incorrectly passes two arguments toon_event; it expects only the event name and returns a decorator to apply to a function.Step 2: Identify common mistake
FastAPI expects the decorator syntax@app.on_event("shutdown")placed above the function definition for clarity and proper registration.Final Answer:
The decorator syntax is incorrect; should use @app.on_event("shutdown") above the function. -> Option AQuick Check:
Use @app.on_event("shutdown") decorator syntax [OK]
- Assuming function must be async (it can be sync)
- Using wrong function names
- Believing FastAPI lacks shutdown support
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"Solution
Step 1: Understand global variable usage
Sincedbis defined outside functions, to modify it inside functions,global dbis needed.Step 2: Check startup and shutdown logic
The correct version usesglobal dbin both async event handlers, settingdb = "Connected"on startup anddb = Noneon shutdown. Versions withoutglobal dbcreate local variables. One version reverses the connection and disconnection logic.Final Answer:
Option A correctly manages the global db connection on startup and shutdown. -> Option AQuick Check:
Use global to modify external variables in event handlers [OK]
- Forgetting global keyword causes local variable shadowing
- Reversing startup and shutdown logic
- Assuming async is required for all event handlers
