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.
What the client does
Section titled “What the client does”call(req)makes up toattemptscalls tosend. Each one is limited bytimeoutMs.- A failed attempt that is not the last waits
baseDelayMs * 2 ** (attempt - 1)and tries again: 100ms, 200ms, 400ms for a base of 100. - The first success returns
ok(value). If every attempt fails, it returnserr(new ExhaustedError(attempts, lastError)).callnever rejects. on(name, listener)reports what happens:attempt,retryandgaveUp. It returns a function that unsubscribes.
How the pieces fit
Section titled “How the pieces fit”- Lesson 1:
Result<A, E>is generic, socallreturnsResult<Res, ClientError>with the success type taken fromsend. - Lesson 4: the emitter is generic over an event map. The listener’s payload
type depends on the event name, and
on("retry", (p) => ...)knowsp.delayMs. - Lesson 5: the delay is a function of the attempt number, the same idea as
backoff.sleepis 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:
withTimeoutand the retry loop. A timeout is just another failed attempt.
Exercise
Section titled “Exercise”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.
Run it locally
Section titled “Run it locally”In the Relay project, send is a thin wrapper over fetch. The client adds the timeout, retries
and events around it:
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 fromsend, andcallreturnsPromise<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. callreturns 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.
Further reading
Section titled “Further reading”- Promise (MDN): promises, timeouts and cancellation.
- Promise.allSettled() (MDN): collecting every outcome.
- Handbook: Generics: generic functions.