Skip to content

TypeScript types are only one part of a reliable integration

Runtime validation, token lifecycle handling, bounded retries and failure-path tests make the boundary dependable.

Published
Reading time
3 minutes
Written by
Cyber Vision engineering

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.

adapters/accounting/invoices.ts
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.

retry.ts
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:

ScenarioExpected behaviour
Missing or renamed fieldValidation error naming the field, no partial write
401 after token expiryOne refresh, then the original request succeeds
429 with Retry-AfterWait as instructed, no extra attempts
Duplicate webhook deliveryProcessed once, second delivery acknowledged
Timeout on a writeReconcile 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.

  1. Infrastructure · 3 min read

    Changing a PostgreSQL schema without taking the application down

    Expand, migrate, contract: how to add columns, indexes and constraints to a live table without long locks or a maintenance window.

  2. AI Engineering · 3 min read

    Why operational AI needs an approval boundary

    Separate analysing information from taking consequential actions, bind every approval to a specific change, and make each decision traceable.

  3. Software Architecture · 3 min read

    Idempotency keys in PostgreSQL: a pattern that survives retries

    Clients retry, webhooks repeat and networks time out. A small table and one unique constraint make a write safe to repeat.