From 4d3662d4da44579ba0ba860786d1ea06056615e1 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 3 Jul 2023 13:21:59 -0500 Subject: [PATCH] Tune httpx keep alives for polling integrations (#95782) * Tune keep alives for polling integrations aiohttp closes the connection after 15s by default, and httpx closes the connection after 5s by default. We have a lot of integrations that poll every 10-60s which create and tear down connections over and over. Set the keep alive time to 65s to maximize connection reuse and avoid tls negotiation overhead * Apply suggestions from code review * adjust --- homeassistant/helpers/httpx_client.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/homeassistant/helpers/httpx_client.py b/homeassistant/helpers/httpx_client.py index beb084d8c1c..93b199b1db5 100644 --- a/homeassistant/helpers/httpx_client.py +++ b/homeassistant/helpers/httpx_client.py @@ -19,8 +19,13 @@ from homeassistant.util.ssl import ( from .frame import warn_use +# We have a lot of integrations that poll every 10-30 seconds +# and we want to keep the connection open for a while so we +# don't have to reconnect every time so we use 15s to match aiohttp. +KEEP_ALIVE_TIMEOUT = 15 DATA_ASYNC_CLIENT = "httpx_async_client" DATA_ASYNC_CLIENT_NOVERIFY = "httpx_async_client_noverify" +DEFAULT_LIMITS = limits = httpx.Limits(keepalive_expiry=KEEP_ALIVE_TIMEOUT) SERVER_SOFTWARE = "{0}/{1} httpx/{2} Python/{3[0]}.{3[1]}".format( APPLICATION_NAME, __version__, httpx.__version__, sys.version_info ) @@ -78,6 +83,7 @@ def create_async_httpx_client( client = HassHttpXAsyncClient( verify=ssl_context, headers={USER_AGENT: SERVER_SOFTWARE}, + limits=DEFAULT_LIMITS, **kwargs, )