How do I implement rate limiting? My SIP trunk pro...
# ask-ai
h
How do I implement rate limiting? My SIP trunk provider cannot handle more than 13 channels (13 concurrent calls)
t
Thanks for reaching out, tri.nguyen. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
It sounds like you want to cap outbound SIP calls at 13 concurrent channels for your trunk. LiveKit doesn’t expose a per-trunk concurrency cap, so gate new calls in your app before creating them. Here’s the simplest approach: 1. Track active SIP calls in your app using SIP participant state (e.g., when
sip.callStatus
indicates the call is active, and when it ends) Making outbound calls. 2. Before calling
CreateSIPParticipant
, count active calls for that trunk/number. 3. If active < 13 → proceed to `CreateSIPParticipant`; otherwise → queue or reject until a call ends. Helpful references: • SIP overview and APIs: SIP overview, SIP APIs • Outbound call flow: Making outbound calls • Project-level quotas (separate from per-trunk): Quotas and limits Would you like a short code example (server-side) showing the counter and queue? Sources: SIP overview | LiveKit Docs | SIP APIs | LiveKit Docs | Making outbound calls | LiveKit Docs | Quotas and limits | LiveKit docs
h
Yes, show me an example
t
You’re asking for a code example to cap concurrent SIP calls at 13. Below is a minimal server-side flow that: • Counts active SIP calls for a trunk using SIP participant attributes • Gates new calls before calling CreateSIPParticipant Node.js-style pseudocode:
Copy code
const LIMIT = 13;

// deps: LiveKit server SDK clients for SIP + Room/Participants
// ensure your auth token includes SIP `call` grant for CreateSIPParticipant
// and appropriate grants to list/inspect participants

async function countActiveCallsForTrunk(sipClient, trunkId) {
  // List SIP participants (or list room participants and filter SIP ones)
  const participants = await sipClient.listSIPParticipants(); // use SDK/CLI equivalent
  return participants.filter(p =>
    p.sip?.trunkID === trunkId &&
    p.sip?.callStatus === 'active' // connected/ongoing
  ).length;
}

async function placeCallIfUnderLimit(sipClient, trunkId, toNumber, roomName) {
  const active = await countActiveCallsForTrunk(sipClient, trunkId);
  if (active >= LIMIT) {
    // queue or reject
    return { allowed: false, reason: 'rate_limited' };
  }

  // Proceed to create outbound SIP participant (places the call)
  const resp = await sipClient.createSIPParticipant({
    sip_trunk_id: trunkId,
    sip_call_to: toNumber,
    room_name: roomName,
    // optional fields: participant_identity, dtmf, wait_until_answered, etc.
  });

  return { allowed: true, call: resp };
}

// Example: webhook/event hook to keep counts fresh (decrement when calls end)
function onParticipantUpdated(event) {
  // Inspect event participant’s `sip.callStatus` changes to update your queue
  // If status -> 'ended' | participant disconnected, release a slot and dequeue next
}
Docs for the APIs and fields: • SIP APIs (CreateSIPParticipant, trunk listing): SIP APIs • SIP participant fields (e.g.,
sip.trunkID
,
sip.callStatus
): SIP participant • Managing participants/room events (for keeping counts accurate): Managing participants • Project-wide quotas (separate from per-trunk): Quotas and limits Want this in concrete Node.js or Python with specific SDK calls wired up? Sources: SIP APIs | LiveKit Docs | Managing participants | LiveKit docs | Quotas and limits | LiveKit docs | SIP participant | LiveKit Docs | Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki
h
I don't think there is a
sipClient.listSIPParticipants
method
t
You’re right—there isn’t a
sipClient.listSIPParticipants
. To count active SIP calls, list room participants and filter those of kind
SIP
, then gate
CreateSIPParticipant
. Here’s a minimal Python-style example:
Copy code
MAX = 13

async def count_active_sip(room_svc, room_name):
  parts = await room_svc.list_participants(room=room_name)  # requires roomList grant
  return sum(1 for p in parts if p.kind == "SIP")

async def place_call_if_under_limit(sip_api, room_svc, room_name, trunk_id, to_number):
  if await count_active_sip(room_svc, room_name) >= MAX:
    return {"ok": False, "reason": "rate_limited"}
  res = await sip_api.create_sip_participant(
    sip_trunk_id=trunk_id,
    sip_call_to=to_number,
    room_name=room_name,
  )
  return {"ok": True, "participant": res}
References: • Listing participants: Managing participants • Outbound calls API: SIP APIs Do you want this in Node.js or Go instead, and is your limit per room or global across rooms? Sources: SIP overview | LiveKit Docs | SIP APIs | LiveKit Docs | Rooms, participants, and tracks | LiveKit docs | Managing participants | LiveKit docs | Creating SIP Inbound Trunks and Dispatch Rules with Python SDK
h
Make your examples in Node.js
t
Got it—you want Node.js examples. Below are two patterns to cap outbound calls at 13 before calling CreateSIPParticipant. Option A: Simple in-process gate (single instance)
Copy code
import fetch from 'node-fetch';

const LIVEKIT_BASE = 'https://your-livekit-host';
const CREATE_SIP_PARTICIPANT = '/twirp/livekit.SIP/CreateSIPParticipant';
const MAX_CONCURRENT = 13;

const activeByTrunk = new Map(); // trunkId -> count
const getCount = (t) => activeByTrunk.get(t) ?? 0;
const inc = (t) => activeByTrunk.set(t, getCount(t) + 1);
const dec = (t) => activeByTrunk.set(t, Math.max(0, getCount(t) - 1));

// token must include SIP `call` grant
export async function placeCallIfUnderLimit({
  token, trunkId, toNumber, roomName, participantIdentity,
}) {
  if (getCount(trunkId) >= MAX_CONCURRENT) {
    return { ok: false, reason: 'rate_limited' };
  }

  const body = {
    sip_trunk_id: trunkId,
    sip_call_to: toNumber,
    room_name: roomName,
    participant_identity: participantIdentity,
    // optional: wait_until_answered, dtmf, headers, etc.
  };

  const resp = await fetch(`${LIVEKIT_BASE}${CREATE_SIP_PARTICIPANT}`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });

  if (!resp.ok) {
    const text = await resp.text();
    return { ok: false, error: `CreateSIPParticipant failed: ${resp.status} ${text}` };
  }

  const sipParticipantInfo = await resp.json();
  inc(trunkId);
  return { ok: true, participant: sipParticipantInfo };
}

// Call this when the SIP participant ends (e.g., on participant disconnect or sip.callStatus=hangup)
export function onCallEnded(trunkId) {
  dec(trunkId);
}
Option B: Distributed gate with Redis (multiple instances)
Copy code
import fetch from 'node-fetch';
import Redis from 'ioredis';

const LIVEKIT_BASE = 'https://your-livekit-host';
const CREATE_SIP_PARTICIPANT = '/twirp/livekit.SIP/CreateSIPParticipant';
const MAX_CONCURRENT = 13;
const redis = new Redis(process.env.REDIS_URL);

function key(trunkId) { return `sip:active:${trunkId}`; }

export async function placeCallIfUnderLimit({
  token, trunkId, toNumber, roomName, participantIdentity,
}) {
  const k = key(trunkId);
  const active = parseInt((await redis.get(k)) || '0', 10);
  if (active >= MAX_CONCURRENT) return { ok: false, reason: 'rate_limited' };

  // Optimistic increment; you can also wrap in a Lua script for strict atomicity with the API call
  await redis.incr(k);

  try {
    const body = {
      sip_trunk_id: trunkId,
      sip_call_to: toNumber,
      room_name: roomName,
      participant_identity: participantIdentity,
    };

    const resp = await fetch(`${LIVEKIT_BASE}${CREATE_SIP_PARTICIPANT}`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    });

    if (!resp.ok) {
      const text = await resp.text();
      await redis.decr(k);
      return { ok: false, error: `CreateSIPParticipant failed: ${resp.status} ${text}` };
    }

    const sipParticipantInfo = await resp.json();
    return { ok: true, participant: sipParticipantInfo };
  } catch (e) {
    await redis.decr(k);
    return { ok: false, error: String(e) };
  }
}

// Decrement when the call ends (on participant disconnect or sip.callStatus change)
export async function onCallEnded(trunkId) {
  await redis.decr(key(trunkId));
}
Decrementing the counter • Listen for participant lifecycle to know when to call
onCallEnded(trunkId)
. Inspect SIP participant attributes like
sip.callStatus
(e.g., 'hangup') or participant disconnect events, then decrement. Docs: • Create outbound calls (CreateSIPParticipant): SIP APIs • SIP participant fields (e.g.,
sip.trunkID
,
sip.callStatus
): SIP participant • Managing participants and events: Managing participants Do you want an example listener that watches participant updates and decrements automatically when
sip.callStatus
indicates the call ended? Sources: SIP APIs | LiveKit Docs | SIP Integration & Telephony | livekit/livekit_composite | DeepWiki | SIP participant | LiveKit Docs | Managing participants | LiveKit docs | Quotas and limits | LiveKit docs
h
How do I list global participants across rooms
t
You’re asking how to list participants globally across rooms. Do this by listing rooms, then listing participants in each room. Node.js example using RoomService APIs:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const roomService = new RoomServiceClient(process.env.LIVEKIT_URL, process.env.LK_API_KEY, process.env.LK_API_SECRET);

// Returns an array of { roomName, participants[] }
export async function listAllParticipants() {
  const rooms = await roomService.listRooms(); // list all active rooms
  const results = [];
  for (const room of rooms) {
    const parts = await roomService.listParticipants(room.name); // requires roomList grant
    results.push({ roomName: room.name, participants: parts });
  }
  return results;
}

// Example: filter SIP participants globally
export async function listAllSipParticipants() {
  const all = await listAllParticipants();
  const sip = [];
  for (const { roomName, participants } of all) {
    for (const p of participants) {
      if (p.kind === 'SIP') {
        sip.push({ roomName, participant: p });
      }
    }
  }
  return sip;
}
References: • List rooms/participants: Managing rooms, Managing participants Sources: SIP Integration & Telephony | livekit/livekit_composite | DeepWiki | SIP APIs | LiveKit Docs | SIP participant | LiveKit Docs | Managing participants | LiveKit docs | Managing rooms | LiveKit docs