we are facing issue with self hosted livekit so ba...
# ask-ai
h
we are facing issue with self hosted livekit so basically when web call is initiated the job is been assigned to another worker rather than the worker we are running i am not sure how is this happening i am sharing the logs of the self hosted server we get. We are not running any other worker then why is this happening
Copy code
2025-10-07T09:35:51.725Z        INFO    livekit service/roommanager.go:964      created TURN password   {"username": "LpUZql1VNh3cYZ0UfKIo4rpmWzIjormiaqO3aKJoCC", "password": "RCReAyVgyNBjxwNLmy142ZScsId3hgrJZTAX1w8jqSH"}
2025-10-07T09:35:52.153Z        INFO    livekit.agents  service/agentservice.go:413     assigned job to worker  {"jobID": "AJ_kvZuvT6cA5vP", "namespace": "", "agentName": "", "jobType": "JT_ROOM", "room": "room_22e866d2-db32-4102-9428-99c71afef767", "roomID": "RM_8jCVfLNMqqaA", "workerID": "AW_viZnLorTiLMj"}
t
Thanks for reaching out, Sahil. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm sorry to hear you're having trouble with job assignment in your self-hosted LiveKit setup. Even with just one worker running, there are a few things that might be causing this, and I’m here to help you work through them: • Job Acceptance Timeout: Sometimes, if the worker doesn’t accept the job within 7.5 seconds, the server might try to reassign it. This could be due to slow startup, heavy load, or network delays. • Worker Load Threshold: If your worker’s load goes above the default threshold (0.7 in production), it might be considered unavailable, leading to job reassignment. • Explicit or Implicit Rejection: If the worker’s job handling logic (like
request_fnc
) rejects or doesn’t accept the job properly, it will get reassigned. • Systemic Retry Behavior: Sometimes, the server retries job assignment under certain conditions, even if there’s only one worker. Here are some steps that might help: • Make sure your worker responds to job assignments promptly within the timeout window. • Keep an eye on the load threshold and adjust it if needed. • Review your worker’s job handling logic to catch any possible issues. • Try running the worker on dedicated hardware or containers to minimize any interference. Please feel free to reach out if you'd like me to walk you through any of these steps or if you have any other questions. I’m here to support you! Sources: livekit-agents/livekit/agents/job.py | README.md | pkg/agent/testutils/server.go | Worker options | LiveKit Docs | Getting Help & Troubleshooting | livekit/livekit_composite | DeepWiki
h
but how is this other worker coming from is it something livekit has default and this is my entrypoint func async def entrypoint(ctx: JobContext): await ctx.connect() """Main entry point for LiveKit voice agent""" logger.info(f"🚀 Starting LiveKit Voice Agent for room: {ctx.room.name}") # session_start=datetime.utcnow() start_time = datetime.utcnow() # Resolve call_id in this priority: # 1) room metadata (if you set it via server API) # 2) Redis mapping room_name -> callId (saved by /api/token) # 3) Parse from room name "room_<callId>" # 4) fallback "default" call_id = ctx.room.metadata or None if not call_id: mapped = await get_call_id_for_room(ctx.room.name) if mapped: call_id = mapped if not call_id: nm = ctx.room.name or "" if nm.startswith("room_") and len(nm) > 5: call_id = nm[5:] call_id = call_id or "default" # Fetch config from Redis (shared store). Fallback to RAM (combined) or default. config = await load_config_from_redis(call_id) if not config: config = active_calls.get(call_id, AssistantConfig()) logger.info(f"Using config for call_id: {call_id}, name: {config.name}") # await ctx.connect() # Warn for non-azure providers if config.transcriber.provider.lower() != "azure": logger.warning(f"Transcriber provider '{config.transcriber.provider}' not implemented; using Azure STT.") if config.voice.provider.lower() != "azure": logger.warning(f"Voice provider '{config.voice.provider}' not implemented; using Azure TTS.") if config.model.provider.lower() != "azure": logger.warning(f"Model provider '{config.model.provider}' not implemented; using Azure OpenAI.") def recording_filepath(call_id: str): # produces sessions/<call_id>-2025-09-17T103001.ogg (timestamp iso w/o :) ts = datetime.utcnow().isoformat(timespec='seconds').replace(":", "-") return f"sessions/{ctx.room.name}-{ts}.ogg" try: async def post_transcript_to_backend(payload: dict): if not BACKEND_URL: logger.warning("No TRANSCRIPT_BACKEND_URL configured; skipping post.") return False # Build dynamic endpoint url = f"{BACKEND_URL}/voice/transcript" logger.info(url) logger.info("✅ before function") async with httpx.AsyncClient(timeout=5) as client: logger.info("✅ before post") resp = await client.post(url, json=payload) logger.info("✅ after function") logger.info(resp) if resp.status_code == 200: logger.info("✅ Transcript posted to backend") return True except Exception as e: logger.exception(": %s", e) filepath = recording_filepath(call_id) try: # Initialize Azure services stt = azure.STT( speech_key=os.getenv("AZURE_SPEECH_API_KEY"), speech_region=os.getenv("AZURE_SPEECH_REGION"), language=config.transcriber.language, ) tts = azure.TTS( speech_key=os.getenv("AZURE_SPEECH_API_KEY"), speech_region=os.getenv("AZURE_SPEECH_REGION"), voice=config.voice.voice_id or "en-US-AriaNeural", ) llm = openai.realtime.RealtimeModel.with_azure( azure_deployment=os.getenv("AZURE_OPENAI_MODEL") or config.model.model, azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), api_version="2024-10-01-preview", temperature=config.model.temperature, modalities=["text"] ) agent = DynamicVoiceAssistant(config, call_id) session = AgentSession( preemptive_generation=True, stt=stt, llm=llm, tts=tts, # vad=silero.VAD.load(), vad=ctx.proc.userdata["vad"], ) async def _save_transcript_and_stop_egress(): # safe guard: if session object exists; otherwise try to read ctx.room history if available try: # session.history.to_dict() is LiveKit's conversation view transcript_data = None try: transcript_data = session.history.to_dict() logger.info(transcript_data) except Exception: logger.exception("Could not collect session.history; building minimal payload.") transcript_data = {"items": []} payload = { "botId":config.metadata.bot_id, "userId":config.metadata.user_id, "tenantId": config.metadata.tenant_id, "callId": call_id, "messages": transcript_data.get("items", []), # flatten to just messages "recording": { "egress_id": 'test_1234', "filepath": filepath }, } print(json.dumps(payload, indent=4)) # post to backend await post_transcript_to_backend(payload) except Exception as e: logger.exception("Error while saving transcript to backend: %s", e) # await lkapi.aclose() # register shutdown callback to save transcript and stop egress ctx.add_shutdown_callback(_save_transcript_and_stop_egress) # Store session (meaningful only in combined mode) active_sessions[call_id] = session await session.start( agent=agent, room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ) ) if config.first_message: say_start = datetime.utcnow() await session.say(config.first_message) say_end = datetime.utcnow() logger.info( f"⏱️ First message took {(say_start - start_time).total_seconds():.2f}s " f"to reach say() call, and {(say_end - start_time).total_seconds():.2f}s " f"until it finished queuing TTS." ) # await ctx.connect() except Exception as e: logger.error(f"❌ Error starting agent: {e}") raise
t
Thanks for reaching out! I want to clarify that LiveKit doesn’t automatically create default workers or agents in self-hosted setups. You’ll need to explicitly deploy and start your worker by running your agent code, which then registers itself with the LiveKit server to handle job assignments. If you’re noticing jobs assigned to a worker ID that you didn’t start, it might be due to one of a few reasons: • A worker process you started earlier is still running in the background. • Another instance of your agent code was accidentally launched. • There might be a misconfiguration or an issue in your deployment environment causing duplicate worker registrations. To help you get to the bottom of this, you could try the following: • Check all running processes on your server to make sure no extra worker instances are active. • Take a look at your LiveKit server logs to see when and how that unexpected worker got registered. • Double-check your deployment scripts or environment settings to ensure they aren’t unintentionally starting multiple workers. Please feel free to reach out if you’d like a hand with any of these steps or if anything needs more explanation. I’m here to help! Sources: LiveKit Pricing | LiveKit Docs | README.md | Worker lifecycle | LiveKit Docs | examples/avatar_agents/audio_wave/dispatcher.py
h
how can i check the number of workers for a livekit server
t
To help you check the number of workers connected to your self-hosted LiveKit server, here are a few friendly methods you can try: • Worker HTTP Endpoint: Each worker runs a local HTTP server with a
/worker
endpoint (usually on port 8081). You can reach out to this endpoint to see details about that specific worker, like active jobs and the agent name. Keep in mind, this gives info for each worker individually, not the total count. • Custom Monitoring: If you have several workers, setting up a monitoring service can be really helpful. It can check all the
/worker
endpoints and gather the data to give you an overview of all running workers. • Prometheus Metrics: You might also consider enabling Prometheus metrics in your worker configuration. This lets you connect with monitoring tools like Grafana, making it easier to visualize your workers’ status. Just make sure to turn on the
prometheus_port
option when setting up your workers. And if you’re using a hybrid deployment with LiveKit Cloud, you can conveniently see connected workers right in the LiveKit Cloud dashboard. Please don’t hesitate to ask if you’d like a hand setting any of this up or if you want me to explain anything in more detail. I’m here to help! Sources: Deploying to custom environments | LiveKit Docs | Deploying to production | LiveKit Docs | examples/primitives/room_stats.py | README.md | src/pages/api/room_info/[room].ts