Notes
The problem
Here is a doctor portal that needs a lab report. Before it can ask the HospitalLabArchive, it checks patient consent, looks in a cache, and opens the archive connection if that has not happened yet. Only then does it fetch. Every screen that shows a report repeats this, and so does the mobile app. Forget the consent check in one place and you have a privacy breach. The real work is one line; the rest is guarding it.
String view(String patient) {
if (!consents.allows(me, patient))
throw new SecurityException(...);
String hit = cache.get(patient);
if (hit != null) return hit;
if (archive == null)
archive = new HospitalLabArchive();
String r = archive.fetch(patient);
cache.put(patient, r);
return r;
} The idea
The idea in one sentence: put a stand in in front of the real object, with exactly the same interface. The client calls the stand in as if it were the real thing. The proxy decides when the real object is created, whether this call is allowed, and how the call reaches it. Because the interface is identical, the client code does not change at all, and it cannot tell a proxy from the real object.
- an object with the SAME
- interface as the real one,
- standing in front of it
- it decides when, whether
- and how a call reaches
- the real object
- the client cannot tell the
- difference
The structure
The participants. The subject is the LabReportService interface, with one method, fetch. The real subject is HospitalLabArchive, which reads from a slow archive. Then three proxies, each implementing the same interface: ConsentGuardProxy, CachingReportProxy and LazyArchiveProxy. Each one holds a reference to the next object and passes calls along. The DoctorPortal only knows the interface.
- subject: LabReportService
- real subject:
- HospitalLabArchive
- proxies (same interface):
- ConsentGuardProxy
- CachingReportProxy
- LazyArchiveProxy
- client: DoctorPortal
- each proxy holds the next
- object in the chain
Virtual proxy: lazy
First, the lazy proxy, also called a virtual proxy. Opening the archive connection is expensive, and many sessions never look at a report. So LazyArchiveProxy holds a supplier instead of the real object. On the first fetch it creates the archive, then forwards the call. Later calls go straight through. The method is synchronized, so two threads cannot both create the archive. Hibernate uses the same idea for entities it loads lazily.
final class LazyArchiveProxy
implements LabReportService {
private final Supplier<LabReportService>
maker;
private LabReportService real;
public synchronized String fetch(
String patientId) {
if (real == null) real = maker.get();
return real.fetch(patientId);
} Caching proxy
Second, the caching proxy. Doctors open the same report many times during a ward round. CachingReportProxy keeps a map from patient id to report. If the report is there, it returns it. If not, it asks the next object and stores the answer. In a real system you also add an expiry time and a size limit, so stale results and memory growth stay under control. The archive is now read once per patient.
final class CachingReportProxy
implements LabReportService {
private final LabReportService next;
private final Map<String, String> seen
= new ConcurrentHashMap<>();
public String fetch(String patientId) {
return seen.computeIfAbsent(
patientId, next::fetch);
}
} Protection proxy
Third, the protection proxy. ConsentGuardProxy knows which doctor is signed in. Before passing the call on, it asks the consent registry whether this doctor may see this patient. If not, it throws a security exception, and the call never reaches the cache or the archive. The archive class stays simple; it knows nothing about consent. Access rules now live in exactly one class.
final class ConsentGuardProxy
implements LabReportService {
public String fetch(String patientId) {
if (!consents.allows(doctorId,
patientId))
throw new SecurityException(
doctorId + " has no consent");
return next.fetch(patientId);
}
} Run-through
Follow a call. The portal calls fetch for patient P one zero four. The guard checks consent and passes it on. The cache misses, so it asks the lazy proxy, which opens the archive for the first time and reads the report. The answer flows back and is cached on the way. Notice the order: the guard sits in front of the cache. Put the cache first, and a doctor without consent could read a report another doctor already loaded.
Second call
Now the same doctor opens the report again. The guard allows it, the cache answers, and the archive is not touched. Then a second doctor, with no consent for this patient, asks for the same report through their own guard. The guard says no before the cache is even asked. Each proxy did one job, and none of them needed the others to change.
Remote proxy
Fourth, the remote proxy. The object you call is local and implements the interface, but each call is turned into a network request to another machine, and the reply is turned back into a return value. Java RMI stubs work this way, gRPC generated client stubs do too, and so do declarative HTTP clients such as OpenFeign, where you write only an interface. The danger is that a remote call looks cheap but can be slow or fail, so always add timeouts.
- local object, same interface
- turns each call into a
- network request and back
- examples:
- Java RMI stubs
- gRPC generated client stubs
- OpenFeign HTTP interfaces
- add timeouts: a remote call
- is not a cheap method call
Dynamic proxies
Writing a proxy class by hand for every interface gets repetitive. Java can generate one at runtime. The Proxy class in the java dot lang dot reflect package creates an object that implements the interfaces you list and sends every method call to one InvocationHandler. Here the handler times each call and forwards it to the target. One handler can add timing, logging or retries to any interface. The limit: JDK dynamic proxies work only for interfaces, not for plain classes.
InvocationHandler h =
(proxy, method, args) -> {
long t0 = System.nanoTime();
try {
return method.invoke(target, args);
} finally { log(method, t0); }
};
LabReportService timed =
(LabReportService) Proxy.newProxyInstance(
loader, new Class<?>[] {...}, h); Proxies in Spring
If you use Spring, you use proxies every day. The transactional, cacheable and async annotations, and method security, work because Spring hands other beans a proxy instead of your object. The proxy starts the transaction, then calls your method. It is either a JDK dynamic proxy or a generated CGLIB subclass, and Spring Boot uses CGLIB by default. The classic trap: calling another annotated method on this skips the proxy, so its transaction never starts.
- Spring wraps beans in proxies
- for @Transactional, @Cacheable,
- @Async and method security
- JDK dynamic proxy or a CGLIB
- subclass; Spring Boot picks
- CGLIB by default
- trap: this.save() inside the
- bean skips the proxy, so its
- @Transactional is ignored
Proxy vs Decorator
Proxy and Decorator look the same in a class diagram: both wrap an object with the same interface. The difference is intent. A proxy controls access to the real object. It often creates or owns that object, and the client usually does not know a proxy is there. A decorator adds behaviour, and the client builds the stack on purpose, around an object it already has. An adapter is different again: it changes the interface.
- both wrap an object with
- the same interface
- Proxy: controls ACCESS
- often creates or owns the
- real object; the client may
- not know it is there
- Decorator: adds BEHAVIOUR
- the client stacks them on
- purpose around its object
- Adapter: changes interface
When to use it
Reach for a proxy for lazy creation of heavy objects, for caching, for access checks kept in one place, for remote calls, and for logging, metrics or retries around an interface. Be careful when a proxy hides something important. A remote proxy makes a network call look like a cheap method call, and a stale cache can return old data. Every proxy layer is also one more thing to debug, so add them only for a real need.
- use a proxy for:
- • lazy creation of heavy
- objects
- • caching repeat reads
- • access checks in one place
- • remote calls behind an
- interface
- • logging, metrics, retries
- careful: a proxy can hide
- latency and stale data
In LLD interviews
In LLD interviews, proxies hide in plain sight. A rate limiter that wraps an API client and refuses calls over the limit is a protection proxy. A read through cache in front of a slow service is a caching proxy. A document store or file system design checks permissions in a proxy. An image gallery loads full size images only when opened. Common mistakes are putting the cache before the access check and lazy creation that is not thread safe.
- • rate limiter wrapping an
- API client: protection
- • cache in front of a slow
- service or database
- • file system or document
- store: permission checks
- • image gallery: load full
- images only when opened
- mistakes: cache before guard,
- unsafe lazy creation
Say it like this
How to say it. Clients only see the LabReportService interface. A consent guard proxy checks access first, a caching proxy answers repeat reads, and a lazy proxy opens the archive connection on first use. The real class only reads reports. Each proxy has one job, they can be added or removed without touching the client, and the guard must sit in front of the cache.
- "Clients see LabReportService.
- A consent guard proxy checks
- access first, a caching proxy
- answers repeats, and a lazy
- proxy opens the archive on
- first use. The real class
- only reads reports. Order
- matters: guard before cache."