Like its mentioned in the livekit documentation, 4...
# ask-ai
a
Like its mentioned in the livekit documentation, 4core CPU with 8GB Ram can easily handle 30 concurrent audio only sessions at a time. What I want to have about 500 concurrent audio session running at the same time without compromising on latency?
t
Thanks for reaching out, Hiren. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Great news! Scaling to 500 concurrent audio-only sessions is definitely something LiveKit can handle smoothly. Here are some options to consider: • For Self-Hosting: You can deploy LiveKit with Redis to enable clustering and distributed operation. Using a compute-optimized machine (like one with 16 vCPUs) is ideal, and keeping an eye on bandwidth and CPU usage will help ensure everything runs efficiently. A single node is usually enough to support this load comfortably. • For Best Latency & Resilience: LiveKit Cloud is a fantastic choice. It scales automatically, keeps latency under 100ms globally, and manages failure recovery seamlessly. Plus, it can support up to 100,000 participants per session! Both options benefit from LiveKit’s efficient audio handling features, including Opus DTX, which helps reduce bandwidth usage. If you'd like, I’m here to help with any setup questions or to provide more details—just let me know! Sources: Bringing Zoom's end-to-end optimizations to WebRTC | Benchmarking | LiveKit docs | config-sample.yaml | examples/voice_agents/llamaindex-rag/data/raw_data.txt
a
Self Hosting with 16 vCPUs is for the only Livekit Server to be installed.. right?? how many concurrency it can handle?? What about workers?
t
Thank you for reaching out! When it comes to a self-hosted LiveKit server with 16 vCPUs, the number of concurrent users it can support really depends on a few things like your room setup, the media resolution you're using, and your network conditions. While we don’t have exact benchmarks for this specific setup, LiveKit is designed with scalability in mind. For instance, a single node with 16 vCPUs can typically handle thousands of audio-only subscribers under normal conditions. About workers—they’re special processes that take care of tasks like media processing or AI inference. You can set them up to handle jobs at the room or publisher level, which helps spread the workload across multiple cores for better performance. If you’d like, I’d be happy to walk you through how to configure workers or help you test your setup to find its concurrency limits. Just let me know! Sources: Going beyond a single-core | Quotas and limits | LiveKit docs | LiveKit Docs | examples/avatar_agents/audio_wave/dispatcher.py | agents/src/worker.ts
a
Yes.. please walk me through to configure workers
t
To help you set up workers in your self-hosted LiveKit server, here’s a friendly step-by-step guide you can follow: 1. Set Environment Variables: Start by configuring your worker to connect to your LiveKit server. You’ll want to set these variables:
Copy code
LIVEKIT_URL=ws://your-livekit-server:7880
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret
2. Define Worker Options: Next, use the
WorkerOptions
class to customize how your worker behaves. This includes: ◦ Choosing an entrypoint function for your job logic ◦ Setting up a request handler to accept or reject jobs ◦ Monitoring load and setting thresholds ◦ Specifying the worker type (ROOM or PUBLISHER) ◦ Assigning permissions like publish and subscribe 1. Run the Worker: You can implement your worker logic in Python or Node.js. Here’s a simple example in Python:
Copy code
from livekit.agents import WorkerOptions, worker
worker_options = WorkerOptions(
    ws_url="ws://your-livekit-server:7880",
    api_key="your-api-key",
    api_secret="your-api-secret",
    worker_type="ROOM",
    permissions={"can_publish": True, "can_subscribe": True},
    load_threshold=0.7
)
worker = Worker(worker_options)
await worker.run()
2. Deploy the Worker: When you’re ready to deploy, Docker or Kubernetes are great options. For Docker, your Dockerfile might look like this:
Copy code
FROM python:3.11-slim
WORKDIR /app
COPY . .
CMD ["python", "worker.py"]
3. Monitor and Scale: Your workers will balance load automatically and can handle multiple jobs at once. It’s a good idea to keep an eye on health checks and resource usage to keep everything running smoothly. If you have any questions or want to dive deeper into any of these steps, just let me know—I’m here to help! Sources: Worker lifecycle | LiveKit Docs | Deploying to custom environments | LiveKit Docs | Worker options | LiveKit Docs | examples/avatar_agents/audio_wave/dispatcher.py
a
this is how my worker is configured.. but to have 500 concurrency where these workers will be engaged in rooms handled by that 16 vCpu server.. what config of machine would require to host this worker
t
To comfortably host workers for 500 concurrent sessions, here’s a recommended machine setup that has worked well in similar situations: • CPU and Memory: A 16-core machine with 32GB of memory is a solid choice and has been tested successfully. • Network: I’d suggest using a 10Gbps ethernet connection or faster to ensure smooth handling of high data throughput. • Performance Tuning: You can optimize system settings with these commands:
Copy code
ulimit -n 65535
sysctl -w fs.file-max=2097152
sysctl -w net.core.somaxconn=65535
This setup should support your load effectively. If you’d like, I’m here to help you with deployment or discuss scaling options further—just let me know! Sources: LiveKit Server Platform | livekit/livekit_composite | DeepWiki | README.md | Deploying LiveKit | LiveKit Docs | examples/server-do.yaml
a
you didnt mentioned ram size for livekit server hosting, there you only said 16vCore cpu
t
For a LiveKit server with 16 vCPUs, a good starting point for RAM would be around 4-6GB. This suggestion comes from looking at how 8-core setups usually use about 2GB of memory. That said, the exact amount you’ll need really depends on your specific workload, including things like: • How many users are connected at the same time and how your rooms are set up • Any extra services you might be running, such as Ingress/Egress or AI agents • Your media settings, like video resolution and the number of tracks If you’d like, feel free to share more details about your setup, and I’d be happy to help tailor this recommendation just for you. Sources: examples/server-gke-vpc-native.yaml | Self-hosting the Ingress Service | LiveKit docs | Deploying to custom environments | LiveKit Docs | Deploying LiveKit | LiveKit Docs
a
There's not going to be video at all.. Only 2 participants in a single room which is a single session.. there are more than 500 rooms means total about 1000 participants talking over audio with ai agent.. with egress for call recording
t
Thank you for sharing your setup details with 500 audio-only rooms, 1,000 participants, AI agents, and call recording egress. Here are some recommendations to help you get everything running smoothly: • LiveKit Server: I suggest using a 16 vCPU, 32GB RAM compute-optimized instance with 10Gbps networking. This setup should comfortably handle your load. • Egress Service: It’s best to deploy separate egress pods with autoscaling. You can start with 1 replica and scale up to 5 based on CPU usage. Each egress pod would need around 5-8 vCPUs and 1-2GB RAM. • AI Agents: For the AI agents, allocating 4 vCPUs and 8GB RAM per worker usually works well. Each worker can manage 10–25 concurrent jobs depending on how complex they are. • Horizontal Scaling: Starting with 2-3 LiveKit server replicas will provide good redundancy. Then, you can set up autoscaling to go up to 8 replicas when CPU usage hits about 60%. • Redis Coordination: Don’t forget to configure Redis properly for distributed setups. This helps manage room distribution smoothly across your nodes. This architecture balances vertical and horizontal scaling nicely to support your workload. If you’d like, I’m here to help with any specific configurations or deployment steps you might need. Just let me know! Sources: Deploying LiveKit | LiveKit Docs | Benchmarking | LiveKit docs | Deploying to custom environments | LiveKit Docs | examples/server-do.yaml
i
async def entrypoint(ctx: JobContext) -> None: await ctx.connect() logger.info("Connected to LiveKit room") if ctx.room and ctx.room.local_participant: agent_identity = ctx.room.local_participant.identity logger.info(f"LiveKit Agent connected with ID: {agent_identity}") else: logger.warning("No local participant found for this worker.") base_llm = openai.LLM(model="gpt-4o-mini") session = AgentSession( vad=silero.VAD.load(), turn_detection='stt', stt=assemblyai.STT( end_of_turn_confidence_threshold=0.5, min_end_of_turn_silence_when_confident=200, max_turn_silence=1500, ), llm=base_llm, tts=openai.TTS(model="gpt-4o-mini-tts", voice="alloy"), ) vatar = bey.AvatarSession( avatar_id="694c83e2-8895-4a98-bd16-56332ca3f449", api_key=os.getenv("BEYOND_PRESENCE_API_KEY") ) await avatar.start(session, room=ctx.room) # Start the agent session await session.start( agent=QuizBot(topic=department), room=ctx.room, room_input_options=RoomInputOptions( text_enabled=True, noise_cancellation=noise_cancellation.BVC(), close_on_disconnect=False, ), room_output_options=RoomOutputOptions( audio_enabled=False ) ) def handle_data_packet(data_packet): async def _process_packet(dp): try: # Log the raw packet and participant info logger.info("DATA PACKET RAW: participant=%s, kind=%s, data_len=%d", getattr(dp, "participant", None), getattr(dp, "kind", None), len(getattr(dp, "data", b""))) part = getattr(dp, "participant", None) pid = getattr(part, "identity", None) if part else None logger.info("DATA PACKET participant.identity: %s", pid) text = dp.data.decode("utf-8") if dp.data else "" logger.info("User text decoded: '%s'", text) # Call generate_reply and capture the result logger.info("Calling session.generate_reply(...) now") handle = await session.generate_reply(user_input=text) logger.info("generate_reply returned: %s", repr(handle)) # If handle supports waiting for playback, await it (best-effort) if handle is not None: # try common names for playback completion methods for attr in ("wait_for_playback_completion", "wait", "wait_playback", "join"): if hasattr(handle, attr): logger.info("Awaiting playback via handle.%s()", attr) try: await getattr(handle, attr)() logger.info("Playback wait returned successfully.") except Exception as e: logger.exception("Error while awaiting handle.%s: %s", attr, e) break # Small pause and then dump session.history (string-limited) await asyncio.sleep(0.8) try: hist = session.history.to_dict() logger.info("Session history snapshot keys: %s", list(hist.keys())[:10]) # log last assistant item if present msgs = hist.get("messages", []) if isinstance(hist, dict) else [] logger.info("Last 3 history messages (summary): %s", msgs[-3:]) except Exception as e: logger.exception("Could not read session.history: %s", e) logger.info("Finished processing data packet for text: '%s'", text) except Exception as exc: logger.exception("Unhandled exception inside _process_packet: %s", exc) try: asyncio.create_task(_process_packet(data_packet),name="process_data_packet") except RuntimeError: loop=asyncio.get_event_loop() loop.create_task(_process_packet(data_packet)) # Register the data packet handler on the room ctx.room.on("data_received", handle_data_packet) logger.info("Data packet handler registered") # ctx.shutdown(reason="user left the room") if name == "__main__": mp.set_start_method('spawn', force=True) cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint,shutdown_process_timeout=5))
t
Thank you so much for sharing your worker configuration! It looks like you’ve set it up thoughtfully for handling audio-only sessions with AI agents and egress. If you have any questions about fine-tuning this setup or need a hand with deployment, scaling, or troubleshooting, please don’t hesitate to reach out. I’m here to help and would love to guide you through any challenges you might be facing.