late-businessperson-58140
12/05/2025, 6:16 AMtall-airline-16756
12/05/2025, 6:16 AMtall-airline-16756
12/05/2025, 6:16 AMegress_started webhook (confirms recording has actually begun) before allowing room deletion or calling StopEgress.
◦ Only delete the room after egress_ended (or after you confirm the file uploaded).
• If your workflow auto-deletes rooms when participants leave, add a short delay (start with 5–10 seconds) before deletion, or keep the agent connection alive until you see `egress_started`/`egress_ended`.
• If you call StopEgress programmatically, ensure it isn’t triggered by the same event that deletes the room; stop only after egress_started and desired recording duration.
If you'd like, tell me:
• How you currently trigger egress and room deletion (webhook or backend logic), and
• Whether you already use `egress_started`/`egress_ended` webhooks.
I can then suggest exactly where to add the delay or webhook checks in your flow.
Sources: Egress API | LiveKit docs | Recording and export | LiveKit docs | Webhooks | LiveKit docslate-businessperson-58140
12/05/2025, 6:18 AMtall-airline-16756
12/05/2025, 6:18 AMegress_started webhook before allowing any room deletion or calling StopEgress.
• Only delete the room after receiving egress_ended (or confirming file upload).
1. Prevent premature room deletion
• If your app auto-deletes rooms when non-agent participants leave, add logic to:
◦ Keep the agent (or a lightweight headless participant) in the room until egress_started is received, OR
◦ Add a fixed grace period (start with 5–10 seconds) before deleting the room / calling StopEgress.
1. Ensure StopEgress timing is safe
• Do not call StopEgress immediately after starting egress. Wait for egress_started and the intended recording duration to complete, then call StopEgress (or rely on the agent to leave after egress_ended).
1. Test with instrumentation
• Add logs for: egress request timestamp, egress_started webhook timestamp, egress_ended webhook timestamp, room-deletion/StopEgress timestamp. Confirm egress_started occurs before any stop/delete action.
If you share how you currently trigger egress and room deletion (webhook-driven, backend cron, or agent lifecycle), I’ll give exact code placements or pseudocode to add the webhook checks/delay. Would you like that?late-businessperson-58140
12/05/2025, 6:21 AMtall-airline-16756
12/05/2025, 6:21 AMegress_started and egress_ended. Only delete the room or remove the agent after you receive egress_ended (or at least after egress_started and desired duration).
• Place webhook handling on your backend; do not rely on timing alone.
3) Where to change your code (precise places)
• After starting egress:
◦ Store egress_info.egress_id (you already do this in active_recordings) and do NOT delete the room or call StopEgress until webhook confirms egress_started and later egress_ended.
• In the code path that deletes rooms when participants leave:
◦ If you auto-delete on last non-agent participant leaving, add logic:
▪︎ If room in `active_recordings`: delay deletion until egress_ended webhook or at least wait 10 seconds after egress_started.
▪︎ Or keep an agent/keepalive participant in the room until egress completes.
• For StopEgress calls:
◦ Ensure StopEgress is triggered only after egress_started and after desired recording time, or rely on egress_ended to signal completion.
4) Fix S3 URL construction (bug in your string)
• Your constructed URL is malformed. Replace:
◦ f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.amazonaws.com/{room_name}.mp4"
• With:
◦ f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.amazonaws.com/{room_name}.mp4"
• Use that only after egress_ended confirms success; otherwise the file may not exist.
5) Add logging/instrumentation (minimal)
• Log timestamps for:
◦ egress start request
◦ egress_started webhook receipt
◦ any StopEgress call or room deletion
◦ egress_ended webhook receipt
• This will prove ordering and show if Stop/Delete happens before egress can initialize.
6) Quick test plan
• Start a test room, start egress, then:
◦ Wait for egress_started webhook (confirm in logs).
◦ Wait a few seconds, then call StopEgress or let egress finish.
◦ Confirm egress_ended webhook and S3 file exists at the corrected URL.
If you want, I can:
• Provide a small webhook handler snippet (FastAPI) to process egress_started / egress_ended and tie it to your room-deletion logic, or
• Show the exact code changes to your leave/delete logic to add the 10-second grace and webhook checks.
Which would you prefer?late-businessperson-58140
12/05/2025, 6:23 AMtall-airline-16756
12/05/2025, 6:24 AMegress_started / egress_ended webhooks.
• Delay/delete rooms only after egress completes.
• Fix the S3 URL construction.
• Track active egress IDs and pending deletions.
Add or adapt the following to your codebase.
1) Webhook handler and small helper state (FastAPI):
from fastapi import FastAPI, Request, BackgroundTasks, HTTPException
from fastapi.responses import JSONResponse
import asyncio
import logging
from typing import Dict
app = FastAPI()
logger = logging.getLogger("livekit")
logging.basicConfig(level=logging.INFO)
# In-memory stores (persist to DB in production)
active_egresses: Dict[str, str] = {} # room_name -> egress_id
egress_to_room: Dict[str, str] = {} # egress_id -> room_name
pending_deletions: Dict[str, asyncio.Task] = {} # room_name -> cancellation task
# configurable grace time to wait before deleting a room when last participant leaves
ROOM_DELETE_GRACE_SECONDS = 10
2) Webhook endpoint to track egress lifecycle (handle egress_started and egress_ended):
@app.post("/livekit/webhook")
async def livekit_webhook(request: Request):
body = await request.json()
event_type = body.get("event")
egress_info = body.get("egress_info") or {}
logger.info(f"webhook received: {event_type} for egress_info={egress_info}")
if event_type == "egress_started":
egress_id = egress_info.get("egress_id")
room_name = egress_info.get("room_name")
if egress_id and room_name:
active_egresses[room_name] = egress_id
egress_to_room[egress_id] = room_name
# if there's a pending deletion scheduled for this room, keep it until egress ends
if room_name in pending_deletions:
# do not cancel here; keep pending deletion but ensure it waits for egress_ended
logger.info(f"egress_started: tracked {egress_id} for room {room_name}")
elif event_type == "egress_ended":
egress_id = egress_info.get("egress_id")
room_name = egress_to_room.get(egress_id) or egress_info.get("room_name")
if egress_id:
# cleanup tracking
if egress_id in egress_to_room:
del egress_to_room[egress_id]
if room_name and room_name in active_egresses:
del active_egresses[room_name]
logger.info(f"egress_ended: {egress_id} for room {room_name}")
# If we have a pending deletion scheduled for this room, cancel the scheduled task and delete the room now
task = pending_deletions.pop(room_name, None)
if task:
task.cancel()
# call actual delete logic now (run in background)
asyncio.create_task(delete_room_and_cleanup(room_name))
return JSONResponse({"status": "ok"})
3) Helper to schedule room deletion with grace period and respect egress lifecycle:
async def delete_room_and_cleanup(room_name: str):
"""
Run actual room deletion and cleanup here.
Replace the body with your LiveKit delete room API call and any app cleanup.
"""
try:
logger.info(f"Deleting room now: {room_name}")
# TODO: Call LiveKit API to delete the room, e.g. lkapi.room.delete_room(...)
# await lkapi.room.delete_room(api.DeleteRoomRequest(name=room_name))
except Exception as e:
logger.exception(f"Error deleting room {room_name}: {e}")
finally:
# remove from tracking maps
active_egresses.pop(room_name, None)
logger.info(f"Room deleted and cleaned up: {room_name}")
async def schedule_room_deletion(room_name: str):
"""
Called when last non-agent participant leaves.
If an egress is active for the room, wait for egress to finish (egress_ended).
Otherwise wait ROOM_DELETE_GRACE_SECONDS then delete.
"""
# if there is an active egress, schedule deletion but do not delete until egress_ended webhook arrives
if room_name in active_egresses:
logger.info(f"Room {room_name} has active egress {active_egresses[room_name]}; deferring deletion until egress ends")
# create a task that waits for a hard timeout in case egress never ends
async def fallback_delete():
try:
await asyncio.sleep(300) # hard timeout (5 min) to avoid leaked rooms; adjust as needed
# if still active, force delete
if room_name in active_egresses:
logger.info(f"Hard timeout reached; forcing delete for room {room_name}")
await delete_room_and_cleanup(room_name)
except asyncio.CancelledError:
logger.info(f"Pending deletion for {room_name} cancelled due to egress_ended")
task = asyncio.create_task(fallback_delete())
pending_deletions[room_name] = task
else:
# no active egress: delete after short grace period
async def grace_and_delete():
try:
logger.info(f"Grace period {ROOM_DELETE_GRACE_SECONDS}s before deleting room {room_name}")
await asyncio.sleep(ROOM_DELETE_GRACE_SECONDS)
await delete_room_and_cleanup(room_name)
except asyncio.CancelledError:
logger.info(f"Pending grace deletion cancelled for {room_name}")
task = asyncio.create_task(grace_and_delete())
pending_deletions[room_name] = task
4) Integrate with your join endpoint and last-participant-leave handler:
• On join: you already start egress. Keep storing egress id returned by LiveKit in active_egresses and egress_to_room if you want immediate tracking. But real tracking comes from webhooks.
• On last non-agent participant leaving: call schedule_room_deletion(room_name) instead of calling delete immediately.
Example snippet showing where to call schedule:
# when you detect the last non-agent participant left:
await schedule_room_deletion(room_name)
5) Fix S3 URL construction when returning recording link:
Replace your incorrect string:
# wrong:
f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.[amazonaws.com/{room_name}.mp4](http://amazonaws.com/{room_name}.mp4)"
With correct form:
recording_url = f"https://{settings.S3_BUCKET}.s3.{settings.S3_REGION}.amazonaws.com/{room_name}.mp4"
Only return that URL after you see egress_ended for the egress that produced the file — or verify the file exists in S3 before returning.
6) Optional: stop egress safely (if you call StopEgress manually)
• Only call StopEgress after receiving egress_started AND the desired recording duration has elapsed. If you need to force stop after some timeout, ensure you do not call it immediately when last participant leaves.
7) Logging and testing
• Add logs around: starting egress request, storing egress_id, scheduling deletion, webhook receipts, and actual delete call. Test the flow:
a. Join room, start egress.
b. Leave room (simulate last participant exit) — scheduler should run.
c. Confirm egress_started arrives (webhook).
d. Confirm egress_ended arrives (webhook) and deletion runs afterwards.
e. Confirm file in S3 at corrected URL.
If you want, I can provide a quick sample for the delete-room LiveKit API call you use in your code (showing how to call lkapi.room.delete_room) and a small example of verifying S3 file existence before returning the URL. Which of those would you like next?late-businessperson-58140
12/05/2025, 7:07 AMtall-airline-16756
12/05/2025, 7:07 AMlate-businessperson-58140
12/05/2025, 8:38 AMtall-airline-16756
12/05/2025, 8:39 AMroom.connect(...) for testing).
Example (JS, after connect succeeds):
room.connect(url, token).then(() => {
// layout/render setup...
console.log("START_RECORDING");
});
2) Don’t delete/stop before egress finishes
• Use webhooks to gate deletion: wait for egress_started (recording active) and especially egress_ended (file finalized + uploaded) before deleting the room or removing agent participants.
• If your flow auto-deletes on last participant leave, change it to:
◦ If an active egress exists: schedule deletion but wait for egress_ended (or keep an agent in-room).
◦ Else: use a short grace (5–10s) before delete.
Quick checklist to validate:
• Your template is reachable (no 404/CORS) from the egress Chrome instance.
• Template prints console.log("START_RECORDING") after connect.
• Your webhook endpoint receives egress_started then egress_ended.
• You only delete room/StopEgress after egress_ended.
• Correct S3 URL format when checking file:
◦ https://{bucket}.s3.{region}.amazonaws.com/{room_name}.mp4
If you want, I can:
• Provide a minimal egress template HTML/JS that connects and logs START_RECORDING, or
• Show the exact webhook handler snippet to gate room deletion.
Which would help you most?
Sources: Custom recording templates | LiveKit docs | Webhooks | LiveKit docslate-businessperson-58140
12/05/2025, 8:47 AMtall-airline-16756
12/05/2025, 8:47 AMroom.connect(wsUrl, token).then(() => {
// render layout / attach tracks...
console.log("START_RECORDING");
}).catch(err => console.error(err));
5) Test and verify
• Use lk egress test-template or deploy the template and watch the headless Chrome console (or webhook events).
• Confirm you receive egress_started then egress_ended webhooks before deleting the room.
• Only return/fetch S3 URL after egress_ended (or verify file exists).
If you want, I can provide a minimal HTML template (with LiveKit client setup, simple layout, and the START/END logs) you can host for egress to load — would you like that?
Sources: RoomComposite Egress | LiveKit Docs | Custom recording templates | LiveKit docs