본문 바로가기
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 는 sync 용 httpx.Client 와 async 용 httpx.AsyncClient 를 제공해. 둘 다 context manager 로 닫을 수 있고 TCP connection pool 을 유지해. 요청마다 새로 만들면 pool 을 재사용하지 못해 처리량이 떨어져.

process 마다 client 하나를 재사용해

OpenAI SDK와 같은 원칙이야. app 이 시작할 때 하나를 만들고 끝날 때까지 함께 써. httpx.get() 같은 단발 호출은 매번 새 connection 과 TLS handshake 를 만들고 keep-alive 이점을 잃어.

LLM streaming 에 맞게 timeout 을 나눠

httpx 기본 5초 timeout 은 긴 응답을 중간에 끊을 수 있어. connect=10, read=300, write=10, pool=10 처럼 단계별로 설정해. timeout=None 은 멈춘 응답이 connection 을 끝없이 잡게 할 수 있어.

여러 호출에는 AsyncClient

동시에 여러 요청을 보낼 가능성이 있다면 AsyncClient와 asyncio.gather가 잘 맞아. sync Client는 단일 thread에서 순서대로 처리하는 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) helper 를 만들어. asyncio.gather 로 URL 열 개를 가져오되 하나는 느린 URL로 두고 timeout이 깨끗하게 처리되는지 확인해.

Progress

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

댓글 0

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

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