Skip to content

Capstone: a resilient client

Relay tells people about failed jobs through an upstream notifier service. It is slow, and it sometimes fails for no reason that retrying would not fix. Callers should not each write their own timeout and loop. They want one client: give it a request, get back a result, and never see an exception.

This lesson joins the module into that client. createClient(options) wraps one send function. The request and response types come from send, so a client for a different service needs no new types.

  1. call(req) makes up to attempts calls to send. Each one is limited by timeoutMs.
  2. A failed attempt that is not the last waits baseDelayMs * 2 ** (attempt - 1) and tries again: 100ms, 200ms, 400ms for a base of 100.
  3. The first success returns ok(value). If every attempt fails, it returns err(new ExhaustedError(attempts, lastError)). call never rejects.
  4. on(name, listener) reports what happens: attempt, retry and gaveUp. It returns a function that unsubscribes.
  • Lesson 1: Result<A, E> is generic, so call returns Result<Res, ClientError> with the success type taken from send.
  • Lesson 4: the emitter is generic over an event map. The listener’s payload type depends on the event name, and on("retry", (p) => ...) knows p.delayMs.
  • Lesson 5: the delay is a function of the attempt number, the same idea as backoff. sleep is passed in, so the client has no clock of its own.
  • Lesson 6: the client is a small pipeline of steps. Each keeps the types of the one before.
  • Lesson 7: withTimeout and the retry loop. A timeout is just another failed attempt.

The starter gives you Result, TimeoutError, ExhaustedError, the event map, withTimeout and a small typed emitter. You write createClient. The starter’s call sends once and on is missing. The rules at the top give the exact order of events and delays.

In the Relay project, send is a thin wrapper over fetch. The client adds the timeout, retries and events around it:

src/notifier.ts
declare function createClient<Req, Res>(options: {
send: (req: Req) => Promise<Res>
timeoutMs: number
attempts: number
baseDelayMs: number
sleep: (ms: number) => Promise<void>
}): {
call(req: Req): Promise<unknown>
on(name: "retry", listener: (payload: { attempt: number; delayMs: number; error: string }) => void): () => void
}
interface Notification {
readonly to: string
readonly text: string
}
interface Receipt {
readonly id: string
}
async function send(req: Notification): Promise<Receipt> {
const res = await fetch("https://notifier.example.com/send", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(req),
})
if (!res.ok) throw new Error(`notifier replied ${res.status}`)
return (await res.json()) as Receipt
}
const client = createClient({
send,
timeoutMs: 2000,
attempts: 4,
baseDelayMs: 250,
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
})
client.on("retry", (p) => console.log(`retry ${p.attempt} in ${p.delayMs}ms: ${p.error}`))
const result = await client.call({ to: "ops", text: "job j1 failed" })

Replace the declare with an import of your own createClient. The as Receipt is a promise about the server’s JSON. Real code would parse it, as in parsing.

  • createClient<Req, Res> infers both types from send, and call returns Promise<Result<Res, ClientError>>.
  • Delays double with each attempt. Time comes in through sleep, so tests record delays instead of waiting.
  • A timeout is a failed attempt like any other, and the last error is kept as cause.
  • call returns errors as values and never rejects. Events report progress without changing the result.
  • A typed emitter makes each listener’s payload depend on the event name.