LOW-LEVEL DESIGN · STRUCTURAL PATTERNS · STRUCTURAL · 33 OF 48

Proxy Pattern in Java: Lazy, Caching, Protection and Remote

The Proxy pattern through a hospital lab report service: a protection proxy that checks consent, a caching proxy, a lazy proxy that opens the archive on first use, remote proxies, JDK dynamic proxies with java.lang.reflect.Proxy, how Spring uses proxies, Proxy vs Decorator, and where proxies appear in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 17

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 172 lines, with a small main() demo. Save it as LabReportProxyDemo.java, then run javac LabReportProxyDemo.java && java LabReportProxyDemo.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * Proxy: stand-ins with the same interface as a slow lab archive.
 * Problem first (a screen does consent, caching and set-up itself), then guard, cache and lazy proxies,
 * and finally a JDK dynamic proxy that times every call.
 */
public class LabReportProxyDemo {

    /** The subject: the only type clients see. */
    interface LabReportService {
        String fetch(String patientId);
    }

    /** The real subject: costly to open, slow to read. It knows nothing about consent or caching. */
    static final class HospitalLabArchive implements LabReportService {
        static int opened = 0;
        static int reads = 0;

        HospitalLabArchive() {
            opened++;
            System.out.println("    (opening the archive connection: slow)");
        }

        @Override
        public String fetch(String patientId) {
            reads++;
            return "report " + patientId + ": HbA1c 6.1 percent";
        }
    }

    record ConsentRegistry(Map<String, Set<String>> patientsByDoctor) {
        boolean allows(String doctorId, String patientId) {
            return patientsByDoctor.getOrDefault(doctorId, Set.of()).contains(patientId);
        }
    }

    // ---------- the problem: the screen guards, caches and connects by itself, in every screen ----------
    static final class NaiveDoctorScreen {
        private final ConsentRegistry consents;
        private final String doctorId;
        private final Map<String, String> cache = new HashMap<>();
        private HospitalLabArchive archive;

        NaiveDoctorScreen(ConsentRegistry consents, String doctorId) {
            this.consents = consents;
            this.doctorId = doctorId;
        }

        String view(String patientId) {
            if (!consents.allows(doctorId, patientId)) {
                throw new SecurityException(doctorId + " has no consent");
            }
            String hit = cache.get(patientId);
            if (hit != null) return hit;
            if (archive == null) archive = new HospitalLabArchive();
            String report = archive.fetch(patientId);
            cache.put(patientId, report);
            return report;
        }
    }

    // ---------- proxies: same interface, one job each ----------
    /** Virtual proxy: the archive is created on the first real request, once. */
    static final class LazyArchiveProxy implements LabReportService {
        private final Supplier<LabReportService> maker;
        private LabReportService real;

        LazyArchiveProxy(Supplier<LabReportService> maker) { this.maker = maker; }

        @Override
        public synchronized String fetch(String patientId) {
            if (real == null) real = maker.get();
            return real.fetch(patientId);
        }
    }

    /** Caching proxy: repeat reads never reach the archive. A real one adds expiry and a size limit. */
    static final class CachingReportProxy implements LabReportService {
        private final LabReportService next;
        private final Map<String, String> seen = new ConcurrentHashMap<>();

        CachingReportProxy(LabReportService next) { this.next = next; }

        @Override
        public String fetch(String patientId) { return seen.computeIfAbsent(patientId, next::fetch); }
    }

    /** Protection proxy: one per signed-in doctor. It must sit in front of the cache. */
    static final class ConsentGuardProxy implements LabReportService {
        private final LabReportService next;
        private final ConsentRegistry consents;
        private final String doctorId;

        ConsentGuardProxy(LabReportService next, ConsentRegistry consents, String doctorId) {
            this.next = next;
            this.consents = consents;
            this.doctorId = doctorId;
        }

        @Override
        public String fetch(String patientId) {
            if (!consents.allows(doctorId, patientId)) {
                throw new SecurityException(doctorId + " has no consent");
            }
            return next.fetch(patientId);
        }
    }

    /** The client: it only knows the interface, so it cannot tell proxies from the real thing. */
    record DoctorPortal(String name, LabReportService reports) {
        void open(String patientId) {
            try {
                System.out.println("  " + name + " sees: " + reports.fetch(patientId));
            } catch (SecurityException e) {
                System.out.println("  " + name + " blocked: " + e.getMessage());
            }
        }
    }

    // ---------- a dynamic proxy: one handler that times calls on any interface ----------
    static LabReportService timed(LabReportService target) {
        InvocationHandler handler = (proxy, method, args) -> {
            long t0 = System.nanoTime();
            try {
                return method.invoke(target, args);
            } catch (InvocationTargetException e) {
                throw e.getCause();   // rethrow what the target really threw
            } finally {
                System.out.println("    [timing] " + method.getName() + " took "
                        + (System.nanoTime() - t0) / 1_000 + " microseconds");
            }
        };
        return (LabReportService) Proxy.newProxyInstance(
                LabReportService.class.getClassLoader(), new Class<?>[] {LabReportService.class}, handler);
    }

    public static void main(String[] args) {
        ConsentRegistry consents = new ConsentRegistry(
                Map.of("dr-17", Set.of("P-104"), "dr-9", Set.of("P-220")));

        System.out.println("Before: the screen does everything itself");
        NaiveDoctorScreen screen = new NaiveDoctorScreen(consents, "dr-17");
        System.out.println("  " + screen.view("P-104"));
        HospitalLabArchive.opened = 0;
        HospitalLabArchive.reads = 0;

        System.out.println("After: guard, then cache, then lazy archive");
        LabReportService shared = new CachingReportProxy(new LazyArchiveProxy(HospitalLabArchive::new));
        DoctorPortal first = new DoctorPortal("dr-17", new ConsentGuardProxy(shared, consents, "dr-17"));
        DoctorPortal second = new DoctorPortal("dr-9", new ConsentGuardProxy(shared, consents, "dr-9"));
        System.out.println("  portals ready, archives opened so far: " + HospitalLabArchive.opened);

        first.open("P-104");    // guard ok, cache miss, lazy proxy opens the archive, one slow read
        first.open("P-104");    // guard ok, cache hit, archive untouched
        second.open("P-104");   // stopped by the guard before the cache is asked
        System.out.println("  archives opened: " + HospitalLabArchive.opened
                + ", slow reads: " + HospitalLabArchive.reads);

        System.out.println("Dynamic proxy around the same chain");
        LabReportService withTiming = timed(new ConsentGuardProxy(shared, consents, "dr-17"));
        System.out.println("  " + withTiming.fetch("P-104"));
        System.out.println("  is a generated proxy class? " + Proxy.isProxyClass(withTiming.getClass()));
    }
}

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.

Inside every screen
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.

Proxy in plain words
  • 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.

Participants
  • 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.

LazyArchiveProxy
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.

CachingReportProxy
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.

ConsentGuardProxy
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.

Remote proxies
  • 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.

One handler, any interface
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 uses proxies
  • 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.

Look alike, act differently
  • 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 it or skip it
  • 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.

Where it shows up
  • • 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.

In the interview
  • "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."

Interview questions

What is the Proxy pattern?

A proxy is an object that implements the same interface as a real object and stands in front of it. It controls access to the real object: it can create it lazily, cache results, check permissions or forward calls over a network, while the client code stays unchanged.

What kinds of proxy are there?

The common kinds are the virtual proxy (creates an expensive object on first use), the caching proxy (answers repeat requests), the protection proxy (checks access rights) and the remote proxy (hides a network call behind a local object). Logging and metrics proxies are also common.

What is the difference between Proxy and Decorator?

Structurally they are the same: both wrap an object that shares their interface. A proxy controls access and often creates or owns the real object, usually without the client knowing. A decorator adds behaviour and is stacked on purpose by the client around an object it already has.

How do JDK dynamic proxies work?

java.lang.reflect.Proxy.newProxyInstance generates, at runtime, a class that implements the given interfaces and routes every method call to one InvocationHandler. The handler receives the Method and arguments and usually forwards to a real target with extra logic around it. It works only for interfaces.

Why does @Transactional not work when a method calls another method on this?

Spring applies @Transactional through a proxy around the bean. A call from outside goes through the proxy, which starts the transaction. A call on this inside the bean goes straight to the object, skipping the proxy, so the annotation on the inner method has no effect.

How do you make a lazy proxy thread safe?

Guard the creation so only one thread builds the real object, for example with a synchronized method, double-checked locking on a volatile field, or a holder that initialises once. Without this, two threads can both see null and create two expensive objects.

Where would you place a cache relative to an access check?

The access check must come first. If a caching proxy sits in front of the protection proxy, a caller without permission could get a result another caller already loaded into the cache. Order the chain as guard, then cache, then the real object.

What is the risk of a remote proxy?

It makes a network call look like an ordinary method call, so callers may forget it can be slow, time out or fail partway. Remote proxies need timeouts, retries with care, and clear error types so callers handle failure.