We are self-hosting livekit on aws. with sip serve...
# ask-ai
f
We are self-hosting livekit on aws. with sip server also. When the instance is under high load, 3000 concurrent dialings through SIP Server, 120 agent servers with each of 4 vCPU and 8 GB RAM, then agent joins after a long time even on created rooms with SIP participant waiting. I have used explicit dispatch.
t
Thanks for reaching out, Sk. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — you're seeing long agent join times when self-hosting LiveKit + SIP under heavy load (≈3000 concurrent dialings, 120 agent servers, each 4 vCPU/8GB) and you used explicit dispatch. I can help diagnose and narrow this down — a few targeted questions and checks will quickly point to the likely bottleneck. Quick checks to run now • Confirm agent servers' real-time load: what are CPU, memory, and goroutine counts on agent servers during the spike? • Check agent server job counts and `load_threshold`/`load_fnc` settings so we know if servers are refusing new jobs. • Inspect agent-dispatch API latency and error rates (timeouts, 429s, 5xx) when the SIP dial bursts occur. • Verify SIP server logs for any delays between call arrival and dispatch call-out. • Check network latency/bandwidth between SIP server, agent servers, and LiveKit SFU (packet loss, high RTT). • Look at LiveKit SFU and room logs for any errors or throttling when participants are created but an agent hasn’t joined. Questions to narrow scope 1. Are agent servers autoscaled or statically provisioned? If autoscaled, what triggers scale (CPU, queue length)? 2. Are agent servers registering healthy with the dispatch service during the spike? Any frequent connect/disconnects? 3. Does the delay happen for all rooms uniformly or only some rooms/regions? 4. What dispatch method are you using exactly for explicit dispatch (dispatch rule via SIP, AgentDispatchService API, etc.)? 5. Do you see any rate limits or auth/token errors in the dispatch or agent logs at the times of delay? Short actionable suggestions you can try immediately • Prewarm or increase agent capacity so available agents exceed peak concurrent calls (reduce time waiting for new agent spin-up). • Lower
load_threshold
or adjust
load_fnc
to allow more concurrent jobs per agent if CPU/memory permits. • Add short-term scaling headroom (extra servers) to handle bursts and observe if join latency improves. • Instrument and collect metrics (dispatch latency, agent accept time, API response times) to correlate where the wait occurs. • If dispatch API is a bottleneck, spread dispatch calls slightly (backoff) or parallelize dispatch endpoints. If you share: • agent server
load_threshold
and
load_fnc
settings, • whether autoscaling is used and scale policy, • a short snippet of dispatch error logs or latency numbers, I can recommend precise config changes and the next diagnostic commands to run. Sources: SIP dispatch rule | LiveKit docs | Agent dispatch | LiveKit docs | Agents telephony integration | LiveKit docs | Deploying to custom environments | LiveKit Docs | Introducing LiveKit Inference: A unified model interface for voice AI
f
see I have used this:
def compute_load(worker: Worker) -> float:
return min(len(worker.active_jobs) / 25, 1.0) if name == "__main__": cli.run_app(WorkerOptions( entrypoint_fnc=entrypoint, prewarm_fnc=prewarm_process, load_fnc=compute_load, agent_name="xyz-outbound-agent", load_threshold=0.8, shutdown_process_timeout=5 ))
t
Thanks — this is helpful. You're currently capping each worker at 25 jobs and using a 0.8 threshold, so each agent accepts up to 20 concurrent jobs (20/25 = 0.8). With 120 agents that gives 120 × 20 = 2400 capacity, which is below your ~3000 concurrent dialings — that explains the join queueing. Concrete, safe changes to try now 1. Increase per-agent capacity (if CPU/RAM allows) • Change divisor to 50 and raise threshold:
Copy code
def compute_load(worker: Worker) -> float:
    return min(len(worker.active_jobs) / 50, 1.0)

# and
load_threshold=0.9
This yields ~45 jobs/server → 120 × 45 = 5400 capacity. 1. Use actual resource metrics in load calculation • Combine job count with CPU/memory so availability reflects real load:
Copy code
import psutil

def compute_load(worker: Worker) -> float:
    job_load = len(worker.active_jobs) / 50
    cpu = psutil.cpu_percent() / 100.0
    mem = psutil.virtual_memory().percent / 100.0
    return min(max(job_load, cpu, mem), 1.0)
1. Add autoscaling headroom • Scale up sooner (trigger at ~60% average load) and keep a 20–30% buffer so bursts don’t exhaust capacity. 1. Prewarm workers and avoid cold starts • Ensure prewarm_fnc readies models/sessions and keep idle processes running during expected peaks. 1. Increase shutdown grace • Raise
shutdown_process_timeout
from 5s to something longer (e.g., 120s) so active calls aren’t cut during drains/updates. Quick diagnostics to confirm root cause • During a spike, report: avg len(worker.active_jobs) per server, CPU/memory %, and dispatch API latency/errors. • Check agent registration/connect/disconnect rates and any 429/5xx on dispatch calls. • Verify whether job distribution is even across agents. If you want, share the above runtime numbers (active_jobs avg, CPU%, dispatch latency) and I’ll recommend exact divisor/threshold values and autoscaling triggers for your fleet. Sources: Agent server options | LiveKit docs | Deploying to custom environments | LiveKit Docs | Agent server | LiveKit docs | Deploy and scale agents on LiveKit Cloud | Deploy and scale agents on LiveKit Cloud
f
but the dialings are only on sip server, among those, the agent is required to join via dispatch only for the calls which are getting picked up. The percentage is around 30%
t
Thanks — that 30% pickup rate changes the capacity math and gives more headroom. I'll outline what to change and what to measure next. What this means for capacity • If ~30% of 3000 dialings need an agent, peak agent jobs ≈ 0.3 × 3000 = 900 concurrent agent jobs. • With your current config (20 jobs/agent), 120 agents → 2,400 capacity, so you already have capacity above 900. That means join delays are likely not purely a total-capacity shortage. Where delays can still arise • Short bursts: even if overall capacity is sufficient, many picked-up calls arriving simultaneously can create transient contention and dispatch API queuing. • Uneven distribution: jobs may be unevenly assigned, causing some agents to fill while others stay idle. • Agent prewarm / cold-start latency if picked-up calls require spinning up processes. • Dispatch API throttling, auth/token delays, or network latency between SIP, dispatch, and agents. • Shutdown/grace settings causing agents to be unavailable during rolling updates. Recommended next steps (quick and concrete) 1. Measure real-time metrics during a peak burst • peak concurrent picked-up jobs (should be ~900 if 30% of 3000) • per-agent avg and p95
len(worker.active_jobs)
• dispatch API latency histogram and error rates (timeouts, 429, 5xx) • agent process start time (prewarm vs cold start latency) • agent connect/disconnect rates 1. Short-term tweaks to reduce join latency • Ensure prewarm_fnc keeps idle processes ready for immediate join. • Confirm agents aren’t frequently restarting (check connect/disconnect). • If you see transient spikes in dispatch latency, add a small buffer or short delay/backoff on SIP->dispatch calls to smooth bursts. • If distribution is uneven, verify round-robin dispatch and ensure all agents register with the same agent_name and capabilities. 1. If you see cold-start or burst queuing, increase concurrency per agent temporarily • If CPU/memory allow, raise divisor to 50 or raise
load_threshold
(e.g., 0.9) to reduce queuing for simultaneous picked-up calls. 1. Keep
shutdown_process_timeout
> 120s for voice sessions so drains don’t reduce available capacity. Two quick clarifying questions 1. During peak periods, what is the measured peak concurrent picked-up jobs and the per-agent avg/p95 active_jobs? 2. Do picked-up calls arrive in tight bursts (many at once) or spread over time? Share those numbers and I’ll recommend exact
compute_load
divisor,
load_threshold
, and autoscaling triggers to eliminate the join delays.
f
currently per agent server it has 4 vCPU and 8 GB memory. what is the max number of concurrent jobs it can handle?
t
Good question — there isn’t a single fixed “max” because it depends on how CPU‑/memory‑intensive each job is. I’ll give a concise way to estimate capacity for your 4 vCPU / 8 GB server and what to measure to pick a safe limit. How to estimate a safe concurrent-job limit 1. Measure one job’s resource use under realistic load: ◦ Run a representative call handled by an agent and record steady-state CPU% (per core) and memory (MB). ◦ Collect several samples (avg and p95). 1. Compute capacity from CPU and memory separately: ◦ CPU-based limit ≈ (number of vCPUs × 100%) / avg_cpu_percent_per_job. Example: if one job uses 5% of a single core (i.e., ~5% of 1 core), 4 vCPU ×100% = 400%; 400 / 5 = ~80 jobs. • Memory-based limit ≈ (available memory for jobs in MB) / avg_mem_per_job. Reserve some RAM for OS/overheads (e.g., keep 10–20% free). Example: usable ≈ 6.4 GB → 6,400 MB; if job uses 50 MB → 128 jobs. 1. Pick the lower of the two and apply a safety factor (50–75%) to avoid saturation: ◦ Conservative example: if CPU suggests 80 and memory 128, use 0.6×80 ≈ 48 jobs as a safe target. Practical recommendations for your environment • Instrument and report: avg / p95 CPU% and memory per job during peak picked-up calls. Also collect network I/O and goroutine counts if available. • If you can’t measure yet, start conservatively: try 30–50 concurrent jobs per 4vCPU/8GB instance, monitor CPU p95 (<85%) and memory headroom, then raise if headroom remains. • Use the load function to reflect measured limits (e.g., divisor = 40 or 50) and set load_threshold ≈ 0.85–0.9. • Keep autoscaler headroom (20–30%) so bursts don’t exhaust capacity. • If jobs are I/O or model-heavy (large audio processing, ASR/LLM calls), memory or external service latency may be the limiting factor — measure those specifically. If you share one representative job’s avg/p95 CPU% and memory usage, I’ll compute an exact recommended divisor and safe concurrent-job target for your agent servers.
f
from livekit server how to know how many workers registered and how many idle?
t
You're on the right track — here are concise ways to see registered agents and estimate idle workers from your LiveKit server. 1) Quick CLI checks (self-hosted or cloud) • List registered agents:
Copy code
lk agent list
• Detailed status (replicas/instances) for an agent:
Copy code
lk agent status --id <agent_id>
2) Infer active vs idle via sessions (Analytics API) • List active sessions (counts show current agent activity):
Copy code
curl -H "Authorization: Bearer $TOKEN" \
"https://cloud-api.livekit.io/api/project/$PROJECT_ID/sessions?limit=100"
• Compare active session count to agent replicas to estimate idle capacity. 3) Self-hosted / programmatic: expose metrics • Enable Prometheus metrics on agents (set
prometheus_port
) and export metrics like active jobs per worker. • Track: ◦
active_jobs
(per worker) ◦ agent registration/connect counts ◦ dispatch API latencies/errors • Idle workers ≈ registered replicas − sum(active_jobs > 0); use a threshold for "idle" (e.g., active_jobs == 0). 4) Practical approach to compute idle count • Registered workers: from
lk agent list
/ agent status. • Active workers: count workers where
len(active_jobs) > 0
from metrics or session list. • Idle workers = registered − active. If you tell me whether you use the LiveKit CLI, Analytics API, or Prometheus, I’ll give the exact commands/metric names and a short script to compute registered vs idle automatically. Sources: Agent deployment CLI reference | LiveKit docs | Analytics API | LiveKit docs | Deploying to custom environments | LiveKit Docs | Self-hosting the Ingress Service | LiveKit docs | Self-hosting the Egress Service | LiveKit docs
f
this error is coming : 2025-12-02T131303.322Z ERROR livekit service/signal.go:186 could not handle new participant {"room": "room_7586069171_9c80b951-b2d4-4448-b74f-104dfb53acbe", "participant": "agent-AJ_2yLMV3xWYwJ9", "connID": "CO_BkpPVZnigDeh", "error": "could not restart participant", "errorVerbose": "could not restart participant\ngithub.com/livekit/livekit-server/pkg/service.(*RoomManager).StartSession\n\t/workspace/pkg/service/roommanager.go:398\ngithub.com/livekit/livekit-server/pkg/service.(*defaultSessionHandler).HandleSession\n\t/workspace/pkg/service/signal.go:115\ngithub.com/livekit/livekit-server/pkg/service.(*signalService).RelaySignal\n\t/workspace/pkg/service/signal.go:183\ngithub.com/livekit/psrpc/pkg/server.(*streamHandler[...]).handleOpenRequest\n\t/go/pkg/mod/github.com/livekit/psrpc@v0.7.0/pkg/server/stream.go:202\ngithub.com/livekit/psrpc/pkg/server.(*streamHandler[...]).handleRequest.func1\n\t/go/pkg/mod/github.com/livekit/psrpc@v0.7.0/pkg/server/stream.go141\nruntime.goexit\n\t/usr/local/go/src/runtime/asm amd64.s1693"} github.com/livekit/livekit-server/pkg/service.(*signalService).RelaySignal /workspace/pkg/service/signal.go:186 github.com/livekit/psrpc/pkg/server.(*streamHandler[...]).handleOpenRequest /go/pkg/mod/github.com/livekit/psrpc@v0.7.0/pkg/server/stream.go:202 github.com/livekit/psrpc/pkg/server.(*streamHandler[...]).handleRequest.func1 /go/pkg/mod/github.com/livekit/psrpc@v0.7.0/pkg/server/stream.go:141
t
You're seeing "could not restart participant" when an agent participant tries to join. Focus on signaling, agent availability, and resource exhaustion. Please run these checks and share results: 1) LiveKit server logs around the timestamp (±30s) — any preceding WARN/ERROR. 2) Agent logs for that agent name (
agent-AJ_2yLMV3xWYwJ9
) at the same time — connect/disconnect, accept/reject, errors, process start times. 3) Dispatch API metrics — latency, 429s, 5xx during the event. 4) Server resource state at the time — CPU%, memory%, open file descriptors, goroutine counts. 5) Network checks — packet loss/RTT between SIP ⇄ LiveKit ⇄ agent. 6) Is the agent process in draining state or recently restarted? What is
shutdown_process_timeout
? Quick immediate actions you can try • Restart the specific agent process and watch for successful registration and acceptance of a test job. • If agent logs show it’s refusing jobs due to load, temporarily increase per-agent capacity (divisor) or raise
load_threshold
. • Increase
shutdown_process_timeout
(e.g., 120s) if it's currently low (5s). • If dispatch latency or 5xx/429s appear, add short smoothing/backoff when SIP triggers dispatch bursts. Send the requested logs/metrics (or paste excerpts) and I’ll point to the exact config changes or deeper traces to fix the restart failure. Sources: client-sdk-js | livekit/livekit_composite | DeepWiki | Agents (Python) | livekit/livekit_composite | DeepWiki | Understanding &#34;silence detected on local audio track&#34; warning | Understanding the STATE_MISMATCH Disconnect Reason | Deploying to custom environments | LiveKit Docs