TL;DR
- A video meeting has two planes. Your application owns users, meeting policy, invitations, billing, and audit records. LiveKit handles real-time rooms, participants, tracks, and media delivery.
- Mint participant tokens only after authenticating the caller and checking meeting membership. Scope each short-lived JWT to one opaque room and one participant identity, with explicit publish and subscribe grants.
- Keep LiveKit API secrets on the server. Do not put personal information in room names or identities, and do not treat client claims or room metadata as your authorization database.
- Verify webhooks over the raw request body, deduplicate by event ID, and apply state transitions idempotently. Webhooks improve synchronization but are not a substitute for the application’s source of truth.
Separate the meeting product from the media room
A WebRTC meeting feature is easier to reason about when the product’s control plane is separate from its media plane. The control plane answers who may create a meeting, who may join, who can publish audio or video, who can admit a guest, and when the business meeting is considered complete. The media plane forwards real-time tracks between participants.
LiveKit provides the room and participant infrastructure. Your FastAPI service should remain authoritative for account identity, tenant membership, host roles, invitations, waiting-room policy, moderation decisions, and application lifecycle. A valid LiveKit token proves that its holder can exercise the grants encoded in it. It does not prove that the caller may create an invoice, view another tenant’s meeting record, or change a host’s decision in your product.
LiveKit access tokens are signed JWTs containing a participant identity, room, permissions, and expiration. The client presents the token to connect. Keep the signing secret server-side and issue tokens from a route that performs your application authorization first. LiveKit server token and grant documentation
Do not put a person’s email or phone number in the room name or participant identity. LiveKit notes that these fields appear in service logs and traces. Use an opaque meeting identifier and a stable, non-PII participant identifier, then resolve display names inside your application. LiveKit access token and grant reference
Model application meeting state explicitly
Before calling the room service, persist a meeting record with a unique application ID, tenant ID, host user ID, opaque LiveKit room name, state, scheduled time, and policy. Model participants separately with application user ID, role, admission status, and an opaque LiveKit identity. Never trust a tenant ID, room name, host role, or grant requested by the browser.
A practical meeting state machine might include scheduled, open, waiting_for_host, ended, and cancelled. Store participant admission and removal as separate records. A participant can leave and rejoin while the meeting remains open. A “participant left” media event should not necessarily mark the application meeting complete.
Use a stable room name derived from a server-generated random identifier or an opaque database ID. Avoid concatenating user input into provider resource names. Add a uniqueness constraint so two concurrent requests cannot create two application meetings for the same logical operation. If your API retries after a timeout, return the existing meeting record for the same idempotency key rather than creating a second room.
Create the LiveKit room when useful for configuration or lifecycle control. The server API supports room creation with settings such as an empty timeout and maximum participant count, and can delete a room to disconnect participants. Room service methods require server-side grants. LiveKit Python room service API · LiveKit RoomService API operations
Mint a narrowly scoped participant token
For every join request, authenticate the user, load the meeting within the caller’s tenant scope, check that its state permits joining, verify the user’s participant row, and apply admission policy. Generate the participant identity on the server. Choose publish rights based on role and product policy, not on a client-supplied boolean. Then create a short-lived access token limited to that room and identity.
The current Python SDK pattern uses AccessToken, with_identity, with_ttl, and with_grants. The Python SDK defaults publishing and data permissions to enabled, so explicitly set them when a participant should be receive-only. LiveKit grant defaults and Python examples
from datetime import timedelta
from livekit import api
def mint_join_token(
api_key: str,
api_secret: str,
room_name: str,
participant_identity: str,
can_publish: bool,
) -> str:
token = (
api.AccessToken(api_key, api_secret)
.with_identity(participant_identity)
.with_ttl(timedelta(minutes=10))
.with_grants(
api.VideoGrants(
room_join=True,
room=room_name,
can_publish=can_publish,
can_subscribe=True,
can_publish_data=False,
)
)
)
return token.to_jwt()
This example limits the join grant to a single room and disables data publication. Add only the capabilities needed by the meeting feature. If only the camera and microphone should be publishable, use supported source-level grants in the SDK version you deploy. Do not grant room_admin, room_create, or recording rights to ordinary participants.
Token expiry bounds how long an unused token can start a connection; it is not a session-duration limit. LiveKit refreshes tokens for connected participants so they can reconnect. If immediate removal is required, invoke the server-side participant removal API and update application admission state. Token revocation behavior differs between LiveKit Cloud and self-hosted deployments, so follow the current guidance for the deployment type you operate. LiveKit token lifecycle, refresh, and revocation · LiveKit participant removal and room management
Return tokens with private, non-cacheable responses. Never log them, send them to analytics, include them in URLs, or persist them in browser local storage unless your threat model explicitly accepts that exposure. Keep API keys and secrets in a secret manager and rotate them using the platform’s documented procedure.
Implement the FastAPI join boundary
Keep the API endpoint focused on access checks and token issuance. Use a dependency that authenticates the caller, and query the meeting with both its ID and tenant scope. The database query should also confirm participant admission. If the check fails, do not call LiveKit or create a token.
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import BaseModel
from uuid import UUID
router = APIRouter()
class JoinResponse(BaseModel):
server_url: str
participant_token: str
@router.post("/meetings/{meeting_id}/join", response_model=JoinResponse)
async def join_meeting(
meeting_id: UUID,
response: Response,
user = Depends(current_user),
db = Depends(database),
):
meeting = await db.fetch_one(
"""
SELECT m.id, m.livekit_room, m.state, p.livekit_identity, p.admission
FROM meeting AS m
JOIN meeting_participant AS p ON p.meeting_id = m.id
WHERE m.id = :meeting_id
AND m.tenant_id = :tenant_id
AND p.user_id = :user_id
""",
{
"meeting_id": meeting_id,
"tenant_id": user.tenant_id,
"user_id": user.id,
},
)
if meeting is None or meeting.admission != "admitted":
raise HTTPException(status_code=404, detail="Meeting not found")
if meeting.state not in {"open", "waiting_for_host"}:
raise HTTPException(status_code=409, detail="Meeting is not accepting joins")
response.headers["Cache-Control"] = "private, no-store"
token = mint_join_token(
settings.livekit_api_key,
settings.livekit_api_secret,
meeting.livekit_room,
meeting.livekit_identity,
can_publish=policy_allows_publish(user, meeting),
)
return JoinResponse(
server_url=settings.livekit_public_url,
participant_token=token,
)
The code is an architectural example; adapt database methods, response handling, and policy checks to the application. In particular, a waiting-room state should not accidentally grant room access before admission. Either withhold the join token until the host admits the participant or implement a separate, deliberately restricted lobby flow. A hidden button in the browser is not an authorization check.
Use the same object-level checks for room listing, participant removal, recording, and metadata updates. A user must not gain authority by changing a path parameter to another tenant’s meeting ID. Keep administrative LiveKit API calls behind application authorization and server-side grants.
Handle webhooks as signed, duplicate events
LiveKit sends room and participant events to configured webhook destinations. Requests use the application/webhook+json content type and an Authorization header containing a signed JWT with a SHA-256 hash of the payload. The server SDK receiver validates the token and verifies the hash against the raw body. FastAPI must read and preserve those original bytes before parsing JSON. LiveKit webhook event and verification guide · LiveKit Python WebhookReceiver API
from fastapi import APIRouter, HTTPException, Request, Response
from livekit import api
router = APIRouter()
receiver = api.WebhookReceiver(
api.TokenVerifier(settings.livekit_api_key, settings.livekit_api_secret)
)
@router.post("/webhooks/livekit")
async def livekit_webhook(request: Request, db = Depends(database)):
raw_body = (await request.body()).decode("utf-8")
auth_header = request.headers.get("Authorization")
if not auth_header:
raise HTTPException(status_code=401, detail="Missing signature")
try:
event = receiver.receive(raw_body, auth_header)
except Exception:
raise HTTPException(status_code=401, detail="Invalid webhook")
async with db.transaction():
inserted = await db.insert_if_absent(
"livekit_webhook_inbox",
key=event.id,
event_name=event.event,
payload=event,
)
if inserted:
await apply_room_event_idempotently(db, event)
return Response(status_code=200)
Use the exact receiver construction supported by the installed livekit-api version and retain the raw body as a string for verification. Do not parse and re-serialize the JSON before calling receive, because whitespace and byte representation affect the signed hash. Return success only after the event is durably recorded. For expensive follow-up work, commit an inbox row and enqueue processing rather than keeping the webhook request open.
LiveKit documents that webhook delivery is not guaranteed, though it retries transient failures and sequences queued events until delivery or abandonment. Every event includes an ID, event name, and creation timestamp. Store the event ID under a unique constraint so duplicate attempts do not apply the same state transition twice. LiveKit webhook delivery behavior and event fields
Reconcile event state without treating webhooks as truth
Webhooks arrive asynchronously and can be delayed or retried. An application may also miss a delivery if its endpoint is unavailable long enough. Treat the event stream as a synchronization signal, then reconcile against the LiveKit room or participant service when the product requires an accurate current snapshot. Keep a periodic reconciliation job for meetings that remain in an impossible state beyond a defined age.
Make event handlers idempotent and tolerate out-of-order business effects. For example, a late participant_left event should not overwrite a later rejoin record from the same identity. Store event time and provider sequence information if available, but decide state transitions from durable current state and an explicit rule. Do not infer billing from a single join event without accounting for reconnects and duplicates.
Use the room service to inspect active rooms and participants when reconciliation is needed. Track differences such as an application meeting marked open with no active room, or an active room whose application meeting was cancelled. Decide whether the repair is to create, close, notify, or escalate. Avoid deleting a room solely because one delayed event says a participant left.
Room lifecycle can be controlled through LiveKit settings such as empty timeout and maximum participants. The application still owns scheduled meeting semantics, host cancellation, audit history, and any retention rules for recordings or metadata. A media room becoming empty is not automatically equivalent to a business meeting being complete.
Design waiting rooms and host controls as policy transitions
A waiting room is an application authorization decision. When a guest asks to join, persist an admission request and notify the host. Do not issue the normal room token until approval. If the product needs a lobby inside the media service, define an isolated lobby room and a controlled transfer or promotion operation. Ensure that lobby participants cannot publish into the main room, inspect its metadata, or call privileged APIs.
Host controls should be server-verified. To mute, remove, admit, or change a participant’s permissions, authorize the host’s application role against the meeting record, then make the corresponding LiveKit server API call. Do not trust a client event that claims the user is a host. Keep an audit record containing actor, action, target participant, timestamp, and result.
If host approval changes while a token is already issued, decide how quickly the change must take effect. Short token TTLs limit stale token lifetime, while participant removal can terminate an active session. Recheck policy on reconnect and issue a new grant set rather than assuming that the initial authorization remains valid forever.
Test security, lifecycle, and race conditions
- Attempt to join another tenant’s meeting by substituting a meeting ID.
- Request a token before admission, after cancellation, and after the meeting has ended.
- Verify ordinary participants cannot create rooms, list all rooms, remove other participants, or start recording.
- Confirm tokens contain opaque identities, the intended room grant, explicit publish permissions, and an expiration.
- Replay the same signed webhook several times and assert that the event inbox applies it once.
- Change the raw body while keeping the Authorization header and confirm verification rejects it.
- Deliver a late participant event after a reconnect and confirm application state does not regress.
- Simulate webhook outage and reconcile the room through the server API.
- Race two meeting-creation requests and confirm the uniqueness rule returns one logical meeting.
Test both authorization and lifecycle. A valid JWT can still contain excessive permissions, and a correct webhook signature can still be replayed. Also measure token issuance failures, webhook verification failures, webhook age, duplicate rate, room reconciliation mismatches, and participant removal outcomes without logging token contents or PII.
Frequently asked questions
Should the browser create LiveKit rooms or mint its own access token?
No. Keep the LiveKit API secret on the server. The browser should call an authenticated FastAPI endpoint, which checks tenant membership and meeting policy before minting a short-lived token scoped to one room and participant identity.
Can LiveKit webhooks be the source of truth for meeting membership?
Use webhooks to synchronize provider events, but keep application membership and admission in your own database. Delivery is asynchronous and can be retried or abandoned. Deduplicate events by ID and reconcile provider state when a meeting remains inconsistent.
What should I do with a participant who is waiting for host approval?
Withhold the main-room join token until the host approves the participant, or use a separate restricted lobby flow with its own room and permissions. A client-side waiting screen alone does not prevent a caller from joining directly with a valid token.
How do I verify a LiveKit webhook in FastAPI?
Read the raw request body, pass it with the Authorization header to LiveKit’s Python WebhookReceiver, and only process a successfully verified event. Store the event ID under a unique constraint and apply its state transition idempotently.
Keep the control plane authoritative
FastAPI should decide whether a user may enter, publish, moderate, or end a meeting. LiveKit tokens carry narrow time-limited room grants, while signed webhooks report changes that your application can record and reconcile. Separate those responsibilities and a media-layer retry or disconnect is less likely to corrupt the product’s meeting state.
Webhook signature verification and duplicate handling follow the same reliable-delivery principles used for payment integrations. See our guide to securing and processing webhooks and our guide to durable workflows for longer-running meeting and notification processes.
If you are building video rooms, waiting lobbies, or meeting moderation into a SaaS product, talk to our engineering team about token scope, lifecycle reconciliation, and safe control-plane boundaries.
