Pattern 11/22 · Structural
Facade
Collapse a subsystem's scattered API into ONE API phrased in business language: the client calls one function, and call order, parameters, retries and logging are the facade's job.
01 — It starts with code that is breaking
Problem
The first order needs payment. You open server/api/checkout.post.ts and write all six steps: validate the order, taxOf(), shipOf(), gateway.charge() with a retry because the gateway often returns 5xx, ledger.record(), then publish("order:paid"). Twelve lines. Works. Done.
Next week the mobile team needs the exact same flow — they copy the twelve lines. The admin team builds "create an order on behalf of a customer" — copy twelve lines. Batch importing orders from a CSV file — copy twelve lines but deliberately drop logger.info, "because who needs logs for a bulk import". Now you have four versions of the same process, and none of them is the original.
Next month the gateway makes idempotencyKey mandatory. You fix checkout.post.ts, the build passes, that page's tests are green. In production, 100% of mobile orders fail, because its copy is still missing that parameter. No test caught it, because even you don't remember how many copies there are.
There's a second, subtler failure mode: a colleague "tidies things up" by having a component call gateway.charge() directly because it "saves passing parameters through three layers". Six months later nobody can answer "which files make up the payment subsystem", and every signature change means grepping the whole repo and praying.
The problem isn't "a missing class". The problem is that clients are carrying the subsystem's knowledge: what to call first, which parameters go together, which errors are retryable, which mean a junk order. That knowledge lives in N places, and N grows with the number of pages — when it should live in exactly one.
02 — The idea, before touching code
Solution
Facade means: one API for the whole subsystem. A module exports a few functions named after business operations (pay(order), refund(ref, amount), statusOf(ref)), and internally calls all the steps in the right order. The client only needs to know "pay" — not which tax engine is running, which gateway is in use, or how many retries there are.
Two things need spelling out, because people get both wrong. One: a facade hides, it doesn't forbid — anyone who needs the low-level gateway (a reconciliation route, the gateway's webhook) can still import the subsystem directly; the facade doesn't build a wall. Two: a facade is not a 1-to-1 layer — if each of its functions just forwards to exactly one subsystem function, that's an Adapter or dead weight, not a Facade. Its value is in combining many calls into one, and it knows the business, while the subsystem doesn't.
In TypeScript, a facade almost never needs a class: a server/utils/checkout.ts module with export function pay() is enough, since you don't need multiple instances of "the payment process". The facade here is a named module boundary, not an object. Use a class when it needs to hold config or be injected for testing.
03 — Doing it for real, one code fragment per step
Step by step
Count the copies of the same call sequence
A facade doesn't start with "this class is too big". It starts with grep. The same sequence of calls shows up in ≥ 2-3 places, and each copy starts to drift a little (one is missing a log, one is missing a retry) — that's the signal.
This is code that runs and is "nothing wrong" syntactically. Look at where it actually breaks: not the length, but knowledge in the wrong place.
export default defineEventHandler(async (event) => {
const order = await readOrder(event)
if (!order.items.length) throw createError({ statusCode: 400, statusMessage: 'empty order' })
const total = order.subtotal + taxOf(order) + shipOf(order)
const ref = await withRetry(() => gateway.charge(total, order.idempotencyKey), 3)
await ledger.record(order.id, total, ref)
logger.info('order paid', { id: order.id, total, ref })
await queue.publish('order:paid', { id: order.id, ref })
return { ref }
})
// The same twelve lines also live in:
// mobile/checkout.ts (no publish -> webhook never fires)
// admin/manual-order.ts (no retry -> fails when the gateway 5xx's)
// import-batch.ts (its own retry, 3 attempts -> 5 attempts)Split those twelve lines: which line belongs to whom?
Before moving any code, go through it line by line. Those twelve lines are four responsibilities wrongly packed into one handler: order rules, pricing, I/O to the gateway, and observability. The last three belong to subsystems; the first belongs to checkout.
This classification determines the quality of the facade. A good facade doesn't contain the tax formula — it calls taxOf(). What it contains is ordering and promises: "the order must be written to the ledger before it's published", "if the gateway fails, retry 3 times before giving up".
validate(order) -> order rules -> STAYS with checkout
taxOf / shipOf -> pure computation -> pricing subsystem
gateway.charge + retry -> I/O, can fail -> payment subsystem
ledger / logger / queue-> observability, invariant -> ledger subsystemif that computes business logic, it starts becoming a god object today.Design the API in business language, not subsystem names
Settle the API before writing the body. Three questions: how many times per session does a client call it, which errors does the client need to tell apart, and what must never leak out (gateway, taxRuleId).
Note the name: pay(order), not charge(order) or callGateway(). The clients are pages/mobile/batch jobs; they think in "pay", not in "gateway". Naming from the caller's side is the cheapest way to keep an API from bloating.
// The entire "front" of the payment subsystem is these 3 functions.
export function pay(order: OrderDraft): Promise<PaymentResult>
export function refund(paymentRef: string, amount: number, reason: string): Promise<PaymentResult>
export function statusOf(paymentRef: string): Promise<PaymentStatus>
// THESE NEVER appear on the facade:
// gateway.charge / gateway.verify3ds / taxRule.pick / ledger.connect
// Whoever really needs them imports straight from the subsystem (see Step 7), not through here.Move the body into the facade, keeping the order intact
Only now do you move code. Move it line by line, don't casually rewrite the logic along the way: if this refactor changes behaviour, you won't be able to tell old bugs from bugs you introduced.
Every dependency is either a direct import or a parameter — the facade doesn't decide "which gateway to use" on its own; it gets that from config/injection. That's what separates it from a "God Service".
export async function pay(order: OrderDraft): Promise<PaymentResult> {
if (!order.items.length) return { ok: false, reason: 'empty-order' }
const total = order.subtotal + taxOf(order) + shipOf(order)
const ref = await withRetry(() => gateway.charge(total, order.idempotencyKey), 3)
.catch(() => null)
if (!ref) return { ok: false, reason: 'gateway-unavailable' }
await ledger.record(order.id, total, ref) // ledger BEFORE publish: the facade's promise
logger.info('order paid', { id: order.id, total, ref })
await queue.publish('order:paid', { id: order.id, ref })
return { ok: true, ref, total }
}Translate subsystem errors into business errors
A facade that leaks gateway errors (ECONNRESET, 402 card_declined) means clients have to know what the gateway is — and you've just dug yourself an information-leak hole. The facade translates: clients only receive outcomes the UI can act on.
Use a union type instead of throwing all over the place. TypeScript will force every call site to handle all the branches, including copies you didn't know existed.
export type PaymentResult =
| { ok: true, ref: string, total: number }
| { ok: false, reason: 'empty-order' } // customer can fix it
| { ok: false, reason: 'declined' } // customer picks another card
| { ok: false, reason: 'gateway-unavailable' } // try again later, keep the order
// 'ECONNRESET', '402', the gateway's stack trace: they stop here, logs only.
// The client renders a message based on reason, never the raw message from the gateway.The call site is down to one line
The four copied places are down to one line each. When the gateway demands an idempotencyKey, you change one file, and the "mobile silently fails" scenario is gone.
Mind the other direction too: the facade must not make clients "remind" it who they are. pay(order) takes everything from order and doesn't read useRequest() internally — otherwise batch jobs and tests can't call it.
// checkout page
const r = await pay(order)
if (!r.ok) showToast(r.reason)
// mobile
const r = await pay(order)
// bulk import: reuse the exact same path, don't copy the process
for (const order of batch) results.push(await pay(order))Keep the back door: the facade hides, it doesn't block
The reconciliation route needs gateway.listCharges(date) with fields the facade doesn't expose. Fine. It imports the subsystem directly. The facade serves the common client; it isn't the only gatekeeper, and trying to make it a monopoly is the fastest way to get everyone writing // @ts-ignore.
The practical consequence of "doesn't block": the facade does not guarantee every path goes through it. It lowers the cost of doing the right thing; it doesn't make the wrong thing impossible. Don't sell the team that illusion — use a lint rule if you really need to block it.
// The facade has no listCharges(), and shouldn't: common clients don't need it.
import { listCharges } from '~/server/subsystems/payment/gateway'
export default defineEventHandler(async () => {
const charges = await listCharges(yesterday()) // low-level gateway, on purpose
return reconcile(charges, await ledger.rowsOf(yesterday()))
})eslint-plugin-local-rules to watch this path if you want to block it.On-call duty: the facade must not grow
A facade breaks in one very recognisable way: it starts deciding instead of coordinating. Today it's an if (order.kind === "b2b") in pay(); six months later it's 400 lines and nobody dares delete anything.
Three recurring questions: does the facade have state (it mustn't)? Does it have computation formulas (call the subsystem)? Is any function > 30 lines (split it, or split the subsystem)? When it bloats, the right answer is usually "there are two subsystems sharing one file".
// Smell 1: the facade holds computation logic
if (order.kind === 'b2b') total = total * 0.9 // <- where's the tax/pricing engine?
// Smell 2: the facade holds state
private cache = new Map() // <- the facade is now a singleton with memory, tests are toast
// Smell 3: the facade is 1-to-1 with the subsystem
export const charge = (n) => gateway.charge(n) // <- this is an Adapter, delete it
// Smell 4: facade = barrel file
export * from './gateway'; export * from './tax' // <- hides nothing at all04 — Who talks to whom
Structure
- FacadeThe subsystem's public API, named after business operations (`pay`, `refund`). Holds call order and promises, not formulas.
- SubsystemThe real working modules: pricing, gateway, ledger. Unaware the facade exists, and still usable directly.
- ClientPage, mobile, batch job, cron. Calls 1-2 functions, only receives business errors (`reason: "declined"`).
- Low-level consumerReconciliation route, the gateway's webhook. Deliberately bypasses the facade to get detailed fields — the facade doesn't block it.
Client Facade Subsystem
------ ------ ---------
page ┐
mobile ├── pay(order) ┌──────────────┐
batch import ┘ ────────────► │ checkout.ts │──► pricing: taxOf, shipOf
│ 1 API in │──► payment: charge+retry
reconcile / webhook ───────────►│ business │──► ledger: record
│ terms │
(and gateway can still be └──────────────┘
imported directly — not banned)05 — Edit freely, run it right here
Try it: six subsystem steps, one call from the client
type Order = { id: string, subtotal: number, weightKg: number }
// --- Subsystem: a few separate steps, the call order is the important knowledge ---
const validate = (o: Order) => {
if (!o.id || o.subtotal <= 0) throw new Error('invalid order: ' + o.id)
}
const taxOf = (o: Order) => Math.round(o.subtotal * 0.1)
const shipOf = (o: Order) => (o.weightKg > 5 ? 60_000 : 30_000)
const audit = (line: string) => 'AUDIT ' + line
// Fake gateway: the first call always fails, so the retry has work to do
let gatewayCalls = 0
const charge = (total: number) => {
gatewayCalls++
return gatewayCalls === 1 ? null : 'CH-' + total
}
class CheckoutFacade {
pay(order: Order): string {
validate(order)
const total = order.subtotal + taxOf(order) + shipOf(order)
const ref = this.retry(total, 3) ?? 'FAILED'
console.log(audit(order.id + ' total=' + total + ' ref=' + ref))
return ref
}
private retry(total: number, max: number): string | null {
for (let i = 0; i < max; i++) {
const ok = charge(total)
if (ok) return ok
}
return null
}
}
const checkout = new CheckoutFacade()
checkout.pay({ id: 'ORD-01', subtotal: 500_000, weightKg: 2 })
checkout.pay({ id: 'ORD-02', subtotal: 250_000, weightKg: 9 })
try {
checkout.pay({ id: 'BAD', subtotal: 0, weightKg: 1 })
}
catch (e) {
console.log('REJECTED ' + (e as Error).message)
}AUDIT ORD-01 total=580000 ref=CH-580000 AUDIT ORD-02 total=335000 ref=CH-335000 REJECTED invalid order: BAD
The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- The same call sequence (validate → compute → I/O → log → publish) is repeated in ≥ 2-3 places, and the copies are starting to drift apart.
- The clients are very different (web, mobile, batch, cron) but all need the same business process.
- You want the subsystem to change internally (swap the gateway, swap the tax engine, add retries) without touching any client file.
- There's a complex/messy API (legacy, a third-party SDK, a multi-step ORM) where 90% of clients only use one scenario.
- You need a legitimate place to put ordering promises ("write the ledger before publishing") instead of trusting each call site to remember.
Don't use it when
- The facade grows into a god object. All it takes is one computational
ifand it starts sucking in every bit of "convenient" logic. Fix: no formulas, no state, no more than ~30 lines per function. - The 1-to-1 facade: each function just forwards to one subsystem function under a new name. That isn't a Facade, it's a middleware layer that does nothing — delete it, it only adds stack frames.
- Facade = barrel file:
export * from "./gateway"and call it a facade. A barrel file gathers exports; it hides nothing and keeps no promises. A facade must shrink the surface, not relocate it. - Confusing it with Adapter / a DI container. Adapter: one existing API with the wrong shape, and you fix the shape for a specific client. Facade: many APIs, and you collapse them into one easy API for every client. DI container: decides which instance gets created; a facade decides what clients get to know. They're independent, and real projects usually have both.
- Over-engineering. One client, a three-function subsystem, a clear API? No facade needed — call it directly. A facade pays off when the number of call sites for a process exceeds the number of steps in it.
07 — You have met it already, just not by name
In real code
Server routes in Nuxt/Express
A POST /api/checkout sitting in front of validate + pricing + gateway + ledger + queue is a facade, and it's why clients should never stitch those steps together in the browser. A route handler is the cheapest place to put a facade in a fullstack TS app.
The browser's fetch()
You call one function with one URL. DNS, TCP, TLS, cookies, redirects, gzip, HTTP/2 multiplexing and HTTP caching are all behind it. This is a facade in the true sense: a small, stable API covering an extremely complex subsystem — and you can still drop to a lower level (XMLHttpRequest, interceptors) if you really need to.
navigator.clipboard.writeText()
One function hiding focus rules, the permission prompt, encoding, and the different OS clipboard backends. This kind of facade also shows the downside: when you need lower-level behaviour, you have to ask for a different API, not "go through the facade".
A framework's API layer: useFetch()
One function hiding SSR fetching, payload serialisation to the client, key deduplication, hydration and retries. It's a facade plus a lot more, and it proves two things at once: a facade improves DX, and a facade makes it hard to see the real cost unless you read the docs.
08 — Try it yourself
Exercise
Six admin pages all copy the same four steps: `loadUser(id)`, `can(actor, "user:read")`, mapping to a `UserViewModel`, `audit.log(...)`. Pull them into a `userView.ts` facade and point out at least two things the facade should **not** expose, plus one thing that is very easy to stuff into the facade and turn it into a god object.
Hints, open them one at a time:
- What's the business API? One function or two? Which name describes the caller's intent rather than the subsystem's name?
- Which errors does the client need to tell apart (not found vs forbidden vs not verified)? Model them with a union type.
- Where should sensitive fields (
passwordHash,salt, reset tokens) live: in the ViewModel, in the facade, or in the repository?
A two-function facade: loadUserView(id, actor) and loadUserViews(ids, actor). It calls the repository, calls can(), writes the audit log, maps to a ViewModel that does not contain sensitive fields, and returns a UserViewResult union. The repository, the audit sink, passwordHash and PrismaClient are all off the facade. The thing that most easily rots a facade is role-based filtering/permission logic: it belongs to can()/the policy, and the facade just calls it.
// app/utils/user-view.ts <- this is the entire facade
export type UserViewResult =
| { ok: true, view: UserViewModel }
| { ok: false, reason: 'not-found' | 'forbidden' | 'not-verified' }
export async function loadUserView(id: string, actor: Actor): Promise<UserViewResult> {
const user = await userRepo.findById(id)
if (!user) return { ok: false, reason: 'not-found' }
if (!can(actor, 'user:read', user)) return { ok: false, reason: 'forbidden' }
if (!user.verifiedAt) return { ok: false, reason: 'not-verified' }
audit.log('user.view', { id, actor: actor.id })
return { ok: true, view: toViewModel(user) } // toViewModel does NOT copy passwordHash
}09 — Read them in pairs to see the essence
Related patterns
- AdapterAdapter fixes the **shape** of an existing API to fit a specific client (1-to-1). Facade collapses **many** APIs into one simple API. Adapter knows nothing about the business; Facade lives on it.
- MediatorMediator is a two-way relationship: modules call the mediator and the mediator calls them back. Facade is one-way: the subsystem doesn't know the facade exists.
- SingletonA facade usually only needs one instance, so it often gets written as a module singleton. The two are unrelated — don't treat "the facade is a singleton" as its reason to exist.
- ProxyProxy keeps the **same** interface as the real object to control access; Facade **changes** the interface to simplify it. Read this pair to see that "standing in front of an object" can serve two very different purposes.