Patterns for structure · Chapter 13

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.

IntermediateInterview priority: Medium45 min
On this page
  1. The problem: paying for objects nobody uses
  2. The idea: a stand-in with the same interface
  3. Build it: a virtual proxy and a protection proxy
  4. Caching and remote proxies
  5. Proxies that frameworks write for you
  6. Proxy, Decorator, Adapter, Facade: how they differ
  7. When not to use it
  8. In the interview
  9. Quiz

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

  1. 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.
RoleIn this exampleResponsibility
Subject (interface)PhotoWhat callers depend on: display()
Real subjectRealPhotoDoes the real, expensive or sensitive work
ProxyLazyPhoto, GuardedPhotoSame interface; holds or creates the real subject and controls calls to it
ClientThe gallery screenUses Photo and never knows whether it holds a proxy

The four classic kinds differ only in what they control:

KindControlsEveryday example
Virtual proxyWhen the real object is created: on first useHibernate lazy-loaded entities, image placeholders
Protection proxyWhether a caller may use itPermission checks, read-only views
Caching proxyWhether the real call is needed at allA cache in front of a slow service
Remote proxyWhere it runs: the real object is on another machinegRPC 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

  1. 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());
        }
    }
}

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

  1. 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;
    }
}

If 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

  1. 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, @Cacheable and @Async work 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 of Customer that runs the SQL query the first time you call a getter on it.
  • Java's java.lang.reflect.Proxy creates an object implementing any interfaces at run time, sending every call to one InvocationHandler. Mocking libraries such as Mockito build on the same idea.
  • Python: unittest.mock.Mock objects and weakref.proxy are 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

  1. 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.
ProxyDecoratorAdapterFacade
InterfaceSame as the real objectSame as the wrapped objectDifferent: converts to the expected oneNew and simpler
IntentControl access: lazy, guarded, cached, remoteAdd featuresMake it fitMake a subsystem easy to use
Who creates the real objectOften the proxy itself (lazy, remote)Always passed in by the clientPassed inThe facade owns its parts
Stacked by clients?Rarely; usually set up by a framework or factoryYes, freelyRarelyNo
May skip the real call?Yes, that is often the pointRarely; it normally always delegatesNon/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

Your turn: a document service

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.

Your turn: the requirement changes

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.

Proxy on one page
  • 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 synchronized so 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.
Interactive labPractise it: load a photo gallery without loading every photoOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

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?

2. Two threads call display() on the same lazy proxy at the same moment, and the proxy has no locking. What can happen?

3. In a Spring service, checkout() calls this.reserveStock(), which is annotated @Transactional(propagation = REQUIRES_NEW). No new transaction starts. Why?

4. Which wrapper is best described as a proxy rather than a decorator?

5. A loop prints order.getCustomer().getName() for 500 orders loaded with JPA, and the database log shows 501 queries. What is going on?

6. A gRPC client stub is a remote proxy. Which risk is most specific to remote proxies?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.