0
0
FastAPIframework~3 mins

Why Startup and shutdown events in FastAPI? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your app start and stop like a pro, without messy code everywhere!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
def start_app():
    connect_db()
    load_settings()

# but what about shutdown?

# scattered cleanup code elsewhere
After
@app.on_event('startup')
async def startup():
    await connect_db()
    load_settings()

@app.on_event('shutdown')
async def shutdown():
    await close_db()
What It Enables

You can ensure your app always prepares and cleans up resources reliably, improving stability and performance.

Real Life Example

A chat app connects to a message broker on startup and disconnects on shutdown, preventing lost messages and resource leaks.

Key Takeaways

Manual resource management is risky and scattered.

Startup and shutdown events centralize setup and cleanup.

This leads to safer, cleaner, and more reliable apps.