asyncio의 효과를 가장 자주 보는 사례가 「많은 HTTP 요청 동시 처리」입니다.
requests는 동기 전용이라 asyncio와 안 맞음 — aiohttp나 httpx 같은 비동기 클라이언트가 필요합니다.
aiohttp — 가장 인기 있는 async HTTP.
import aiohttp.
async def fetch(url): async with aiohttp.ClientSession() as session: async with session.get(url) as r: return await r.text().
세션은 재사용(연결 풀링)이 핵심.
httpx — sync·async 통합.
pip install httpx.
import httpx.
동기는 httpx.get(url), 비동기는 async with httpx.AsyncClient() as client: r = await client.get(url).
같은 API로 양쪽 모두 지원.
성능 효과.
100개 URL을 100ms씩이라고 합시다.
requests 순차: 10초.
aiohttp gather: 0.2초.
50배 차이.
외부 API 의존도가 높은 서비스에서 압도적 개선.
주의 — 호스트 부담.
한 번에 1000개 요청을 보내면 상대 서버에 DoS급 부하.
asyncio.Semaphore로 동시성 제한(예: 10개씩) 또는 asyncio.sleep으로 간격 두기.
requests.adapters의 Connection Pool처럼 매너 있는 사용 필요.
한 줄 요약
aiohttp·httpx는 async HTTP 클라이언트.
100개 URL이 0.2초로 줄어드는 극적 개선.
Semaphore로 동시성 제한 매너 필수.
httpx는 sync·async 통합 API.
더 알아볼 것
- aiohttp ClientSession 재사용
- httpx vs aiohttp 비교
- async retry — tenacity