← Blog

Claude API Async Requests: Python Example Guide

2026-11-14 · 5 min read · SubToAPI Team

If you're sending more than one Claude API request at a time in Python, synchronous requests calls will leave your program blocked waiting on the network for most of its runtime. The fix is asyncio combined with an async HTTP client — this lets you fire off dozens or hundreds of requests concurrently and process responses as they complete, instead of one at a time.

This article walks through a working async example using httpx, explains how to control concurrency so you don't hit rate limits, and shows how to apply the same pattern whether you're calling the Claude API directly or through a gateway like SubToAPI.

Why async matters for Claude API calls

A single Claude request can take anywhere from a few hundred milliseconds to several seconds, depending on model and output length. If you need to process 100 documents, summarize 50 support tickets, or run a batch of classification prompts, doing this synchronously means your total runtime is the sum of every individual call. Async lets those calls overlap, so your runtime is closer to the duration of the slowest single call (plus whatever concurrency limit you set).

The core building blocks in Python are:

Basic async request example

Here's a minimal async call to a Claude-compatible messages endpoint:

import asyncio
import httpx
import os

API_KEY = os.environ["SUBTOAPI_KEY"]
URL = "https://api.subtoapi.app/v1/messages"

async def send_message(client, prompt):
    response = await client.post(
        URL,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        json={
            "model": "claude-3-5-sonnet",
            "max_tokens": 512,
            "messages": [{"role": "user", "content": prompt}],
        },
        timeout=30.0,
    )
    response.raise_for_status()
    return response.json()

async def main():
    async with httpx.AsyncClient() as client:
        result = await send_message(client, "Summarize this in one sentence: ...")
        print(result["content"])

asyncio.run(main())

This works for a single call, but the real value of async shows up when you batch multiple requests.

Running multiple requests concurrently

Use asyncio.gather to run several coroutines at once:

import asyncio
import httpx
import os

API_KEY = os.environ["SUBTOAPI_KEY"]
URL = "https://api.subtoapi.app/v1/messages"

async def send_message(client, prompt):
    response = await client.post(
        URL,
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={
            "model": "claude-3-5-sonnet",
            "max_tokens": 300,
            "messages": [{"role": "user", "content": prompt}],
        },
    )
    response.raise_for_status()
    return response.json()

async def main():
    prompts = [
        "Translate 'good morning' to French.",
        "Translate 'good morning' to German.",
        "Translate 'good morning' to Japanese.",
    ]
    async with httpx.AsyncClient(timeout=30.0) as client:
        tasks = [send_message(client, p) for p in prompts]
        results = await asyncio.gather(*tasks, return_exceptions=True)
    for r in results:
        print(r)

asyncio.run(main())

return_exceptions=True is important here — without it, a single failed request cancels the entire batch. With it, you get the exception object back in the results list and can handle failures individually.

Limiting concurrency with a semaphore

Running 500 requests all at once will trigger rate limit errors on almost any API, Claude included. A semaphore caps how many requests are in flight simultaneously:

import asyncio
import httpx

CONCURRENCY_LIMIT = 10
semaphore = asyncio.Semaphore(CONCURRENCY_LIMIT)

async def send_message_limited(client, prompt):
    async with semaphore:
        response = await client.post(
            "https://api.subtoapi.app/v1/messages",
            headers={"Authorization": "Bearer $SUBTOAPI_KEY"},
            json={
                "model": "claude-3-5-sonnet",
                "max_tokens": 300,
                "messages": [{"role": "user", "content": prompt}],
            },
        )
        response.raise_for_status()
        return response.json()

async def main(prompts):
    async with httpx.AsyncClient(timeout=30.0) as client:
        tasks = [send_message_limited(client, p) for p in prompts]
        return await asyncio.gather(*tasks, return_exceptions=True)

Start with a low number like 5–10 and increase it based on how your account's rate limits behave. If you're on a plan with per-key limits via a gateway, check your dashboard for current usage before cranking concurrency up.

Handling retries on transient failures

Network blips and 429/5xx responses are normal at scale. A simple retry wrapper with exponential backoff keeps the batch resilient without extra dependencies:

import asyncio
import random

async def send_with_retry(client, prompt, max_retries=3):
    for attempt in range(max_retries):
        try:
            return await send_message_limited(client, prompt)
        except httpx.HTTPStatusError as e:
            if e.response.status_code in (429, 500, 502, 503) and attempt < max_retries - 1:
                wait = (2 ** attempt) + random.random()
                await asyncio.sleep(wait)
                continue
            raise

This retries on rate-limit and server errors, with jitter to avoid every request in the batch retrying at the exact same moment.

Streaming inside an async batch

If you need streamed responses for each prompt rather than a single blocked-until-done call, httpx.AsyncClient.stream() works the same way — just iterate the response body line by line inside each coroutine. Full details on streamed response formats are in the streaming docs.

Where SubToAPI fits in

If you're already sending Claude usage through a subscription rather than managing raw API billing, SubToAPI turns that access into a standard HTTPS API with application keys (sub_live_...), so the async patterns above work unchanged — same JSON shape, same streaming support, same tool-use format. You get usage metadata per request, which is useful for tracking cost per batch job, and team seats if multiple people or services share the same underlying access. Check the quickstart or messages endpoint docs for request/response schemas, and pricing for plan details — Solo, Team, and Scale all include a free trial at signup via /signup.

questions

Do I need a special async SDK for Claude, or can I just use httpx? You don't need a dedicated async SDK. Any async-capable HTTP client — httpx, aiohttp, or similar — works fine since the API is just HTTPS and JSON. httpx is the most common choice because its API mirrors requests closely.

How many concurrent Claude requests can I run safely? It depends on your account's rate limits. Start with a semaphore limit of 5–10 concurrent requests, monitor for 429 responses, and increase gradually. Gateways with visible usage metadata make this easier to tune.

What's the difference between asyncio.gather and a task queue for batch processing? asyncio.gather is fine for a few dozen to a few hundred requests known upfront. For larger or continuously arriving workloads, a bounded queue with worker coroutines gives you more control over backpressure and avoids holding too many pending tasks in memory at once.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →