Python applications often communicate with AWS services to upload files, read database records, send messages, and process background jobs. These operations usually involve network communication, which means an application may spend more time waiting for responses than executing Python code.
For example, imagine an application that needs to retrieve information from 50 Amazon S3 objects. If it processes every request synchronously, it must wait for one operation to finish before moving to the next one. This can increase the total processing time, especially when network latency is high.
Asynchronous programming provides another way to handle these operations. Instead of blocking the entire execution flow while waiting for an AWS response, an asynchronous client allows Python to work on other tasks.
AWS provides different ways to build asynchronous applications. The established AWS SDK for Python, commonly known as Boto3, provides synchronous clients. Developers can use community libraries such as aiobotocore and aioboto3 to add asynchronous access to many Boto3 operations. AWS has also introduced AWS SDK for Python v4, which provides native asynchronous clients using Python's async and await syntax.
There is an important difference between these options. AWS SDK for Python v4 is currently in Developer Preview, so it is intended for development and testing rather than production workloads. Boto3 remains the recommended production SDK.
This article explains how asynchronous AWS clients work, how to create them, how to run multiple AWS operations concurrently, and how to handle common problems in real applications.
Understanding Asynchronous Programming in Python
Before creating an asynchronous AWS client, it is useful to understand how asynchronous programming works in Python.
In a synchronous program, an operation blocks the current thread until it completes.
Consider the following example:
import time
def download_file(file_name):
print(f"Downloading {file_name}")
time.sleep(3)
print(f"Completed {file_name}")
download_file("file1.txt")
download_file("file2.txt")
download_file("file3.txt")Each operation waits for three seconds. Since the operations run one after another, the total waiting time is approximately nine seconds.
This example uses time.sleep() to simulate a network delay. Actual AWS requests involve network communication, authentication, request processing, and response handling.
An asynchronous approach allows the application to wait without blocking the entire event loop.
import asyncio
async def download_file(file_name):
print(f"Downloading {file_name}")
await asyncio.sleep(3)
print(f"Completed {file_name}")
async def main():
await asyncio.gather(
download_file("file1.txt"),
download_file("file2.txt"),
download_file("file3.txt")
)
asyncio.run(main())The three operations can wait concurrently. Their combined waiting time is approximately three seconds rather than nine seconds, assuming they can all run at the same time.
This is the basic idea behind asynchronous AWS clients.
An important point is that asynchronous programming does not automatically make every operation faster. It is most useful when an application spends significant time waiting for network or other asynchronous I/O operations.
CPU-intensive operations still require a different approach, such as multiprocessing or moving the work to an appropriate worker thread or process.
Understanding the AWS SDK Options for Asynchronous Clients
Developers have several choices when building Python applications that communicate with AWS services.
The correct choice depends on production requirements, service coverage, and whether the application already uses asyncio.
Option | Execution model | Production status | Main purpose |
|---|---|---|---|
Boto3 | Synchronous | Generally available | Standard AWS access for Python |
aiobotocore | Asynchronous wrapper around Botocore | Community-maintained | Async access using Botocore service models |
aioboto3 | Asynchronous Boto3-style interface built on aiobotocore | Community-maintained | Async clients and resources |
AWS SDK for Python v4 | Native synchronous and asynchronous clients | Developer Preview | Evaluate native async APIs and modern SDK architecture |
Boto3 is the established AWS SDK for Python. It supports a broad range of AWS services and remains the recommended option for production workloads.
aiobotocore provides asynchronous access by building on Botocore. aioboto3 builds on aiobotocore and provides an interface closer to Boto3, including resource support.
AWS SDK for Python v4 introduces native asynchronous clients. It uses Python's async and await syntax without requiring a community wrapper. However, its Developer Preview status means that developers should use it for evaluation and testing rather than production deployments.
Creating an Asynchronous AWS Client With aiobotocore
If you need asynchronous access while continuing to use the established Boto3 and Botocore ecosystem, aiobotocore is one option.
It provides asynchronous clients for AWS services and uses asyncio to manage network operations.
Install aiobotocore
Create a Python virtual environment before installing the package.
python -m venv venvActivate it on Windows:
venv\Scripts\activateOn macOS or Linux:
source venv/bin/activateInstall aiobotocore:
pip install aiobotocoreThe package includes the required Botocore integration. You should avoid independently installing incompatible versions of Botocore and aiobotocore.
If your project has additional AWS dependencies, check their compatibility before updating the package versions.
Configure AWS Credentials
The asynchronous client needs valid AWS credentials and a Region.
For local development, you can configure credentials using the AWS CLI:
aws configureThe command allows you to configure an access key, secret key, and default Region.
For production applications running on AWS, use an appropriate IAM role or workload identity mechanism instead of storing permanent access keys in source code.
You can also configure the Region through the application or supported AWS configuration settings.
Create an Asynchronous S3 Client
The first step is to create an aiobotocore session and use it to create an asynchronous S3 client.
import asyncio
from aiobotocore.session import get_session
async def main():
session = get_session()
async with session.create_client(
"s3",
region_name="ap-south-1"
) as s3_client:
response = await s3_client.list_buckets()
for bucket in response.get("Buckets", []):
print(bucket["Name"])
if __name__ == "__main__":
asyncio.run(main())Let's understand the important parts.
get_session() creates a session that can be used to create AWS service clients.
The create_client() method creates an asynchronous client for the selected AWS service. In this example, the service is Amazon S3.
The async with statement manages the client lifecycle. It ensures that the client is closed properly after the application finishes using it.
The await keyword is important. Calling an asynchronous operation without awaiting or scheduling its coroutine does not send the request.
For example, this is incorrect:
response = s3_client.list_buckets()The method returns a coroutine instead of the completed AWS response.
Use await to execute the operation:
response = await s3_client.list_buckets()This is a common difference between synchronous and asynchronous AWS clients.
Uploading and Downloading Files Asynchronously
Amazon S3 is a common use case for asynchronous AWS clients. Applications frequently upload documents, images, backups, and other files.
The following example uploads a file to an S3 bucket using aiobotocore.
import asyncio
from aiobotocore.session import get_session
async def upload_file(bucket_name, file_name, object_key):
session = get_session()
async with session.create_client(
"s3",
region_name="ap-south-1"
) as s3_client:
with open(file_name, "rb") as file:
await s3_client.put_object(
Bucket=bucket_name,
Key=object_key,
Body=file
)
print(f"Uploaded: {object_key}")
async def main():
await upload_file(
"my-application-bucket",
"report.pdf",
"documents/report.pdf"
)
if __name__ == "__main__":
asyncio.run(main())The put_object() operation sends the file to S3. The application awaits the response instead of blocking the entire event loop.
There is one important consideration in this example: Python's normal open() operation is synchronous. Reading a file from a local disk can block the event loop, even though the AWS request is asynchronous.
For small files, this may be acceptable. For large files or applications that handle many files concurrently, use a suitable asynchronous file I/O library or move blocking file operations to a worker thread.
The following example uses asyncio.to_thread() to read a file without blocking the event loop:
import asyncio
from aiobotocore.session import get_session
async def upload_file(bucket_name, file_name, object_key):
session = get_session()
file_content = await asyncio.to_thread(
lambda: open(file_name, "rb").read()
)
async with session.create_client(
"s3",
region_name="ap-south-1"
) as s3_client:
await s3_client.put_object(
Bucket=bucket_name,
Key=object_key,
Body=file_content
)
print(f"Uploaded: {object_key}")
asyncio.run(
upload_file(
"my-application-bucket",
"report.pdf",
"documents/report.pdf"
)
)This version moves the synchronous file-reading operation to a worker thread. It is useful for understanding the pattern, but reading an entire large file into memory may not be appropriate for production.
For large files, use a streaming approach or a suitable transfer utility rather than loading the complete file into memory.
Running Multiple AWS Requests Concurrently
One of the biggest benefits of asynchronous clients is the ability to run independent operations concurrently.
Consider an application that needs to retrieve metadata for multiple S3 objects.
A sequential implementation waits for every request to finish before starting the next one.
An asynchronous implementation can schedule several requests together.
import asyncio
from aiobotocore.session import get_session
async def get_object_metadata(
s3_client,
bucket_name,
object_key
):
response = await s3_client.head_object(
Bucket=bucket_name,
Key=object_key
)
return {
"key": object_key,
"size": response["ContentLength"]
}
async def main():
session = get_session()
object_keys = [
"documents/report1.pdf",
"documents/report2.pdf",
"documents/report3.pdf",
"documents/report4.pdf"
]
async with session.create_client(
"s3",
region_name="ap-south-1"
) as s3_client:
tasks = [
get_object_metadata(
s3_client,
"my-application-bucket",
key
)
for key in object_keys
]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
if __name__ == "__main__":
asyncio.run(main())In this example, asyncio.gather() schedules all metadata operations and waits for their results.
Instead of waiting for each request sequentially, the event loop can manage multiple requests while they are waiting for network responses.
This can improve throughput when the operations are independent and the AWS service can handle the request volume.
However, running thousands of requests simultaneously is not a good default strategy. It can increase memory usage, create unnecessary network pressure, and trigger AWS throttling.
Limit Concurrency With asyncio.Semaphore
A production application should control how many requests run simultaneously.
For example, suppose an application needs to process 500 S3 objects. Starting all 500 requests at once may create unnecessary pressure on the application and AWS service.
An asyncio.Semaphore allows you to set a maximum number of concurrent operations.
import asyncio
from aiobotocore.session import get_session
async def get_metadata(
s3_client,
semaphore,
bucket_name,
object_key
):
async with semaphore:
response = await s3_client.head_object(
Bucket=bucket_name,
Key=object_key
)
return {
"key": object_key,
"size": response["ContentLength"]
}
async def main():
session = get_session()
semaphore = asyncio.Semaphore(10)
object_keys = [
f"documents/file-{number}.pdf"
for number in range(1, 101)
]
async with session.create_client(
"s3",
region_name="ap-south-1"
) as s3_client:
tasks = [
get_metadata(
s3_client,
semaphore,
"my-application-bucket",
key
)
for key in object_keys
]
results = await asyncio.gather(*tasks)
print(f"Processed {len(results)} objects")
if __name__ == "__main__":
asyncio.run(main())
Join the conversation! Your thoughts help the community grow.