Ledgerline
Case Study
Overview
A payments console set like a newspaper. Payouts, Risk, Support and the Ledger are separate modules, so each team ships on its own schedule, and a GraphQL Partner API lets outside partners read their ledger and create payouts.
Each module has its own endpoint, cache and error boundary, so one that crashes leaves the rest working. Partner payouts are idempotent: six identical requests sent at once create one payout.
Where it started
At one of my restaurants, doing anything in the back-office system lagged the whole console, especially inventory and timesheets. Every change meant reloading and logging in again.
That frustration sparked Ledgerline, and with it my love for being financially literate.
The idea
Ledgerline is a payments console set like a newspaper. The Front Page writes its lead headline from live numbers, and Payouts, Risk, Support and the Ledger are separate desks. Each desk is its own module, so it loads, updates and fails on its own instead of dragging the whole console down with it.
apps/console/modules.ts
export const modules = [risk, payouts, support];
// The newsroom: the front page and the ledger read across every desk.
export const newsroom = { lead: frontpage, archive: ledger };
One endpoint per module
Every module is served from its own endpoint with its own router and context. A deployment can mount just one module (LEDGERLINE_MODULES=payouts), and a console on another origin can point at it, so the risk, payouts and support teams ship on their own schedule.
apps/console/app/api/m/[module]/[trpc]/route.ts
// Each module is served from its own endpoint (/api/m/<module>) with its own router and context.
async function handler(req: Request, { params }: { params: Promise<{ module: string }> }) {
const { module: name } = await params;
const mod = findModule(name);
if (!mod) return Response.json({ error: `Module "${name}" is not mounted` }, { status: 404, headers: corsHeaders });
return fetchRequestHandler({
endpoint: `/api/m/${name}`,
req,
router: mod.router,
createContext: async () => mod.createContext(await createBaseContext(name)),
});
}
Risk before money moves
Money can't be recalled once it's sent, so every approval runs through Risk's standing orders first (payouts over £20,000 need a second review), lands in the audit log, and gets a five-second undo before it goes. When it does, a PAID stamp lands on the payout.
modules/payouts/router.ts
approve: withRiskCheck(protectedProcedure)
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
await ctx.audit("payout.approve", input.id);
return ctx.payouts.approve(input.id);
}),
Desks that don't import each other
Modules never import one another. When one changes data it fires a browser event, and every mounted module (the ticker, the front page, the nav badges) refreshes its own cache.
packages/core/src/client.tsx
const DATA_CHANGED = 'ledgerline:data-changed';
/**
* Tells every mounted module (ticker, front page, nav badges) that data changed,
* without the modules knowing about each other.
*/
window.dispatchEvent(new Event(DATA_CHANGED));
Opening the books to partners
Version 2.1 lets outside partners in, like a marketplace paying its sellers. They can read their ledger and create payouts through a separate Partner API (Express, Apollo GraphQL and Prisma over Postgres) that sits beside the console and changes nothing in it.
Why two APIs? The console's tRPC API serves its own UI. The types are shared and both ship together, so it's the quickest thing to change. Partners need the opposite: a contract that doesn't move under them. So the internal API stays cheap to change and the external one is hard to break. The GraphQL schema is published and only ever grows, API keys swap for 15-minute tokens limited to what each partner may do, and every query is filtered to the caller, so one partner can never see another's books.
A retry never pays twice
Networks drop requests halfway through, and a partner's server will retry. In payments, paying someone twice is the worst bug there is. So every mutation needs an Idempotency-Key, recorded in the same database transaction as the payout itself. A retry replays the original response. Six identical requests sent at once create one payout. Reusing a key for a different request is refused, and a request that fails doesn't use its key up.
partner-api/src/services/idempotency.ts
/**
* Runs `work` at most once per (partner, Idempotency-Key).
*
* The key row is inserted in the same transaction as the work, so:
* - a retry after success replays the stored result;
* - a concurrent duplicate waits on the unique index, then replays;
* - if the work fails, everything rolls back and the key can be retried;
* - reusing a key for a different request is a 409 IDEMPOTENCY_KEY_REUSED.
*/
const value = await db.$transaction(async (tx) => {
const row = await tx.idempotencyKey.create({
data: { id: newId('idem'), partnerId, key, requestHash: hash, expiresAt: new Date(Date.now() + RETENTION_MS) },
});
const result = await work(tx);
await tx.idempotencyKey.update({ where: { id: row.id }, data: { state: 'COMPLETED', response: args.toJson(result) } });
return result;
});
Keys a leak can't use
An API key is shown once. The database keeps only its prefix and a peppered HMAC, so a leaked database doesn't hand out working keys, and revoking a key stops its tokens straight away. Every payout status change is written as a signed webhook in the same transaction as the change, then delivered with retries and backoff.
A developer portal inside the console creates and revokes keys, documents the live schema and runs queries in a playground. It talks to the API from the server, so the admin token never reaches the browser. The integration tests start a throwaway Postgres with Testcontainers and run the real migrations, so idempotency and webhooks are proven against a real database, not a mock.