2

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.

andnik
  • 2,405
  • 2
  • 22
  • 33
  • 1
    Typically the OS will close all connections open by a process if the process has ended. The same is valid for Docker containers, they are just isolated processes. – Klaus D. Dec 02 '20 at 06:09
  • I upvoted your answer but I don't think that is the answer I was looking for in this question, as I was trying to understand do I need to call aclose() on application shutdown specifically or connection will be closed automatically. The answer below answers it a bit better. – andnik May 24 '23 at 14:03

1 Answers1

5

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.

lsabi
  • 3,641
  • 1
  • 14
  • 26
  • Thanks @Isabi , but that's not exactly what I am asking. I wonder what can happen if I don't close client on application shutdown. – andnik Dec 03 '20 at 05:52