# Seven promises a good SDK keeps

What a TypeScript API client owes the people who call it, with examples and what the well-known SDKs do.

- Author: Joshua Jordan
- Published: 2026-11-11
- Tags: TypeScript, SDK design, APIs
- URL: https://modataconsulting.com/blog/seven-sdk-promises

## The client everyone writes first

An API client is *easy to write* and *hard to write well*. The easy version wraps `fetch`, adds types and ships. It works for the person who wrote it, because that person knows where it's fragile.

I built one of those for an advertising API and ran it in production for months. Then I read how Stripe, AWS, OpenAI and Azure build theirs, and found the same seven promises in all of them. **I'd kept about half.**

> **The idea**
>
> An SDK serves two sides. It protects the caller from the API, and it protects the caller from itself. Most hand-built clients do only the first.

Here's the client almost everyone starts with. Everything below is about what's missing from it.

```typescript title="client.ts"
export async function getReport(id: string): Promise<Report> {
  const res = await fetch(`${BASE_URL}/reports/${id}`, {
    headers: { Authorization: `Bearer ${process.env.API_KEY}` },
  });
  if (!res.ok) throw new Error(`Request failed: ${res.status}`);
  return res.json();
}
```

It has **no timeout**, so a hung connection hangs the caller. It **can't be cancelled**. One network blip fails the call. The error is **a string**. The return type is a promise the server never made. And the key comes from a global, so you can't test it or point it at staging without changing the environment.

## The API in the examples

Every example below uses the same small, made-up API. Call it the **upstream API**. It has reports you can start and fetch, and campaigns you can list. Three endpoints are enough to show every problem.

| Endpoint          | What it does                                              | What makes it awkward                             |
| ----------------- | --------------------------------------------------------- | ------------------------------------------------- |
| POST /reports     | Starts a report job and returns a job ID straight away.   | It's a write. Sending it twice makes two reports. |
| GET /reports/{id} | Returns the job's status, then the result once it's done. | You have to keep asking until it finishes.        |
| GET /campaigns    | Returns one page of campaigns and a cursor for the next.  | The full list takes many requests.                |

Here is what comes back, written as the types an SDK would hand you.

```typescript title="schema.ts"
type Report = {
  id: string;
  status: "queued" | "running" | "done" | "failed";
  rows?: number;
};

type Page<T> = { data: T[]; nextCursor: string | null };

type ApiErrorBody = { code: string; message: string };
```

An **SDK** is the library that sits between your code and those endpoints. It turns HTTP calls into methods, JSON into types, and status codes into errors. A small one is laid out like this.

**reports-sdk** client.ts holds configuration, auth and the request loop. Each file in resources is one group of endpoints. The other files are the promises below, one each.

The caller only ever sees the methods. `client.reports.create`, `client.reports.get` and `client.campaigns.list`. Everything else in that tree exists so those three calls behave well when the network or the API doesn't.

## 1. One client, and every call can override it

Configuration lives on one object. Each call can then override it for that call alone.

```typescript
const client = new Client({ apiKey, timeoutMs: 30_000, maxRetries: 2 });

await client.reports.get(id);
await client.reports.get(id, { timeoutMs: 5_000, signal });
```

**The second argument is the part people skip.** Without it, one slow endpoint forces you to raise the timeout for every call. The order of precedence should be boring and the same everywhere. The *call* beats the *client*, the client beats the *environment*, and the environment beats the built-in *default*.

**Interactive figure.** Interactive: a per-call option of 5 seconds beats a client option of 30 seconds, which beats an environment variable of 60 seconds, which beats the built-in default of 120 seconds.

Stripe, the OpenAI and Anthropic SDKs, and AWS all take per-request options. AWS documents the same precedence order explicitly. Mine took no per-call options at all.

## 2. A shape you can guess

There are four common shapes for the same call. **Pick one and use it everywhere.**

**Interactive figure.** Interactive: the same call as a namespace method, a command object, a standalone function and a path-typed request, with who uses each and what it costs in bundle size.

For a server-side client I'd take the namespace tree. It reads like the API's own docs, and bundle size doesn't matter on a server. If the SDK has to run in a browser, flat functions are worth the plainer look. Cloudflare's SDK ships both from one package.

Whatever you choose, **name methods after what the API calls them**. If the docs say "list campaigns", the method is `campaigns.list`. A caller who has read the docs should be able to type the call without opening yours.

## 3. Types that match what the server sends

A TypeScript type is *a claim about data you haven't seen yet*. Generate types from the provider's spec when there's a spec you trust. Hand-written types drift, and AWS said as much about its own older SDK.

When you can't trust the spec, validate at runtime. The question is how strictly. Try the three policies against four things a server might do.

**Interactive figure.** Interactive: with no validation a renamed field becomes undefined silently. Strict validation throws when the API adds a harmless field. Lenient validation keeps new fields and still throws on a renamed or mistyped one.

No validation is the calmest until the day a field is renamed. Then the bug shows up three functions away from the cause. Strict validation catches that, and also breaks every caller the day the API adds a harmless field. Lenient checks the fields you rely on and lets the rest through.

```typescript
// Going out: strict. Reject a bad request before sending it.
const body = requestSchema.strict().parse(params);

// Coming back: check what you rely on, let the rest through.
const data = responseSchema.passthrough().parse(json);
```

The well-known SDKs split on this. Anthropic's doesn't validate responses at all, on purpose. Speakeasy validates both ways so drift fails loudly. **Strict out and lenient in** gets most of both.

## 4. Errors that say what happened

The same failure, reported three ways.

**Interactive figure.** Interactive: a 429 reported as a bare Error with only a message, as a typed RateLimitError carrying status, request ID and retry delay, and as a result value the compiler makes you handle.

Whichever style you pick, the error has to carry four facts. The **HTTP status**, the **request ID**, the **response headers**, and the **parsed error body**. Give all errors one base class so a caller can catch anything from this SDK in one line.

```typescript title="errors.ts"
export class ApiError extends Error {
  constructor(
    message: string,
    readonly status: number,
    readonly requestId: string | undefined,
    readonly headers: Headers,
    readonly body: unknown,
  ) { super(message); }
}

export class RateLimitError extends ApiError {}
export class ValidationError extends ApiError {}
```

> **Where mine fell short**
>
> My client generated a correlation ID for every request and never attached it to the error. The one moment you need that ID is when something fails.

## 5. Retries, timeouts and a way to stop

Networks fail. A good client retries on its own, a small number of times, and gets out of the way when told to. The details matter more than they look.

**Interactive figure.** Interactive: a retry schedule with exponential backoff from 500 milliseconds. Jitter shortens each wait by up to 25 percent, which spreads twenty clients out instead of having them all retry at the same instant. A Retry-After header of 2 seconds is honoured and one of 120 seconds is over the cap and ignored.

Turn jitter off and look at the bottom strip. Every client comes back at the same instant, which is how a recovering server gets knocked over again. **Jitter spreads them out for free.**

- **Retry reads by default.** Two or three attempts on connection errors, 408, 429 and 5xx.
- **Listen to the server.** Honour `Retry-After`, with a cap. The OpenAI client ignores values over 60 seconds so a bad header can't stall you.
- **Time out every attempt**, not only the whole call, and accept an `AbortSignal`.

Writes need one more thing. If a `POST` times out you don't know whether it happened. Retrying blind can charge a card twice. An **idempotency key** fixes that. Generate it once, send it on every attempt, and the server treats the repeats as the same request.

```typescript title="retry.ts"
const key = options.idempotencyKey ?? crypto.randomUUID();

for (let attempt = 0; attempt <= maxRetries; attempt++) {
  const res = await send(request, { headers: { "Idempotency-Key": key } });
  if (!shouldRetry(res)) return res;
  await sleep(backoff(attempt, res.headers.get("retry-after")));
}
```

This connects to something I've [written about before](/blog/implicit-vs-explicit). Retries and timeouts are facts the SDK can work out, so they should be *implicit*. Anything that costs money or changes data is a decision, so the caller states it *explicitly*.

## 6. Lists you can walk

The caller shouldn't manage cursors by hand. They also shouldn't get a helper that silently loads a million rows into memory. Here are ten items behind a page size of three.

**Interactive figure.** Interactive: reading ten items with a page size of three. With for await, reading two items costs one request. With fetch-all, the first item costs four requests and holds all ten in memory.

With the iterator, a caller who needs the first two items pays for **one request**. With fetch-all they pay for every page before seeing anything. Stripe and the OpenAI SDK return an object that works both ways, and it keeps the cursor so a job can resume.

```typescript
const page = await client.campaigns.list({ limit: 3 });
page.data;        // the three items
page.nextCursor;  // save this to resume later

for await (const campaign of client.campaigns.list({ limit: 3 })) {
  if (campaign.status === "paused") break; // stops fetching
}
```

Azure's guidelines forbid a method that collects all pages into an array. Stripe offers one and makes you pass a limit.

## 7. Long jobs you can wait on, or walk away from

Many APIs have operations that take minutes. You start a job, poll it, then fetch the result. Offer the three raw calls, then **one helper on top**.

```typescript
const job = await client.reports.create(params);

const done = await client.reports.waitFor(job.id, {
  maxWaitMs: 15 * 60_000,
  signal,
  onProgress: (s) => log(s.status),
});
```

**Interactive figure.** Interactive: a report job polled with doubling waits until done. It can be cancelled, which stops polling and leaves the server job running. It times out after a maximum wait. A new process can resume it from the saved job ID.

Each button is a promise the helper has to keep. It gives up after a maximum wait. It backs off between polls. Cancelling stops the *polling* and leaves the server-side *job* alone. And the job ID is something a different process can pick up later.

AWS makes the maximum wait a required argument. Azure asks for a poller that can be serialised and resumed. Also decide what a failed job does. OpenAI's helpers return the object and let you check its status. Throwing is fine too. Pick one and document it.

## Three smaller promises

### Sign last, and log safely

If requests are signed, **sign as the final step** before sending, and sign again on every retry. A signature over a timestamp is stale on the second attempt. Redact credentials before a log line is built.

```text title="Debug log"
-> GET /reports/r_81  attempt 1
   authorization: Bearer ****
   x-signature: ****
<- 200  184 ms  request-id req_7Qm2
```

### Make it testable without a network

Accept a `fetch` in the constructor. That one option covers tests, proxies and odd runtimes, and it means no mocking library.

```typescript title="client.test.ts"
const client = new Client({
  apiKey: "test",
  fetch: async () => Response.json({ id: "r_81", status: "done" }),
});
```

### Leave a way out

The API will ship an endpoint before you do. Expose the low-level request so callers keep auth, retries and errors while calling something you haven't wrapped.

```typescript
const beta = await client.request("POST", "/v2/experimental/forecasts", { body });
```

## What to make implicit

Most of this post is a list of things the SDK should decide so the caller doesn't have to. A few things run the other way.

| The SDK works it out               | The caller states it                       |
| ---------------------------------- | ------------------------------------------ |
| Base URL and API version           | Credentials                                |
| Retries, backoff and timeouts      | Anything that spends money or changes data |
| Idempotency keys on retried writes | The maximum wait on a long job             |
| JSON encoding and the user agent   | A limit, when collecting a whole list      |
| Fetching the next page             | Running in a browser with a secret key     |

## Score your own

Here is all of it as thirteen checks. Tick what your client does.

**Interactive figure.** Interactive: thirteen checks covering per-call options, injectable fetch, validated types, rich errors, jittered retries, Retry-After, idempotency keys, timeouts and abort, iterable lists, resumable long jobs, pluggable auth with redacted logs, and an escape hatch.

When I ran my own client through this I had three, with six more half done. **Every gap was on the caller's side of the list.** I'd been the only caller, so I'd never felt them.

## The short version

- One client. Every call takes options.
- One shape, used everywhere, named after the API's own docs.
- Strict requests, lenient responses.
- Errors carry status, request ID, headers and body.
- Retries and timeouts are implicit. Writes and spend are explicit.
- Lists iterate and keep the cursor.
- Long jobs can be awaited, cancelled and resumed.

## Sources

- [Azure SDK TypeScript design guidelines](https://azure.github.io/azure-sdk/typescript_design.html)
- [Stripe on idempotency keys and retries](https://stripe.com/blog/idempotency)
- [AWS SDK retry behaviour](https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html)
- [AWS on waiters](https://aws.amazon.com/blogs/developer/waiters-in-modular-aws-sdk-for-javascript/)
- [openai-node client source](https://github.com/openai/openai-node/blob/master/src/client.ts)
- [Anthropic TypeScript SDK docs](https://platform.claude.com/docs/en/api/sdks/typescript)
- [Speakeasy on fetch-only SDKs and validation](https://www.speakeasy.com/blog/how-we-built-universal-ts)
- [openapi-fetch](https://openapi-ts.dev/openapi-fetch/)
- [Google AIP-151, long-running operations](https://google.aip.dev/151)
