Proxy pattern
Put a stand-in with the same interface in front of an object to load it lazily, guard it, cache it or reach it over the network. Java and Python code, Spring and Hibernate proxies, and Proxy vs Decorator.
On this page
The problem: paying for objects nobody uses
A photo gallery opens an album of 20 photos. The first version creates a RealPhoto for each one, and the constructor reads and decodes the file: about 20 MB per photo in memory. Opening the album means 400 MB of decoding before anything is shown, yet only 4 photos fit on the screen, and most users look at two of them and leave.
Three more requests arrive in the same quarter: private photos must only be shown to their owner, a slow exchange-rate service should not be called for the same answer twice a minute, and the gallery should be able to load photos from a remote server. Each request is about controlling access to an object, and none of them should require changing RealPhoto or the code that calls display().
The idea: a stand-in with the same interface
A proxy implements the same interface as the real object (the subject) and sits in front of it. Callers can't tell the difference, but the proxy decides when, whether and how the real object is used.
A stand-in that controls access to the real thing
- A proxy is a stand-in. It has the same interface as the real object and sits in front of it. Callers can’t tell the difference, but the proxy gets to decide when, whether and how the real object is used.
| Role | In this example | Responsibility |
|---|---|---|
| Subject (interface) | Photo | What callers depend on: display() |
| Real subject | RealPhoto | Does the real, expensive or sensitive work |
| Proxy | LazyPhoto, GuardedPhoto | Same interface; holds or creates the real subject and controls calls to it |
| Client | The gallery screen | Uses Photo and never knows whether it holds a proxy |
The four classic kinds differ only in what they control:
| Kind | Controls | Everyday example |
|---|---|---|
| Virtual proxy | When the real object is created: on first use | Hibernate lazy-loaded entities, image placeholders |
| Protection proxy | Whether a caller may use it | Permission checks, read-only views |
| Caching proxy | Whether the real call is needed at all | A cache in front of a slow service |
| Remote proxy | Where it runs: the real object is on another machine | gRPC and Java RMI client stubs |
Build it: a virtual proxy and a protection proxy
Virtual proxy: load the photo the first time it is shown
- A virtual proxy delays expensive work. A photo gallery shows 20 photos, but only 4 fit on screen. The proxies are cheap placeholders, and each loads its 20 MB photo only the first time display() is called.
1. The subject interface is what the gallery already uses.
2. The virtual proxy stores only the file name. On the first display() it creates the RealPhoto; later calls reuse it. Twenty proxies cost a few hundred bytes each.
3. The protection proxy checks the user before delegating, so a refused caller never touches the real object.
4. Proxies compose: a GuardedPhoto can wrap a LazyPhoto, so a private photo is both guarded and lazy.
import java.util.*;
// 1. The subject: what callers depend on
interface Photo {
void display();
default void displayFor(String user) { display(); }
}
// The real subject: expensive to create
class RealPhoto implements Photo {
private final String file;
private final byte[] pixels;
RealPhoto(String file) {
this.file = file;
this.pixels = new byte[1024]; // stands in for a 20 MB decode
System.out.println(" loading " + file + " from disk");
}
public void display() { System.out.println(" showing " + file); }
}
// 2. Virtual proxy: creates the real object on first use
class LazyPhoto implements Photo {
private final String file;
private RealPhoto real; // null until needed
LazyPhoto(String file) { this.file = file; }
public synchronized void display() { // synchronized: two threads, one load
if (real == null) real = new RealPhoto(file);
real.display();
}
}
// 3. Protection proxy: checks permission before delegating
class GuardedPhoto implements Photo {
private final Photo inner;
private final String owner;
private final boolean isPrivate;
GuardedPhoto(Photo inner, String owner, boolean isPrivate) {
this.inner = inner;
this.owner = owner;
this.isPrivate = isPrivate;
}
public void display() { displayFor(null); } // no user: treat as anonymous
@Override public void displayFor(String user) {
if (isPrivate && !owner.equals(user))
throw new SecurityException(user + " may not see this photo");
inner.display();
}
}
public class Main {
public static void main(String[] args) {
// 20 placeholders cost almost nothing; no file is read yet
List<Photo> gallery = new ArrayList<>();
for (int i = 1; i <= 20; i++) gallery.add(new LazyPhoto("photo" + i + ".jpg"));
for (Photo p : gallery.subList(0, 4)) p.display(); // only the 4 visible load
gallery.get(0).display(); // already loaded: no second read
// 4. Proxies compose: guarded AND lazy
Photo secret = new GuardedPhoto(new LazyPhoto("diary.jpg"), "ana", true);
secret.displayFor("ana"); // allowed
try {
secret.displayFor("guest"); // refused before loading anything
} catch (SecurityException e) {
System.out.println("Refused: " + e.getMessage());
}
}
}import threading
from abc import ABC, abstractmethod
class Photo(ABC): # 1. the subject
@abstractmethod
def display(self) -> None: ...
def display_for(self, user: str | None) -> None:
self.display()
class RealPhoto(Photo): # the real subject: expensive
def __init__(self, file: str):
self.file = file
self.pixels = bytearray(1024) # stands in for a 20 MB decode
print(f" loading {file} from disk")
def display(self) -> None:
print(f" showing {self.file}")
class LazyPhoto(Photo): # 2. virtual proxy
def __init__(self, file: str):
self.file = file
self._real: RealPhoto | None = None
self._lock = threading.Lock()
def display(self) -> None:
with self._lock: # two threads, one load
if self._real is None:
self._real = RealPhoto(self.file)
self._real.display()
class GuardedPhoto(Photo): # 3. protection proxy
def __init__(self, inner: Photo, owner: str, is_private: bool):
self._inner = inner
self._owner = owner
self._private = is_private
def display(self) -> None:
self.display_for(None)
def display_for(self, user: str | None) -> None:
if self._private and user != self._owner:
raise PermissionError(f"{user} may not see this photo")
self._inner.display()
gallery = [LazyPhoto(f"photo{i}.jpg") for i in range(1, 21)] # nothing loaded yet
for p in gallery[:4]:
p.display() # only the visible 4 load
gallery[0].display() # already loaded
secret = GuardedPhoto(LazyPhoto("diary.jpg"), owner="ana", is_private=True) # 4. composed
secret.display_for("ana")
try:
secret.display_for("guest")
except PermissionError as e:
print("Refused:", e)The numbers: opening the album now decodes 4 × 20 MB = 80 MB instead of 400 MB, and nothing at all until the screen asks. The synchronized (or lock) matters: without it, two threads calling display() at the same moment can both see null and decode the same 20 MB file twice.
Protection proxy: refuse before the real object is touched
- A protection proxy checks permission first. If a guest asks for a private photo, the proxy refuses, and the real object is never touched.
Caching and remote proxies
A caching proxy answers repeated calls itself. Here it sits in front of a slow exchange-rate service and keeps each answer for 60 seconds (its time to live, or TTL). The clock is injected so tests can move time forward.
interface RateService { BigDecimal rate(String from, String to); }
class CachingRateService implements RateService {
private record Entry(BigDecimal value, Instant fetchedAt) {}
private final RateService inner;
private final Duration ttl;
private final Clock clock;
private final ConcurrentHashMap<String, Entry> cache = new ConcurrentHashMap<>();
CachingRateService(RateService inner, Duration ttl, Clock clock) {
this.inner = inner;
this.ttl = ttl;
this.clock = clock;
}
public BigDecimal rate(String from, String to) {
String key = from + "->" + to;
Entry e = cache.get(key);
if (e != null && clock.instant().isBefore(e.fetchedAt().plus(ttl)))
return e.value(); // fresh: no remote call
BigDecimal v = inner.rate(from, to); // miss or stale: ask the real one
cache.put(key, new Entry(v, clock.instant()));
return v;
}
}import time
from decimal import Decimal
from typing import Callable
class CachingRateService: # same rate() method as the real service
def __init__(self, inner, ttl_seconds: float, clock: Callable[[], float] = time.monotonic):
self._inner = inner
self._ttl = ttl_seconds
self._clock = clock
self._cache: dict[tuple[str, str], tuple[Decimal, float]] = {}
def rate(self, frm: str, to: str) -> Decimal:
hit = self._cache.get((frm, to))
if hit and self._clock() - hit[1] < self._ttl:
return hit[0] # fresh: no remote call
value = self._inner.rate(frm, to) # miss or stale
self._cache[(frm, to)] = (value, self._clock())
return valueIf 50 threads miss the same key at once, this simple version makes 50 remote calls; that is a cache stampede, covered in caching. ConcurrentHashMap.computeIfAbsent or a per-key lock lets one caller fetch while the others wait.
A remote proxy looks like a local object, but each method call is turned into a network request. A gRPC client stub is one: stub.getUser(request) serialises the request, sends it, waits and deserialises the reply. See REST, gRPC and WebSockets.
Caching and remote proxies
- A caching proxy remembers answers, so asking twice is instant. And a remote proxy looks like a local object while really sending each call over the network, which is what a gRPC client stub is.
Proxies that frameworks write for you
Most proxies in real code are generated at run time, not written by hand:
- Spring AOP:
@Transactional,@Cacheableand@Asyncwork because Spring injects a proxy of your bean (a JDK dynamic proxy or a generated CGLIB subclass; Spring Boot uses CGLIB by default) that starts the transaction or checks the cache, then calls your method. - Hibernate / JPA lazy loading: with a lazy association (
@ManyToOne(fetch = FetchType.LAZY); JPA's default for to-one links is eager),order.getCustomer()returns a proxy subclass ofCustomerthat runs the SQL query the first time you call a getter on it. - Java's
java.lang.reflect.Proxycreates an object implementing any interfaces at run time, sending every call to oneInvocationHandler. Mocking libraries such as Mockito build on the same idea. - Python:
unittest.mock.Mockobjects andweakref.proxyare proxies; a class with__getattr__can forward any attribute it doesn't define to a wrapped object.
A dynamic proxy in a few lines
A dynamic proxy writes the "check, then delegate" logic once for every method of an interface:
@SuppressWarnings("unchecked")
static <T> T timed(T target, Class<T> iface) {
return (T) Proxy.newProxyInstance(iface.getClassLoader(), new Class<?>[]{iface},
(proxy, method, args) -> {
long start = System.nanoTime();
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw e.getCause(); // rethrow the real exception
} finally {
System.out.printf("%s: %d µs%n", method.getName(), (System.nanoTime() - start) / 1000);
}
});
}
RateService rates = timed(new HttpRateService(), RateService.class);
This one adds timing, which is decorator-like intent built with proxy machinery. The mechanism is the same; the name follows the intent.
Proxy, Decorator, Adapter, Facade: how they differ
Same diagram as a decorator, different intent
- Proxy and decorator look the same in a diagram: both wrap an object with the same interface. The difference is the intent. A decorator adds features; a proxy controls access to the real thing.
| Proxy | Decorator | Adapter | Facade | |
|---|---|---|---|---|
| Interface | Same as the real object | Same as the wrapped object | Different: converts to the expected one | New and simpler |
| Intent | Control access: lazy, guarded, cached, remote | Add features | Make it fit | Make a subsystem easy to use |
| Who creates the real object | Often the proxy itself (lazy, remote) | Always passed in by the client | Passed in | The facade owns its parts |
| Stacked by clients? | Rarely; usually set up by a framework or factory | Yes, freely | Rarely | No |
| May skip the real call? | Yes, that is often the point | Rarely; it normally always delegates | No | n/a |
The name also appears in networking: a forward proxy acts for clients, and a reverse proxy such as Nginx stands in front of servers to cache, check and route requests. Same idea, at the level of machines instead of objects.
When not to use it
In the interview
An online editor lists up to 500 documents per user. Each Document has title(), content() (can be several MB, stored in object storage) and save(text). Shared documents may be read-only for some users. Design the proxies: which kinds, in what order, and what each does.
Compare with our answer
interface Document { String title(); String content(); void save(String text); }
class LazyDocument implements Document { // virtual proxy
private final String id, title; private final BlobStore store; private String content;
LazyDocument(String id, String title, BlobStore store) { this.id = id; this.title = title; this.store = store; }
public String title() { return title; } // cheap: from the listing query
public synchronized String content() {
if (content == null) content = store.get(id);
return content;
}
public synchronized void save(String text) { store.put(id, text); content = text; }
}
class ReadOnlyGuard implements Document { // protection proxy
private final Document inner; private final boolean canWrite;
ReadOnlyGuard(Document inner, boolean canWrite) { this.inner = inner; this.canWrite = canWrite; }
public String title() { return inner.title(); }
public String content() { return inner.content(); }
public void save(String text) {
if (!canWrite) throw new SecurityException("read-only");
inner.save(text);
}
}
class LazyDocument(Document): # virtual proxy
def __init__(self, doc_id: str, title: str, store: BlobStore):
self._id, self._title, self._store = doc_id, title, store
self._content: str | None = None
self._lock = threading.Lock()
def title(self) -> str:
return self._title # cheap: from the listing query
def content(self) -> str:
with self._lock:
if self._content is None:
self._content = self._store.get(self._id)
return self._content
def save(self, text: str) -> None:
with self._lock:
self._store.put(self._id, text)
self._content = text
class ReadOnlyGuard(Document): # protection proxy
def __init__(self, inner: Document, can_write: bool):
self._inner, self._can_write = inner, can_write
def title(self) -> str:
return self._inner.title()
def content(self) -> str:
return self._inner.content()
def save(self, text: str) -> None:
if not self._can_write:
raise PermissionError("read-only")
self._inner.save(text)
A strong answer mentions: titles come from one listing query while content loads lazily per document · the guard outermost, so a refused save never reaches storage · thread safety of the lazy load · permission also enforced on the server, since a client-side proxy is not security · keeping 500 loaded contents in memory is itself a risk, so cap or release them.
The team adds @Cacheable("prices") to PriceService.price(sku) in Spring, and it works from controllers. But PriceService.basketTotal(skus), which loops and calls price(sku) for each item, is as slow as before. Why, and what are two ways to fix it?
Compare with our answer
A strong answer mentions: @Cacheable is applied by a proxy around the bean · basketTotal calls this.price() on the real object, so the call never passes through the proxy (self-invocation) · fix 1: move price() into a separate bean (for example PriceLookup) and inject it · fix 2: inject the proxy of the bean itself (or use AopContext.currentProxy() with exposeProxy enabled), which works but is less clear · or cache explicitly with a cache object instead of the annotation.
- Intent: a stand-in with the same interface that controls access to a real object.
- Kinds: virtual (create on first use) · protection (check permission) · caching (reuse answers) · remote (call another machine).
- Roles: subject interface · real subject · proxy · client that can't tell them apart.
- Lazy load safely: lock or
synchronizedso two threads don't both create the object. - Real ones: Spring
@Transactional/@Cacheable, Hibernate lazy entities, gRPC stubs,java.lang.reflect.Proxy, Mockito,unittest.mock. - Not Decorator: same diagram; proxy controls access and may skip or defer the call, decorator adds features.
- Breaks on: self-invocation, lazy loading after the session (and N+1), hidden network latency, stale caches, final methods.
1. A file browser shows 1,000 files, each with a large preview that takes 200 ms to generate. Users usually open two or three. Which design fits best?
A virtual proxy defers the expensive work until it is needed, so 1,000 placeholders cost almost nothing. Precomputing all previews spends 200 seconds of CPU for three views.
2. Two threads call display() on the same lazy proxy at the same moment, and the proxy has no locking. What can happen?
The null check and the assignment are separate steps, so both threads can pass the check. Use synchronized, a lock, or a holder idiom so the expensive creation happens once.
3. In a Spring service, checkout() calls this.reserveStock(), which is annotated @Transactional(propagation = REQUIRES_NEW). No new transaction starts. Why?
Spring applies @Transactional with a proxy around the bean. A call on this stays inside the real object and never reaches the proxy. Move the method to another bean or call through the proxy.
4. Which wrapper is best described as a proxy rather than a decorator?
A caching proxy decides whether the real object is called at all: it controls access. The other three always call through and add something, which is a decorator's intent.
5. A loop prints order.getCustomer().getName() for 500 orders loaded with JPA, and the database log shows 501 queries. What is going on?
One query loads the orders; each lazy customer proxy runs its own query on first access: the N+1 problem. Fetch customers with the orders (a join fetch or entity graph) or batch-load them.
6. A gRPC client stub is a remote proxy. Which risk is most specific to remote proxies?
A remote proxy hides the network behind an ordinary method call. Callers still need timeouts, retries and care with loops, because latency and partial failure are real.
Score 60% or more and the lesson is marked complete.