Claude Async Python: Concurrent Requests with AsyncAnthropic

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 7 min read🎯 D2 Messages API Mechanics · D2 Integration Resilience

👋 In plain words: Calling Claude one request at a time is slow when you have hundreds of items. Async code lets you send many requests at once and wait for them together. This lesson shows you, step by step, how to do that safely without tripping rate limits or losing failed items.

Advertisement

A test suite with 300 failing tests to triage, a backlog of 500 bug reports to label: sequential calls turn minutes into hours. In this lesson you will switch to AsyncAnthropic, run requests concurrently with asyncio.gather, cap concurrency with a semaphore so you stay inside rate limits, keep one failure from crashing the whole run, and stream asynchronously in a web server.

📖 What You’ll Learn: You will be able to use AsyncAnthropic, run Claude calls concurrently, limit concurrency with asyncio.Semaphore, collect per-item errors, and stream with the async client.

🔑 Key terms

  • Async (asynchronous) code: code that can start several slow operations and wait for them together instead of one after another.
  • Coroutine: a function defined with async def. You run it with await or hand it to the event loop.
  • asyncio.gather: runs several coroutines concurrently and returns their results in the same order.
  • Semaphore: a counter that lets only N tasks into a section of code at the same time.

🪜 Step 1: Switch to the async client

AsyncAnthropic has the same methods as Anthropic, but you await them:

📄 async_one.py

import asyncio

import anthropic

client = anthropic.AsyncAnthropic()


async def main():
    response = await client.messages.create(
        model="claude-opus-5-5",
        max_tokens=100,
        messages=[{"role": "user", "content": "Label as bug, feature or question: 'Export to CSV crashes'"}],
    )
    print(response.content[0].text)


asyncio.run(main())

⌨️ Terminal

python async_one.py

🖥️ Output (sample run)

bug
  • Create one client and reuse it. It holds a connection pool; creating a client per request wastes connections.
  • asyncio.run(main()) starts the event loop. In a web framework such as FastAPI, the framework runs the loop for you.
Advertisement

🪜 Step 2: Run many requests concurrently

asyncio.gather starts all coroutines at once and returns results in input order:

📄 async_gather.py

import asyncio

import anthropic

client = anthropic.AsyncAnthropic()

TICKETS = [
    "Export to CSV crashes",
    "Add dark mode",
    "How do I reset my password?",
    "Cart total wrong after coupon",
]


async def label(ticket: str) -> str:
    r = await client.messages.create(
        model="claude-haiku-5-5",
        max_tokens=10,
        output_config={"effort": "low"},
        messages=[{"role": "user", "content": f"Label as bug, feature or question. One word.\n\n{ticket}"}],
    )
    return r.content[0].text.strip()


async def main():
    labels = await asyncio.gather(*(label(t) for t in TICKETS))
    for ticket, lab in zip(TICKETS, labels):
        print(f"{lab:<9} {ticket}")


asyncio.run(main())

⌨️ Terminal

python async_gather.py

🖥️ Output (sample run)

bug       Export to CSV crashes
feature   Add dark mode
question  How do I reset my password?
bug       Cart total wrong after coupon

The four calls overlap, so the total time is close to the slowest single call, not the sum of all four.

🪜 Step 3: Cap concurrency with a semaphore

With 500 tickets, starting 500 requests at once will hit your rate limits (requests per minute and tokens per minute) and fill your logs with 429s. A semaphore keeps only N requests in flight:

📄 async_semaphore.py

import asyncio

import anthropic

client = anthropic.AsyncAnthropic()
LIMIT = asyncio.Semaphore(5)  # at most 5 requests in flight
in_flight = peak = 0


async def label(ticket: str) -> str:
    global in_flight, peak
    async with LIMIT:
        in_flight += 1
        peak = max(peak, in_flight)
        try:
            r = await client.messages.create(
                model="claude-haiku-5-5", max_tokens=10, output_config={"effort": "low"},
                messages=[{"role": "user", "content": f"Label as bug, feature or question. One word.\n\n{ticket}"}],
            )
            return r.content[0].text.strip()
        finally:
            in_flight -= 1


async def main():
    tickets = [f"Ticket {i}: checkout button does nothing" for i in range(40)]
    labels = await asyncio.gather(*(label(t) for t in tickets))
    print("labelled:", len(labels), "| distinct labels:", sorted(set(labels)))
    print("peak requests in flight:", peak)


asyncio.run(main())

⌨️ Terminal

python async_semaphore.py

🖥️ Output (sample run)

labelled: 40 | distinct labels: ['bug']
peak requests in flight: 5
  • async with LIMIT: waits until one of the 5 slots is free. The peak never goes above 5.
  • Pick N from your organisation’s rate limits and the size of each request. Start small and raise it while watching for 429s.
  • The SDK still retries 429s automatically (Lesson 11), but a semaphore prevents most of them in the first place.
Advertisement

🪜 Step 4: Keep one failure from sinking the batch

By default, if any coroutine in gather raises, gather raises too and you lose track of the others. Pass return_exceptions=True and handle failures item by item:

📄 async_errors.py

import asyncio

import anthropic

client = anthropic.AsyncAnthropic(max_retries=0)


async def summarise(log_name: str) -> str:
    r = await client.messages.create(
        model="claude-opus-5-5", max_tokens=100,
        messages=[{"role": "user", "content": f"Summarise failure log {log_name} in one line."}],
    )
    return r.content[0].text


async def main():
    names = ["build-101", "build-102", "build-103"]
    results = await asyncio.gather(*(summarise(n) for n in names), return_exceptions=True)
    retry_later = []
    for name, result in zip(names, results):
        if isinstance(result, Exception):
            print(f"{name}: FAILED ({type(result).__name__}) -> queued for retry")
            retry_later.append(name)
        else:
            print(f"{name}: {result}")
    print("to retry:", retry_later)


asyncio.run(main())

⌨️ Terminal

python async_errors.py

🖥️ Output (sample run)

build-101: Timeout waiting for the payment iframe in test_checkout.
build-102: FAILED (OverloadedError) -> queued for retry
build-103: Assertion failed: expected 3 items in cart, found 2.
to retry: ['build-102']
🎯 Exam focus: For large, non-urgent jobs, the Message Batches API (next lesson) is usually better than concurrent real-time calls: it is billed at 50% and you do not manage concurrency at all. Use async concurrency when results are needed now.
Advertisement

🪜 Step 5: Stream asynchronously

In an async web server, use async with client.messages.stream(...) and async for:

📄 async_stream.py

import asyncio

import anthropic

client = anthropic.AsyncAnthropic()


async def main():
    async with client.messages.stream(
        model="claude-opus-5-5",
        max_tokens=500,
        messages=[{"role": "user", "content": "Give two tips for stable Selenium tests."}],
    ) as stream:
        async for text in stream.text_stream:
            print(text, end="", flush=True)
        final = await stream.get_final_message()
    print("\nstop_reason:", final.stop_reason)


asyncio.run(main())

⌨️ Terminal

python async_stream.py

🖥️ Output (sample run)

1. Use explicit waits for the exact condition you need instead of fixed sleeps. 2. Locate elements by stable attributes such as data-testid rather than layout-based XPath.
stop_reason: end_turn

Note that get_final_message() is awaited on the async client.

🌍 Real-world example: Ravi’s nightly triage

Ravi’s sequential script took 40 minutes to summarise 300 failures. With AsyncAnthropic, a semaphore of 8 and return_exceptions=True, it finishes in about 4 minutes, and the 3 items that hit overload errors are retried at the end instead of crashing the run. When the team later decided results could wait until morning, he moved the job to the Batches API to halve the cost.

🧪 Practice Questions

Question 1. A script starts 2,000 concurrent Claude requests with asyncio.gather and gets many 429 errors. What is the best first fix?

  • A. Create a new client for each request
  • B. Limit concurrency with an asyncio.Semaphore sized to your rate limits
  • C. Disable the SDK’s retries
  • D. Switch to synchronous calls with no limit
Show answer

Answer: B. Rate limits cap requests and tokens per minute. A semaphore keeps requests in flight below the limit.

Question 2. One of 50 coroutines passed to asyncio.gather raises an exception, and the script loses all results. Which change keeps the successful results?

  • A. Wrap asyncio.run in a try/except
  • B. Call asyncio.gather(…, return_exceptions=True) and check each result
  • C. Use a larger max_tokens
  • D. Use a semaphore of 1
Show answer

Answer: B. With return_exceptions=True, gather returns exceptions as values in place, so you can keep successes and retry failures.

Question 3. A nightly job summarises 20,000 test reports; results are needed by the next morning. What is the most cost-effective choice?

  • A. AsyncAnthropic with a semaphore of 50
  • B. The Message Batches API
  • C. Streaming each request
  • D. One request containing all 20,000 reports
Show answer

Answer: B. Batches are processed asynchronously at 50% of standard prices, which suits large jobs without a real-time need.

Question 4. Which two statements about AsyncAnthropic are true? (Choose 2.)

  • A. Its methods have the same names and parameters as the sync client but are awaited
  • B. It ignores max_retries
  • C. You should reuse one client instance across requests
  • D. It cannot stream
Show answer

Answer: A and C. The async client mirrors the sync API, keeps retries and supports streaming. Reusing one client shares its connection pool.

📝 Assignment

  1. Task 1: Convert one of your sequential Claude scripts to AsyncAnthropic with asyncio.gather.
    ✅ Done when: the async version gives the same results and you have recorded both run times.
  2. Task 2: Add a semaphore and print the peak number of requests in flight.
    ✅ Done when: the peak never exceeds your limit.
  3. Stretch: Add a second pass that retries only the failed items from async_errors.py, at most twice, with a short pause between passes.
    ✅ Done when: items that fail once and then succeed end up with a result.
Advertisement

❓ Frequently Asked Questions

🤔 How do I make concurrent calls to the Claude API in Python?

Use anthropic.AsyncAnthropic, write an async def function that awaits client.messages.create, and run many of them with asyncio.gather.

🤔 How many concurrent requests can I send to Claude?

It depends on your organisation’s rate limits (requests and tokens per minute). Limit concurrency with a semaphore and raise it gradually while watching for 429 errors.

🤔 Is async faster than the Batches API?

Async gives results sooner. The Batches API is slower (most batches finish within an hour, up to 24 hours) but costs 50% less.

🤔 Does AsyncAnthropic retry failed requests?

Yes. It has the same automatic retries as the sync client, configured with max_retries.

🏁 Summary

  • AsyncAnthropic mirrors the sync client; reuse a single instance.
  • asyncio.gather runs calls concurrently and keeps input order.
  • An asyncio.Semaphore keeps requests in flight below your rate limits.
  • return_exceptions=True lets you keep successes and retry failures item by item.
  • Choose Batches for large non-urgent jobs and async concurrency when results are needed now.
📝 Test yourself: D2 Applications and Integration practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Message Batches API in Python: 50% Cheaper Bulk Jobs.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.