Facade puts one simple, higher-level interface in front of a subsystem made of several classes. Instead of every client creating and calling five objects in the right order, clients call one method, and the facade makes those calls for them. The subsystem is not hidden or changed: code that needs fine control can still use its classes directly. What changes is that most clients now depend on one entry point, so a change inside the subsystem is absorbed in one place.
Think of it like
Ordering from a waiter
In a restaurant you do not walk to the grill, then the salad station, then the bar, telling each one what you want and when. You tell the waiter, and the waiter knows which station gets which part of the order and in what sequence. The kitchen still exists and still works the same way; a regular who knows the bartender can still order a drink at the bar. The waiter is the facade, the stations are the subsystem, and you are the client who only needs to know one person.
The problem
A shop places an order in three steps, and the order matters: reserve the item in Inventory, charge the card through Payments, then book delivery with Shipping. The shop has two front ends, a web checkout and a mobile app, and each one was written to do those three steps itself. This is the Before version in the visualizer above. It works; the trouble is what each client has to know.
class WebCheckout {
constructor(
private inv: Inventory,
private pay: Payments,
private ship: Shipping,
) {}
buy(sku: string, usd: number) {
this.inv.reserve(sku);
this.pay.charge(usd);
const t = this.ship.schedule(sku);
return `web: ${t}`;
}
}
class MobileCheckout {
constructor(
private inv: Inventory,
private pay: Payments,
private ship: Shipping,
) {}
buy(sku: string, usd: number) {
this.inv.reserve(sku); // the same three calls,
this.pay.charge(usd); // in the same order,
const t = this.ship.schedule(sku); // written again
return `app: ${t}`;
}
}- Every client is coupled to every subsystem class. Two clients and three classes already make six dependencies. A kiosk, a partner API and an admin tool each add three more.
- The recipe is duplicated. The order of the calls (reserve before charge, charge before ship) is a rule, and it is written once per client. Nothing guarantees the copies agree.
- Subsystem changes ripple outward. When payments need a fraud screen first, or shipping changes its API, every client is edited. The visualizer's change request shows exactly this.
- Clients are harder to read and test. UI code that should say "place this order" is full of inventory, payment and shipping details, and a test of it needs fakes for all three.
The pattern
Intent: provide a unified interface to a set of interfaces in a subsystem. The facade defines a higher-level interface that makes the subsystem easier to use.
- Facade (
OrderFacade) - Knows which subsystem classes handle a request and in what order. Its methods are tasks the clients care about (
place(sku, usd)), and each one delegates to the subsystem. It holds no business rules of its own beyond that sequencing. - Subsystem classes (
Inventory,Payments,Shipping) - Do the real work. They do not know the facade exists and keep their own public APIs, so advanced code can still call them directly.
- Clients (
WebCheckout,MobileCheckout) - Call the facade instead of the subsystem. Each one holds a single reference and makes a single call per order.
The dependencies point one way: clients depend on the facade, the facade depends on the subsystem, and the subsystem depends on neither. The facade is usually a plain class that the subsystem objects are passed into (see Dependency Injection); it does not need an interface unless you want to swap it in tests.
What the visualizer shows
- Class diagram: in the With Facade version,
WebCheckoutandMobileCheckoutsit on top with one arrow each intoOrderFacade, and the facade has three arrows down toInventory,PaymentsandShipping. In the Before version, both clients have their own lines down to all three subsystem classes: six associations instead of two. - Objects at runtime:
webandmobileeach have one field,orders, and both point at the sameorders : OrderFacade. Onlyordersholdsinv,payandship. - Sequence of calls: this is the view to watch. One
place("lamp", 40)message fromwebtoordersfans out intoreserve,chargeandschedule, always in that order, and the tracking id travels back up. Thenmobilesends the same single message and gets the same fan-out, from the same code. - Controls: press Play in the visualizer at the top of the page, or step with the arrow buttons; it really runs the classes in the code panel. The Before / With Facade toggle switches versions. Add fraud check applies the change request to whichever version is shown: changed classes get a badge, and the Change request panel beside the code counts what each version had to change. On a phone, the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Build the subsystem
With With Facade selected, the client creates
inv,payandship. Nothing about them changes in this pattern; they are the same classes the Before version uses. - 2
Wrap it once
The client creates
orders, anOrderFacadethat receives the three subsystem objects. Then it createswebandmobile, and gives both the sameorders. Neither client holdsinv,payorship. - 3
One call in
web.buy("lamp", 40)callsorders.place("lamp", 40). That is the only thingWebCheckoutknows about placing an order. - 4
Fan out, in order
The facade calls
inv.reserve("lamp")(returns"H-lamp"), thenpay.charge(40)(returns"P-40"), thenship.schedule("lamp")(returns"T-lamp"). In the Sequence view these are three messages from theorderslifeline, one after another. - 5
One result out
placereturns"T-lamp"toweb, andweb.buyreturns"web: T-lamp"to the client. - 6
The second client reuses the recipe
mobile.buy("mug", 12)goes through the sameplacemethod and produces the same three calls, ending in"app: T-mug". The orchestration exists once. - 7
Add the fraud check (change request)
With Add fraud check applied,
OrderFacadegains afraudfield and one guard, soplacefirst callsfraud.screen(40)(returnstrue) and only then reserves stock. The two clients run unchanged code.
Before and after
Without the pattern
- Each client holds
Inventory,PaymentsandShipping - The call sequence is copied into every client
- A subsystem change edits every client
- Client tests need fakes for every subsystem class
- No extra class; fine while there is one client and the sequence is trivial
With Facade
- Each client holds one
OrderFacade - The call sequence lives in one method
- A subsystem change edits the facade, usually nothing else
- Client tests fake one small class
- The subsystem stays public for the rare caller that needs more
| Change request: add fraud check | Before | With Facade |
|---|---|---|
| Existing classes edited | 2 (WebCheckout, MobileCheckout) | 1 (OrderFacade) |
| New classes | 1 (FraudCheck) | 1 (FraudCheck) |
| Lines changed in existing classes | 6 (+6 −0) | 3 (+3 −0) |
Read the numbers honestly. With two clients, the facade saves one edited class and three lines, which is not dramatic. The cost of the Before version grows with the number of clients: every new front end is another copy of the sequence that must be found and changed, and the danger is less the typing than one copy being missed or putting the check after the reservation. The facade's version is also the only place the new rule can live, so the order of the steps is decided once. The client wiring changes in both versions, because something has to create the FraudCheck.
Variations
Keep it thin: facade vs god object
A facade is convenient to call, so it attracts code. First a discount rule, then a loyalty-points update, then an email template, and soon OrderFacade is a 2,000-line class that everything depends on: a god object. The fix is to keep the facade's job narrow. It decides which subsystem calls happen and in what order, translates between them (pass the hold id to shipping), and handles failure across them (release the hold when the charge fails). Decisions that belong to one part of the domain go into that part: pricing rules in a pricing class, fraud rules in FraudCheck.
Several facades over one subsystem
Nothing says a subsystem gets exactly one facade. Different clients want different simplifications: a CheckoutFacade for placing orders, a ReturnsFacade for refunds and restocking, an AdminFacade for manual adjustments. Each is small and has one reason to change, which is the single responsibility principle from SOLID Principles. Splitting by client need also keeps each facade's interface narrow (the interface segregation principle).
A facade as a module's public API
At the package level the same idea is a module that exports a few high-level functions and keeps its many internal classes private. In TypeScript that is an index.ts that re-exports only the entry points; in Java 9+ it is a module that exports one package and keeps the implementation packages unexported. Callers cannot couple to internals they cannot import, so the module can be refactored freely behind its facade.
// orders/index.ts
export { OrderFacade } from "./order-facade";
export type { OrderResult } from "./types";
// Inventory, Payments, Shipping and FraudCheck live in this
// folder too, but they are not exported. Other packages write:
// import { OrderFacade } from "./orders";
// and cannot reach the internals. Advanced callers inside the
// package can still use them directly.Layers of facades. In a layered design each layer can present a facade to the layer above: controllers call an application service that orchestrates domain objects and repositories, and the repositories present a simple API over the database driver. Each layer talks only to the facade of the layer below. The application services of Layered, Hexagonal & Clean Architecture are facades in this sense: one method per use case, coordinating the domain objects underneath.
A facade over legacy code
A facade is a good first step when you have to live with an old, tangled subsystem. Put a clean facade in front of it, move callers onto the facade, and the legacy code now has one caller you control. You can then rewrite the internals piece by piece while the facade's interface stays the same. At the level of a whole system this is the Strangler Fig migration: a routing facade in front of the old system sends each feature to the old or new implementation until the old one can be removed. When the legacy code also speaks a different model, the facade's methods use Adapters to translate, which together form an anti-corruption layer.
The system-design version: API gateway and BFF
Scale the idea from classes to services and you get an API gateway: one endpoint in front of many backend services, so a client makes one call and the gateway fans out, combines the answers and returns one response. A backend for frontend (BFF) is the "several facades" variation: one thin gateway per client type, each shaped for what that client needs. Both are covered in Proxies & API Gateways and API Gateway & Backend for Frontend. They add concerns a class facade does not have (network failures, timeouts, authentication, rate limits), but the design pressure is the same: keep them thin, or they become the distributed version of a god object.
| Class-level facade | API gateway / BFF | |
|---|---|---|
| Hides | Several classes in one process | Several services across the network |
| Client sees | One method per task | One endpoint per task (or per screen, for a BFF) |
| Fan-out | Sequential method calls | Often parallel requests, with timeouts and partial failures |
| Typical extras | Ordering, translation, undo on failure | Auth, rate limiting, caching, response shaping |
| Main risk | Growing into a god object | Growing into a bottleneck that holds business logic |
In real code
| Where | The facade, and what it hides |
|---|---|
| SLF4J (Java) | The Simple Logging Facade for Java. Application code logs through its Logger API and does not know which logging framework is underneath (Logback, Log4j 2, java.util.logging); that is chosen at deployment. Its API-versus-provider split also has Bridge's intent. |
Python subprocess.run() | One call starts a process, waits for it and returns its exit code and output. The Python docs recommend run() for the cases it can handle and point to the lower-level Popen class for more advanced use: the subsystem stays available. |
jQuery $.ajax() | One function call with an options object instead of creating and configuring an XMLHttpRequest and handling its state changes yourself. |
Java HttpClient | In java.net.http: build a request, call send(), read the response. Connections are managed inside the client, and so are protocol details such as falling back from HTTP/2 to HTTP/1.1. |
| The GoF book | Its own example: a Compiler class with one compile() method over the compiler subsystem (scanner, parser, syntax-tree builder, code generator), which specialized tools can still use directly. |
When to use it, and when not to
Reach for Facade when
- Several clients repeat the same sequence of calls to the same classes
- Most callers need a simple path through a complicated subsystem
- You want a stable entry point to a module, library or layer
- You are wrapping legacy code before changing it
- Third-party libraries should be used from one place, not everywhere
Skip it when
- The "subsystem" is one class: call it directly
- Every caller needs the full power of the subsystem anyway
- The facade would only forward calls one to one (that is a middle man)
- You are tempted to put business rules in it so they have somewhere to live
Facade vs similar patterns
| Pattern | How it relates to Facade |
|---|---|
| Adapter | Both wrap existing code. Adapter makes one class fit an interface clients already expect. Facade defines a new, simpler interface over many classes. |
| Mediator | Both centralize coordination. In Mediator the colleague objects talk to each other through the mediator and know it exists. In Facade clients talk to the facade, and the subsystem does not know the facade exists. |
| Proxy | Both stand in front of something. A proxy has the same interface as one real object and controls access to it. A facade has a different, higher-level interface over a group. |
| Abstract Factory | Often used together. An abstract factory can create the subsystem objects a facade uses, so the facade works with any family of them. |
| Singleton | Often used together. A process usually needs only one facade, so it is often a singleton. Creating one instance at startup and passing it in (Dependency Injection) gives the same result without global state. |
Implementation
The visualizer's scenario after the change request, as a complete program. OrderFacade runs the fraud screen, reserves stock, charges the card and books shipping, in that order, and releases the reservation if the charge fails. WebCheckout and MobileCheckout only know the facade. The demo also calls Inventory directly to show the subsystem is still available.
# ---- The subsystem: separate classes, each with one job ----
class Inventory:
def __init__(self) -> None:
self._stock = {"lamp": 3, "mug": 1}
self._holds: dict[str, str] = {} # hold id -> sku
self._next_hold = 1
def reserve(self, sku: str) -> str:
left = self._stock.get(sku, 0)
if left == 0:
raise RuntimeError(f"{sku} is out of stock")
self._stock[sku] = left - 1
hold = f"H{self._next_hold}"
self._next_hold += 1
self._holds[hold] = sku
return hold
def release(self, hold: str) -> None:
sku = self._holds.pop(hold, None)
if sku is not None:
self._stock[sku] = self._stock.get(sku, 0) + 1
def available(self, sku: str) -> int:
return self._stock.get(sku, 0)
class Payments:
def charge(self, usd: int) -> str:
if usd > 500:
raise RuntimeError("card declined")
return f"P-{usd}"
class Shipping:
def __init__(self) -> None:
self._next = 1
def schedule(self, sku: str) -> str:
tracking = f"T{self._next}-{sku}"
self._next += 1
return tracking
class FraudCheck:
def screen(self, usd: int) -> bool:
return usd < 1000
# ---- The facade: one entry point that knows the order of the steps ----
class OrderFacade:
def __init__(self, inventory: Inventory, payments: Payments,
shipping: Shipping, fraud: FraudCheck) -> None:
self._inventory = inventory
self._payments = payments
self._shipping = shipping
self._fraud = fraud
def place_order(self, sku: str, usd: int) -> str:
"""Returns a tracking id, or raises if the order fails."""
if not self._fraud.screen(usd):
raise RuntimeError("rejected by fraud check")
hold = self._inventory.reserve(sku)
try:
self._payments.charge(usd)
except RuntimeError:
self._inventory.release(hold) # undo step 1 if step 2 fails
raise
return self._shipping.schedule(sku)
# ---- Clients: they know the facade, not the subsystem ----
class WebCheckout:
def __init__(self, orders: OrderFacade) -> None:
self._orders = orders
def buy(self, sku: str, usd: int) -> str:
try:
return f"web: {self._orders.place_order(sku, usd)}"
except RuntimeError as e:
return f"web: failed ({e})"
class MobileCheckout:
def __init__(self, orders: OrderFacade) -> None:
self._orders = orders
def buy(self, sku: str, usd: int) -> str:
try:
return f"app: {self._orders.place_order(sku, usd)}"
except RuntimeError as e:
return f"app: failed ({e})"
if __name__ == "__main__":
inventory = Inventory()
orders = OrderFacade(inventory, Payments(), Shipping(), FraudCheck())
web = WebCheckout(orders)
mobile = MobileCheckout(orders)
print(web.buy("lamp", 40)) # web: T1-lamp
print(mobile.buy("mug", 12)) # app: T2-mug
print(web.buy("mug", 12)) # web: failed (mug is out of stock)
print(web.buy("lamp", 600)) # web: failed (card declined)
print(mobile.buy("lamp", 2000))
# app: failed (rejected by fraud check)
# The subsystem is still public for code that needs more control.
print(inventory.available("lamp")) # 2Key takeaways
- Facade gives a subsystem of several classes one simpler, task-level interface, so clients make one call instead of orchestrating many.
- The facade owns the sequence: which subsystem calls happen, in what order, and how failures are undone. Business rules stay in the subsystem.
- The subsystem does not know the facade and stays public, so advanced code can still use it directly.
- In the visualizer's "Add fraud check" request, the facade version edits 1 existing class by 3 lines; without it, both clients change (2 classes, 6 lines), and every new client adds another copy.
- The same idea appears at every scale: a module's exported API, an application service per use case, a facade over legacy code, and an API gateway or BFF in front of services.
- Adapter changes one interface to fit; Facade simplifies many into one; Mediator coordinates objects that talk to each other through it.
Common pitfalls
- Letting the facade grow into a god object: pricing rules, notifications and reporting pile up in it because everything already calls it. Keep it to orchestration and split it by task.
- Forwarding one call to one class with the same arguments. That adds a layer without hiding anything; call the class directly.
- Making the facade the only way in by hiding the subsystem completely, then adding a facade method for every advanced need. Simplify the common path and leave the parts reachable.
- Leaking subsystem types through the facade's methods (returning a
Paymentsreceipt object, taking aShippingoption enum). Clients are coupled to the subsystem again; use types that belong to the facade's level. - Making it a global singleton by reflex. One instance is normal, but creating it once and passing it in keeps clients testable (see Dependency Injection).
Interview tips
- In LLD rounds, when a use case touches several components (book a ride, place an order, check out a library book), say that a service or facade method coordinates them so controllers stay thin. It shows you know where orchestration belongs.
- Be ready for "Facade vs Adapter vs Mediator". Adapter converts one interface, Facade simplifies a whole subsystem, Mediator sits between peers that talk through it. The subsystem behind a facade does not know the facade exists.
- Mention the god-object risk unprompted: the facade orchestrates, the domain classes decide. Interviewers like to hear the limit of a pattern, not only its benefit.
Real-world applications
- Application or use-case services (
OrderService.placeOrder) that coordinate repositories, payment and messaging for controllers. - A package or module that exports a few entry points and keeps its internal classes private.
- Wrapping a complex third-party SDK or legacy subsystem so the rest of the code uses it in one place.
- Logging, HTTP and process libraries that offer a one-call path over a detailed lower-level API.
- API gateways and backend-for-frontend services in front of many microservices.
- Test setup helpers that build a whole subsystem with one call.
Test yourself
What is the main purpose of the Facade pattern?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.