http_context builds a new SSLContext (full CA bundle load) for every job, on the job's event loop
Bug Description
Every job builds its own ssl.SSLContext. ssl.create_default_context() loads and parses the whole CA bundle on each call, and the call runs synchronously on the job's event loop.
At livekit-agents==1.8.4:
- The job runner calls
http_context._new_session_ctx()at job start (job_proc_lazy_main.py#L334) andhttp_context._close_http_ctx()at job end (job_proc_lazy_main.py#L419). - The first
http_session()call of the job runs_new_session, which passesssl=_create_ssl_context()to theTCPConnector(http_context.py#L83)._create_ssl_context()(http_context.py#L47-L62) callsssl.create_default_context()every time. _close_http_ctx()callsval().close()(http_context.py#L108-L113). If the job never usedhttp_session(),val()creates a session (and an SSLContext) only to close it.
So every job pays for one CA bundle load, including jobs that never make an HTTP request. The context does not depend on the job: it depends only on SSL_CERT_FILE / SSL_CERT_DIR and the system trust store, which the worker settles once at startup in _set_default_cert_env().
This started with #6231. Before that change the shared TCPConnector used aiohttp's default context, which aiohttp builds once at import (aiohttp.connector._SSL_CONTEXT_VERIFIED).
Impact: our production worker uses the THREAD executor (all jobs in one process, 2 CPU pods), so every job pays this on its event loop. In the reproduction below the call takes 3.4 ms median per job on an idle laptop, with a 26 ms outlier in the run against main. In my reproduction a second event loop on another thread was not delayed, so the block lands on the job's own loop (its audio and RPC handling) and the CPU time is taken from the other sessions on the host.
Upstream main (96341b0db2d0224403a36612cb04a1e38d60d405) has the same code and the same result.
Expected Behavior
The worker process builds the TLS context once and reuses it for every job's http session. A job that never calls http_session() builds no context at all.
Reproduction Steps
1. Save the script below as repro.py.
2. uv run --no-project --with "livekit-agents==1.8.4" python repro.py
3. The script runs 20 jobs the way the THREAD executor does: one thread and one event loop per job, calling _new_session_ctx() at start and _close_http_ctx() at end. Half of the jobs call http_session(). It counts and times ssl.create_default_context() (a timing wrapper around the real function) and measures how late a 1 ms timer on another loop fires.
- repro.py -
"""livekit-agents builds a new TLS context (full CA bundle parse) for every job.
Runs the same http_context calls the job runner makes
(ipc/job_proc_lazy_main.py: _new_session_ctx() at job start,
_close_http_ctx() at job end), one job per thread with its own event loop,
as the THREAD executor does. A ticker loop on another thread stands for a
concurrent session and records how late its 1 ms timer fires.
"""
import asyncio
import ssl
import statistics
import threading
import time
import livekit.agents
from livekit.agents.utils import http_context
JOBS = 20
TICK = 0.001
ctx_ms: list[float] = []
_orig = ssl.create_default_context
def _timed(*a, **kw):
t0 = time.perf_counter()
try:
return _orig(*a, **kw)
finally:
ctx_ms.append((time.perf_counter() - t0) * 1000)
ssl.create_default_context = _timed # timing wrapper only, calls the real function
async def job(uses_http: bool) -> float:
"""One job as the runner drives it. Returns the longest loop block in ms."""
worst = 0.0
http_context._new_session_ctx()
if uses_http:
t0 = time.perf_counter()
http_context.http_session() # first plugin call opens the session
worst = max(worst, (time.perf_counter() - t0) * 1000)
t0 = time.perf_counter()
await http_context._close_http_ctx() # opens a session first if the job never did
return max(worst, (time.perf_counter() - t0) * 1000)
def run_job(uses_http: bool, out: list[float]) -> None:
out.append(asyncio.run(job(uses_http)))
def ticker(stop: threading.Event, lags: list[float]) -> None:
async def main() -> None:
while not stop.is_set():
t0 = time.perf_counter()
await asyncio.sleep(TICK)
lags.append((time.perf_counter() - t0 - TICK) * 1000)
asyncio.run(main())
def main() -> None:
http_context._set_default_cert_env() # the worker does this once at startup
print(f"livekit-agents {livekit.agents.__version__}, {ssl.OPENSSL_VERSION}")
print(f"default verify paths: {ssl.get_default_verify_paths()}")
# baseline lag of the ticker with no jobs running
stop, base = threading.Event(), []
t = threading.Thread(target=ticker, args=(stop, base))
t.start()
time.sleep(0.5)
stop.set()
t.join()
stop, lags, blocks = threading.Event(), [], []
t = threading.Thread(target=ticker, args=(stop, lags))
t.start()
time.sleep(0.1)
for i in range(JOBS):
j = threading.Thread(target=run_job, args=(i % 2 == 0, blocks))
j.start()
j.join()
time.sleep(0.02)
stop.set()
t.join()
def q(xs: list[float]) -> str:
xs = sorted(xs)
return f"median {statistics.median(xs):.2f} ms, p95 {xs[int(len(xs) * 0.95) - 1]:.2f} ms, max {xs[-1]:.2f} ms"
print(f"jobs run: {JOBS} (half never call http_session())")
print(f"ssl.create_default_context calls: {len(ctx_ms)}; per call: {q(ctx_ms)}")
print(f"job loop block in http_context calls: {q(blocks)}")
print(f"other session's 1 ms timer lateness, idle: {q(base)}")
print(f"other session's 1 ms timer lateness, during jobs: {q(lags)}")
if len(ctx_ms) > 1:
print(f"FAIL: {len(ctx_ms)} TLS contexts built for {JOBS} jobs (expected 1 per process)")
else:
print("PASS: one TLS context per process")
if __name__ == "__main__":
main()
- Output on livekit-agents 1.8.4 (macOS, Python 3.14.3) -
livekit-agents 1.8.4, OpenSSL 3.5.5 27 Jan 2026
default verify paths: DefaultVerifyPaths(cafile='/private/etc/ssl/cert.pem', capath='/private/etc/ssl/certs', openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/private/etc/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/private/etc/ssl/certs')
jobs run: 20 (half never call http_session())
ssl.create_default_context calls: 20; per call: median 3.42 ms, p95 3.94 ms, max 4.65 ms
job loop block in http_context calls: median 3.57 ms, p95 4.24 ms, max 4.94 ms
other session's 1 ms timer lateness, idle: median 0.15 ms, p95 0.17 ms, max 0.21 ms
other session's 1 ms timer lateness, during jobs: median 0.15 ms, p95 0.18 ms, max 0.40 ms
FAIL: 20 TLS contexts built for 20 jobs (expected 1 per process)
- Output on main 96341b0db2d0224403a36612cb04a1e38d60d405 -
$ uv run --no-project --with "livekit-agents @ git+https://github.com/livekit/agents@96341b0db2d0224403a36612cb04a1e38d60d405#subdirectory=livekit-agents" python repro.py
livekit-agents 1.8.4, OpenSSL 3.5.5 27 Jan 2026
default verify paths: DefaultVerifyPaths(cafile='/private/etc/ssl/cert.pem', capath='/private/etc/ssl/certs', openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/private/etc/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/private/etc/ssl/certs')
jobs run: 20 (half never call http_session())
ssl.create_default_context calls: 20; per call: median 3.59 ms, p95 7.05 ms, max 25.93 ms
job loop block in http_context calls: median 3.77 ms, p95 7.36 ms, max 26.00 ms
other session's 1 ms timer lateness, idle: median 0.15 ms, p95 0.16 ms, max 0.21 ms
other session's 1 ms timer lateness, during jobs: median 0.15 ms, p95 0.17 ms, max 0.39 ms
FAIL: 20 TLS contexts built for 20 jobs (expected 1 per process)
Operating System
macOS 26 (Darwin 25.5.0) arm64 for the reproduction; Linux containers (2 CPU) in production
Models Used
Not model specific (the shared http session is used by every aiohttp based plugin)
Package Versions
livekit-agents==1.8.4 (also upstream main 96341b0db2d0224403a36612cb04a1e38d60d405)
aiohttp==3.14.3
Python 3.14.3, OpenSSL 3.5.5
Session/Room/Call IDs
Not applicable (self-hosted, reproduces without a room).
Proposed Solution
# livekit/agents/utils/http_context.py
import functools
@functools.cache
def _create_ssl_context() -> ssl.SSLContext:
...
Additional Context
Proposed solution note: One SSLContext can be shared across threads and event loops. Applying exactly this cache in process to 1.8.4 makes the reproduction report ssl.create_default_context calls: 1 and PASS: one TLS context per process, and the job loop block drops from 3.4 ms to 0.06 ms median. The worker could also build it once right after _set_default_cert_env(), so the first job does not pay for it either. Separately, _close_http_ctx() could skip creating a session when none was created.
We work around this in our worker by wrapping http_context._create_ssl_context in functools.cache and calling it once in the prewarm hook.
I used an AI assistant to trace this and draft the report; I verified the reproduction myself.
Screenshots and Recordings
None.