How to retry Sent API requests safely
This guide shows you how to retry failed Sent API v3 mutations (after timeouts, network drops, or 5xx errors) without sending the same message or creating the same resource twice. It assumes you know the idempotency contract: key format, 24-hour expiry, and replay semantics.
The pattern has three parts: derive a stable key for the operation, reuse that exact key on every retry attempt, and handle the conflict case when two attempts overlap.
Derive the key from a business identifier
Generate the key once per logical operation, from identifiers your system already tracks. A retry must present the same key, so the key cannot depend on when or how the attempt happens:
// Good: derived from the business operation — any retry reproduces it
const key = `payment-${userId}-${invoiceId}`;
// Good: derived from a client-generated request ID stored with the operation
const key = `contact-create-${clientRequestId}`;
// Bad: static key (blocks every later operation of this type for 24 hours)
const key = 'create-message';
// Bad: fresh random value per attempt (each retry becomes a new operation)
const key = crypto.randomUUID();If an operation can legitimately repeat (the same invoice reminder sent weekly), include the occurrence in the identifier: for example invoice-1234-reminder-2026-07, not a timestamp captured at send time.
A random UUID is only safe if you generate it when the operation is created and persist it alongside the operation. A UUID generated inside the send path produces a different key on each retry and defeats idempotency.
Reuse the same key across retry attempts
Send the key on the first attempt and on every retry. Retry 5xx and network errors with exponential backoff. Don't retry 4xx errors; they fail the same way every time until you fix the request:
async function sendMessageWithRetry(
payload: MessagePayload,
operationId: string, // stable, caller-supplied (e.g. an order ID)
maxRetries = 3
): Promise<APIResponse> {
const idempotencyKey = `msg-${operationId}`;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch('https://api.sent.dm/v3/messages', {
method: 'POST',
headers: {
'x-api-key': API_KEY,
'Idempotency-Key': idempotencyKey, // Same key on retry
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (response.ok) {
return await response.json();
}
// Don't retry on 4xx errors (client errors)
if (response.status >= 400 && response.status < 500) {
throw new Error(`Client error: ${response.status}`);
}
// Retry on 5xx or network errors
if (attempt < maxRetries) {
await sleep(Math.pow(2, attempt) * 1000);
}
} catch (error) {
if (attempt === maxRetries) throw error;
}
}
throw new Error('Max retries exceeded');
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}The API caches only 2xx responses for replay, so a retry after a 5xx error executes the request again. With the same key, at most one attempt ever takes effect.
Handle concurrent duplicates
If a duplicate request arrives while the original is still executing and the original does not finish within about 5 seconds, the API returns 409 Conflict with code CONFLICT_001. Wait briefly and retry with the same key to receive the cached response:
async function sendWithIdempotency(
url: string,
payload: object,
key: string
): Promise<APIResponse> {
try {
return await apiRequest(url, payload, key);
} catch (error: any) {
if (error.code === 'CONFLICT_001') {
// Wait for the original request to complete
await sleep(500);
return await apiRequest(url, payload, key);
}
throw error;
}
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}Wrap the pattern in a reusable client
For codebases with many call sites, centralize the header handling and replay detection in one client class. The caller supplies the operation identifier, so keys stay stable across retries and are easy to trace in logs:
class IdempotentClient {
constructor(private apiKey: string, private baseUrl = 'https://api.sent.dm') {}
async request(
method: string,
endpoint: string,
payload?: object,
options: { idempotencyKey?: string } = {}
) {
const headers: Record<string, string> = {
'x-api-key': this.apiKey,
'Content-Type': 'application/json'
};
// Add idempotency key if provided
if (options.idempotencyKey) {
headers['Idempotency-Key'] = options.idempotencyKey;
}
const response = await fetch(`${this.baseUrl}${endpoint}`, {
method,
headers,
body: payload ? JSON.stringify(payload) : undefined
});
const data = await response.json();
// Check if this was a replay
if (response.headers.get('Idempotent-Replayed')) {
console.log('Idempotent replay detected');
console.log('Original request ID:', response.headers.get('X-Original-Request-Id'));
}
if (!data.success) {
throw new Error(`${data.error.code}: ${data.error.message}`);
}
return data.data;
}
// Send a message; the caller supplies a stable operation ID
async sendMessage(
to: string[],
templateId: string,
operationId: string,
parameters?: Record<string, string>
) {
return this.request('POST', '/v3/messages', {
to,
template: { id: templateId, parameters }
}, { idempotencyKey: `msg-${operationId}` });
}
}
// Usage
const client = new IdempotentClient(process.env.SENT_API_KEY!);
// The order ID makes the send idempotent per order
await client.sendMessage(
['+1234567890'],
'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'order-confirmation-8412',
{ name: 'John' }
);
// Or provide your own key for other operations
await client.request('POST', '/v3/contacts', {
phone_number: '+1234567890'
}, { idempotencyKey: 'import-user-12345' });Verify the behavior
Confirm your retries are safe by forcing a replay: send the same request twice with the same key. The second response returns the original status and body with the Idempotent-Replayed: true header, and X-Original-Request-Id names the first request. If the second call creates a second resource instead, the key changed between attempts. Check that it derives only from stable identifiers.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Retry executed again even though the key matched | Key contains characters outside A-Z a-z 0-9 - _ or exceeds 255 chars, so the API ignored it | Sanitize the identifiers you build keys from |
409 with CONFLICT_001 | Duplicate sent while the original is still executing | Wait briefly, retry with the same key |
422 with CONFLICT_005 | Key reused within 24 hours for a request with a different method, path, query, or body | Use a new key for a new operation; resend the original request unchanged when retrying |
| Retry executed as a new operation | More than 24 hours passed and the key expired, or the key changed between attempts | Retry within 24 hours; derive keys from stable identifiers |
Related
- Refer to the Idempotency reference for the full contract: key format, caching rules, and response headers.
- How to handle Sent API errors
- How to handle Sent API rate limits
How to handle Sent API errors
Handle Sent API v3 error responses in client code: check the success flag, branch on error codes, capture request IDs, and test failures with sandbox mode.
How to handle Sent API rate limits
Keep your integration under Sent API v3 rate limits: back off on 429 responses, honor Retry-After, throttle requests client-side, and pace batch workloads.