Proxy

A stand-in that controls access to another object — virtual (lazy), protection, remote, caching and logging proxies, dynamic proxies in Java, JavaScript Proxy objects, and how frameworks use them.

Intermediate 2 min readLesson 11 of 24

Intent: provide a surrogate or placeholder for another object to control access to it. The proxy has the same interface as the real object, so clients can't tell the difference.

requestforwards (maybe)ClientProxysame interfaceReal subjectexpensive / remote / protected

Kinds of proxy

KindControlsExample
VirtualWhen the real object is createdLazy-load a big image or an ORM relation on first access
ProtectionWho may call itCheck permissions before delegating
RemoteWhere it livesA local stub for an object on another machine (gRPC stubs, Java RMI)
CachingWhether to call at allReturn cached results for repeated calls
Logging / metricsObserves callsRecord timings and arguments
Smart referenceLifecycleReference counting, releasing resources

Virtual proxy (lazy loading)

interface Image { void display(); }

class HighResImage implements Image {
    private final byte[] pixels;
    HighResImage(String path) { this.pixels = loadFromDisk(path); }   // slow
    public void display() { /* draw pixels */ }
}

class LazyImage implements Image {
    private final String path;
    private HighResImage real;                     // not loaded yet
    LazyImage(String path) { this.path = path; }

    public void display() {
        if (real == null) real = new HighResImage(path);   // load on first use
        real.display();
    }
}

List<Image> gallery = paths.stream().map(LazyImage::new).toList();  // instant
gallery.get(0).display();                                          // only this one loads

Protection and caching proxies

class SecuredDocumentStore implements DocumentStore {
    private final DocumentStore real;
    private final CurrentUser user;
    SecuredDocumentStore(DocumentStore real, CurrentUser user) { this.real = real; this.user = user; }

    public Document get(String id) {
        if (!user.canRead(id)) throw new AccessDeniedException(id);
        return real.get(id);
    }
    public void delete(String id) {
        if (!user.isAdmin()) throw new AccessDeniedException(id);
        real.delete(id);
    }
}

Dynamic proxies

Writing a proxy class per interface is tedious. Runtimes can generate them:

// java.lang.reflect.Proxy: intercept every call on any 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); }
            finally {
                System.out.printf("%s took %d µs%n", method.getName(), (System.nanoTime() - start) / 1000);
            }
        });
}

OrderRepository repo = timed(new JdbcOrderRepository(ds), OrderRepository.class);

How frameworks use proxies

  • Spring AOP: @Transactional, @Cacheable, @Async work by wrapping your bean in a proxy (JDK dynamic proxy or CGLIB subclass) that starts a transaction, checks the cache, or submits to an executor before calling your method.
  • Hibernate/JPA lazy relations: order.getCustomer() returns a proxy that loads the row on first access (and throws LazyInitializationException if the session is closed).
  • Mocking libraries (Mockito, unittest.mock) generate proxies that record calls.
  • Vue, MobX, Immer use JS Proxies to track reads and writes.
Key takeaways
  • Proxy has the same interface as the real object and controls access to it.
  • Virtual (lazy), protection, remote, caching and logging are the main kinds.
  • Dynamic proxies (Java Proxy, JS Proxy, getattr) intercept calls generically.
  • Frameworks use proxies for transactions, lazy loading, caching and reactivity.