Understanding Startup and Shutdown Events in FastAPI and ASGI Applications

Posted by

What you need to know about Startup and Shutdown Events in FastAPI and ASGI Applications

What you need to know about Startup and Shutdown Events in FastAPI and ASGI Applications

When building FastAPI and ASGI applications, it’s important to understand the concepts of startup and shutdown events. These events allow you to perform actions before the application starts and after it shuts down, respectively.

Startup Events

Startup events are triggered when the application is initialized. This is where you can perform tasks like setting up database connections, initializing caches, or loading configuration settings. In FastAPI, you can define startup event handlers using the app.on_event("startup") decorator.


from fastapi import FastAPI

app = FastAPI()

@app.on_event("startup")
async def startup_event():
    # Perform startup tasks here

Shutdown Events

Shutdown events are triggered when the application is shutting down. This is where you can perform tasks like closing database connections, cleaning up resources, or saving application state. In FastAPI, you can define shutdown event handlers using the app.on_event("shutdown") decorator.


@app.on_event("shutdown")
async def shutdown_event():
    # Perform shutdown tasks here

Order of Execution

It’s important to note that startup events are executed in the order they are defined, while shutdown events are executed in the reverse order. This means that if you have multiple event handlers, you can control the order in which they are executed by defining them accordingly.

Conclusion

Understanding startup and shutdown events in FastAPI and ASGI applications is crucial for ensuring that your application starts and stops gracefully. By utilizing these event handlers, you can perform necessary setup and cleanup tasks to ensure that your application runs smoothly.

0 0 votes
Article Rating
16 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@graingert
1 month ago

On FastAPI you can use anyio.fail_after instead of asyncio.timeout or wait_for

@nitishvirtual4745
1 month ago

Again, awesome video. Please cover middleware and CORS.

@LiquidMasti
1 month ago

Very Good and Informative series using FASTAPI for 2 years now but never knew this much is going into backend.

@Ca1vema
1 month ago

What you really have to know is that it is poorly designed and you cannot start asyncio tasks prior ASGI application startup. So if your application is something more complex than CRUD – you'll have to start all your background tasks in framework's lifespan handler, which, sometimes, is strange, because HTTP API might not be the only part of an application.

**It might already be fixed though.

***all the flaws of ASGI applications might be the reason for why it still has no PEP

@sebastianrossetti6167
1 month ago

Awesome video as usual. Will this series include a global request rate limiter? Both for incoming requests to avoid sever overload, and requests from the app to an external API. I know you showed how to do an external API rate limiter in a previous video, but it was for batch requests, it was not in the context of an ASGI application. Thanks!

@YADOLBAYOB
1 month ago

Thank you. This series is very interesting.

I have a question about the assertion you used. What is your opinion about it on production code? I always avoid this kind of code, except for test cases (pytest and etc) .

@Ontaro
1 month ago

this is amazing! thank you!

@prosodyspeaks4036
1 month ago

this series is super useful, thanks so much!

@mattmess1221
1 month ago

I hope the next video is about middleware.

@cgyh68748
1 month ago

could you do how to install certain packages in arch linux?

@matis9783
1 month ago

great video and great series

@YuvrajRaghuvanshiS
1 month ago

It's past midnight and I won't sleep, love your videos!

@softbubble_
1 month ago

this is great

@aashayamballi
1 month ago

thank you!

@alice-smith
1 month ago

Hey James, this series is awesome :^)

@sanscipher9166
1 month ago

Discord gang. (Damn, there are a lot of bots)