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

httpx Basics — Client lifecycle 와 timeouts

~22 min · httpx, client, timeouts

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

httpx 는 두 client class — httpx.Client (sync), httpx.AsyncClient (async). 둘 다 context manager (with httpx.Client() as client, async with httpx.AsyncClient() as client). 둘 다 TCP connection pool. Per-request 생성은 pool 무효화 + throughput 죽임.

1 process 1 client (또 다시)

OpenAI SDK 와 같은 룰. App startup 에 하나, 끝까지 share. httpx.get() 같은 bare 호출은 매번 fresh connection — TLS handshake 매번, no keep-alive.

LLM streaming 의 timeout

httpx default timeout 5 초 — LLM streaming 에서 즉사. 권장 — connect=10 (DNS resolution wait), read=300 (streaming 길게 가능), write=10, pool=10. timeout=None 은 위험 — hanging response 가 leaked connection 됨.

Async 권장

다중 동시 호출이 거의 항상 성립. AsyncClient + asyncio.gather 가 표준 패턴. Sync Client 는 단일 스레드 batch 도구에만.

Code

Sync httpx.Client with timeout·python
import httpx

client = httpx.AsyncClient(
    base_url="https://api.openai.com/v1",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    timeout=httpx.Timeout(
        connect=10.0,   # TCP connection timeout
        read=300.0,     # Response read timeout (long for streaming)
        write=30.0,     # Request upload timeout
        pool=5.0,       # Connection pool acquisition timeout
    ),
    limits=httpx.Limits(
        max_keepalive_connections=20,  # Idle connections
        max_connections=100,           # Max total connections
        keepalive_expiry=30.0,         # Seconds before closing idle
    ),
    http2=True,  # Enable HTTP/2 multiplexing
)

External links

Exercise

Timeout 권장값으로 httpx.AsyncClient 쓰는 get_or_none(url, *, client) 헬퍼 build. asyncio.gather 로 10 URL fetch — 그중 하나는 known-slow URL. Timeout 이 깨끗하게 fire 되는지 verify.

Progress

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

댓글 0

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

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