Compile-time types describe what your code expects. They say nothing about what an external API actually returns at three in the morning after a provider deploy. A reliable integration treats the boundary as untrusted and makes every failure mode explicit.
Validate at the boundary#
Parse external responses at runtime, then translate them into your own domain model. Provider field names and quirks stay inside the adapter, so a change on their side breaks one file instead of spreading through the application.
import { z } from "zod";
const ProviderInvoice = z.object({
Id: z.string(),
TotalAmt: z.number(),
CurrencyRef: z.object({ value: z.string().length(3) }),
DueDate: z.string().date().optional(),
});
export type Invoice = {
externalId: string;
amountMinor: number; // integer minor units, never floats for money
currency: string;
dueDate: Date | null;
};
export function toInvoice(input: unknown): Invoice {
const raw = ProviderInvoice.parse(input); // throws with a precise path on drift
return {
externalId: raw.Id,
amountMinor: Math.round(raw.TotalAmt * 100), // assumes a 2-decimal currency
currency: raw.CurrencyRef.value,
dueDate: raw.DueDate ? new Date(raw.DueDate) : null,
};
}Treat authentication as a lifecycle#
Token acquisition, refresh, expiry and revocation each need explicit handling. Refresh shortly before expiry rather than waiting for a 401, and make sure concurrent requests share one refresh instead of racing. Never log credentials or full authorisation headers.
A failed refresh should put the connection into a clear state such as needs_reauthorisation, visible to an operator, rather than an unbounded retry loop.
Give retries a budget#
A timeout does not prove the remote action failed. Retry reads freely, retry writes only when they are idempotent, and always within an explicit budget.
export async function withRetry<T>(
fn: () => Promise<T>,
{ attempts = 4, baseMs = 250, maxMs = 5_000, isRetryable = defaultRetryable } = {},
): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt >= attempts || !isRetryable(error)) throw error;
const backoff = Math.min(maxMs, baseMs * 2 ** (attempt - 1));
await sleep(backoff / 2 + Math.random() * (backoff / 2)); // jitter
}
}
}
function defaultRetryable(error: unknown) {
const status = (error as { status?: number }).status;
return status === undefined || status === 429 || status >= 500;
}When the provider sends a Retry-After header on a 429, honour it instead of your own backoff.
Test what breaks#
The happy path is the least informative test. Contract tests should cover the responses you hope never to see:
| Scenario | Expected behaviour |
|---|---|
| Missing or renamed field | Validation error naming the field, no partial write |
| 401 after token expiry | One refresh, then the original request succeeds |
| 429 with Retry-After | Wait as instructed, no extra attempts |
| Duplicate webhook delivery | Processed once, second delivery acknowledged |
| Timeout on a write | Reconcile before retrying, never blind repeat |
Keep provider-specific assumptions in adapters and run this suite whenever the contract or the SDK version changes.
Leave a trail#
Correlate requests and workflow runs with an ID that follows the work across systems. Record timing, outcome and a safe error category, but not sensitive payloads.