Async Clients and Concurrency

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 59 of 224

Why Waiting Synchronously Wastes Time

Every example in this course so far has made one request, waited for it to finish, and only then moved on to the next line of code — perfectly fine for a script processing one thing at a time, but a real constraint the moment an application needs to make many independent requests around the same time. A synchronous call to client.responses.create() spends most of its time simply waiting for a network round trip to complete, during which the program does nothing else at all; processing a hundred independent documents one after another, each waiting on its own network round trip in turn, takes roughly a hundred times as long as it would if those waits could overlap. Async support exists specifically to let those waits overlap.

The Async Client

The SDK provides an async counterpart to the client used throughout this course, whose methods are awaited rather than called directly, for use inside an async def function.

import asyncio
from openai import AsyncOpenAI

async_client = AsyncOpenAI()

async def get_response(prompt: str):
    response = await async_client.responses.create(
        model="gpt-5.6-terra",
        input=prompt,
    )
    return response.output_text

result = asyncio.run(get_response("Summarize the plot of a short mystery story."))
print(result)

Note: The exact async client class name and whether every synchronous method has a directly corresponding async method can vary by SDK version. Confirm the current async interface against your installed SDK version's documentation.

Used this way — one call, awaited, inside asyncio.run() — the async client behaves identically to the synchronous version and offers no advantage on its own; the benefit only appears once multiple independent calls are allowed to run concurrently instead of one after another, which is what the rest of this lesson builds toward.

Running Multiple Requests Concurrently

asyncio.gather() runs several async calls concurrently, waiting only as long as the slowest one takes, rather than for the sum of all of them.

async def summarize_document(document_text: str) -> str:
    response = await async_client.responses.create(
        model="gpt-5.6-terra",
        input=f"Summarize this document in two sentences:\n\n{document_text}",
    )
    return response.output_text

async def summarize_all(documents: list) -> list:
    tasks = [summarize_document(doc) for doc in documents]
    return await asyncio.gather(*tasks)

documents = ["Document one's full text...", "Document two's full text...", "Document three's full text..."]
summaries = asyncio.run(summarize_all(documents))
for summary in summaries:
    print(summary)

Summarizing three documents this way takes roughly as long as summarizing the single slowest one, rather than the sum of all three — for a batch of a hundred documents needing individual, immediate responses (as opposed to the non-time-sensitive bulk work Lesson 5's Batch API is built for), this difference is the difference between a task that finishes in seconds and one that takes minutes.

Bounding Concurrency Rather Than Running Everything at Once

Running every request in an unbounded asyncio.gather() call risks launching far more concurrent requests than the account's actual rate limit (Lesson 3) can sustain — a hundred documents launched all at once might comfortably fit under a rate limit, but ten thousand almost certainly won't. A semaphore caps how many requests actually run concurrently, letting the rest wait their turn.

async def summarize_with_limit(document_text: str, semaphore: asyncio.Semaphore) -> str:
    async with semaphore:
        response = await async_client.responses.create(
            model="gpt-5.6-terra",
            input=f"Summarize this document in two sentences:\n\n{document_text}",
        )
        return response.output_text

async def summarize_all_bounded(documents: list, max_concurrent: int = 10) -> list:
    semaphore = asyncio.Semaphore(max_concurrent)
    tasks = [summarize_with_limit(doc, semaphore) for doc in documents]
    return await asyncio.gather(*tasks)

summaries = asyncio.run(summarize_all_bounded(documents, max_concurrent=10))

asyncio.Semaphore(10) allows at most 10 of the scheduled tasks to actually be inside the async with semaphore: block — making an actual request — at any one time; the rest wait until a slot frees up. Choosing an appropriate max_concurrent value connects directly back to Lesson 3's rate-limiting discussion: too high a value and the account's actual rate limit gets exceeded regardless of how careful the async code is; too low and concurrency's benefit is left mostly unused.

Handling Failures Within a Concurrent Batch

By default, asyncio.gather() raises the first exception it encounters and cancels the rest of the still-running tasks — often not the desired behavior when some documents succeeding and others failing independently is an acceptable, even expected, outcome.

async def summarize_all_with_error_handling(documents: list, max_concurrent: int = 10) -> list:
    semaphore = asyncio.Semaphore(max_concurrent)
    tasks = [summarize_with_limit(doc, semaphore) for doc in documents]
    results = await asyncio.gather(*tasks, return_exceptions=True)

    successes, failures = [], []
    for document, result in zip(documents, results):
        if isinstance(result, Exception):
            failures.append({"document": document, "error": str(result)})
        else:
            successes.append(result)

    return successes, failures

successes, failures = asyncio.run(summarize_all_with_error_handling(documents))
print(f"{len(successes)} succeeded, {len(failures)} failed")

return_exceptions=True changes gather()'s behavior so a failed task's exception is returned as a value in the results list instead of being raised immediately and cancelling every other still-running task — this is almost always the more appropriate choice for a batch of otherwise-independent requests, since one document's failure (perhaps due to a malformed input triggering the 400 error Lesson 1 covered) has no bearing on whether the other ninety-nine should also be abandoned.

When Async Is Worth the Added Complexity

Async code is genuinely more complex to write and reason about than the synchronous code used throughout this course, and it isn't the right choice for everything.

SituationRecommendation
A script processing requests one at a time, no urgencySynchronous client — simpler, no added complexity for no benefit
Many independent requests needing individual, timely responsesAsync client with bounded concurrency
A very large volume of requests with no immediate deadlineThe Batch API (Lesson 5), rather than either sync or async loops
A web server (Unit 14) handling many simultaneous usersAsync client — a synchronous call would block the entire server while waiting on one user's request

The web-server case deserves particular attention going into Unit 14: a synchronous, blocking call inside a request handler ties up that handler for the entire duration of the wait, unable to serve any other incoming request in the meantime — a web application serving multiple concurrent users needs an async client specifically to avoid one slow request blocking every other user's request from being handled at all.

Common Mistakes

Mixing synchronous and async client calls inside the same async function, calling the blocking client.responses.create() instead of await async_client.responses.create() inside an async def, which defeats the entire purpose of using async code in the first place.

Launching unbounded concurrency with asyncio.gather() over a large list of tasks, risking exceeding the account's actual rate limit by launching far more simultaneous requests than it can sustain.

Letting one failed task cancel an entire batch of otherwise-independent concurrent requests, by omitting return_exceptions=True when partial success is an acceptable, expected outcome.

Using async for a simple script with no concurrency need, adding meaningful code complexity for a benefit that only exists when multiple independent operations can actually run at once.

Best Practices

Use the async client and asyncio.gather() for any batch of many independent, time-sensitive requests, rather than looping through them synchronously one at a time.

Bound concurrency with a semaphore sized to stay comfortably under the account's actual rate limit, connecting directly to Lesson 3's rate-limiting guidance.

Use return_exceptions=True when partial failure within a batch is acceptable, and handle each result explicitly rather than letting one failure cancel the rest.

Reserve async specifically for genuine concurrency needs — many simultaneous requests, or a web server handling multiple users — rather than adding it to code that only ever does one thing at a time.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Async Clients and Concurrency and get answers drawn from it.

Signed-in readers only.