Facade Pattern
Provide a simplified interface to a complex subsystem. A structural pattern that hides implementation details behind a clean API.
Overview
Your codebase grew. What started as a few classes for video conversion is now a tangle of decoders, encoders, bit rate calculators, audio mixers, and file splitters — and every feature team that touches it wires the pieces together differently. One client forgets to close the stream, another picks the wrong bitrate, a third skips the audio pass entirely. The subsystem works; the ways people use it don’t.
The Facade Pattern fixes that usage problem. The Gang of Four catalog defines it as “a unified interface to a set of interfaces in a subsystem” — one class that exposes only the operations callers actually need and orchestrates the rest internally. Clients call convert("movie.mp4", "output.avi") instead of manually sequencing five objects. The subsystem stays fully available underneath; the facade is a convenient front door, not a wall.
You see facades everywhere in production code: ORM sessions hiding transaction plumbing, cloud SDK methods hiding retries and multipart uploads, service layers shielding controllers from repository chaos. The pattern earns its keep whenever “easy to use correctly” matters more than “every knob exposed.”
When to Use
- A subsystem has grown many interdependent components and every new client re-learns the wiring. The facade becomes the documented, supported entry point.
- You integrate a third-party library or legacy module whose API you can’t change and don’t want leaking into your domain code — the same impulse that drives an Anti-Corruption Layer.
- A single task requires coordinating several subsystems (charge payment, reserve stock, create shipment) and you want that orchestration testable in one place.
- You’re layering an architecture: a service facade over repositories, a module boundary over internal files, or a public API over internal packages.
- Most callers need the 20% of functionality that covers the common case, while a few power users can drop to the subsystem directly.
When to Avoid
- The subsystem is already simple. A facade over two or three small classes is indirection that buys nothing.
- Every caller genuinely needs low-level control. A facade that hides what everyone uses just produces a second API to keep in sync.
- The underlying design is broken. A facade papers over bad structure; it doesn’t fix it. Refactor first, then add the facade if the entry point still earns its place.
- You’re tempted to put business rules in the facade “because it’s convenient.” That’s how a thin entry point quietly grows into the system’s dumping ground.
Solution
Consider the video conversion subsystem: four classes that must run in the right order with the right data. The VideoConverter facade exposes a single convert() call that coordinates them — decode the source, calculate the target bitrate, mix the audio track, encode to the destination format.
Python
class VideoDecoder:
def decode(self, file):
return f"Decoded {file}"
class VideoEncoder:
def encode(self, stream, format, bitrate_kbps):
return f"Encoded to {format} at {bitrate_kbps} kbps"
class BitRateCalculator:
def calculate(self, source):
return 1024
class AudioMixer:
def mix(self, stream):
return f"Mixed audio for {stream}"
class VideoConverter:
"""Facade that hides the complexity of video conversion."""
def __init__(self):
self._decoder = VideoDecoder()
self._encoder = VideoEncoder()
self._bitrate = BitRateCalculator()
self._audio = AudioMixer()
def convert(self, source_file, destination_format):
decoded = self._decoder.decode(source_file)
bitrate = self._bitrate.calculate(decoded)
mixed = self._audio.mix(decoded)
return self._encoder.encode(mixed, destination_format, bitrate)
# Client code
converter = VideoConverter()
result = converter.convert("movie.mp4", "avi")
print(result)
Java
class VideoDecoder {
String decode(String file) { return "Decoded " + file; }
}
class VideoEncoder {
String encode(String stream, String format, int bitrateKbps) {
return "Encoded to " + format + " at " + bitrateKbps + " kbps";
}
}
class BitRateCalculator {
int calculate(String source) { return 1024; }
}
class AudioMixer {
String mix(String stream) { return "Mixed " + stream; }
}
class VideoConverter {
private final VideoDecoder decoder = new VideoDecoder();
private final VideoEncoder encoder = new VideoEncoder();
private final BitRateCalculator bitrate = new BitRateCalculator();
private final AudioMixer audio = new AudioMixer();
public String convert(String sourceFile, String destinationFormat) {
String decoded = decoder.decode(sourceFile);
int rate = bitrate.calculate(decoded);
String mixed = audio.mix(decoded);
return encoder.encode(mixed, destinationFormat, rate);
}
}
// Client code
VideoConverter converter = new VideoConverter();
System.out.println(converter.convert("movie.mp4", "avi"));
JavaScript
class VideoDecoder {
decode(file) { return `Decoded ${file}`; }
}
class VideoEncoder {
encode(stream, format, bitrateKbps) {
return `Encoded to ${format} at ${bitrateKbps} kbps`;
}
}
class BitRateCalculator {
calculate(source) { return 1024; }
}
class AudioMixer {
mix(stream) { return `Mixed ${stream}`; }
}
class VideoConverter {
constructor() {
this.decoder = new VideoDecoder();
this.encoder = new VideoEncoder();
this.bitrate = new BitRateCalculator();
this.audio = new AudioMixer();
}
convert(sourceFile, destinationFormat) {
const decoded = this.decoder.decode(sourceFile);
const rate = this.bitrate.calculate(decoded);
const mixed = this.audio.mix(decoded);
return this.encoder.encode(mixed, destinationFormat, rate);
}
}
// Client code
const converter = new VideoConverter();
console.log(converter.convert('movie.mp4', 'avi'));
Explanation
The pattern has three participants, and the direction of the arrows is the whole point:
| Participant | Role in the example | What it owns |
|---|---|---|
| Facade | VideoConverter | Knows the right call sequence for common operations; contains no conversion logic of its own |
| Subsystem classes | VideoDecoder, VideoEncoder, BitRateCalculator, AudioMixer | Do the real work; never call back into the facade |
| Client | The code calling convert() | Depends on the facade, not on five subsystem types |
Dependencies flow one way: client → facade → subsystem. The facade composes existing operations into a higher-level workflow — it adds no new capability, it removes the need to know the choreography.
Consequences and trade-offs
- Coupling drops where it matters. Callers depend on one stable interface, so the subsystem can change internally — swap the codec, reorder the pipeline — without touching client code. The GoF book lists this decoupling as the pattern’s main benefit.
- The facade can leak. If clients routinely bypass it, the “simplified” interface is actually the wrong abstraction. Watch for that signal early; it usually means a missing operation or a facade that hides something callers need.
- Testing gets simpler, not trivial. You can unit-test the facade with mocked subsystems and cover orchestration in one place, but the subsystem classes still need their own tests — the facade doesn’t absorb that responsibility.
- One more layer to keep honest. When the subsystem gains features, someone has to decide whether the facade should expose them. An unmaintained facade quietly becomes a broken promise.
Applied Example: Checkout Facade
Video conversion is the textbook example; checkout is the production one. Five services — inventory, pricing, payment, shipping, notifications — must run in sequence with early exits on failure. Exposing that orchestration to every controller or queue consumer duplicates fragile logic across the codebase.
// Subsystem: 5 services the client should not orchestrate by hand
class InventoryService {
async checkStock(itemId: string): Promise<boolean> { /* ... */ return true; }
async reserve(itemId: string, qty: number): Promise<void> { /* ... */ }
}
class PricingService {
calculateTotal(items: CartItem[]): number {
return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
applyCoupon(total: number, coupon: string): number { /* ... */ return total * 0.9; }
}
class PaymentService {
async charge(amount: number, token: string): Promise<PaymentResult> { /* ... */ return { success: true, txId: "tx_123" }; }
}
class ShippingService {
async createLabel(address: Address): Promise<string> { /* ... */ return "TRK_456"; }
calculateCost(address: Address): number { /* ... */ return 9.99; }
}
class NotificationService {
async sendConfirmation(email: string, orderId: string): Promise<void> { /* ... */ }
}
// Facade: one entry point for the whole flow
class CheckoutFacade {
constructor(
private inventory: InventoryService,
private pricing: PricingService,
private payment: PaymentService,
private shipping: ShippingService,
private notification: NotificationService
) {}
async checkout(cart: CartItem[], coupon: string, paymentToken: string, address: Address): Promise<OrderResult> {
// 1. Check stock and reserve
for (const item of cart) {
const inStock = await this.inventory.checkStock(item.id);
if (!inStock) throw new Error(`Item ${item.id} out of stock`);
await this.inventory.reserve(item.id, item.qty);
}
// 2. Calculate price
let total = this.pricing.calculateTotal(cart);
if (coupon) total = this.pricing.applyCoupon(total, coupon);
total += this.shipping.calculateCost(address);
// 3. Charge
const paymentResult = await this.payment.charge(total, paymentToken);
if (!paymentResult.success) throw new Error("Payment failed");
// 4. Create shipment
const trackingNumber = await this.shipping.createLabel(address);
// 5. Notify
await this.notification.sendConfirmation(address.email, paymentResult.txId);
return { orderId: paymentResult.txId, total, trackingNumber };
}
}
// Usage: the client calls one method
const facade = new CheckoutFacade(
new InventoryService(),
new PricingService(),
new PaymentService(),
new ShippingService(),
new NotificationService()
);
const result = await facade.checkout(cart, "SAVE10", paymentToken, address);
console.log(result); // { orderId, total, trackingNumber }
A few things worth stealing from this shape: the services are injected rather than constructed inside the facade, which keeps each one mockable in tests. The facade orchestrates the sequence — stock, price, payment, shipping, notification — but the payment or shipping rules still live in their own services. And nothing stops an admin tool from calling InventoryService directly when it needs stock data without a checkout. The facade is the common path, not the only path.
Variants
| Variant | Use case |
|---|---|
| Class facade | Instance methods on a dedicated class; the default shape for most subsystems |
| Static facade | Stateless operations where carrying an instance adds noise (logging, utility APIs) |
| Service facade | Injected dependency that wraps repositories and external APIs — the layering workhorse in DI frameworks |
| API gateway | A facade at the network boundary that aggregates calls to several microservices |
| Module facade | A package’s public index/__init__ surface that hides internal file structure |
The first three differ only in how callers obtain the facade. The last two scale the same idea up a level: from a class in front of classes to a service in front of services.
Facade vs. Related Patterns
Structural patterns overlap enough that teams routinely mix them up. The distinguishing question is what the extra class actually changes:
| Pattern | What it changes | Ask |
|---|---|---|
| Adapter | The interface — translates one contract into another | ”How do I use this incompatible class?” |
| Facade | The surface area — narrows a subsystem to the operations callers need | ”How do I hide this subsystem’s complexity?” |
| Proxy | The access — controls how you reach the real object, same interface | ”How do I defer, cache, or guard this object?” |
| Mediator | The communication — colleagues talk through it instead of to each other | ”How do I stop these objects referencing each other?” |
| Anti-Corruption Layer | The boundary — translates and protects your model from a foreign one | ”How do I keep their design out of my code?” |
| Backend for Frontend | The audience — a dedicated facade per client type, at service level | ”How do I serve web and mobile differently?” |
An API gateway sits next to the facade family rather than inside it: it is the same simplification instinct applied at the network layer, where it also absorbs cross-cutting work like auth, rate limiting, and routing. If the boundary you need is in-process, write a facade class. If it’s between services, that’s gateway territory.
What Works
- Keep the facade thin. It orchestrates; it doesn’t implement. The moment a facade starts containing conversion rules, discount math, or retry policies, business logic has migrated to the wrong layer.
- Leave the subsystem reachable. Facades in the GoF style are optional, not encapsulating — power callers should still be able to construct and call subsystem classes directly for the 20% of cases the facade does not cover.
- Inject subsystem dependencies. Passing services into the facade’s constructor (as in the checkout example) keeps orchestration unit-testable and avoids hidden construction order inside the class.
- Document what the facade silently does. If
convert()retries a failed encode or picks a default bitrate, say so in the method’s contract — otherwise callers file bugs against behavior that is working as designed. - One facade per subsystem. A mega-facade spanning billing, search, and notifications is a God Object with a friendlier name.
Common Mistakes
- Putting business logic in the facade turns it into an unmaintainable middle layer. Facades delegate; they don’t decide.
- Hiding too much forces every client with a specialized need to request facade changes. Expose a second “advanced” interface or let those callers use the subsystem directly.
- Creating a facade for a trivial subsystem adds indirection without value — three simple classes do not need a doorman.
- Not updating the facade when the subsystem changes leaves a stale abstraction that promises operations the subsystem no longer performs.
- Multiple facades with overlapping responsibilities confuse callers about which to use. Consolidate, or split along subsystem boundaries rather than along callers.
- Treating the facade as a boundary it isn’t. A plain facade doesn’t translate models or defend your domain — when you need that protection, the pattern is an Anti-Corruption Layer, not a facade.
Real-World Examples
ORM Session
SQLAlchemy’s Session is a facade over connection pools, transaction management, and unit-of-work tracking. You call session.commit() instead of coordinating inserts, updates, and flush ordering yourself — and you can still drop to session.execute() when the simplified surface is not enough.
Framework Router
Express.js app.get('/users', handler) hides HTTP parsing, middleware chains, routing tables, and response serialization behind a two-argument call. The raw http module remains available underneath for anyone who needs it.
Cloud SDK
AWS S3 upload_file(bucket, key, path) conceals multipart chunking, retry logic, checksum validation, and credential refresh behind one method. The boto3 client interface exposes the same internals — the facade simply makes the common call cheap.
See Also
- Adapter Pattern — translate an incompatible interface instead of simplifying a complex one
- Backend for Frontend Pattern — a dedicated facade per client type, at service level
- Design Patterns Guide — the full GoF catalog hub this pattern belongs to
- Facade — Refactoring.Guru — canonical reference with UML diagrams and more examples
- Design Patterns (GoF) — the original catalog the pattern comes from
- Companion repository — the facade examples as runnable Python, JavaScript, and Java files
Frequently Asked Questions
What is the difference between Facade and Adapter?
Adapter changes an interface to match what a client expects. Facade keeps the subsystem's contracts and wraps them in a simpler entry point.
Can a facade expose subsystem methods directly?
Yes — that's the "optional facade" shape. Callers use the simple methods for common work and reach the subsystem classes when they need fine-grained control.
Is a REST API gateway a facade?
Conceptually yes — it aggregates calls to multiple microservices behind one client-facing endpoint. In practice it is a separate infrastructure component, not a class inside your codebase.
How do I test a facade?
Inject mocks for the subsystem classes and assert the orchestration: call order, early exits, and error propagation. The subsystem classes still need their own unit tests.
Does a facade have to hide every subsystem class?
No. Hiding everything is the "encapsulating facade" variant, which is a deliberate trade-off: stronger isolation, less flexibility for callers. Most facades hide only the complexity, not the capabilities.
When does a facade become a God Object?
When it fronts several unrelated subsystems or accumulates the rules that belong inside them — "one facade per subsystem" is the guardrail.
Related Resources
Adapter Pattern
Convert the interface of a class into another interface clients expect. A structural design pattern for interface compatibility.
PatternProxy Pattern
Provide a surrogate or placeholder for another object to control access to it. A structural design pattern for access control, lazy loading, and logging.
PatternMediator Pattern
Define an object that encapsulates how a set of objects interact. A behavioral design pattern for reducing chaotic dependencies.
PatternAnti-Corruption Layer: Isolate Legacy with Adapters
How to isolate legacy systems with translation adapters. Covers ACL facade, domain translation, bidirectional mapping, and gradual legacy replacement.
PatternBackend for Frontend (BFF) Pattern
Give each client type its own backend that aggregates downstream services and shapes data to that platform's needs.
GuidePractical Design Patterns Guide
Pick the right design pattern for each problem: Singleton, Factory, Observer, Strategy and more, with runnable code and honest trade-offs.