Proxy Pattern
A Proxy implements the same interface as another object – its subject – holds a reference to it, and decides what happens before the call reaches it. There are four classic kinds, and the pattern is only comprehensible as a family: a virtual proxy creates the subject lazily, on the first call that needs it; a protection proxy checks whether this caller is allowed through; a remote proxy makes a network call look local; a caching or smart proxy memoises answers or counts references. All four share one structure – same interface, one held subject, forward the call – and differ only in what the proxy does before it forwards.
💡 Subject = the real object the proxy stands in for. Subject and proxy implement the same interface, so no caller can tell which of the two it holds.
Why this matters: every machine-coding prompt with a remote dependency raises the same question – where do the timeout, the permission check, the cache and the failure budget live? Most candidates answer by accident, inlining all four into the caller, and that is the version that gets marked down: the policy is scattered across call sites and the class cannot be tested without a network. Proxy is the answer interviewers ask for by name, through rate limiting, circuit breaking and lazy loading.
Prerequisites
- Inheritance vs Composition – a proxy holds its subject by composition while sharing its interface, and that pairing is the whole shape of the pattern
- Decorator Pattern – structurally the same wrapper, so learning it first leaves intent as the only thing left to learn
- State Machines – the proxy below is a three-state machine, and the transitions are the hard part
The Problem: the call site that grew a cache, a guard and a failure counter
OrderService needs unit prices from a remote service. What happens next arrives one incident at a time: a latency complaint adds a cache, a security review adds a permission check, an outage that took checkout down with it adds a hand-rolled failure counter.
public class OrderService {
private final PricingClient pricing; // remote HTTP client
private final Map<String, Quote> quoteCache = new HashMap<>(); // after an incident
private int pricingFailures = 0; // after another one
private long stopCallingUntil = 0L;
public Order price(Cart cart, User user) {
List<OrderLine> lines = new ArrayList<>();
for (CartItem item : cart.items()) {
// Access control, inline.
if (item.isContractPriced() && !user.hasPermission("VIEW_CONTRACT_PRICE")) {
throw new AccessDeniedException("contract pricing");
}
// Cache lookup, inline. No TTL, no size bound, no invalidation.
Quote quote = quoteCache.get(item.sku());
if (quote == null) {
// Failure accounting, inline.
if (System.currentTimeMillis() < stopCallingUntil) {
throw new IllegalStateException("pricing is down");
}
try {
quote = pricing.fetchQuote(item.sku(), item.quantity());
pricingFailures = 0;
} catch (IOException e) {
if (++pricingFailures >= 5) {
stopCallingUntil = System.currentTimeMillis() + 30_000;
}
throw new PricingUnavailableException(e);
}
quoteCache.put(item.sku(), quote);
}
lines.add(new OrderLine(item.sku(), item.quantity(), quote.unitPrice()));
}
return new Order(cart.customerId(), lines);
}
}
Three costs, and interviewers name all three:
- The business method is about 80% plumbing. Pricing a cart is two lines – walk the items, build the lines. The rest is authorization, caching and failure accounting braided together so tightly you cannot read one concern without reading all four.
- The cache and the counter are fields on this one call site.
QuoteApiControllercallsfetchQuotetoo and gets neither: a cold cache and its own failure count. Two counters of five means the upstream absorbs ten failures before anything stops, and neither counter sees the other’s successes. A failure budget that is not shared is not a budget. - None of it can be tested without the remote client. Asserting “we stop after five failures” needs five real
IOExceptions out ofPricingClient, and the only handle on the recovery window is aThread.sleep(30_000)in a unit test.
Class Diagram
classDiagram
class PricingService {
<<interface>>
+quoteFor(sku, quantity) Quote
}
class RemotePricingService {
-HttpClient http
-Duration timeout
+quoteFor(sku, quantity) Quote
}
class CircuitBreakerPricingProxy {
-PricingService subject
-State state
-AtomicInteger consecutiveFailures
-long openUntilMillis
-Map~Quote~ lastKnownBySku
+quoteFor(sku, quantity) Quote
}
class OrderService {
-PricingService pricing
+price(cart) Order
}
PricingService <|.. RemotePricingService
PricingService <|.. CircuitBreakerPricingProxy
CircuitBreakerPricingProxy --> PricingService
OrderService --> PricingService
The non-obvious part is the pair of edges on the proxy: it implements PricingService and also points at PricingService. That self-referential pair is the proxy shape, and it is byte-for-byte the Decorator diagram. subject is typed as the interface too, which is what later lets you slide a caching proxy underneath the breaker without editing either class.
Real-World Example: a circuit-breaking proxy over a remote pricing service
The breaker has three states and the proxy owns all of them. CLOSED lets calls through and counts consecutive failures. Once the count crosses a threshold it trips to OPEN, and every call is answered from the fallback without touching the subject. When the open window expires it becomes HALF_OPEN and admits exactly one trial call: success closes the breaker, failure restarts the window. Circuit Breaker covers why that beats retrying a sick service, and three states is also a candidate for State Pattern – though with one transition table, an enum plus a branch is the right amount of machinery.
// ---- The interface the real service and the proxy both implement ----
public interface PricingService {
Quote quoteFor(String sku, int quantity);
}
public record Quote(String sku, Money unitPrice, Instant asOf) { }
// ---- Real subject: one network call, and no opinions about failure ----
public final class RemotePricingService implements PricingService {
private final HttpClient http;
private final URI endpoint;
private final Duration timeout;
public RemotePricingService(HttpClient http, URI endpoint, Duration timeout) {
this.http = http; this.endpoint = endpoint; this.timeout = timeout;
}
@Override public Quote quoteFor(String sku, int quantity) {
HttpRequest req = HttpRequest.newBuilder(endpoint.resolve("/quote/" + sku))
.timeout(timeout).GET().build();
try {
HttpResponse<String> res = http.send(req, BodyHandlers.ofString());
if (res.statusCode() >= 500) throw new PricingUnavailableException("5xx");
return Quote.parse(res.body());
} catch (IOException e) { // HttpTimeoutException is a subclass
throw new PricingUnavailableException("pricing call failed", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag, then report
throw new PricingUnavailableException("interrupted", e);
}
}
}
// ---- The proxy: same interface, holds the subject, decides whether to call it ----
public final class CircuitBreakerPricingProxy implements PricingService {
private enum State { CLOSED, OPEN, HALF_OPEN }
private final PricingService subject; // held, never inherited from
private final int failureThreshold;
private final Duration openDuration;
private final Clock clock; // injected, so tests never sleep
private volatile State state = State.CLOSED;
private volatile long openUntilMillis = 0L;
private final AtomicInteger consecutiveFailures = new AtomicInteger();
private final AtomicBoolean trialInFlight = new AtomicBoolean(false);
// Last good answer per sku: the fallback, and the reason a trip is survivable.
private final Map<String, Quote> lastKnownBySku = new ConcurrentHashMap<>();
public CircuitBreakerPricingProxy(PricingService subject, int failureThreshold,
Duration openDuration, Clock clock) {
this.subject = subject; this.failureThreshold = failureThreshold;
this.openDuration = openDuration; this.clock = clock;
}
@Override public Quote quoteFor(String sku, int quantity) {
State current = currentState(); // this read may flip OPEN to HALF_OPEN
if (current == State.OPEN) {
return fallback(sku, "breaker open"); // the subject is not touched at all
}
if (current == State.HALF_OPEN && !trialInFlight.compareAndSet(false, true)) {
return fallback(sku, "trial in flight"); // another thread owns the trial
}
try {
Quote quote = subject.quoteFor(sku, quantity); // the only delegation here
onSuccess(quote);
return quote;
} catch (PricingUnavailableException e) {
onFailure();
return fallback(sku, e.getMessage());
} finally {
if (current == State.HALF_OPEN) trialInFlight.set(false);
}
}
// Two threads can both land here and both write HALF_OPEN; harmless, because the
// CAS on trialInFlight -- not this read -- admits exactly one trial call.
private State currentState() {
if (state == State.OPEN && clock.millis() >= openUntilMillis) state = State.HALF_OPEN;
return state;
}
private void onSuccess(Quote quote) {
lastKnownBySku.put(quote.sku(), quote);
consecutiveFailures.set(0);
state = State.CLOSED; // a HALF_OPEN success closes it
}
private void onFailure() {
// A failure during the trial call re-trips immediately; no second chance.
if (state == State.HALF_OPEN
|| consecutiveFailures.incrementAndGet() >= failureThreshold) {
openUntilMillis = clock.millis() + openDuration.toMillis();
state = State.OPEN; // deadline first, then the state
consecutiveFailures.set(failureThreshold);
}
}
// Stale on purpose, and Quote.asOf carries the age where a caller can see it --
// which is what keeps this a fallback rather than a silent lie.
private Quote fallback(String sku, String reason) {
log.warn("pricing short-circuited sku={} reason={}", sku, reason); // never silent
Quote stale = lastKnownBySku.get(sku);
if (stale == null) throw new PricingUnavailableException("no price for " + sku);
return stale;
}
}
// ---- Wiring. OrderService.price() is unchanged; what it is handed is not. ----
PricingService remote = new RemotePricingService(http, pricingUri, Duration.ofMillis(300));
PricingService pricing = new CircuitBreakerPricingProxy(remote, 5, Duration.ofSeconds(30),
Clock.systemUTC());
OrderService orders = new OrderService(pricing); // constructor takes PricingService
import functools
from typing import Any, Protocol
class PricingService(Protocol):
def quote_for(self, sku: str, quantity: int) -> "Quote": ...
class ProtectionProxy:
"""A generic protection proxy over any subject at all.
__getattr__ runs only for names this object does not already have, so the fields
set in __init__ resolve normally and every method of the subject falls through to
the interceptor. One class proxies any interface: this is the dynamic form.
"""
def __init__(self, subject: Any, principal: "Principal",
guarded: frozenset[str], audit: "AuditLog") -> None:
self._subject = subject
self._principal = principal
self._guarded = guarded
self._audit = audit
def __getattr__(self, name: str) -> Any:
attr = getattr(self._subject, name) # an AttributeError here is the right error
if not callable(attr) or name not in self._guarded:
return attr # plain fields pass through untouched
@functools.wraps(attr)
def guarded(*args: Any, **kwargs: Any) -> Any:
if not self._principal.may(name):
self._audit.denied(self._principal.id, name)
raise PermissionError(f"{self._principal.id} may not call {name}")
return attr(*args, **kwargs) # checked, then delegated, unchanged
return guarded
def __repr__(self) -> str:
# Dunders need declaring explicitly: special-method lookup goes to the type,
# not the instance, so __getattr__ never sees repr, len, iter or eq. That is
# the classic Python proxy bug -- it behaves until someone prints it.
return f"ProtectionProxy({self._subject!r})"
pricing = ProtectionProxy(RemotePricingService(session), principal,
frozenset({"quote_for", "override_price"}), audit)
quote = pricing.quote_for("SKU-91", 4)
#include <chrono>
#include <memory>
#include <mutex>
#include <unordered_map>
class PricingService {
public:
virtual ~PricingService() = default;
virtual Quote quoteFor(const std::string& sku, int quantity) = 0;
};
// Same three states and transitions as the Java tab; ownership and locking differ.
// shared_ptr because the real service is built once and outlives any proxy wrapped
// around it -- the subject is a member, never a base class.
class CircuitBreakerPricingProxy : public PricingService {
enum class State { Closed, Open, HalfOpen };
std::shared_ptr<PricingService> subject_;
int failureThreshold_;
std::chrono::milliseconds openFor_;
std::mutex m_; // guards every field below
State state_ = State::Closed;
int failures_ = 0;
bool trialInFlight_ = false;
std::chrono::steady_clock::time_point openUntil_{};
std::unordered_map<std::string, Quote> lastKnownBySku_;
Quote fallbackLocked(const std::string& sku) { // caller already holds m_
auto it = lastKnownBySku_.find(sku);
if (it == lastKnownBySku_.end()) throw PricingUnavailable("no price " + sku);
return it->second;
}
public:
CircuitBreakerPricingProxy(std::shared_ptr<PricingService> subject, int threshold,
std::chrono::milliseconds openFor)
: subject_(std::move(subject)), failureThreshold_(threshold), openFor_(openFor) {}
Quote quoteFor(const std::string& sku, int quantity) override {
bool trial = false;
{
std::lock_guard<std::mutex> lock(m_);
if (state_ == State::Open && std::chrono::steady_clock::now() >= openUntil_)
state_ = State::HalfOpen;
if (state_ == State::Open || (state_ == State::HalfOpen && trialInFlight_))
return fallbackLocked(sku);
if (state_ == State::HalfOpen) { trialInFlight_ = true; trial = true; }
}
// The remote call runs with the mutex released; holding it across a network
// round trip would serialise every caller behind one request.
try {
Quote q = subject_->quoteFor(sku, quantity);
std::lock_guard<std::mutex> lock(m_);
lastKnownBySku_[sku] = q;
failures_ = 0; state_ = State::Closed; trialInFlight_ = false;
return q;
} catch (const PricingUnavailable&) {
std::lock_guard<std::mutex> lock(m_);
if (trial || ++failures_ >= failureThreshold_) {
state_ = State::Open;
openUntil_ = std::chrono::steady_clock::now() + openFor_;
}
trialInFlight_ = false;
return fallbackLocked(sku);
}
}
};
// The idiomatic C++ smart-proxy form is the other one: give the proxy an operator->
// returning T*, and it becomes syntactically a pointer to the subject with a hook on
// every member access. The compiler re-applies -> until it reaches a raw pointer,
// which is how shared_ptr and every lazy handle in the standard library work, and it
// binds at compile time, so it costs no indirect call:
//
// T* operator->() const { metrics_.bump("touch"); return subject_.get(); }
Same interface, and that is the whole trick
The proxy’s only structural requirement is type compatibility with its subject, and that is what makes it insertable. OrderService above never changed – one constructor argument did. You can wrap, unwrap, stack, or swap the breaker for a pass-through in tests, and not one caller is edited.
That is also the danger. Type compatibility is a compile-time property; behaviour is not. A proxy that blocks for 300 ms, returns a price four hours old, or throws an exception type the subject never threw has changed what calling quoteFor does, behind a signature saying nothing changed.
So here is the rule that keeps one honest: a proxy may change when and whether the subject is called. It must never change what the call means. Caching, lazy creation, a typed refusal, breaking while the subject is sick – all legal, because each still answers the question that was asked. Returning a different unit, clamping a value into range, swallowing an error into a default, or substituting a different subject are not: those are business decisions in an infrastructure costume. The stale-quote fallback above sits right on that line, and stays legal only because Quote.asOf carries the age.
Dynamic proxies, which is how this scales
Hand-writing one forwarding method per subject method is fine for a one-method interface and absurd for a thirty-method one, so every language has a mechanism for generating the forwarding instead:
- Java:
java.lang.reflect.Proxy.newProxyInstanceplus anInvocationHandler, whose singleinvoke(proxy, method, args)receives every call reflectively. Interfaces only; concrete classes need bytecode subclassing (CGLIB, ByteBuddy). - Python:
__getattr__catches any name the proxy does not define – the Python tab above is a complete generic proxy in thirty lines. - C++: templates plus
operator->, resolved at compile time, so the indirection costs nothing at runtime.
💡 Dynamic proxy = a proxy whose forwarding methods are generated at runtime rather than written by hand, so one handler class can stand in front of any interface.
This is how two things you use daily work. An ORM’s lazy-loading entity is a virtual proxy: order.getCustomer() hands back a generated subclass whose first real accessor triggers the SELECT. A Spring @Transactional bean is one too – the container hands callers a proxy that opens a transaction, calls the real bean, then commits or rolls back. Which explains the gotcha that burns people: inside a bean, this.doWork() reaches the real object directly and bypasses the proxy, so the annotation silently does nothing.
Proxy vs Decorator vs Adapter vs Facade
All four put a class in front of another class. Two share the subject’s interface and two do not, which splits the group before intent comes up:
| Pattern | Intent | Tell |
|---|---|---|
| Proxy | Control access to a subject – when, whether, by whom | Same interface, and the wrapper decides whether the call happens at all |
| Decorator | Add behaviour the caller wants, on top of the subject | Same interface, stacks three deep, and the caller chose the stack |
| Adapter | Make a class satisfy an interface it does not implement | Two interfaces in play; wrapper’s type differs from the wrappee’s |
| Facade | Invent a smaller API over a subsystem | A new interface nobody else implements, usually over several objects |
Be honest about the overlap, because the interviewer already knows: Proxy and Decorator are structurally identical. Same interface, one held subject, forward the call. No compiler, linter or diagram separates them – intent is the only separator. Three weak signals help: who constructs the wrapper (the caller, for a decorator; a container or factory, for a proxy), whether it stacks, and whether the subject always gets called. Only one structural tell is real: a virtual proxy can create its subject, and the caller often cannot reach that subject at all.
When to Use vs When to Avoid
| Use Proxy When | Avoid When |
|---|---|
| The subject is expensive to build and often never used | You own the subject and can put the logic inside it |
| Access must be checked and the subject cannot hold the check | Callers want to compose and stack the behaviour – Decorator |
| The subject lives across a network and callers should not care | The interface has to change – Adapter, or a new method |
| You need caching, counting or rate limiting around an interface | The indirection hides a cost the caller has to budget for |
| You want resilience added without touching subject or callers | One cheap subject forever, no access rules – pure indirection |
The characteristic failure mode is the invisible proxy, with two canonical bugs. A lazy-loading proxy issues a database query inside a getter, so a loop over 200 orders touching order.getCustomer() runs 201 queries where 2 would do – the N+1 select, and nothing in that signature hints at a database. A caching proxy with no TTL serves a price from last Tuesday forever, and the only symptom is a wrong number on an invoice. Neither bug is visible to the type system or to a reviewer reading the call site. Make the surprising part visible instead: name it (loadCustomer(), not getCustomer()), carry the age in the returned value the way Quote.asOf does, log every time the proxy declines to delegate, and never hide an unbounded wait behind a plain getter.
💡 N plus 1 select = one query to fetch a collection, then one more per element because each element lazily loads a relation. Learn more →
Interview Questions
-
“Proxy vs Decorator?” – Intent, and say out loud that the two are structurally identical, because the interviewer knows and is checking whether you do. A decorator adds behaviour the caller asked for and expects to stack; a proxy controls access, usually stands alone, and is usually installed by infrastructure rather than chosen by the caller. The one genuine structural tell is creation: a virtual proxy can construct its own subject, while a decorator always receives an already-built component.
-
“How does a lazy-loading proxy cause N+1 queries, and what do you do about it?” – The proxy defers the
SELECTto first access, which wins for the entities nobody touches and loses badly inside a loop: 200 orders with one lazygetCustomer()each is 201 round trips. Three fixes in order of preference – fetch the relation eagerly for the use cases that need it, scoped to the query rather than baked into the mapping; batch the loads so proxies collect ids and issue oneINquery; or make the load explicit in the API. Then make detection routine: count queries per request in tests and fail the build when the count jumps, because N+1 stays invisible until the data grows. -
“Should a proxy be thread-safe, and where is the race in a half-open circuit?” – Yes, whenever the subject is shared, because the proxy holds mutable policy state that every caller mutates. The race is the trial call: two threads both read HALF_OPEN and both decide to make it, so with 500 threads in flight you fire 500 requests at a service you just concluded was sick – the exact stampede the breaker existed to prevent. The fix is a single-permit gate, the
trialInFlight.compareAndSet(false, true)above, so one request goes through and everyone else takes the fallback. MakingquoteForsynchronizedis not the fix: it serialises every caller behind one network round trip. -
“How do you test a proxy?” – A hand-written fake subject plus an injected clock. The fake counts calls and can be told to fail on demand, which lets you assert the proxy’s only two jobs: did it delegate when it should, and did it not when it should not. Drive the state machine by advancing the injected
Clock, neverThread.sleep, which turns a thirty-second window into a thirty-second test and still flakes. Worth asserting: five failures trip it, the sixth call never reaches the fake, advancing past the deadline admits exactly one call, and that call’s outcome either closes or re-opens the breaker. Testing in machine coding covers fakes versus mocks. -
“Can you proxy a class instead of an interface?” – Only with bytecode subclassing, and then the rules bite: a
finalclass cannot be proxied at all, andfinal,privateorstaticmethods are silently not proxied, so the call compiles, runs, and skips your proxy. That is the practical argument for programming against an interface even when exactly one implementation exists – it preserves the seam a proxy can later go into, and Dependency Injection is what puts the proxy there.
See It in Action
- Circuit Breaker – this lesson’s example, three states and the single trial call
- Mini ORM – virtual proxies for lazy relations, and the N+1 they produce in a loop
- Rate Limiter – a protection proxy that refuses when the bucket for that key is empty
- Multilevel Cache – caching proxies over the backing store, stacked, which makes them decorators too