little-hair-53270
10/24/2025, 10:51 AMtall-airline-16756
10/24/2025, 10:51 AMtall-airline-16756
10/24/2025, 10:52 AMimport asyncio
import aiohttp
import time
import psutil
import logging
from livekit import api
from livekit.protocol import room as room_proto
from typing import List, Optional
# Configure logging for monitoring
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ResourceAwareRoomCreator:
def __init__(self, max_concurrent_requests: int = 5, request_delay: float = 0.1):
self.max_concurrent_requests = max_concurrent_requests
self.request_delay = request_delay
self.semaphore = asyncio.Semaphore(max_concurrent_requests)
async def create_room_with_backoff(self, session: aiohttp.ClientSession, room_name: str, retries: int = 3) -> Optional[dict]:
async with self.semaphore:
for attempt in range(retries):
try:
cpu_percent = psutil.cpu_percent(interval=0.1)
if cpu_percent > 80:
await asyncio.sleep(0.5)
logger.warning(f"High CPU usage ({cpu_percent}%), backing off")
lkapi = api.LiveKitAPI(session=session)
room_info = await lkapi.room.create_room(
room_proto.CreateRoomRequest(
name=room_name,
empty_timeout=300,
max_participants=10,
)
)
logger.info(f"Created room: {room_info.name}")
await asyncio.sleep(self.request_delay)
return {"name": room_info.name, "sid": room_info.sid}
except Exception as e:
wait_time = (2 ** attempt) * 0.5
logger.warning(f"Failed to create room {room_name} (attempt {attempt + 1}): {e}")
if attempt < retries - 1:
await asyncio.sleep(wait_time)
else:
logger.error(f"Failed to create room {room_name} after {retries} attempts")
return None
async def create_rooms_in_batches(self, room_count: int = 30, batch_size: int = 5) -> List[dict]:
connector = aiohttp.TCPConnector(limit=10, limit_per_host=5, keepalive_timeout=30, enable_cleanup_closed=True)
timeout = aiohttp.ClientTimeout(total=30, connect=10)
session = aiohttp.ClientSession(connector=connector, timeout=timeout, headers={'Connection': 'keep-alive'})
try:
successful_rooms = []
for batch_start in range(0, room_count, batch_size):
batch_end = min(batch_start + batch_size, room_count)
batch_rooms = [f"vm-room-{i:03d}" for i in range(batch_start, batch_end)]
logger.info(f"Creating batch {batch_start//batch_size + 1}: rooms {batch_start}-{batch_end-1}")
memory_percent = psutil.virtual_memory().percent
cpu_percent = psutil.cpu_percent(interval=1)
logger.info(f"System resources - CPU: {cpu_percent}%, Memory: {memory_percent}%")
if cpu_percent > 70 or memory_percent > 80:
logger.warning("High resource usage detected, adding delay")
await asyncio.sleep(2)
batch_tasks = [self.create_room_with_backoff(session, room_name) for room_name in batch_rooms]
batch_results = await asyncio.gather(*batch_tasks, return_exceptions=True)
for result in batch_results:
if isinstance(result, dict) and result is not None:
successful_rooms.append(result)
if batch_end < room_count:
await asyncio.sleep(1)
return successful_rooms
finally:
await session.close()
async def main():
creator = ResourceAwareRoomCreator(max_concurrent_requests=3, request_delay=0.2)
rooms = await creator.create_rooms_in_batches(room_count=30, batch_size=3)
print(f"Created {len(rooms)} rooms successfully")
if __name__ == "__main__":
asyncio.run(main())
This script carefully balances the load by limiting concurrent requests, keeping an eye on system resources, and processing rooms in manageable batches. If you have any questions or need help customizing it further, please don’t hesitate to reach out—I’m here to help!
Sources: Going beyond a single-core | mcp/server.py | cmd/lk/room.go | Distributed Setup | LiveKit Docs