For the Idempotency-Key header on an SMS send, use a deterministic key derived from the business event ("reminder 24 hours before appointment 8841") when the same event can be triggered more than once, and a random UUID only when you generate and store the key once, before the first attempt. The key's job is to make two requests that mean the same text look identical to the API.
The two approaches fail in different ways, and picking the wrong one either sends duplicates or silently drops a text you wanted. This guide walks through both, with collision rules and the scheduled reminder case. For what the header does at the API level, start with how to stop duplicate texts from your SMS API with idempotency keys.
What the key has to do
We make Ready, and our API takes an Idempotency-Key header: send one UUID per message and reuse it on every retry of that message, so a retried request never sends twice. That's the whole contract. Everything else is about where the UUID comes from.
A good key has two properties:
- Same logical message, same key. A retry after a timeout, a crash, or a duplicate queue delivery must reuse it.
- Different logical message, different key. Two reminders to the same person for two different appointments must not share one, or the second is treated as a replay and never sent.
Those pull in opposite directions, and the design choice is which side you trust your own code to get right.
Option 1: a random UUID, stored first
Generate a UUID when the message is created, save it in your database in the same transaction as the intent to send, and read it back on every attempt.
import uuid
def enqueue_text(db, tenant_id: int, to: str, body: str) -> str:
key = str(uuid.uuid4())
db.execute(
"INSERT INTO outbound_texts (idempotency_key, tenant_id, to_number, body, state) "
"VALUES (%s, %s, %s, %s, 'pending')",
(key, tenant_id, to, body),
)
return key This is the safest choice when nothing in the business domain names the message. A one-off "your export is ready" text has no natural identifier, so a stored random key is correct. The failure mode is generating the key at send time instead of at creation time. If the worker makes a new UUID on each attempt, every retry is a new message, and the header protects nothing.
Option 2: a deterministic hash of the business event
When an event has a natural identity, derive the key from it. A name-based UUID (version 5) gives you a valid UUID that is the same every time for the same input.
import uuid
NAMESPACE = uuid.UUID("6f1c2a52-8d0b-4c1e-9a77-3f0d5b2c9e11") # a fixed value you generate once
def event_key(tenant_id: int, kind: str, subject_id: str, *parts: str) -> str:
name = "|".join([str(tenant_id), kind, subject_id, *parts])
return str(uuid.uuid5(NAMESPACE, name))
# reminder 24 hours before appointment 8841, for this tenant
key = event_key(42, "appt-reminder", "8841", "T-24h") Now it doesn't matter how many times the trigger fires. A cron that runs twice, a webhook your system receives twice, a worker that crashes and restarts: all of them compute the same key and the API sees one message. You also don't need a database round trip just to remember the key.
The cost is that you must put every field that distinguishes two real messages into the name. Forget one and you've built a silent suppressor.
Choosing between them
| Situation | Better choice | Why |
|---|---|---|
| One-off notification with no business ID | Random, stored first | Nothing stable to hash |
| Reminder tied to an appointment or invoice | Deterministic | The trigger can fire more than once |
| Drip campaign step per contact | Deterministic | Contact plus step number is the identity |
| User clicks "resend" on purpose | New random key | The user wants a second text |
| Retry after timeout or 5xx | Same key as the first try | The whole point |
| Bulk batch in a long job | Deterministic over the batch contents | A resumed job must rebuild the same key |
The "resend" row is the one people miss. If a user deliberately sends the same text again, a deterministic key built only from the contact and the body will swallow it. Include a counter or the time of the click in the name, or use a fresh random key for explicit user actions.
Collisions
A collision here means two different messages mapping to one key. With a 128-bit hash, accidental hash collisions aren't a realistic worry. The real collision risk is a name that's too coarse.
Watch for these:
- Missing tenant ID. Two tenants with an appointment number 8841 would share a key. Put the tenant in the name, always.
- Missing the kind of message. The confirmation and the reminder for one appointment need different keys.
- Reusing a key with a different body. A key should map to one message. If you edit the reminder wording and resend under the same key, it's still a repeat of the first request, so don't count on the new wording going out. Include a version in the name when the body can change.
- Separator ambiguity.
"a|bc"and"ab|c"differ because of the delimiter, but joining without one can merge fields. Always delimit.
Do the tenant scoping on your side, in the name, instead of assuming anything about how keys are scoped.
Scheduled reminders
Reminders are where deterministic keys earn their keep. There are two ways to schedule one.
You can hold the reminder in your own job system and send it at the right time with POST /v1/messages. The key is derived from the appointment and the offset, so a rescheduled job that fires twice sends once.
Or you can ask us to hold it with POST /sms/schedule, which takes message, send_at and contact_id or to. Nothing is charged until it sends. Before you create it, check whether you already created one for this event, because a retried create would otherwise queue a second text. Store the event key next to the schedule you created and skip creation when it's there.
def ensure_reminder(db, appt) -> None:
key = event_key(appt.tenant_id, "appt-reminder", str(appt.id), "T-24h", appt.starts_at.isoformat())
created = db.execute(
"INSERT INTO reminder_log (event_key, appt_id) VALUES (%s, %s) "
"ON CONFLICT (event_key) DO NOTHING RETURNING 1",
(key, appt.id),
).fetchone()
if not created:
return # already scheduled or sent for this exact appointment time
schedule_reminder(appt, key) # your call to POST /sms/schedule Notice that the appointment's start time is in the name. If the appointment moves, the key changes, and the new reminder is a legitimately new message. You'd also cancel the old one, which is a separate step.
Test it by running the job twice
The cheapest proof is running the same trigger twice and asserting one send. Use a test key, which simulates sends with no number, card or charge, and check that the second run creates no new message. Then change one input, such as the appointment time, and check that it does send. A deterministic scheme needs both tests, because the failure modes are opposite: duplicates and suppressed texts.
The short version
Use a stored random UUID when the message has no natural identity. Use a name-based UUID when it does, and put the tenant, the kind, the subject and anything that changes the text into the name. Reuse the key on every retry and never reuse it for a message you want sent again. The retries and failure handling guide covers what to do after a timeout.