본문 바로가기
C.W.K.
Stream
Lesson 04 of 07 · published

Agent SDK 서브프로세스 풀은 독립 인프라야

~14 min · subprocess, pool, agent-sdk

Level 0Observer
0 XP0/64 lessons0/13 achievements
0/150 XP to next level150 XP to go0% complete

대화마다 매번 띄우는 비용을 없애

Agent SDK 서브프로세스를 요청마다 시작하면 프로세스 준비, MCP 연결, 시스템 프롬프트 예열을 반복해. 채팅에서는 conversation_id로 키를 둔 장기 클라이언트 풀이 지연을 크게 줄여. cwkPippa의 ClaudeSessionManager가 이 역할을 맡아.

풀은 수명과 고장을 함께 소유해

첫 사용 때 연결하고 TTL이나 종료 때 끊으며, 죽은 클라이언트를 교체하고, 최대 동시 프로세스 수를 제한해야 해. 활성 수와 수명, 마지막 사용 시각도 측정해. DB 연결 풀과 같은 운영 규율이 필요한 인프라야.

쓰지 않는 프로세스를 주기적으로 거둬

오래 산다는 이유로 잊어버리면 자원과 MCP 연결이 새어. N분 동안 활동 없는 클라이언트를 정리하고 이유를 기록해. 풀이 가득 찼을 때는 끝없이 대기시키기보다 새 세션을 거부하거나 정한 큐 정책을 적용해 상태를 드러내.

원칙: 서브프로세스 풀은 접착 코드가 아니야. 수명·용량·관측을 가진 독립 구성요소로 만들어.

Code

Minimal 세션 풀·python
import asyncio, time
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

class SessionManager:
    def __init__(self, max_size: int = 50, ttl_seconds: int = 1800):
        self._clients: dict[str, tuple[ClaudeSDKClient, float]] = {}
        self._lock = asyncio.Lock()
        self.max_size = max_size
        self.ttl = ttl_seconds

    async def get(self, conv_id: str, options: ClaudeAgentOptions) -> ClaudeSDKClient:
        async with self._lock:
            await self._sweep()
            if conv_id in self._clients:
                client, _ = self._clients[conv_id]
                self._clients[conv_id] = (client, time.time())
                return client
            if len(self._clients) >= self.max_size:
                raise RuntimeError("session pool full")
            client = ClaudeSDKClient(options=options)
            await client.connect()
            self._clients[conv_id] = (client, time.time())
            return client

    async def _sweep(self):
        now = time.time()
        stale = [cid for cid, (_, last) in self._clients.items() if now - last > self.ttl]
        for cid in stale:
            client, _ = self._clients.pop(cid)
            await client.disconnect()

External links

Exercise

Claude 세션 풀에 TTL 정리기를 추가해. TTL보다 1초 오래 쉰 세션은 끊기고, 사용 중인 세션은 살아남는지 시험해.
Hint
풀이 계속 커진다면 SDK 누수가 아니라 상한과 정리가 없는 풀 버그부터 의심해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.