To send many SMS concurrently from async Python, share one httpx.AsyncClient, cap in-flight requests with an asyncio.Semaphore, and give every message its own idempotency key so a retry never texts the same person twice. Start with about eight concurrent requests and raise it only while you aren't seeing 429 responses.
We make Ready, so the code uses the Ready REST API and only the request shapes we document. The concurrency pattern works with any provider. If you need the basics first, our Python guide covers a single synchronous send.
When concurrency is the right tool
Concurrent single sends fit when each message has its own text, such as order updates, appointment reminders or one-time notices that include a name or a time. If every recipient gets the same text, the bulk endpoint is simpler and uses fewer requests. We compare the two in the last section.
Asyncio helps because each request spends most of its time waiting on the network. One thread can keep dozens of requests in flight. It doesn't help if the work is CPU-bound, and it doesn't make the provider faster. Your useful concurrency is bounded by the rate limits on your account, so a bigger number is not a faster number past a point. Our post on SMS API rate limits goes into that ceiling.
A shared client with explicit limits
Create one AsyncClient for the whole run. It holds a connection pool, so requests reuse TLS connections instead of paying a handshake each time. Set timeouts and pool limits on purpose, because the defaults are not tuned for your workload.
import asyncio
import os
import random
import uuid
import httpx
BASE_URL = "https://api.tryready.com"
KEY_NAMESPACE = uuid.uuid5(uuid.NAMESPACE_DNS, "texts.example")
def make_client() -> httpx.AsyncClient:
return httpx.AsyncClient(
base_url=BASE_URL,
headers={"X-API-Key": os.environ["READY_API_KEY"]},
timeout=httpx.Timeout(35.0, connect=5.0), # the API may take up to 30 s to answer,
limits=httpx.Limits(max_connections=16, max_keepalive_connections=8),
) The pool allows 16 connections while the semaphore will allow 8 requests at once, so the pool never becomes the bottleneck. Keep the pool at least as large as the semaphore. If it's smaller, tasks queue inside httpx and you'll see pool timeouts that look like network errors.
One idempotency key per message
The key must identify the message, not the attempt. Derive it from something stable in your data, such as the campaign and the contact, so a crash and restart produces the same key. uuid5 does that.
def message_key(campaign_id: str, contact_id: str) -> str:
return str(uuid.uuid5(KEY_NAMESPACE, f"{campaign_id}:{contact_id}")) Send it in the Idempotency-Key header on every attempt. If the request times out and you retry with the same key, a second text isn't sent. A fresh uuid4() per attempt defeats the whole mechanism. Our post on idempotency keys and duplicate texts explains what the key protects against.
The semaphore and the retry loop
Acquire the semaphore around each attempt, not around the whole retry loop. Otherwise a task that is sleeping through a backoff holds a slot that another message could use.
async def send_one(
client: httpx.AsyncClient,
sem: asyncio.Semaphore,
to: str,
text: str,
key: str,
max_attempts: int = 4,
) -> tuple[str, int | None]:
payload = {"to": to, "body": text, "consent_attested": True}
status: int | None = None
for attempt in range(1, max_attempts + 1):
try:
async with sem:
resp = await client.post(
"/v1/messages",
json=payload,
headers={"Idempotency-Key": key},
)
status = resp.status_code
in_progress = status == 409 and "idempotency_in_progress" in resp.text
if status != 429 and not in_progress:
return key, status
except httpx.TransportError:
status = None # timeout or connection error: outcome unknown, same key on retry
if attempt < max_attempts:
await asyncio.sleep(0.25 * 2**attempt + random.random() * 0.1)
return key, status httpx.TransportError covers connect, read, write and pool timeouts as well as connection failures. Because the key doesn't change, retrying after one is safe. The function never raises for network trouble. It returns the key with the last status, or None when no response ever arrived, so one bad message can't cancel the rest.
Only 429, a 409 idempotency_in_progress (the first try is still running) and transport errors are retried here, all with the same key. The read timeout is above the API's 30-second limit, so a slow send is waited for instead of being cut off. Every other status goes back to the caller. A 4xx for a malformed number fails the same way on the fourth try. For a 5xx or a final None, the outcome may be unknown, so check GET /v1/messages before you resend and see the errors reference for how each code should be treated.
Run a batch and collect results
asyncio.gather runs all the tasks and the semaphore does the throttling.
async def send_all(items: list[dict]) -> list[tuple[str, int | None]]:
sem = asyncio.Semaphore(8)
async with make_client() as client:
tasks = [
send_one(
client, sem, i["to"], i["text"],
message_key(i["campaign_id"], i["contact_id"]),
)
for i in items
]
return await asyncio.gather(*tasks)
if __name__ == "__main__":
demo = [
{"to": "+12125550199", "text": "Your order #1042 has shipped.",
"campaign_id": "ship-1042", "contact_id": "c-1"},
]
print(asyncio.run(send_all(demo))) Building one coroutine per item is fine for a few thousand messages. For a list of a million, create tasks in chunks of a few hundred, or feed an asyncio.Queue to a fixed set of worker tasks, so you don't hold a million pending coroutines in memory. Persist each result as it finishes. If the process dies, the stored keys tell you which messages already went out, and rerunning with the same keys is safe.
Choosing the concurrency number
Use Little's law to size it: requests in flight equal the request rate multiplied by the latency of each request. As a labelled example with assumed numbers, if you want 20 requests per second and each takes about 0.4 seconds, you need roughly 8 in flight. A semaphore of 8 matches that. Measure your real latency before you copy the figure.
Then watch for 429s. If they show up, lower the number or add delay rather than adding workers. Carrier limits also cap throughput per campaign, however fast your code runs. We describe the carrier side in our post on SMS queue design for platforms.
Bulk endpoint or many single sends
POST /v1/messages/bulk takes to as an array and sends the same body to each number, with at most 100 recipients per call. Here's how the choices compare.
| Situation | Better choice | Why |
|---|---|---|
| Same text to many people | Bulk, 100 per call | Far fewer requests and fewer keys to track |
| Text includes a name, time or link per person | Single sends with a semaphore | Each message differs, so bulk can't carry it |
| You need a per-message result you can store | Single sends | One request, one key, one outcome |
| A list of 5,000 identical notices | Bulk in chunks | 50 calls instead of 5,000 |
If you use bulk, chunk the list and key each chunk. Hash the sorted numbers and the body so the same chunk always gets the same key:
import hashlib
def chunks(items: list[str], size: int = 100):
for start in range(0, len(items), size):
yield items[start:start + size]
def bulk_key(numbers: list[str], text: str) -> str:
digest = hashlib.sha256((",".join(sorted(numbers)) + "|" + text).encode()).hexdigest()
return str(uuid.uuid5(KEY_NAMESPACE, digest)) Send each chunk through the same retry function, with /v1/messages/bulk, a to list and the chunk key. One edge case: if the contact list changes between a crash and a restart, the same chunk can hash differently and get a new key. Persist the chunks and their keys before the first call. Our post on bulk chunking and partial failures covers what to do when part of a chunk is refused, and the bulk messages reference has the response details.
Opted-out numbers are refused up front and aren't charged. Every text that does send costs $0.0075 a segment plus a $0.0045 carrier fee, whichever endpoint you use.
Wrapping up
The recipe is short: one client, a semaphore sized from your latency and rate limit, a key derived from the message's identity, and a retry loop that repeats only transport errors and 429s. Persist keys and results as you go, so a crash costs you time and not duplicate texts.
When you're ready to test it, the API quickstart walks through the key and the first send.
Accounts opened before November 12, 2026 keep their signup prices, shown under Billing.