This message was deleted.
# ask-ai
s
This message was deleted.
t
Thanks for reaching out, Dipesh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks for reaching out! To better assist you, could you please clarify if you’re looking to set concurrency limits on the server-side (like agent workers), client connections, or media subscriptions? Also, are you using LiveKit Cloud or a self-hosted setup? Understanding this will help me guide you in the best way possible. Sources: CHANGELOG.md | .github/workflows/release.yaml | agents/src/worker.ts | Quotas and limits | LiveKit Docs | Agent Deployment & Docker Configuration | livekit/livekit_composite | DeepW...
I'm glad you're looking to implement a concurrency cap for agent workers in LiveKit using Node.js! You can achieve this by using the
loadFunc
and
loadThreshold
parameters within the
WorkerOptions
class. These options let you set up a custom load function that controls how many concurrent jobs a worker can handle, helping you manage workload smoothly. Here’s a friendly example to guide you:
Copy code
import { Worker, WorkerOptions } from '@livekit/agents';

const workerOptions: WorkerOptions = {
  agent: './agent.ts',
  loadFunc: async (worker) => {
    const activeJobs = worker.activeJobs.length;
    const maxJobs = 9;
    return activeJobs / maxJobs; // Returns load between 0 and 1
  },
  loadThreshold: 0.9, // Worker stops accepting new jobs when load reaches this value
};

const worker = new Worker(workerOptions);
await worker.run();
Here are some key parameters to keep in mind: •
loadFunc
: This function returns the current load as a float between 0 and 1.0. You can calculate it based on how many active jobs the worker currently has. •
loadThreshold
: This sets the maximum load at which the worker will still accept new jobs. For example, setting it to
0.9
means the worker will handle up to 9 jobs concurrently. Just a couple of important notes to keep in mind: • In LiveKit Cloud deployments, custom
loadFunc
and
loadThreshold
aren’t supported — the system uses default values based on CPU load with a threshold of 0.7. • When you want to gracefully shut down a worker, you can use the
drain()
method. This stops new jobs from being accepted while allowing current jobs to finish. With this setup, your worker will gracefully stop accepting new jobs once it reaches your specified concurrency limit, helping you maintain a balanced and efficient agent infrastructure. If you have any questions or need further help, feel free to ask—I’m here to support you! Sources: README.md | Worker options | LiveKit Docs | livekit-agents/livekit/agents/worker.py | Worker lifecycle | LiveKit Docs
I'm glad you're looking to manage your LiveKit worker's shutdown right after a call disconnects! You can achieve this smoothly by handling disconnection events within the agent's lifecycle using
JobContext
and
RoomEvent.Disconnected
. Here's a friendly walkthrough on how to set this up:
Copy code
import { JobContext } from '@livekit/agents-sdk';

export async function entrypoint(ctx: JobContext) {
  // First, connect the agent to the room
  await ctx.connect();

  // Then, listen for when the room disconnects
  ctx.room.on('disconnected', () => {
    console.log('Room disconnected — shutting down agent');
    // You can also run any cleanup tasks here if needed
    ctx.shutdown(); // This starts a graceful shutdown
  });

  // Place your agent logic here (like processing audio or responding to events)
  // When the room disconnects, the handler above will take care of shutting down
}
Here are some additional helpful options you might find useful: • If you want to shut down when a specific participant leaves, just listen for
participant_disconnected
like this:
Copy code
ctx.room.on('participant_disconnected', (participant) => {
  console.log(`Participant ${participant.identity} left — shutting down`);
  ctx.shutdown();
});
• To make sure any cleanup tasks run during shutdown, you can register them with `ctx.add_shutdown_callback()`:
Copy code
ctx.add_shutdown_callback(() => {
  console.log('Running cleanup before shutdown');
  // This is a great spot to close files or release resources quickly
});
And a quick tip on configuration: • If you'd like to shorten the default 60-second shutdown timeout, just adjust
shutdownProcessTimeout
in
WorkerOptions
like this:
Copy code
const worker = new Worker({
  agent: './agent.ts',
  shutdownProcessTimeout: 10_000, // 10 seconds
});
With this setup, your worker will gracefully shut down right after the call ends or when a particular participant disconnects. If you have any questions or need further help, feel free to ask—I'm here to support you! Sources: agents/src/worker.ts | Job lifecycle | LiveKit Docs | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik...
Thank you for reaching out! I wanted to let you know that the default grace period before a worker can take a new job after a caller disconnects isn’t explicitly documented. Could you please share if you’re noticing any delays in this situation, or if you’re hoping to adjust how this works? Also, it would be helpful to know if this is connected to a particular deployment setup or worker configuration. I’m here to help you through this!
When
ctx.shutdown
is executed, it gently signals the specific job process to start its graceful shutdown sequence. This includes disconnecting the agent (software participant) from the room using
room.disconnect()
. Just to clarify: • This doesn’t directly reduce the count of active jobs or workers: The LiveKit server takes care of reducing active jobs as a natural result of the job ending. • This doesn’t shut down the room: Disconnecting the agent lets other participants keep enjoying the session. The room will only close when the last non-agent participant leaves, or if you choose to explicitly use the server API’s
deleteRoom
method to end the room for everyone. If you want to make sure the room is fully shut down after the agent disconnects, simply call the
deleteRoom
method through the server API. I hope this helps clarify things for you! Sources: agents/src/ipc/job_proc_lazy_main.ts | livekit-agents/livekit/agents/worker.py | Job lifecycle | LiveKit Docs | pkg/service/agentservice.go
I'm here to help you manage the count of active workers when the last human caller leaves a room and the agent is no longer needed. Here are some thoughtful approaches you can try: 1. Default Room Closure Behavior By default, LiveKit kindly closes a room when the last non-agent participant (like a human caller) leaves. This naturally ends the agent's job and helps reduce the active worker count. 2. Proactively Delete the Room If you want to be extra sure everything is cleaned up right away, you can use the server API’s
deleteRoom
method. This will close the room for everyone, including agents, stopping all related processes and ensuring no unnecessary workers stay active. 3. Implement Participant Disconnection Listeners You might find it helpful to listen for when participants disconnect, and then shut down the agent session once the last human leaves. Here’s a simple example:
Copy code
ctx.room.on('participant_disconnected', (participant) => {
  if (ctx.room.remoteParticipants.length === 0) {
    console.log('Last participant left — shutting down agent');
    ctx.shutdown();
  }
});
4. Configure RoomInputOptions When you start an agent session, you can set it up to automatically delete the room when the session ends. This helps keep things tidy without extra effort:
Copy code
await session.start(
  agent: MyAgent(),
  room: ctx.room,
  room_input_options: RoomInputOptions(
    delete_room_on_close: true
  )
);
5. Proper Cleanup Finally, always remember to clean up properly by calling
session.aclose()
to end agent sessions and free up resources. Here’s a quick example:
Copy code
try {
  await session.start(...);
} finally {
  await session.aclose();
}
By using these approaches, you’ll ensure agent sessions close smoothly, resources are freed, and the active worker count stays just right when agents aren’t needed anymore. If you have any questions or want to walk through these steps together, I’m here for you! Sources: Worker lifecycle | LiveKit Docs | Job lifecycle | LiveKit Docs | examples/voice_agents/realtime_joke_teller.py
Thank you for reaching out! I understand that the delay in reducing
worker.activeJobs.length
after the last human disconnects can be a bit puzzling. This usually happens because of the graceful shutdown process and how LiveKit manages the job lifecycle. Let me walk you through the main points: • Graceful Shutdown Timeout: By default, the system waits up to 60 seconds to allow a job to shut down gracefully before it’s forcefully terminated. You can adjust this timeout using the
shutdownProcessTimeout
parameter in
WorkerOptions
if you’d like to speed things up. • Active Jobs Calculation: The count of active jobs only goes down once the job process has fully completed its shutdown, is removed from the process pool, and the
runningJob
property is cleared. • Session Closure: After the last human participant disconnects, the agent session might need a bit of extra time to finish tasks like generating final responses, running shutdown hooks, and cleaning up. • Room and Agent Coordination: The system also waits for agent participants to leave the room properly, which has a timeout of about 3 seconds. Here are some friendly recommendations to help minimize these delays: • Try reducing the
shutdownProcessTimeout
in
WorkerOptions
to shorten that graceful shutdown period. • Make sure your shutdown hooks and cleanup tasks are optimized to complete quickly. • Consider configuring session close behavior through
RoomInputOptions
to make the process smoother. This delay is actually intentional—it helps ensure jobs terminate reliably and everything cleans up properly. But the great news is, you can tune these timeout settings to find the right balance between responsiveness and reliability that fits your needs. If you have any more questions or want help adjusting these settings, I’m here for you! Sources: agents/src/worker.ts | examples/voice_agents/session_close_callback.py | Job lifecycle | LiveKit Docs | Worker lifecycle | LiveKit Docs | CHANGELOG.md