To send an SMS from a Python background worker, put one small function around POST /v1/messages, generate an Idempotency-Key when you enqueue the job, and let RQ or Dramatiq retry only the failures that deserve it. The queue owns retries. The key makes sure a retry never texts someone twice.

We make Ready, so the code below uses only the request shape we document. If you're on Celery instead, our Django and Celery guide covers it, and the plain synchronous version is in send SMS with Python.

One send function both queues share

Keep the HTTP call out of the worker libraries. Save this as sms.py; both RQ and Dramatiq import it, so retry policy is the only thing that differs.

import os
import requests

API_URL = "https://api.tryready.com/v1/messages"


class RetryableSend(Exception):
    pass


def send_sms(to: str, body: str, key: str) -> dict:
    try:
        res = requests.post(
            API_URL,
            headers={
                "X-API-Key": os.environ["READY_API_KEY"],
                "Idempotency-Key": key,
            },
            json={"to": to, "body": body, "consent_attested": True},
            timeout=15,
        )
    except (requests.Timeout, requests.ConnectionError) as exc:
        raise RetryableSend(str(exc)) from exc

    if res.status_code == 429 or res.status_code >= 500:
        raise RetryableSend(f"status {res.status_code}")
    if res.status_code >= 400:
        return {"sent": False, "status": res.status_code, "detail": res.text}
    return {"sent": True, "status": res.status_code}

Set consent_attested to true only when the recipient agreed to texts. If your job can run for a contact who hasn't, don't hard-code it: pass the value in from the record that proves consent. to is E.164, and READY_API_KEY comes from the worker's environment, never from the job payload.

The function raises for the cases a retry can fix (a timeout, a 429, a 5xx) and returns for everything else. A 4xx such as a bad number or an opted-out contact won't change on the next attempt, so it comes back as a result you can log and alert on.

The idempotency key goes in the job

Create the key once, when you enqueue, and pass it as a job argument. Every retry then re-sends the same key.

import uuid

key = str(uuid.uuid4())

Never generate it inside the worker function. A retry would mint a fresh key and defeat the point. If the same business event can enqueue twice, derive the key from the event instead; our deterministic idempotency keys guide shows how.

RQ

RQ retries are set at enqueue time with Retry. Any exception counts as a failure to retry, which is why the shared function returns on permanent errors instead of raising.

import os
import uuid
from redis import Redis
from rq import Queue, Retry

from sms import send_sms

queue = Queue("sms", connection=Redis.from_url(os.environ["REDIS_URL"]))


def enqueue_text(to: str, body: str):
    return queue.enqueue(
        send_sms,
        to,
        body,
        str(uuid.uuid4()),
        retry=Retry(max=4, interval=[5, 20, 60, 300]),
        job_timeout=60,
    )

Start the worker with rq worker sms -u $REDIS_URL. Each retry waits the next interval in the list, and RQ passes the same arguments, so the same key goes out. When the attempts run out, the job lands in the failed registry where you can see it.

Dramatiq

Dramatiq puts retry settings on the actor and uses exponential backoff between min_backoff and max_backoff, both in milliseconds.

import os
import uuid

import dramatiq
from dramatiq.brokers.redis import RedisBroker

from sms import send_sms

dramatiq.set_broker(RedisBroker(url=os.environ["REDIS_URL"]))


@dramatiq.actor(queue_name="sms", max_retries=5, min_backoff=2000, max_backoff=300000)
def text_contact(to: str, body: str, key: str):
    result = send_sms(to, body, key)
    if not result["sent"]:
        print(f"not sent: {result['status']} {result['detail']}")


def enqueue_text(to: str, body: str):
    text_contact.send(to, body, str(uuid.uuid4()))

Run it with dramatiq your_module. Raising RetryableSend triggers the retry middleware, and returning ends the message cleanly. Swap the print for your logger or an alert.

Which failures retry

ResponseRetry?Why
Timeout or connection errorYes, same keyThe request may or may not have landed; the key makes a repeat safe
429Yes, same keyToo many requests; back off
5xxYes, same keyTransient on our side or in transit
400, 403, 404 and other 4xxNoThe request itself is wrong or refused; record it
409 QUIET_HOURS_BLOCKNo, send again laterA time rule, not an error

On that last row: an API text is held only if the recipient's quiet-hours window opens within a few hours. Otherwise Ready refuses it with 409 QUIET_HOURS_BLOCK and nothing is sent. Don't retry it on a backoff curve. Enqueue it again with a delay until the window opens, using a new key, because the first request was not sent. The quiet hours 409 guide has the pattern, and the error codes page lists the rest.

RQ or Dramatiq

FeatureRQDramatiq
BrokerRedisRedis or RabbitMQ
Retry configAt enqueue, per jobOn the actor
BackoffA list of intervals you chooseExponential between min and max
Good fitSmall apps already on RedisServices that want per-actor settings and middleware

Either works. Pick the one your team already runs.

FAQ

Can I retry a 4xx?

No. A 4xx means the request was refused or malformed, and sending the same thing again gets the same answer. Fix the data, then enqueue a new job with a new key.

What if the worker dies after the request but before it records success?

The queue redelivers the job with the same arguments, so the same Idempotency-Key goes out again and the request isn't sent twice. That's the reason the key lives in the job and not in the function.

Should the web request send the text directly instead?

Only when the user is waiting on the result and a failure is fine to show. For anything that must arrive, enqueue it so a restart or a slow response doesn't lose it.

The short version

One shared function, one key per message created at enqueue, retries for timeouts, 429 and 5xx, and a parked result for everything else. The messages API docs list every field, and you can create an account at tryready.com/signup when you're ready to send a first text.