Proxy puts a stand-in in front of an object. The stand-in has the same interface as the real object, so callers cannot tell the difference, but every call goes through it first, which lets it control access: create the real object only when it is first needed, answer repeat requests from a cache, refuse callers without permission, or forward the call to another machine. The real object stays simple; the access rule lives in one place in front of it.
Think of it like
An executive's assistant
You want a meeting with a busy executive, so you call their assistant. To you, the assistant answers the same questions the executive would ("Is Tuesday free?"), but the assistant handles most of them alone: they know the calendar by heart, turn away callers who should not get through, and only interrupt the executive when it is really needed. Some executives are not even in the building until a meeting is booked. You talked to a stand-in the whole time, and it controlled who reached the real person, and when.
The problem
A photo gallery shows high-resolution images through a small Image interface with one method, show(). Creating a HighResImage is expensive: its constructor reads the whole file from disk. The simple version builds the gallery from real images. This is the Before version of the visualizer's Virtual scenario.
class HighResImage implements Image {
private pixels: string;
constructor(private file: string) {
this.pixels = readWholeFile(file); // slow, 4 MB each
}
show() {
return `drew ${this.file}`;
}
}
const gallery = new Gallery([
new HighResImage("a.png"),
new HighResImage("b.png"),
new HighResImage("c.png"),
]);
gallery.open(0); // only a.png is ever shown- Paying for what is never used. All three files are read before the user sees anything;
b.pngandc.pngcost as much asa.pngbut are never shown. With 300 photos the gallery opens very slowly and holds 1.2 GB. - Moving the check into the callers spreads it around.
Gallerycould keep file names and create images on demand, but then it depends onHighResImage, and every other caller (a slideshow, a thumbnail strip) must repeat the same "loaded yet?" logic. - The same shape appears with any access rule. The Caching scenario has two screens that read reports from a slow database. Without a proxy, each screen keeps its own cache (the same code twice, and the caches do not share), and adding an access check means editing every screen.
The pattern
Intent: provide a surrogate or placeholder for another object to control access to it (Gang of Four, who also call it Surrogate). In practice: write a class that implements the same interface as the real object, holds (or knows how to get) the real object, and decides on every call whether, when and how to forward it.
- Subject (
Image,Reports) - The interface clients use. Both the real object and the proxy implement it, which is why a proxy can be handed to code that expects the real thing.
- Real subject (
HighResImage,ReportDb) - The object that does the actual work. It knows nothing about the proxy and contains no access logic.
- Proxy (
ImageProxy,CachingProxy,ProtectionProxy) - Implements the subject interface and holds a reference to the real subject, often named
real. Each method does its access work (create, check, look up, count) and then forwards, or answers by itself, or refuses. - Client (
Gallery,Dashboard,Exporter) - Code that only knows the subject interface. It is written once and works with the real object or a proxy unchanged.
Two arrows in the class diagram carry the idea. The proxy implements the subject interface, so it can go anywhere the real object can. The proxy also points to the real subject (the real field), so it can pass calls on. Whether a call is passed on, answered from the proxy's own state or refused is the proxy's decision, and that decision is the whole point of the pattern.
What the visualizer shows
- Virtual, objects at runtime: the strongest moment. With With Proxy selected, the gallery is built from three
ImageProxyobjects and the Objects view has noHighResImageat all. On the firstgallery.open(0), proxyafindsreal = null, createsimg : HighResImage, and only then forwardsshow(). The secondopen(0)goes straight through.bandcend the run still holding just a file name andreal = null. - Caching, sequence of calls: the first
dash.show("q3")goes three lifelines deep (dash,proxy,db) anddb.queriesbecomes 1. The second request, and the export screen's request, stop atproxy: the arrow never reaches thedblifeline, anddb.queriesstays 1. - Caching with the access check applied: a
ProtectionProxysits in front of each screen. The admin's call passes the check and continues to the cache; the guest's call is refused atguest, and the exception travels back to the client without reachingproxyordb. - Class diagram: every call to a proxy lights the violet interface (
ImageorReports), because the client only ever calls through it.
Pick Virtual or Caching in the toolbar, then press Play or step with the arrow keys: the visualizer really runs the classes in the code panel and explains each step under the stage. The Before / With Proxy toggle switches to the version without a proxy. In Caching, Add access check applies the change request to whichever version is shown; touched classes get a badge, and the Change request panel beside the code compares the two versions. On a phone the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Build the gallery from proxies
In Virtual with With Proxy selected, the client creates
a,bandc, threeImageProxyobjects. Each constructor stores a file name and setsreal = null. No file is read. - 2
Hand them to the client
new Gallery([a, b, c])accepts them becauseGallerytakes anyImage[]. Its code is identical in the Before version. - 3
First use creates the real subject
gallery.open(0)callsa.show(). The proxy seesreal === null, createsimg = new HighResImage("a.png")(the only disk read in the run), stores it inreal, and forwardsshow()."drew a.png"travels back to the client. - 4
Later uses reuse it
The second
gallery.open(0)reachesa.show()again.realis set, so the proxy forwards immediately. One load instead of three:b.pngandc.pngare never read. - 5
A caching proxy in front of a database
Switch to Caching. Both screens get the same
CachingProxy. The firstdash.show("q3")misses the cache, so the proxy callsdb.get("q3"), which returns42, and the proxy stores it:cachebecomesMap{q3: 42}. - 6
Repeat requests stop at the proxy
The dashboard's second request and the export screen's request are answered from
cache.exp.export("q3")returns"q3,42", anddb.queriesis still 1. In the Before version, each screen has its own cache and the database is queried twice. - 7
Add an access check (change request)
Apply Add access check. The client wraps each screen's reports in a
ProtectionProxy:adminfor the dashboard,guestfor the export screen. The admin's request passes the check and is served as before; the guest'sget("q3")throws"denied"at the proxy, and the client catches it. No existing class changed.
Before and after
Without a proxy
- Virtual: every image is loaded when the gallery is built, shown or not
- Caching: each caller keeps its own cache, so the same query runs once per caller
- Access rules are copied into every caller, and a caller that forgets one is a hole
- Fewer classes and one less call per request
With Proxy
- The real object is created on first use: 1 load instead of 3 in the run
- One cache in front of the subject, shared by every caller: 1 query instead of 2
- A new access rule is a new proxy; callers and the subject are not opened
- One more class per rule, and one more hop on every call
| Change request: add an access check | Before (each screen caches) | With Proxy |
|---|---|---|
| Existing classes edited | 2 (Dashboard, Exporter) | 0 |
| New classes | 0 | 1 (ProtectionProxy) |
| Lines changed in existing classes | 10 | 0 |
The panel counts classes only. The client code changed in both versions: without a proxy, every constructor call gained a role argument; with Proxy, the wiring wraps each screen's reports in a ProtectionProxy. The bigger difference is where the rule lives. Without a proxy it lives in every screen, so a third screen written next month can forget it. With Proxy it lives in front of the data, and nothing reaches the cache or the database without passing it. (The data is a toy on purpose: the database returns 42 for q3, and an image "load" just sets a field to "4 MB", so the values stay readable in the Objects view.)
Variations
Kinds of proxies
| Kind | What it controls | Typical example |
|---|---|---|
| Virtual proxy | When the real object is created: only on first use | A large image, document or ORM entity loaded on demand |
| Protection proxy | Who may call which methods | A permission check in front of a service; a read-only view of an object |
| Caching proxy | Whether the real object needs to be called at all | Memoizing results of a slow query or remote call |
| Remote proxy | Where the real object lives: it encodes the call and sends it to another process or machine | A gRPC client stub, a Java RMI stub |
| Smart reference | What happens around each access: counting references, locking, logging, freeing when unused | std::shared_ptr in C++, a lock-acquiring wrapper, an access log |
| Copy-on-write | When a copy is really made: the original is shared until someone writes | Implicitly shared strings and containers (Qt's containers, Swift's arrays) |
Dynamic proxies
Writing a proxy class by hand means forwarding every method of the interface. Many languages can generate the forwarding at runtime instead: you write one handler that sees every call, and the runtime builds an object that implements the interface and sends each call to the handler.
const db = new ReportDb();
const logged = new Proxy(db, {
get(target, prop, receiver) {
const value = Reflect.get(target, prop, receiver);
if (typeof value !== "function") return value;
return (...args: unknown[]) => {
console.log(`call ${String(prop)}(${args.join(", ")})`);
return value.apply(target, args);
};
},
});
logged.get("q3"); // logs "call get(q3)", returns 42- JavaScript
Proxywraps any object with a handler whose traps (get,set,has,deleteProperty,applyand more) intercept the basic operations on it;Reflectperforms the default behavior. Vue 3's reactivity system and the Immer library are built on it. - Java
java.lang.reflect.Proxy.newProxyInstancecreates, at runtime, an object implementing a list of interfaces and routes every call to anInvocationHandlerthat receives theMethodand its arguments. It works only for interfaces; frameworks that proxy classes generate subclasses with bytecode libraries such as Byte Buddy or CGLIB. Spring builds its proxies for@Transactionaland other aspects this way. - Python has no interface declarations to implement, so a proxy can define
__getattr__, which runs only for attributes the proxy does not have itself, and delegate those to the real object. Special methods such as__len__are looked up on the type, not through__getattr__, so a generic proxy must define them explicitly.
Reports db = new ReportDb();
Reports logged = (Reports) Proxy.newProxyInstance(
Reports.class.getClassLoader(),
new Class<?>[] { Reports.class },
(proxy, method, args) -> {
System.out.println("call " + method.getName());
return method.invoke(db, args);
});
logged.get("q3"); // prints "call get", returns 42Identity and equality
- A proxy is a different object from its subject:
proxy === realis false, and code that keys a map or a set by object identity sees two objects. - Type checks see the proxy's class. A Hibernate lazy proxy for an
Orderis a generated subclass ofOrder, sogetClass() == Order.classis false. Anequalsthat comparesgetClass()breaks on proxies; compare withinstanceofand read the other object's fields through its getters, which load it if needed. - Calls that bypass the interface bypass the proxy. Inside a Spring bean,
this.save()calls the real object directly, so a@Transactionalonsaveis ignored for that self-call. The same holds for any proxy: only calls that go through it are controlled. - A JavaScript
Proxyis a separate object too:new Proxy(obj, {}) === objis false, and some built-in objects (aMap, aDate) do not work through a plain proxy, because their methods need the real object asthis.
Virtual proxy, lazy initialization and Singleton
The core of a virtual proxy, if (real === null) real = create(), is plain lazy initialization. The proxy's contribution is where that code lives: behind the subject's interface, so callers do not know it exists. A lazily created Singleton uses the same check, but for a different goal: one instance for the whole program. A virtual proxy delays one particular object and can exist many times. Both share the same trap in multithreaded code: two threads can see null at the same time and create two objects, so a shared lazy proxy needs a lock or a thread-safe lazy holder.
In real code
| Where | Kind | What the proxy does |
|---|---|---|
| ORM lazy loading (Hibernate, JPA) | Virtual | A lazy @ManyToOne association is filled with a proxy that knows only the id, and so is the result of entityManager.getReference(Order.class, id). The first access to another field runs the SELECT. Touch it after the session is closed and Hibernate throws LazyInitializationException; touch one per row in a loop and you get the N+1 query problem |
| gRPC client stubs | Remote | Generated code gives the client a stub object with one method per service method (newBlockingStub(channel) in Java). Each call serializes the request with Protocol Buffers, sends it over HTTP/2 and decodes the reply |
| Java RMI | Remote | The client holds a stub that implements the remote interface and forwards each call over the network to the server object |
| Spring AOP | Smart reference, protection | Beans with @Transactional, @Cacheable or method security are wrapped in a proxy that starts a transaction, checks a cache or checks permissions around the real call |
C++ std::shared_ptr | Smart reference | Overloads -> and * to reach the object, counts how many owners share it, and deletes it when the last one goes away |
JavaScript Proxy | Any | Vue 3 wraps state in proxies to track which properties a component reads and re-render when they change; Immer hands you a draft proxy that records your writes |
C++ std::vector<bool> | Smart reference | The vector packs bits, so v[0] returns a small proxy object that reads or writes one bit instead of a bool&. A classic surprise: auto x = v[0]; holds the proxy, not a copy of the value |
When to use it, and when not to
Reach for Proxy when
- An object is expensive to create and often not needed (lazy loading)
- Access needs one enforced checkpoint: permissions, rate limits, auditing
- Repeated calls with the same arguments are slow and safe to cache
- The real object lives in another process and callers should not handle the wire format
- Callers must not change, because they already use the subject interface
Skip it when
- The object is cheap and always used: laziness only adds a check
- Only one caller needs the rule; put it in that caller
- Callers depend on object identity or concrete types
- The interface is large and changes often, so a hand-written proxy keeps falling behind
- Hiding a network call behind a local-looking method would hide latency and failures callers must handle
Proxy vs similar patterns
| Pattern | Interface | Relationship to what it wraps | Purpose |
|---|---|---|---|
| Proxy | Same as the subject | One subject, often created, looked up or owned by the proxy | Control access: when it is created, who may call, whether a call is needed, where it runs |
| Decorator | Same as the component | One component, handed in by the client | Add behavior. Decorators are meant to be stacked in combinations the client chooses; a proxy is usually one fixed stand-in. A caching layer can be described either way: the name follows the intent |
| Adapter | Different: translates to the interface the client expects | One adaptee | Make an incompatible class fit; it changes the interface on purpose |
| Facade | New, simpler interface | A whole subsystem of objects | Make a group of classes easy to use. A proxy mirrors one object; a facade summarizes many |
| Flyweight | The object's own | Many contexts share one object | Save memory by sharing what is identical. A virtual proxy saves memory by not loading at all; the two combine well (a proxy that loads a shared flyweight on demand) |
| Proxies & API Gateways | The same network protocol | Servers behind it | The same idea between machines: caching, auth, TLS and routing in front of backend services |
Implementation
The visualizer's Virtual scenario as a complete program. HighResImage loads its file in the constructor; ImageProxy implements the same Image interface, keeps only the file name and creates the real image the first time show() is called. The demo builds a gallery of three proxies, opens the first image twice and prints how many images were actually loaded: one.
from __future__ import annotations
from abc import ABC, abstractmethod
class Image(ABC):
@abstractmethod
def show(self) -> str: ...
class HighResImage(Image):
"""Real subject: expensive to create."""
loads = 0
def __init__(self, file: str) -> None:
self._file = file
HighResImage.loads += 1
self._pixels = "4 MB" # stands in for a slow disk read
print(f"loaded {file} ({self._pixels})")
def show(self) -> str:
return f"drew {self._file}"
class ImageProxy(Image):
"""Virtual proxy: same interface, creates the real image lazily."""
def __init__(self, file: str) -> None:
self._file = file
self._real: HighResImage | None = None
def show(self) -> str:
if self._real is None:
self._real = HighResImage(self._file)
return self._real.show()
class Gallery:
"""Client: knows only the Image interface."""
def __init__(self, images: list[Image]) -> None:
self._images = images
def open(self, i: int) -> str:
return self._images[i].show()
if __name__ == "__main__":
gallery = Gallery(
[ImageProxy("a.png"), ImageProxy("b.png"), ImageProxy("c.png")]
)
print("gallery ready, loads:", HighResImage.loads) # 0
print(gallery.open(0)) # loads a.png first
print(gallery.open(0)) # no second load
print("loads:", HighResImage.loads) # 1Key takeaways
- A proxy implements the same interface as the real object and holds a reference to it, so it can stand in anywhere and decide on every call whether, when and how to forward it.
- The kinds differ only in what they control: virtual (when the object is created), protection (who may call), caching (whether a call is needed), remote (where it runs), smart reference (what happens around each access).
- In the visualizer, the virtual proxy creates
HighResImageon first use (1 load instead of 3), and one shared caching proxy turns 3 requests into 1 query where per-caller caches needed 2. - In the access-check change request, Proxy adds 1 class and edits none; without it, both screens are edited (10 lines) and every future screen must remember the check.
- Same structure as Decorator, different intent: a decorator adds behavior and is stacked by the client, a proxy controls access and usually manages its subject. Adapter changes the interface; Facade simplifies many objects.
- Proxies cost an extra hop per call, move (not remove) the cost of lazy loading, and break identity checks:
proxy !== real, and calls that bypass the proxy are not controlled.
Common pitfalls
- Lazy initialization that is not thread-safe. Two threads can both see
real === nulland create two real objects; guard a shared virtual proxy with a lock or a thread-safe lazy holder. - Equality and type checks on proxies.
getClass()comparisons, identity-keyed maps andinstanceofon concrete classes misbehave when a proxy (an ORM entity proxy, a framework proxy) stands in for the object. - Bypassing the proxy. A self-call like
this.save()inside the real object, or a reference to the real object leaked to callers, skips every check, cache and transaction the proxy provides. - Hiding remote calls behind a local-looking interface. Callers then forget timeouts, retries and partial failure, and loops that look cheap make one network round trip per iteration (the ORM N+1 problem is the same trap).
- Caching without an invalidation rule. A caching proxy that never expires or evicts serves stale data and grows without bound; decide on a lifetime and a size limit up front.
Interview tips
- Draw the two relations that define the pattern: the proxy implements the subject interface and holds the real subject. Then name the kind you are drawing (virtual, protection, caching, remote) and say what it controls.
- Expect "Proxy vs Decorator". Same diagram; the difference is intent (control access vs add behavior), who creates the real object (often the proxy) and whether stacking is the point (Decorator).
- Real examples land well: Hibernate lazy proxies and
LazyInitializationException, gRPC client stubs, Spring's@Transactionalproxies and the self-invocation trap,std::shared_ptr, JavaScript'sProxyobject. - If the discussion moves to systems, connect it to reverse proxies and API gateways: the same idea in front of servers instead of objects.
Real-world applications
- Lazy loading of large resources: images, documents, ORM entities and associations loaded on first access.
- Access control: permission checks, read-only views and rate limits enforced in one place in front of a service.
- Caching and memoization of slow queries, remote calls or expensive computations behind an unchanged interface.
- Remote objects: RPC client stubs (gRPC, Java RMI) that make a call on another machine look like a local method call.
- Framework features: transactions, method security and caching added by proxies generated around application objects (Spring AOP).
- Resource management and reactivity: reference-counting smart pointers, and change tracking with JavaScript
Proxy(Vue 3, Immer).
Test yourself
What makes it possible for Gallery to use an ImageProxy without any change to its code?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.