If i have multiple livekit agents running under EC...
# ask-ai
g
If i have multiple livekit agents running under ECS, then how each agent picks the jobs? I want to understand how does the load balancing happens across different agent ecs instances?
t
Thanks for reaching out, Harsh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how multiple LiveKit agents running on ECS pick up jobs and how load is balanced across those ECS instances — here’s how it works. • Agent registration: Each agent container opens an outbound WebSocket to the LiveKit server and registers itself as an available agent server. • Central dispatch: The LiveKit server is the dispatcher. When a job (room/participant task) appears, the server selects one agent to run it — jobs are assigned to a single agent (no shared execution). • Load-aware selection: The server considers each agent’s reported load before assigning work. Agents expose a
load_fnc
(0–1) and a `load_threshold`; by default
load_fnc
is recent CPU utilization (5s average) and
load_threshold
is 0.7. Agents above the threshold won’t receive new jobs. • Distribution strategy: Dispatch uses a round-robin style with load-awareness so work spreads across healthy agents. • Job isolation: Each job runs in its own subprocess on the agent, so one job crashing won’t take others down. • Graceful draining: On shutdown (`SIGTERM`/`SIGINT`), an agent stops accepting new jobs but finishes active ones before exiting. If you want, I can: • Show where to change
load_fnc
or
load_threshold
for ECS agents, • Explain how to monitor agent load and job assignments in your deployment, • Or walk through a sample ECS task/service configuration for agents. Which would you like next? Sources: Deploying to custom environments | LiveKit Docs | Job lifecycle | LiveKit docs | Agent server | LiveKit docs | LiveKit Docs
g
i want to know all three things that you mentioned next
t
You're asking for all three: (1) how to change
load_fnc
and
load_threshold
for ECS agents, (2) how to monitor agent load and job assignments, and (3) a basic ECS task/service example for running agents. I can help with each — a few quick clarifying questions so I give exactly what you need: 1. Do you want instructions for the LiveKit agent code (changing
load_fnc
in the agent process) or for runtime configuration (environment variables / container args) that your ECS tasks will set? 2. Which monitoring stack do you use or prefer (CloudWatch, Prometheus/Grafana, or something else)? 3. Do you need the ECS example for Fargate or EC2-backed tasks? Answer those and I’ll provide concise, actionable steps for each area.
g
how to use load_func, cloudwatch give me for fargate
t
Responding about using
load_fnc
, CloudWatch monitoring, and a Fargate example. 1) Using
load_fnc
and
load_threshold
for agents • LiveKit agents report a load value (0–1) via
load_fnc
. The server uses that value and
load_threshold
to decide whether an agent can accept new jobs. • To customize, run your agent process with a
load_fnc
implementation that returns a float between 0 and 1 representing current load (for example, a CPU utilization fraction). Set
load_threshold
to the maximum acceptable load (default 0.7). • On ECS Fargate, implement
load_fnc
inside the agent container (in the agent code or startup wrapper) so it measures the desired metric (CPU, memory, custom queue length) and exposes it to the agent process. The agent will use that returned value when registering/heartbeating with the LiveKit server. 2) Monitoring with CloudWatch (Container Insights) • Enable CloudWatch Container Insights for your ECS cluster to collect task and container metrics. • Relevant metrics to monitor agent capacity and health: ◦ CPUUtilization (container/task) — use to verify
load_fnc
values if
load_fnc
is based on CPU. ◦ MemoryUtilization (container/task) — if using memory as part of load. ◦ Task count and running task metrics — to see how many agent tasks are active. ◦ Container restart count and task stop events — to detect crashes or drains. • Use CloudWatch Logs to collect agent stdout/stderr so you can inspect agent registration, job assignment, and any load reporting logs. • Create CloudWatch Alarms / Dashboards: ◦ Alarm when CPUUtilization > (your threshold * 100)% for agent tasks. ◦ Dashboards showing per-task CPU/Memory and task counts so you can correlate load with job assignment. 3) Minimal ECS Fargate task/service example (conceptual JSON) • Run the LiveKit agent container as a Fargate task in a service with desired count >1. • Pass any runtime config via environment variables or container args: e.g.,
LOAD_THRESHOLD=0.7
,
LIVEKIT_SERVER_URL=...
,
AGENT_TOKEN=...
. • Example (conceptual fields shown; adapt image, role ARNs, and networking to your account):
Copy code
{
  "family": "livekit-agent-fargate",
  "networkMode": "awsvpc",
  "requiresCompatibilities": [
    "FARGATE"
  ],
  "cpu": "512",
  "memory": "1024",
  "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
  "taskRoleArn": "arn:aws:iam::123456789012:role/ecsTaskRole",
  "containerDefinitions": [
    {
      "name": "livekit-agent",
      "image": "your-registry/livekit-agent:latest",
      "essential": true,
      "environment": [
        {
          "name": "LIVEKIT_SERVER_URL",
          "value": "wss://your-livekit-server:7885"
        },
        {
          "name": "AGENT_TOKEN",
          "value": "your-agent-token"
        },
        {
          "name": "LOAD_THRESHOLD",
          "value": "0.7"
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/livekit-agent",
          "awslogs-region": "us-west-2",
          "awslogs-stream-prefix": "agent"
        }
      }
    }
  ]
}
Practical notes: • Implement
load_fnc
in the container so it measures whatever you want (CPU fraction, memory fraction, or a composite). The agent will use that to accept/decline new jobs. • Enable Container Insights and send container logs to CloudWatch Logs to trace registration and job assignment events. • Use a service desired count >1 so Fargate runs multiple agent containers; LiveKit server will dispatch jobs across them using their reported loads. Would you like: • a concrete code snippet example for a
load_fnc
that returns CPU utilization inside the container, or • step-by-step instructions to enable Container Insights and a sample CloudWatch dashboard?
g
yeah give example for load_func
t
Below is a concise Go example of a
load_fnc
implementation that returns recent CPU utilization as a value between 0.0 and 1.0, plus brief notes on wiring it via environment variables in your Fargate task. Code (Go):
Copy code
package main

import (
	"context"
	"fmt"
	"os"
	"strconv"
	"time"

	"github.com/shirou/gopsutil/cpu"
)

// loadFnc returns CPU utilization as a float64 between 0 and 1.
// It samples CPU usage over a short interval and clamps to [0,1].
func loadFnc(ctx context.Context) float64 {
	// sample interval (seconds) configurable via env; default 5s
	intervalSec := 5
	if v := os.Getenv("LOAD_SAMPLE_SEC"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 {
			intervalSec = n
		}
	}

	// use gopsutil to get percent over interval
	percents, err := cpu.PercentWithContext(ctx, time.Duration(intervalSec)*time.Second, false)
	if err != nil || len(percents) == 0 {
		// if sampling fails, return a conservative high value so server avoids scheduling
		return 1.0
	}

	// percents[0] is total CPU percent (0-100)
	pct := percents[0] / 100.0
	if pct < 0 {
		pct = 0
	}
	if pct > 1 {
		pct = 1
	}
	return pct
}

func main() {
	ctx := context.Background()

	// example: read threshold from env to log it or use elsewhere
	threshold := 0.7
	if v := os.Getenv("LOAD_THRESHOLD"); v != "" {
		if f, err := strconv.ParseFloat(v, 64); err == nil {
			threshold = f
		}
	}

	// periodically log load for CloudWatch logs (stdout)
	ticker := time.NewTicker(10 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			load := loadFnc(ctx)
			fmt.Printf("agent_load=%.3f load_threshold=%.3f\n", load, threshold)
		case <-ctx.Done():
			return
		}
	}
}
Notes to wire this in Fargate: • Build this into your agent container (or run as a sidecar/process that the agent reads). The agent should call the
loadFnc
and report the returned value when registering/heartbeating with the LiveKit server. • Environment variables you can set in your task definition: ◦
LOAD_SAMPLE_SEC
— seconds to sample CPU (default 5). ◦
LOAD_THRESHOLD
— value between 0 and 1 (e.g., "0.7"). • Send container stdout/stderr to CloudWatch Logs (awslogs driver) so the printed
agent_load
lines are captured for monitoring. • Use Container Insights (CloudWatch) to monitor CPUUtilization and correlate with
agent_load
logs. If you want, I can: • provide a variant that uses memory or a composite metric (CPU+memory), • or show how the agent process should expose the load value to the LiveKit agent API (tell me whether the agent is implemented in Go or another language). Which would you prefer?
g
can u give me in python?
t
Below is a concise Python example of a
load_fnc
that returns a value between 0.0 and 1.0, plus brief wiring notes for Fargate and CloudWatch. Python example (uses psutil to read CPU percent; falls back to job-count if sampling fails):
Copy code
import os
import time
from typing import Callable

import psutil
from livekit.agents import AgentServer

# read config from env
SAMPLE_SEC = int(os.getenv("LOAD_SAMPLE_SEC", "5"))
MAX_CONCURRENT_JOBS = int(os.getenv("MAX_CONCURRENT_JOBS", "10"))

def cpu_load_fraction() -> float:
    """Return recent CPU utilization as 0.0-1.0 using psutil.
    Samples over SAMPLE_SEC seconds."""
    try:
        # psutil.cpu_percent blocks for interval and returns 0-100
        pct = psutil.cpu_percent(interval=SAMPLE_SEC)
        frac = max(0.0, min(pct / 100.0, 1.0))
        return frac
    except Exception:
        return 1.0  # conservative if sampling fails

def jobs_based_load(agent_server: AgentServer) -> float:
    """Fallback load based on active job count."""
    try:
        active = len(agent_server.active_jobs)
        return min(active / MAX_CONCURRENT_JOBS, 1.0)
    except Exception:
        return 1.0

def make_load_fnc() -> Callable[[AgentServer], float]:
    def load_fnc(agent_server: AgentServer) -> float:
        # prefer CPU-based metric; if not usable, fall back to job-count metric
        cpu = cpu_load_fraction()
        if cpu < 1.0:
            return cpu
        return jobs_based_load(agent_server)
    return load_fnc

# instantiate server and assign load_fnc and threshold
server = AgentServer(
    load_threshold=float(os.getenv("LOAD_THRESHOLD", "0.7")),
)

server.load_fnc = make_load_fnc()

# Example: periodically log load to stdout for CloudWatch logs
if __name__ == "__main__":
    import logging
    logging.basicConfig(level=logging.INFO)
    while True:
        try:
            curr = server.load_fnc(server)
            logging.info("agent_load=%.3f load_threshold=%.3f", curr, server.load_threshold)
        except Exception as e:
            logging.exception("load check failed: %s", e)
        time.sleep(int(os.getenv("LOG_INTERVAL_SEC", "10")))
Wiring notes for Fargate + CloudWatch • Build this into your agent container (or run as a sidecar). Add
psutil
to your Python dependencies. • Set env vars in your Fargate task definition: ◦
LOAD_THRESHOLD
(e.g., "0.7") ◦
LOAD_SAMPLE_SEC
(e.g., "5") ◦
MAX_CONCURRENT_JOBS
if using job-count fallback • Send container logs to CloudWatch Logs (awslogs driver) so the printed
agent_load
lines are visible. • Enable Container Insights to see
CPUUtilization
and
MemoryUtilization
per task; correlate those with the
agent_load
logs and create CloudWatch alarms (e.g., when CPU > threshold*100%). If you want, I can: • provide a variant that uses a composite (CPU+memory) metric, • or show the exact task-definition JSON snippet that injects these env vars for Fargate. Which would you like? Sources: Agent server options | LiveKit docs | Automation & Knowledge Management Tools | livekit/livekit_composite | DeepW... | Deploying to custom environments | LiveKit Docs | Log collection | LiveKit Docs
g
how to set the env as production for livekit agent in python?
t
You want to set the LiveKit Python agent to run in production on Fargate. Below are the required/env suggestions, best practices for injecting them in Fargate, and the recommended command to start the agent. Required/important environment variables • LIVEKIT_URL — WebSocket URL of your LiveKit server (e.g., wss://your-project.livekit.cloud) • LIVEKIT_API_KEY — API key for agent authentication • LIVEKIT_API_SECRET — API secret (keep in Secrets Manager) • (Optional) Provider/model keys your agent needs, e.g. OPENAI_API_KEY, DEEPGRAM_API_KEY Recommended runtime/config vars • LOAD_THRESHOLD — e.g., "0.7" (agent stops accepting new jobs above this) • LOAD_SAMPLE_SEC — sampling interval for CPU-based load (e.g., "5") • MAX_CONCURRENT_JOBS — if using a job-count fallback (e.g., "10") • LOG_INTERVAL_SEC — how often to emit load logs (e.g., "10") Best practices for Fargate • Inject secrets via AWS Secrets Manager or SSM Parameter Store in the task definition (do not bake secrets into the image). Use the task's
secrets
and
environment
fields. • Send logs to CloudWatch Logs (awslogs driver) and enable Container Insights to monitor CPU/Memory per task. Correlate
agent_load
log lines with Container Insights metrics. • Avoid placing .env files or secrets in the image; add
.env*
to
.dockerignore
. • Use a service desired count >1 so multiple agent tasks register with the LiveKit server and receive jobs. • Ensure graceful shutdown: Fargate stop timeout may be short — prefer long draining or non-Fargate if you require long drain times. Dockerfile / run pattern (production) • Install dependencies, copy code, and run the agent with the production start command. Example CMD: ◦ CMD ["uv", "run", "src/agent.py", "start"] The
start
mode connects the agent to LiveKit and begins accepting jobs. Example ECS Fargate task snippet (conceptual) • In container definition set: ◦ environment: LIVEKIT_URL (value) ◦ secrets: LIVEKIT_API_SECRET (valueFrom ARN in Secrets Manager) ◦ environment: LOAD_THRESHOLD, LOAD_SAMPLE_SEC, MAX_CONCURRENT_JOBS ◦ logConfiguration: awslogs (log group / stream prefix) Quick security checklist • Use Secrets Manager/Parameter Store for API secrets. • Restrict task role permissions to only what's needed (logs, secrets). • Exclude secrets from images and repo. If you’d like, I can: • provide the exact ECS task-definition JSON snippet that injects these env vars and Secrets Manager references, or • show the minimal Dockerfile and
uv
command for a Python agent image. Which would you like next? Sources: examples/survey | livekit/livekit_composite | DeepWiki | Secrets management | LiveKit Docs | examples/drive-thru | livekit/livekit_composite | DeepWiki | examples/frontdesk | livekit/livekit_composite | DeepWiki | server-sdk-go | livekit/livekit_composite | DeepWiki