To send an SMS from an Airflow DAG, call the messaging API's POST /v1/messages from a Python task with requests, and derive the Idempotency-Key header from something that stays the same across retries of that task run, such as the DAG ID, the logical date and the recipient. Then Airflow's own task retries can't text anyone twice: the second attempt carries the same key, so the API treats it as the same message.

That pairing is the whole point. Airflow retries tasks by design, and a task that sends a text is the classic case where a retry hurts. We make Ready, so the examples use the Ready REST API and only the request shape we document. The idea works with any provider that supports idempotency keys, and the code uses plain Python and the TaskFlow API.

Why Airflow retries are risky for texts

Airflow marks a task failed when the Python process raises, times out or gets killed. It doesn't know whether the HTTP request reached the messaging API before that happened. Three common situations lead to a duplicate:

  • The API accepted the text, but your worker was killed before it read the response.
  • The request timed out on your side after the text had been queued.
  • The task sent 500 texts in a loop, crashed on number 301, and retried from number 1.

A table makes the fix clearer:

SituationWithout a keyWith one stable key per message
Worker killed after the sendRetry sends againRetry is recognized, no second text
Timeout, outcome unknownRetry may send againSame key, no second text
Crash halfway through a listRetry resends the first halfEach recipient's key is the same, so the first half is skipped
Manual clear and re-run of the same dateEveryone is texted againSame keys, no second text

The last row deserves a caution. Clearing and re-running a task for the same logical date is something an on-call engineer does without thinking. If your keys are built from the logical date, a re-run is safe. If you add a random UUID per attempt, it isn't.

Build the key from the task run, not the attempt

Airflow gives each task a stable identity across retries: the DAG ID, the task ID, the logical date (ds in templates) and the map index for dynamic tasks. It also gives each attempt a try_number, which changes on every retry. Use the first set and leave out try_number.

A key per recipient looks like this: <dag_id>:<task_id>:<logical_date>:<recipient_id>. Keep it to a stable record ID, such as a customer ID, instead of the phone number itself, so you aren't scattering numbers through logs. Check the messages docs for any length limit on keys before you pick a format. If a composed key is long, hash it with SHA-256 and send the hex digest.

A DAG that sends one text per row

Here's a complete example. It reads who to text, then sends one text per row as mapped tasks, so each recipient is its own task with its own retries:

import hashlib
import os
from datetime import timedelta

import requests
from airflow.decorators import dag, task
from airflow.exceptions import AirflowFailException
from airflow.operators.python import get_current_context
import pendulum

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


@dag(schedule="0 15 * * *", start_date=pendulum.datetime(2026, 11, 1, tz="UTC"), catchup=False)
def shipment_texts():
    @task
    def recipients():
        # Replace with your warehouse or database query.
        return [
            {"id": "ord-1042", "phone": "+12125550199", "text": "Your order #1042 has shipped."},
            {"id": "ord-1043", "phone": "+12125550142", "text": "Your order #1043 has shipped."},
        ]

    @task(retries=3, retry_delay=timedelta(seconds=30), retry_exponential_backoff=True)
    def send_one(row):
        ctx = get_current_context()
        ti = ctx["ti"]
        raw = f"{ti.dag_id}:{ti.task_id}:{ctx['ds']}:{row['id']}"
        key = hashlib.sha256(raw.encode()).hexdigest()

        res = requests.post(
            API,
            headers={
                "X-API-Key": os.environ["READY_API_KEY"],
                "Idempotency-Key": key,
            },
            json={"to": row["phone"], "body": row["text"], "consent_attested": True},
            timeout=15,
        )
        if res.status_code == 429 or res.status_code >= 500:
            res.raise_for_status()  # let Airflow retry, same key next time
        if res.status_code >= 400:
            raise AirflowFailException(f"refused: {res.status_code} {res.text[:200]}")
        return res.json()

    send_one.expand(row=recipients())


shipment_texts()

Note the two branches after the request. A 429 or a server error raises an ordinary exception, so Airflow retries with its backoff, and the key is identical on the next attempt. Any other 4xx raises AirflowFailException, which fails the task without retrying, because a malformed number fails the same way every time. Read the key from a Connection or secrets backend in a real deployment instead of a bare environment variable.

Idempotency covers retries, not business duplicates

An idempotency key protects against the same request being sent twice. It doesn't protect against two different requests that mean the same thing. If your recipients() query returns the same customer twice, or two DAG runs select overlapping rows with different logical dates, you'll send two texts with two different keys.

Handle that upstream:

  1. Deduplicate the recipient list in the query, not in the send task.
  2. Record what you sent in a table keyed by recipient and campaign, and exclude those rows next run.
  3. Keep max_active_runs=1 on DAGs that must not overlap.

Check opt-outs before you send from a pipeline

A pipeline that reads from a warehouse is the place stale data creeps in. Ready refuses opted-out numbers and numbers on your Ban list up front and doesn't charge for them, so a refused send is the safety net, not your first line. For a list built outside Ready, or after a provider migration, check GET /v1/opt-outs/:phone before the send. GET /v1/opt-outs?scope=all adds the account's whole Ban list, paged by next_cursor. The opt-out API post walks through syncing opt-outs back into your warehouse so tomorrow's query excludes them.

Quiet hours matter for scheduled DAGs too. An API text to a recipient in quiet hours is held only if the window opens within 6 hours. Otherwise it isn't sent and the API answers 409 QUIET_HOURS_BLOCK, so a 9 AM UTC run can hit evening recipients. Don't retry that answer in a loop. Resend after the window opens, or send the request with hold_until_allowed: true, which holds it up to 24 hours like a campaign text.

Large lists: bulk calls and rate limits

One mapped task per recipient is clear but heavy for tens of thousands of rows. For the same message to many numbers, POST /v1/messages/bulk takes to as an array, with at most 100 recipients per call. Make each batch one mapped task, and build its key from the batch index plus the logical date, as long as your batching is deterministic: sort the rows the same way on every run so a retry produces the same batches. See the bulk messages docs and our post on bulk chunking and partial failures.

Use an Airflow pool to cap concurrency. If the API answers 429, fewer parallel slots is the answer, not more retries.

A worked cost example

Assume a DAG texts 3,000 customers a day, one segment each, no emoji. That's 3,000 × ($0.0075 + $0.0045) for the day, at the Standard rate plus the carrier fee. Screening is extra when you switch it on. A card on file and a number of your own are required to send. Accounts opened before November 12, 2026 keep their signup prices, shown under Billing.

Ready's all-in prices per segment include the carrier fee but not screening: Scrub lists and Number validation, the two switches in Settings under Compliance, each add $0.003 per segment when switched on, shown as screening on your bill, and both are off by default. Unless you turn the opt-out footer off, the first text to each contact, and one again from time to time, also gets "Reply STOP to opt out" and your business name if the message does not already have them, so a text close to the segment limit can bill one more segment.

Frequently asked questions

Should I use the logical date or the run ID in the key?

The logical date. A run ID can differ between a scheduled run and a manual re-run of the same period, which would break the protection. Pick whichever identifies the business event, and don't include the try number.

What happens when I clear a task and re-run it?

With a key built from the logical date and recipient, the re-run reuses the same keys, so the API doesn't send those texts again. If you actually want to send again, change the key on purpose.

Is there an Airflow provider package for Ready?

We don't publish one. A plain Python task with requests, as above, is all it takes.

Where to go next

The takeaway: build the key from what's stable, let Airflow retry the transient failures, fail fast on refusals, and deduplicate recipients upstream. For other schedulers, see our guide to sending SMS from GitHub Actions and cron, and for the status-by-status detail read idempotency and duplicate texts. The API quickstart gets you a key and a first send.