Hey folks! How are you dealing with async clients ...
# agents
k
Hey folks! How are you dealing with async clients inside LiveKit agents? I was checking the issue created in June https://github.com/livekit/agents/issues/2585, and we have a similar problem with sharing gRPC and Redis clients between worker calls. The most common pattern we use is to initialize database or API clients as singleton objects in the
main.py
and share these objects with any class that needs to connect to a database/redis cache/grpc service/etc. There is a single client for the entire time that the service is up. The problem with LiveKit workers is that they create a new asyncio event loop for every entrypoint inside
_ProcClient.run
(please correct me if I'm wrong), and calls to, e.g., the async Redis client, will fail because that singleton client was created in a different loop. One way to fix it is to create a new client on every session received in the entrypoint function, creating a new connection pool or asyncio channel, etc. Another option we found is to set up LiveKit to spawn threads instead of processes (by using
opts.job_executor_type = JobExecutorType.THREAD
) and create a
threading.local()
variable to initialize a new Redis client but for each thread. If LiveKit uses a thread pool, it should reuse these clients instead of creating new instances on every call request. But this approach still affects the startup time of the entrypoint function. How feasible is it to share an event loop between worker processes to avoid these issues?
Our current flow right now is something like this: • livekit worker is initialized -> worker receives a call -> creates a Redis/DB/gRPC client -> fetches data to handle the request And the desired flow would be: • A singleton async Redis client is creted -> livekit worker is initialized -> the worker reuses the previous Redis client inside the entrypoint function to fetch data
r
Each agent entrypoint is in it's own process. You would need some sort of REST interface or something if you want to have a common API layer.
k
And if I need the agent to fetch customer data from a cache, the approach should be to create a new instance of the cache client for every request to the entrypoint?