Python SMS API Masterclass: Async Sending, Webhook Signature Verification, and Production Error Handling
Production Python SMS integration: httpx async client, bounded concurrency, retry taxonomy, HMAC webhook verification, and an out-of-order DLR state machine.
The Django app had eight Gunicorn workers, a 30-second upstream timeout, and a login endpoint that called the SMS API inline. At 9 a.m. on launch day, p99 crossed four seconds, the worker pool filled with threads waiting on a socket, and new requests started returning 502 before they ever reached the OTP code. The team did the obvious thing: they doubled the workers. The 502s got worse. So they doubled them again.
The problem was never Python's speed. It was a synchronous third-party call inside a request cycle, wrapped in an unbounded retry policy, competing for a fixed pool of workers and a fixed pool of database connections. Adding workers increased the number of concurrent calls to an upstream that was already rate-limiting them, which increased the retry rate, which increased the load. The system was not under-provisioned. It was amplifying its own failure.
What does a production Python SMS integration need?
A production Python SMS integration needs four things: an async HTTP client with connection pooling and explicit timeouts, a bounded concurrency limit that respects the provider's rate limit, a retry policy that distinguishes retryable from terminal errors and carries an idempotency key, and a webhook receiver that verifies an HMAC signature over the raw body and processes delivery receipts idempotently. The send call should never run inside a user-facing request if it can be queued; when it must, it should be fast, bounded, and observable. Most "Python is slow" incidents are actually unbounded concurrency and retry amplification.
The API itself is simple. You send a bearer token, a destination in E.164 format, a message body, and a sender ID. The service returns a message ID immediately and delivers the message asynchronously; the final status arrives on a webhook. The engineering work is in the boundaries: how long you wait, how many requests you allow in flight, what you do when the answer is a 429, and how you prove that a webhook actually came from the gateway. For the basic request/response contract, see the SMS API integration guide; for the endpoint reference, use the developer docs.
The 30-second version
curl -X POST https://api.sendsmsnokyc.com/sms/send \
-H "Authorization: Bearer $SMSROUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": "+14155552671",
"message": "Your verification code is 849201. Expires in 5 minutes.",
"sender_id": "AUTHMSG",
"callback_url": "https://yourapp.com/webhooks/sms"
}'
The response contains a message ID and a queued status. Store that ID before you do anything else: it is the only key that ties the send to the delivery receipt. If your process crashes between the response and the database write, you have a message you paid for and cannot reconcile. That is why the production client below writes the ID inside the same request handler, before acknowledging success to the caller.
Sync vs async: the numbers that matter
The Python ecosystem offers three ways to send an SMS: a synchronous request per message, a thread pool wrapping synchronous requests, or an async client multiplexing many requests over a small number of connections. The first is fine for a script and disastrous inside a web request. The second is a reasonable bridge for an existing sync codebase. The third is the right default for a service that sends OTPs at scale.
| Mode | Throughput | P50 | P95 | Typical failure |
|---|---|---|---|---|
| requests, sequential | 12 msg/s | 180 ms | 420 ms | Worker starvation |
| requests + ThreadPool(20) | 380 msg/s | 240 ms | 900 ms | Connection churn, GIL contention |
| httpx.AsyncClient (100 in flight) | 2,400 msg/s | 160 ms | 610 ms | Event-loop blocking, provider 429 |
| aiohttp (100 in flight) | 2,300 msg/s | 170 ms | 640 ms | Similar; connection pool misuse |
Client-side send throughput on a 4-vCPU test host, not carrier throughput. The provider's rate limit is the real ceiling; measure it before tuning concurrency.
The async advantage is not that Python executes more instructions per second. It is that a coroutine waiting on a socket does not occupy an OS thread, so one process can keep hundreds of in-flight requests without a 100-thread context-switch tax. A synchronous worker blocked on a 900 ms upstream call is unavailable for anything else; a coroutine yields the event loop and lets another request proceed. The result is higher throughput at the same CPU cost, provided every blocking call in the path is actually async.
That last clause is where most migrations fail. A single synchronous database driver call, a CPU-heavy template render, or a blocking time.sleep() inside an async handler stalls the entire event loop. If you adopt async, adopt it end to end: async HTTP, async database driver, async cache client, and a thread pool only for genuinely blocking work. Otherwise the benchmark looks great and production looks like a traffic jam.
A production-grade async client
The client below is deliberately boring. It has one connection pool, one semaphore, explicit timeouts, a retry budget, jitter, and an error type that preserves the HTTP status and provider error code. It never retries a 400, 401, 402, 403, 404, 409, or 422; those are bugs in your request, your credentials, your balance, or your permissions, and retrying them only wastes time. It does retry 429, 500, 502, 503, 504, and network timeouts.
from __future__ import annotations
import asyncio, logging, os, random, uuid
from typing import Any
import httpx
log = logging.getLogger("smsroute")
RETRYABLE = {429, 500, 502, 503, 504}
class SMSRouteError(RuntimeError):
def __init__(self, status: int, code: str, message: str) -> None:
super().__init__(message)
self.status = status
self.code = code
class SMSRouteClient:
def __init__(self, api_key: str | None = None, max_concurrency: int = 50) -> None:
self._client = httpx.AsyncClient(
base_url="https://api.sendsmsnokyc.com",
headers={"Authorization": f"Bearer {api_key or os.environ['SMSROUTE_API_KEY']}"},
timeout=httpx.Timeout(10.0, connect=2.0, read=10.0, write=10.0, pool=2.0),
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20,
keepalive_expiry=30.0),
http2=True,
)
self._semaphore = asyncio.Semaphore(max_concurrency)
async def send(self, to: str, message: str, sender_id: str = "SMSRoute",
callback_url: str | None = None, max_retries: int = 3) -> dict[str, Any]:
payload = {"to": to, "message": message, "sender_id": sender_id}
if callback_url:
payload["callback_url"] = callback_url
idempotency_key = str(uuid.uuid4())
async with self._semaphore:
for attempt in range(max_retries + 1):
retry_after = 0.0
try:
response = await self._client.post(
"/sms/send", json=payload,
headers={"Idempotency-Key": idempotency_key},
)
except (httpx.ConnectError, httpx.ReadTimeout, httpx.WriteTimeout, httpx.PoolTimeout) as exc:
if attempt == max_retries:
raise SMSRouteError(0, "network_error", str(exc)) from exc
else:
if response.status_code < 300:
return response.json()
detail = response.json() if response.content else {}
if response.status_code not in RETRYABLE:
raise SMSRouteError(response.status_code,
detail.get("code", "http_error"),
detail.get("message", response.text))
retry_after = float(response.headers.get("Retry-After", 0) or 0)
log.warning("smsroute retry status=%s attempt=%s", response.status_code, attempt)
delay = retry_after if retry_after else min(8.0, 0.5 * (2 ** attempt))
await asyncio.sleep(delay + random.uniform(0, 0.25))
raise SMSRouteError(0, "retry_exhausted", "retry budget exhausted")
async def aclose(self) -> None:
await self._client.aclose()
async def __aenter__(self) -> "SMSRouteClient":
return self
async def __aexit__(self, *_: object) -> None:
await self.aclose()
The error taxonomy your retry policy needs
A retry policy is only as good as its classification. Retrying a malformed request five times produces five identical failures and a slower incident. Retrying a rate limit without honoring Retry-After turns a brief throttle into a sustained block. The table below is the minimum taxonomy a production integration should implement, mapped to the status codes and failure modes you will actually see.
| Status / failure | Meaning | Retry? | Correct action |
|---|---|---|---|
| 400 | Malformed JSON or missing field | No | Fix the payload; log the response body |
| 401 | Invalid or expired API key | No | Rotate the key; alert security |
| 402 | Insufficient balance | No | Top up; page treasury if runway is low |
| 403 | Forbidden route or sender ID | No | Check destination and sender registration |
| 409 | Idempotency conflict | Reuse key | Query the original result before retrying |
| 422 | Validation failure | No | Validate E.164 and message length client-side |
| 429 | Rate limit | Yes | Honor Retry-After; reduce concurrency |
| 500 / 502 / 503 / 504 | Server or gateway failure | Yes | Exponential backoff with jitter |
| Timeout | No response within deadline | Yes | Same idempotency key; verify whether it queued |
Verifying webhooks without trusting the network
A webhook endpoint is a public write API. Anyone can POST a JSON body that says a message was delivered, and if your code believes it, an attacker can mark failed messages as successful, suppress a fraud alert, or poison your billing ledger. The defence is an HMAC signature over the exact raw request body, verified with a constant-time comparison before any parsing. Parse first and you have already lost the ability to verify what was signed.
The receiver below also handles the two problems that appear the moment you have more than one webhook: replay and out-of-order delivery. It rejects events older than five minutes when a timestamp is present, and it uses a state rank so a late failed cannot overwrite an earlier delivered.
import asyncio, hashlib, hmac, json, os, sqlite3, time
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import Response
app = FastAPI()
DB_PATH = os.environ.get("SMS_DB", "sms.db")
SECRET = os.environ["SMS_WEBHOOK_SECRET"].encode()
MAX_SKEW = 300
RANK = {"queued": 0, "sent": 1, "delivered": 2, "failed": 2, "undelivered": 2}
def process_dlr(event: dict) -> bool:
status = str(event.get("status", "")).lower()
if status not in RANK:
raise ValueError(f"unknown status: {status}")
message_id = event["message_id"]
con = sqlite3.connect(DB_PATH, timeout=10)
try:
con.execute("""CREATE TABLE IF NOT EXISTS dlr (
message_id TEXT PRIMARY KEY, status TEXT, rank INTEGER,
delivered_at TEXT, error_code TEXT, updated_at REAL)""")
row = con.execute("SELECT rank FROM dlr WHERE message_id = ?", (message_id,)).fetchone()
if row is not None and RANK[status] < row[0]:
return False
con.execute("""INSERT INTO dlr (message_id, status, rank, delivered_at, error_code, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(message_id) DO UPDATE SET status = excluded.status, rank = excluded.rank,
delivered_at = excluded.delivered_at, error_code = excluded.error_code,
updated_at = excluded.updated_at""",
(message_id, status, RANK[status], event.get("delivered_at"),
event.get("error_code"), time.time()))
con.commit()
return True
finally:
con.close()
@app.post("/webhooks/sms")
async def sms_webhook(request: Request, x_sms_signature: str = Header(default="")):
raw = await request.body()
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, x_sms_signature):
raise HTTPException(status_code=401, detail="invalid signature")
event = json.loads(raw)
if not event.get("message_id"):
raise HTTPException(status_code=422, detail="message_id required")
sent_at = event.get("sent_at")
if isinstance(sent_at, (int, float)) and abs(time.time() - sent_at) > MAX_SKEW:
raise HTTPException(status_code=409, detail="stale event")
try:
changed = await asyncio.to_thread(process_dlr, event)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
return Response(status_code=204, headers={"X-Processed": "1" if changed else "0"})
The delivery-receipt state machine
Delivery receipts are events, not a current-state API. They arrive late, out of order, and sometimes more than once. A message can be queued, then sent, then delivered; a retry can produce a second sent after the first delivered. If your handler updates a status column unconditionally, the last event wins, and the last event is often the least accurate.
| State | Meaning | Terminal? | Application action |
|---|---|---|---|
| queued | Accepted by the API | No | Wait; start a delivery timeout |
| sent | Submitted to the carrier | No | Monitor; do not resend yet |
| delivered | Handset acknowledged receipt | Yes | Mark success; stop all retries |
| failed | Terminal carrier failure | Yes | Fallback channel; release credit |
| undelivered | Rejected, expired, or unreachable | Yes | Fallback; investigate if the rate spikes |
The state rank is a simple defence: assign queued=0, sent=1, and all terminal states rank 2. Reject any update whose rank is lower than the stored rank. This lets a late sent arrive without erasing a delivered, while still allowing a terminal failed to arrive after an earlier sent. The rank is not a substitute for an idempotency table; it is a second line of defence for the specific out-of-order case.
Testing the failure paths
The happy path is easy to test and the least likely to break in production. Write tests for the paths that cost money: a 429 with a Retry-After header, a 402 insufficient-balance response, a timeout followed by a successful retry with the same idempotency key, an invalid webhook signature, a duplicate webhook, and a late terminal event that must not overwrite a delivered state. Use httpx.MockTransport or respx to simulate the responses without hitting the network.
For the webhook, compute the signature in the test exactly as the gateway does β HMAC-SHA256 over the raw body β and assert that a one-byte change produces a 401. Test replay by sending the same event twice and checking that the second call is a no-op. Test out-of-order by sending delivered and then failed; the stored state must remain delivered. These tests are unglamorous, and they are the reason a 3 a.m. page does not turn into a billing reconciliation project.
Deployment, pool sizing, and observability
Size the HTTP pool from the concurrency you actually need, not from a round number. If each Uvicorn worker handles 50 concurrent sends and you run four workers, the process needs at most 200 connections; setting max_connections=100 per process gives headroom without exhausting the provider's limit. Keep connections alive for 30 seconds to amortize TLS handshakes, and make sure the upstream's rate limit is lower than your aggregate pool size, or the extra connections will simply queue at the provider.
Emit four metrics: send latency by status, in-flight requests, retry count by reason, and delivery-receipt age (time from send to terminal DLR). Alert on the P95 of receipt age, not the mean; alert on the ratio of 429s to total sends; and alert when the retry rate exceeds 5% for five minutes. A dashboard that shows only success rate will look healthy while every request is retrying twice. The DLR webhook guide covers the deeper event-processing architecture.
Frequently asked questions
Should I send OTPs inside the login request?
Only if the send completes within a strict timeout and you have a queue-backed fallback. The safer pattern is to enqueue the send, return a "code sent" response immediately, and let a worker handle the API call and retries. The user experience is the same, but a slow carrier no longer occupies a web worker or holds a database transaction open.
Why use httpx instead of requests?
requests is synchronous and has no native async client. You can run it in a thread pool, and that is a reasonable bridge for an existing codebase, but you pay for thread context switches and connection-pool contention. httpx offers the same API surface in both sync and async forms, HTTP/2 support, and explicit timeout and limit objects. If your service is already async, use httpx; if it is sync, use requests with a bounded thread pool and do not pretend it is async.
How many retries are too many?
Three retries with exponential backoff and jitter is a sensible default for transient failures. More than that usually means the upstream is down, and the correct action is to shed load, alert, and fall back to another channel β not to keep hammering. Pair the retry budget with a circuit breaker: after a threshold of consecutive failures, stop sending for 30 seconds and let the queue drain.
Do I need a separate webhook secret per environment?
Yes. A staging secret that leaks should not let an attacker forge production delivery receipts. Store each secret in the environment's secret manager, rotate on a schedule, and support two active secrets during rotation so you can verify old and new signatures without downtime. The same rule applies to API keys: separate keys per environment, per service, and per deploy.
Jacky Hossein
Verified AuthorPrincipal Telecommunications & Cryptographic Systems Architect at SMSRoute. Specializes in carrier-grade SS7/SMPP routing protocols, non-custodial cryptocurrency billing rails, and zero-knowledge telecommunications privacy.
Send Global SMS in Under 60 Seconds Without KYC
Sign up with email only. Top up with Bitcoin, USDT, Monero, or Ethereum. Instant carrier interconnects to 149 countries from $0.004/msg.