One toolkit,
both ends of the wire

Why utils, fetch, hooks, and observer belong in your frontend and your backend.

LogosDX · Press Space to start, S for speaker notes, ? for the key list

Four packages, one set of rules. The claim for the next twenty minutes: the patterns you need in a React handler are the same patterns you need in an Express route, so the code that implements them should be the same code.

The same code, written twice

Frontend and backend drift apart because nothing makes them share.

Ask the room which of these they have written this year. Everyone has written the retry loop. The point is not that any one of them is hard. It is that each copy is slightly different, and the differences are where the production bugs live.

Four packages, one set of rules

utilsError tuples, retry, timeout, circuit breaker, rate limit, memoize, batch
fetchHTTP client where timeouts, retries, dedupe, cache, and rate limits are config
hooksNamed extension points that can change arguments, short-circuit, or abort
observerTyped events, regex subscriptions, async iteration, queues

Zero external dependencies. TypeScript first. Tree-shakable. No Node-only or browser-only globals.

Keep this short. The last line is the reason the rest works: nothing here assumes a runtime, so the same import runs in a browser bundle, a Node service, a worker, or a CLI. Packages depend only on each other, so upgrades are predictable.

utils: failure is a value

Errors are values

import { attempt } from '@logosdx/utils';

const [order, err] = await attempt(
    () => loadOrder(orderId)
);

if (err) return respond(503, 'Order store unavailable');
if (!order) return respond(404, 'Order not found');
  • No try/catch, no invisible error path
  • The same line in a React handler and an Express route
  • Only I/O gets a tuple. Business logic returns directly.
attempt returns a pair: the value, or the error. You cannot forget to look at the error because it is sitting in a variable you named. Tests get simpler too: assert on the tuple.

Resilience is a function call

const charge = makeRetryable(gateway.charge.bind(gateway), {
    retries: 3,
    delay: 200,
    jitterFactor: 0.25
});

const guarded = circuitBreaker(charge, {
    maxFailures: 5,
    resetAfter: 10_000
});

const charged = withTimeout(guarded, {
    timeout: 5_000
});
  • Wrap once, call like the original
  • A delay with jitter, so retries do not stampede
  • The breaker fails fast while a dependency is down
Each wrapper returns a function with the same signature, so they stack. Order matters: here the breaker sees the retried call as one call, and the timeout bounds the whole thing. gateway.charge stands in for any flaky dependency.

The same primitives, both sides

In the browserOn the server
attemptForm submit, route loaderRequest handler, background job
retryA flaky save on mobileCalls to a partner API
withTimeoutSearch as you typeDatabase or gateway call
memoizeExpensive derived dataPer-process lookup cache
batchUploading many files1,000 records, 50 at a time
rateLimitButton mashingAn outbound API budget
This is the whole argument in one table. Pick a row: the helper is identical, only the call site changes. A team that learns batch for a data import already knows how to throttle a bulk upload.

fetch: a client that expects trouble

Three channels, no guessing

const [res, err] = await attempt(
    () => api.get<Order>('/orders/42')
);

if (err) return showOffline();
if (!res.ok) return showError(res.status);

render(res.data);
  • err: no response exists (timeout, abort, connection lost)
  • !res.ok: the server said no, and status, headers, and data are all still there
  • res.data: success, typed
Clients that reject on a non-2xx status put a 404 and a lost connection in the same catch, so every caller has to sort them apart. Here a completed exchange always resolves, whatever the status, and the error slot is reserved for transport failure. Over plain fetch you also get the body already parsed, ok narrowing data, and an error that says whether it was a timeout, an abort, or a lost connection.

Policies are config, not code

const api = new FetchEngine({
    baseUrl: 'https://api.example.com',
    totalTimeout: 5_000,
    retry: { maxAttempts: 3, baseDelay: 150 },
    dedupePolicy: true,
    cachePolicy: {
        ttl: 30_000,
        staleIn: 10_000
    },
    rateLimitPolicy: {
        maxCalls: 60,
        windowMs: 60_000,
        waitForToken: true,
        serializer: () => 'partner'
    }
});
  • Browser: a double refresh sends one GET, and the list renders from cache while it revalidates
  • Server: every call to a partner shares one rate-limit budget, and 5xx responses retry
Retry, dedupe, cache, and rate limit are config keys, so there is no p-retry, no in-flight map, no lru-cache to wire up. Two defaults to know: dedupe covers GET only, and rate-limit buckets are per endpoint unless a serializer says otherwise, which is why the partner budget here uses one. rules on each policy give one route its own budget without a second client. Per-call escape hatches exist, such as retry: false.

hooks: extension points you name

Add behavior without editing the caller

interface OrderLifecycle {
    beforeSubmit(order: Order): Promise<Order>;
}

const hooks = new HookEngine<OrderLifecycle>()
    .register('beforeSubmit');

hooks.add('beforeSubmit', (order, ctx) => {
    if (!order.items.length) ctx.fail('Cart is empty');
});

await hooks.run('beforeSubmit', order);
  • Callbacks get the arguments plus a ctx
  • add() returns a cleanup function
  • A typo in a hook name fails at runtime, because names are registered
Hooks are not events. An event is fire and forget. A hook can change what happens next, so the caller stays small and the policy lives in the callbacks. The verbs differ on purpose: add and run here, on and emit in observer.

Callbacks can change the outcome

ctx.args(...)Replace the arguments for the callbacks after this one
return ctx.returns(value)Stop the chain and answer with a value (a cache hit)
ctx.fail(...)Abort with an error (a validation failure)
priority, once, timesOrder and lifetime of each callback
  • Browser: validate, enrich, and track before a submit
  • Server: authenticate, audit, and scope to a tenant before a handler runs
The cache example is the classic: a beforeGet hook returns the cached value and the chain stops, so the request never happens. Priority is a number, lower runs first, default zero.

Fetch is built from them

Retry, dedupe, cache, and rate limit are plugins installed on the engine's own HookEngine.

const cleanup = api.use(auditPlugin);

// later
cleanup();

You extend fetch the same way the library does.

retryPlugin, dedupePlugin, cachePlugin, rateLimitPlugin, and cookiePlugin exist as standalone factories. auditPlugin here is yours: something cross-cutting that should not live in every caller.

observer: events with types and limits

Typed topics, pattern subscriptions

interface Events {
    'order:created': { id: string; total: number };
    'order:failed': { id: string; reason: string };
}

const bus = new ObserverEngine<Events>();

bus.on('order:created', ({ id }) => announce(id));
bus.on(/^order:/, ({ event }) => audit(event));

bus.emit('order:created', { id: 'o_42', total: 1999 });
  • The payload type follows the event name
  • A regex listens to a whole family of events
  • on() with a callback returns a cleanup, and every form takes an AbortSignal
In the browser this is how a component hears about a cart change without a prop chain. On the server it is how a request handler announces an order without knowing who cares. Same API, same types.

Queues with concurrency

bus.queue('order:created', processOrder, {
    name: 'fulfillment',
    concurrency: 4,
    taskTimeoutMs: 30_000
});

// the producer does not change
bus.emit('order:created', order);
  • Server: fulfil orders four at a time, with a timeout per task
  • Browser: send analytics pings on a rate limit, or save edits in order
  • Queues also support priority, pause and resume, and a draining shutdown
Emitting an event is how work gets added, so turning a synchronous listener into a bounded worker pool is a one-line change on the consumer side. Use attempt inside the processor, because a throw in a queue processor is still your problem.

Consume events with for await

for await (const { id } of bus.on('order:created')) {
    await saveToDatabase(id);
}

Events that arrive while you await are buffered in order, so none are dropped.

Calling on() without a callback gives an async iterator. It is handy for a long-lived consumer in a worker, and for tests that want to await the next event.

Together: one order, both ends

The path of a single order

BROWSER                             SERVER
hooks.run('beforeSubmit')
api.post('/orders')        ───────▶ route handler
  retry                               attempt(loadCart)
                                      bus.emit('order:created')
render(res.data)           ◀─────── res.ok / !res.ok
                                    queue, concurrency 4
                                      fetch → payment API
                                      rateLimit + circuitBreaker
  • Hooks validate before anything leaves the browser
  • Fetch retries a dropped connection
  • The handler turns failure into a value and emits an event
  • A queue fans the work out at a safe rate
Walk the diagram left to right. Every box is one of the four packages and none of them is a special case for its side of the wire. When something fails at 2am, there is one way errors look, one way events are named, and one place to read about retries. One caution on the POST: a retried order can be placed twice, so the server needs an idempotency key before you let a write retry.

Share the rules, not just the types

// shared/order-rules.ts, imported by the app and the API
export function addOrderRules(hooks: HookEngine<OrderLifecycle>) {

    return hooks.add('beforeSubmit', (order, ctx) => {
        if (!order.items.length) ctx.fail('Cart is empty');
    });
}
  • The browser runs it for a fast, friendly message
  • The server runs it because the browser cannot be trusted
  • One definition, so the two cannot drift
This is what a monorepo is for. Types can be shared anywhere. Behavior can only be shared when the building blocks run in both places, which is the point of runtime-agnostic packages.

What this is not

Be plain about this. The value shows up when the same patterns repeat across a codebase or across the stack. One retry in one file does not need a library. Fifty of them in two runtimes do.

Start with one call

pnpm add @logosdx/utils @logosdx/fetch @logosdx/hooks @logosdx/observer

Wrap one fetch call in attempt, in the frontend and in the backend. Add a policy when the first failure teaches you to.

Finish on the smallest possible first step. Questions after this slide. This deck is itself a page built with the slides package, so view source to see the markup.