Idempotency and retries
Networks fail in the middle of requests. When your request to send a message times out, you can't tell whether SemaLink received it. Retry blindly and the customer may get the SMS twice. Don't retry and they may get nothing.
An idempotency key fixes this. Send the same key with the retry and SemaLink knows it's the same request.
How it works
Add an Idempotency-Key header to every POST:
POST /v1/messages HTTP/1.1
Authorization: Bearer sk_live_...
Content-Type: application/json
Idempotency-Key: 5f1c9e2a-7b4d-4c1e-9a3f-2d8b6e0c4a172
3
4
- Same key, same request, within 24 hours: SemaLink doesn't do the work again. It answers with the first response, status code and body, plus the header
Idempotent-Replayed: true. "Same request" means the same endpoint and the same body; the order of fields in the JSON doesn't matter. - Same key, different request:
409withidempotency_key_reused. Nothing is done. - Same key while the first request is still running:
409withidempotency_key_in_use. Wait a moment and retry: you'll get the first request's answer. - After 24 hours the key is forgotten and a request with it is treated as new.
What's kept for a replay:
- A success or a
4xxerror is kept and replayed. A request that failed because of something in it fails the same way again, without running. - A
5xxerror isn't kept, so a retry with the same key runs again. That's safe: a5xxmeans the work didn't happen. - An answer larger than 512 KB keeps only its status code. A replay then gets
409idempotency_answer_unavailableinstead of running a second time: look up what the first request made (withGET /v1/messagesand itsreference, say). A batch of 1,000 numbers stays well under this.
Keys belong to the API key that sent them, so two of your servers with different keys never clash.
Choosing keys
A key names one thing you want to happen once. Two good ways to make one:
- A random UUID, made once and stored with the job, so the retry reads it back instead of making a new one.
- Built from your own IDs, such as
invoice-1042-reminder-1. It's naturally the same on every retry, even after a crash.
1 to 255 characters; anything else is 400 idempotency_key_invalid. Don't put personal data in keys.
Make the key before the first try
The key must be the same on every attempt. If your retry code makes a fresh UUID each time, the keys don't match and the protection is gone.
A safe retry
Retry network errors, 429, 5xx and 409 idempotency_key_in_use with the same key, waiting longer each time. Don't retry other 4xx errors: they'll fail the same way.
Every request is stopped after 30 seconds with 503 request_timeout. The work it started may still finish, so retry with the same key: while it's finishing you get idempotency_key_in_use, then its answer. It never runs twice.
# The same key on every attempt: run this twice and only one SMS is sent.
KEY="invoice-1042-reminder-1"
curl --retry 3 https://api.semalink.africa/v1/messages \
-H "Authorization: Bearer $SEMALINK_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $KEY" \
-d '{"to": "+254712345678", "from": "GREENHILL", "text": "Reminder: invoice 1042 is due on Friday."}'2
3
4
5
6
7
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function sendOnce(message, idempotencyKey) {
for (let attempt = 1; attempt <= 5; attempt += 1) {
try {
const response = await fetch('https://api.semalink.africa/v1/messages', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SEMALINK_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey, // the same on every attempt
},
body: JSON.stringify(message),
signal: AbortSignal.timeout(30_000),
});
const body = await response.json();
const inUse = response.status === 409 && body.error?.code === 'idempotency_key_in_use';
const retryable = response.status === 429 || response.status >= 500 || inUse;
if (!retryable) return body;
} catch {
// timeout or dropped connection: safe to retry with the same key
}
await sleep(2 ** attempt * 500); // 1 s, 2 s, 4 s, 8 s
}
throw new Error('SemaLink did not answer after 5 attempts');
}
await sendOnce(
{ to: '+254712345678', from: 'GREENHILL', text: 'Reminder: invoice 1042 is due on Friday.' },
'invoice-1042-reminder-1',
);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import os
import time
import requests
def send_once(message, idempotency_key):
for attempt in range(1, 6):
try:
response = requests.post(
"https://api.semalink.africa/v1/messages",
headers={
"Authorization": f"Bearer {os.environ['SEMALINK_API_KEY']}",
"Idempotency-Key": idempotency_key, # the same on every attempt
},
json=message,
timeout=30,
)
body = response.json()
in_use = response.status_code == 409 and body.get("error", {}).get("code") == "idempotency_key_in_use"
if response.status_code != 429 and response.status_code < 500 and not in_use:
return body
except requests.RequestException:
pass # timeout or dropped connection: safe to retry with the same key
time.sleep(2 ** attempt * 0.5) # 1 s, 2 s, 4 s, 8 s
raise RuntimeError("SemaLink did not answer after 5 attempts")
send_once(
{"to": "+254712345678", "from": "GREENHILL", "text": "Reminder: invoice 1042 is due on Friday."},
"invoice-1042-reminder-1",
)2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
function sendOnce(array $message, string $idempotencyKey): array
{
for ($attempt = 1; $attempt <= 5; $attempt++) {
$ch = curl_init('https://api.semalink.africa/v1/messages');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('SEMALINK_API_KEY'),
'Content-Type: application/json',
'Idempotency-Key: ' . $idempotencyKey, // the same on every attempt
],
CURLOPT_POSTFIELDS => json_encode($message),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$decoded = $body === false ? null : json_decode($body, true);
$inUse = $status === 409 && ($decoded['error']['code'] ?? '') === 'idempotency_key_in_use';
if ($decoded !== null && $status !== 429 && $status < 500 && !$inUse) {
return $decoded;
}
usleep((2 ** $attempt) * 500000); // 1 s, 2 s, 4 s, 8 s
}
throw new RuntimeException('SemaLink did not answer after 5 attempts');
}
sendOnce(
['to' => '+254712345678', 'from' => 'GREENHILL', 'text' => 'Reminder: invoice 1042 is due on Friday.'],
'invoice-1042-reminder-1'
);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Which requests take a key
Every POST that changes something: sending a message, sending or cancelling a batch, and creating or testing webhook endpoints. The estimate accepts the header but keeps nothing, since it changes nothing: a retry simply estimates again. GET, PATCH and DELETE don't take a key; repeating them is harmless (a second DELETE answers 404).
Also worth doing
- Store the message
idas soon as you get it. If you crash after sending, you can look the message up instead of sending again. - Use
referenceto tie messages to your own records, so you can always ask SemaLink "did invoice 1042's reminder go?" withGET /v1/messages?reference=invoice-1042.