In aiohttp or httpx do I need to close session/client on application shutdown

1.9k views Asked by At

I am using httpx library but I think the principle for aiohttp is the same. If I create and reuse AsyncClient for multiple requests throughout the lifetime of the application do I need to call aclose() (or close if use Client) at the application shutdown event? Or will those connections die themselves.

What if I run application in Docker container? Will that be a factor as well?

I don't understand what's going on underneath AsyncClient or Client (or ClientSession in aoihttp) objects.

Thanks for help.

1

There are 1 answers

1
lsabi On BEST ANSWER

I suggest you to use the triggers on startup and shutdown. They are described in the docs https://fastapi.tiangolo.com/advanced/events/#events-startup-shutdown.

Below an adaptation of the example taken from the docs:

from fastapi import FastAPI
import httpx

app = FastAPI()

items = {}
client = None


@app.on_event("startup")
async def startup_event():
    items["foo"] = {"name": "Fighters"}
    items["bar"] = {"name": "Tenders"}
    client = httpx.AsyncClient()

@app.on_event("shutdown")
async def shutdown_event():
    items["foo"] = {"name": "Fighters"}
    items["bar"] = {"name": "Tenders"}
    await client.aclose()

EDIT

Sorry, misunderstood the question.

Anyway, as @Klaus D commented, the system should kill the child process(es if many are spawned) that keep open ports.

In my experience, this may not always be the case, as I remember when programming with php, I had to manually kill all the database connections, otherwise on application restart I got "The process is already using that port".

Although it was the case of a database connection and not an HTTP connection, it is always good practice to close all unused connections, since the OS may have a delay in noticing the running process with the open port and killing it. So your app (or whatever you have) would be stopped, but the process still running after a while.

Updates to the OS may change the behavior of the process watcher and depend on the OS itself. So, take what I say with a grain of salt.