To send an SMS from Django safely, write a row to an outbox table inside the same database transaction as your change, then let a Celery task send it after the commit. That one pattern stops two classic bugs: texting someone about a change that rolled back, and texting them twice when a task retries.
We make Ready, so the example uses the Ready REST API and only the request shape we document. If you want the plain-Python version first, start with our Python guide.
The outbox model
import uuid
from django.db import models
class SmsOutbox(models.Model):
to = models.CharField(max_length=20)
body = models.TextField()
idempotency_key = models.UUIDField(default=uuid.uuid4, unique=True)
status = models.CharField(max_length=12, default="pending")
attempts = models.PositiveSmallIntegerField(default=0)
created = models.DateTimeField(auto_now_add=True) The idempotency_key is created when the row is created and never changes. That's the whole trick. Every retry of the task reads the same key from the row.
Queue after the commit
from django.db import transaction
def notify_shipped(order):
with transaction.atomic():
order.mark_shipped()
row = SmsOutbox.objects.create(
to=order.phone_e164,
body=f"Your order #{order.number} has shipped.",
)
transaction.on_commit(lambda: send_sms_task.delay(row.pk)) transaction.on_commit is what keeps a rollback from texting anyone. If the transaction fails, the callback never runs, and the outbox row disappears with the rest of the change.
The task
import os, requests
from celery import shared_task
@shared_task(bind=True, max_retries=4)
def send_sms_task(self, pk):
row = SmsOutbox.objects.get(pk=pk)
if row.status == "sent":
return
try:
res = requests.post(
"https://api.tryready.com/v1/messages",
json={"to": row.to, "body": row.body, "consent_attested": True},
headers={
"X-API-Key": os.environ["READY_API_KEY"],
"Idempotency-Key": str(row.idempotency_key),
},
timeout=15,
)
except (requests.Timeout, requests.ConnectionError) as exc:
raise self.retry(exc=exc, countdown=2 ** self.request.retries)
in_progress = res.status_code == 409 and res.json().get("code") == "idempotency_in_progress"
if res.status_code == 429 or res.status_code >= 500 or in_progress:
raise self.retry(countdown=2 ** self.request.retries)
row.attempts += 1
row.status = "sent" if res.ok else "failed"
row.save(update_fields=["status", "attempts"]) Retry on timeouts, 429, 5xx and a 409 idempotency_in_progress (the first attempt is still running, so retry with the same key and the stored result comes back). Park everything else as failed, because a bad number or an opted-out contact won't fix itself. A 409 QUIET_HOURS_BLOCK isn't a failure in your code, it's a time rule, so send it again once the window opens. After a 504, or a code ending in OUTCOME_UNKNOWN, look at GET /v1/messages before you resend. The retries guide has the table.
Two things people get wrong
| Mistake | What happens | Fix |
|---|---|---|
.delay() inside the transaction | The worker can run before the commit and find no row | Use on_commit |
| New UUID on each retry | A lost response becomes a duplicate text | Store the key on the row |
| Sending in the request cycle | A slow carrier hop slows your page | Queue it |
FAQ
Should I use Celery or Django's newer task framework?
Either works with this pattern. The outbox row and the stored key matter more than the task runner, so pick whichever your project already runs.
Do I need the outbox if Celery retries already?
Yes. Celery can lose a task on a broker restart, and a task body can't remember its key unless you store it somewhere. The outbox is the durable record, and it's also your audit trail.
How do I test it?
Use a test key, which simulates every send with no card, number or charge. Our mocking guide shows how to keep requests out of unit tests.
The short version
Outbox row, stored key, on_commit, bounded retries. The messages API docs list every request field.
Cost and registration
A segment on the Standard rate is $0.0075 plus a $0.0045 carrier fee, excluding optional screening. An account can send up to 500 texts a month before it registers for 10DLC, and most approvals take 2 to 7 days. See pricing for the full list.