C.W.K.
Stream
Lesson 04 of 07 · published

Persistent 서브프로세스 풀 (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

왜 풀

요청당 Claude Agent SDK 서브프로세스 spin up이 비싸(시작 비용, MCP attach, 시스템 프롬프트 warm-up). Chat-style 워크로드면 conversation_id로 키된 long-lived 클라이언트 풀이 극적으로 빨라. cwkPippa의 ClaudeSessionManager가 정확히 이 풀.

풀이 소유하는 것

풀 소유 — lifecycle(첫 사용에 connect, TTL이나 shutdown에 disconnect), error handling(dead 클라이언트 교체), capacity cap(최대 동시 서브프로세스), metrics(active count, lifetime, last-use timestamp). DB connection pool처럼 다뤄 — 같은 규율 적용.

Stale 서브프로세스 위생

Long-lived 서브프로세스가 잊으면 리소스 leak. 주기적 풀 sweep — N 분 활동 없는 클라이언트 drop, MCP 연결 free, 이유 로그. 풀 크기 bound; full하면 새 세션 거부, queueing forever 대신 failure surface.

원칙: 풀이 자기 컴포넌트. Glue 코드처럼 X, 인프라처럼 빌드.

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 기반 sweeper 추가(또는 빌드). TTL+1초 동안 idle인 세션이 disconnect·free 확인. Active 사용 중 세션이 sweep 살아남기 verify.
Hint
프로덕션에서 풀이 unbounded 성장이면 그게 버그 — 'SDK의 메모리 leak' X.

Progress

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

댓글 0

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

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