Proxy pattern

On this page 7

The proxy pattern is a structural design pattern in which a surrogate object, the proxy, stands in for another object and controls access to it while exposing exactly the same interface. Clients call the proxy as if it were the real object, and the proxy decides whether, when and how to forward each request to the underlying real subject.

In software architecture and programming, the pattern is one of the 23 classic patterns cataloged by the Gang of Four in 1994. It underpins lazy loading in object-relational mappers, remote procedure call stubs, security wrappers, caching layers and the interception mechanisms of many frameworks, which makes it one of the most widely applied patterns in production code.

How the proxy pattern is structured

The proxy pattern is structured around a shared interface that both the proxy and the real object implement. Because the client depends only on that interface, the proxy can be substituted for the real object without any change to client code, which is a direct application of the Liskov substitution principle.

The proxy holds a reference to the real subject, or the information needed to obtain it, and implements each operation by performing its own logic before or after delegating the call. The table below names the participants and their responsibilities.

ParticipantResponsibilityKnows about
SubjectDeclares the common interfaceNothing beyond its own contract
Real subjectPerforms the actual workIts own data and resources
ProxyControls access and delegates callsThe subject interface and the real subject
ClientUses the object through the interfaceOnly the subject interface
Participants in the proxy pattern

The defining feature is access control, not added behavior. The proxy may delay, reject, log, cache or redirect a call, but from the client perspective the semantics of each operation stay those of the real subject.

Types of proxies and when each applies

Proxies are usually classified by the reason access needs to be controlled. Each variant keeps the same structure but places different logic around the delegated call, and a single proxy class can combine several of these roles.

Proxy typeWhat it controlsTypical example
Virtual proxyExpensive creation, deferred until first useLazy-loaded database entity or large image
Remote proxyAccess to an object in another processgRPC or Java RMI client stub
Protection proxyPermission checks before each callRole-based access to administrative operations
Caching proxyRepeated calls with identical resultsMemoized pricing or configuration lookups
Logging proxyObservation of calls and timingsAudit trail or performance tracing
Smart referenceLifetime and reference countingC++ smart pointers releasing a resource
Common proxy variants and their purpose

The virtual proxy is especially common in object-relational mapping. Frameworks such as Hibernate return a generated subclass of an entity whose fields are filled from the database only when a getter is first called, which keeps initial queries small.

Proxy compared with decorator, adapter and facade

The proxy pattern looks structurally similar to several other wrapper patterns, and the difference lies mainly in intent. Confusing them leads to classes with unclear responsibilities, so the distinction matters in design reviews.

PatternInterface toward clientPrimary intent
ProxySame as the wrapped objectControl access to the object
DecoratorSame as the wrapped objectAdd responsibilities dynamically
AdapterDifferent from the wrapped objectMake incompatible interfaces work together
FacadeNew, simplified interfaceHide a complex subsystem
Proxy and related structural patterns

A practical rule separates proxy from decorator: a proxy usually manages the lifecycle of its subject or decides whether to call it at all, whereas a decorator always delegates and is typically stacked by the client at run time. In real code the boundary blurs, and a caching wrapper may reasonably be described either way.

Implementing proxies in modern languages

Proxies can be written by hand or generated at run time. A static proxy is an ordinary class that implements the interface and delegates explicitly; it is easy to read but requires one class per interface and must be updated whenever the interface changes.

A dynamic proxy is generated by the runtime and routes every call through a single handler. Java offers java.lang.reflect.Proxy for interfaces, while libraries such as ByteBuddy generate subclasses; .NET provides DispatchProxy; and JavaScript has a built-in Proxy object with traps for property access. Spring uses dynamic proxies to implement declarative transactions, security and caching, which is why annotations like @Transactional work without changes to business classes.

The table below helps choose an implementation strategy.

SituationRecommended approachReason
One small interface, specific logicStatic proxyExplicit, debuggable and type-checked
Same concern across many interfacesDynamic proxyOne handler covers every method
Concrete classes without interfacesSubclass generationInterface-based proxies cannot wrap them
Calls across a network boundaryGenerated remote stubSerialization code is produced automatically
Choosing a proxy implementation

Pitfalls and design cautions

The proxy pattern is simple in principle, yet several recurring defects appear in systems that rely on it heavily.

  • Self-invocation bypass: a method calling another method on the same object skips the proxy, so framework features such as transactions silently do not apply.
  • Hidden latency: a remote proxy makes a network call look like a local method call, which encourages chatty designs with many round trips.
  • Lazy loading outside its scope: touching a virtual proxy after its session closes raises errors such as Hibernate’s LazyInitializationException.
  • Identity and equality surprises: a proxy is a different object from its subject, so reference comparisons and type checks may fail.
  • Debugging overhead: generated proxies add stack frames and obscure which code actually ran.

The simple explanation

A proxy is like a receptionist who sits in front of a busy manager. Visitors talk to the receptionist exactly as they would to the manager, but the receptionist decides who gets through, when, and whether a question can be answered without disturbing anyone.

In software, the proxy looks just like the real object to the rest of the program. Behind that familiar face, it can wait to create something expensive until it is really needed, check permissions, remember earlier answers or forward a request to another computer. The caller does not need to know any of this is happening.

How it is used in practice

An online retailer exposes a ProductCatalog interface used by about 40 services. The real implementation queries a pricing database that takes roughly 120 milliseconds per call during peak traffic. The architecture team introduces a caching proxy that implements the same interface, keeps results for 60 seconds and forwards only cache misses to the real catalog.

A second protection proxy, wrapped around the first, rejects price-changing operations unless the caller holds an administrative role. No calling service changes a single line, because each one still receives a ProductCatalog through dependency injection. After rollout, median lookup latency falls to a few milliseconds and database load drops by more than half, while access rules are now enforced in one place.