SyntaxPilot
Courses/Low-Level Design/Lesson 29
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 29 of 90

Proxy pattern

Proxy patternsubjectreal subjectproxyvirtual proxylazy loadingprotection proxyaccess controlremote proxycaching proxylogging proxydynamic proxyjava.lang.reflect.ProxyInvocationHandler

These are the notes for Low-Level Design (LLD) episode 29, the third structural pattern. The Decorator (episode 28) wrapped an object to add behaviour. Today's wrapper looks exactly the same from outside, but its job is different: it stands in front of the real object and controls access to it. That is the Proxy. We start with a society security guard, then watch Priya's menu screen load 25 MB to show one photo, and invent the virtual proxy (lazy loading). Then a protection proxy stops a customer from deleting dishes, a caching proxy turns three paid API calls into one, a remote proxy hides a network call, and dynamic proxies (java.lang.reflect.Proxy + InvocationHandler) let Java build the proxy class for you. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real.

1. The real-life idea: the society security guard

At the society gate In code
Priya's flat: where visitors want to go The real subject: the object doing the real work
The guard at the gate: every visitor meets him first The proxy: same interface, stands in front
He checks visitors, writes the register, holds parcels Access control: when, whether, how often the real object is used
Allowed visitors are sent up; the flat is unchanged The proxy forwards the call to the real object

A gated society is a housing complex with a gate and guards.

2. The problem: eager loading

Photo is an interface with one method, show(). HdPhoto (high-definition photo) loads a 5 MB file in its constructor. The menu screen creates a photo for each of 5 dishes; the user looks only at the first.

interface Photo { void show(); }

class HdPhoto implements Photo {                         // the real subject
    private final String file;
    HdPhoto(String file) {
        this.file = file;
        System.out.println("loading " + file + " (5 MB)");   // slow and heavy
    }
    public void show() { System.out.println("showing " + file); }
}

public class Main {
    public static void main(String[] args) {
        String[] dishes = {"dosa.jpg", "idli.jpg", "vada.jpg", "poha.jpg", "upma.jpg"};
        Photo[] menu = new Photo[5];
        for (int i = 0; i < 5; i++) menu[i] = new HdPhoto(dishes[i]);   // the menu screen opens
        menu[0].show();                                     // the user sees only the first one
    }
}
loading dosa.jpg (5 MB)
loading idli.jpg (5 MB)
loading vada.jpg (5 MB)
loading poha.jpg (5 MB)
loading upma.jpg (5 MB)
showing dosa.jpg

Eager loading means doing expensive work as early as possible, whether or not it's needed. Five loads, 25 MB, one photo shown. With 100 dishes the screen would freeze.

Why it failed

  • Creating an HdPhoto is loading it: construction and heavy work are glued together.
  • The menu needs a Photo object for every dish up front, so it can show any of them.
  • We want something that is a Photo, is cheap to create, and loads the real file only when someone actually looks.

3. The fix: a virtual proxy (lazy loading)

interface Photo { void show(); }

class HdPhoto implements Photo {                         // the real subject
    private final String file;
    HdPhoto(String file) {
        this.file = file;
        System.out.println("loading " + file + " (5 MB)");   // slow and heavy
    }
    public void show() { System.out.println("showing " + file); }
}
class PhotoProxy implements Photo {                       // the proxy: same interface
    private final String file;
    private HdPhoto real;                                   // not created yet
    PhotoProxy(String file) { this.file = file; }          // cheap: just a name
    public void show() {
        if (real == null) real = new HdPhoto(file);         // load on first use
        real.show();
    }
}

public class Main {
    public static void main(String[] args) {
        String[] dishes = {"dosa.jpg", "idli.jpg", "vada.jpg", "poha.jpg", "upma.jpg"};
        Photo[] menu = new Photo[5];
        for (int i = 0; i < 5; i++) menu[i] = new PhotoProxy(dishes[i]);
        menu[0].show();
        menu[0].show();                                     // scrolled back up
    }
}
loading dosa.jpg (5 MB)
showing dosa.jpg
showing dosa.jpg

PhotoProxy implements Photo, stores only the file name, and keeps real as null (no object yet). On the first show(), it creates the HdPhoto; later calls reuse it. Shown twice, loaded once; the other four photos are never loaded. The menu code didn't change a single call.

Lazy loading (also called lazy initialization) means doing expensive work only when it is first needed. A proxy that does this is a virtual proxy: "Defer the creation or loading of an expensive object until it is needed."

4. It has a name: the Proxy pattern

Intent: the Proxy pattern "provides a surrogate or placeholder for another object to control access to it." A surrogate is a substitute that acts on someone's behalf.

Role Meaning In our code
Subject The interface shared by the proxy and the real object Photo
Real subject The object doing the real work HdPhoto
Proxy Implements the subject, holds or creates the real subject, controls access, forwards calls PhotoProxy
Client Uses only the subject; can't tell proxy from real the menu screen (main)

5. Protection proxy: access control

RealMenu.deleteDish knows nothing about roles (what a user is allowed to be: owner or customer). A customer can delete a dish:

interface Menu { void deleteDish(String dish, String user); }

class RealMenu implements Menu {                           // knows nothing about roles
    public void deleteDish(String dish, String user) {
        System.out.println(dish + " deleted by " + user);
    }
}

public class Main {
    public static void main(String[] args) {
        Menu menu = new RealMenu();
        menu.deleteDish("paneer tikka", "priya (owner)");
        menu.deleteDish("masala dosa", "asha (customer)");   // a customer found the API
    }
}
paneer tikka deleted by priya (owner)
masala dosa deleted by asha (customer)

A protection proxy checks permissions, then forwards: "Add authentication or authorization checks before granting access." Authentication = checking who you are; authorization = checking what you may do.

import java.util.Set;

interface Menu { void deleteDish(String dish, String user); }

class RealMenu implements Menu {                           // knows nothing about roles
    public void deleteDish(String dish, String user) {
        System.out.println(dish + " deleted by " + user);
    }
}

class MenuGuard implements Menu {                          // protection proxy
    private final Menu real;
    private final Set<String> owners = Set.of("priya");
    MenuGuard(Menu real) { this.real = real; }
    public void deleteDish(String dish, String user) {
        if (!owners.contains(user)) throw new SecurityException(user + " may not delete dishes");
        real.deleteDish(dish, user);                        // allowed: pass it on
    }
}

public class Main {
    public static void main(String[] args) {
        Menu menu = new MenuGuard(new RealMenu());
        menu.deleteDish("paneer tikka", "priya");
        menu.deleteDish("masala dosa", "asha");
    }
}
paneer tikka deleted by priya
Exception in thread "main" java.lang.SecurityException: asha may not delete dishes
    at MenuGuard.deleteDish(Main.java:16)
    at Main.main(Main.java:25)

SecurityException is Java's built-in unchecked exception for a security rule being broken. Set.of(...) creates a small unmodifiable set (episode 4). RealMenu still contains no security code: the check lives in one place, in front of it.

6. Caching proxy (and logging proxy)

The app asks a maps web service for the distance between two places. Each call is slow and costs money. A cache is a store of answers we already got, so we don't ask again. computeIfAbsent(key, f) returns the saved value, or calls f, saves the result and returns it.

import java.util.*;

interface Distance { int km(String from, String to); }

class MapsApi implements Distance {                        // a slow, paid web service
    int calls = 0;
    public int km(String from, String to) { calls++; return 7; }   // pretend: 2 seconds, Rs 0.50
}
class CachedDistance implements Distance {                 // caching proxy
    private final Distance real;
    private final Map<String, Integer> saved = new HashMap<>();
    CachedDistance(Distance real) { this.real = real; }
    public int km(String from, String to) {
        return saved.computeIfAbsent(from + "->" + to, k -> real.km(from, to));
    }
}

public class Main {
    public static void main(String[] args) {
        MapsApi api = new MapsApi();
        Distance d = new CachedDistance(api);
        for (int i = 0; i < 3; i++)
            System.out.println("Koramangala -> HSR: " + d.km("Koramangala", "HSR") + " km");
        System.out.println("real API calls: " + api.calls);
    }
}
Koramangala -> HSR: 7 km
Koramangala -> HSR: 7 km
Koramangala -> HSR: 7 km
real API calls: 1

Three answers, one real call. A logging proxy has the same shape: write a log line, then forward. Real caches also need an expiry (forget old answers) and a size limit; see the homework.

Stacking proxies: the order matters

LoggedDistance is a logging proxy. With the cache outside, only real API calls reach the logger:

import java.util.*;

interface Distance { int km(String from, String to); }
class MapsApi implements Distance { public int km(String from, String to) { return 7; } }
class LoggedDistance implements Distance {                // logging proxy
    private final Distance real;
    LoggedDistance(Distance real) { this.real = real; }
    public int km(String from, String to) {
        System.out.println("LOG: API call " + from + " -> " + to);
        return real.km(from, to);
    }
}
class CachedDistance implements Distance {                // caching proxy
    private final Distance real;
    private final Map<String, Integer> saved = new HashMap<>();
    CachedDistance(Distance real) { this.real = real; }
    public int km(String from, String to) {
        return saved.computeIfAbsent(from + to, k -> real.km(from, to));
    }
}
public class Main {
    public static void main(String[] args) {
        Distance d = new CachedDistance(new LoggedDistance(new MapsApi()));   // cache outside
        for (int i = 0; i < 3; i++) System.out.println(d.km("HSR", "BTM") + " km");
    }
}
LOG: API call HSR -> BTM
7 km
7 km
7 km

Swap them (logger outside, cache inside) and every request is logged, including the ones the cache answers:

import java.util.*;

interface Distance { int km(String from, String to); }
class MapsApi implements Distance { public int km(String from, String to) { return 7; } }
class LoggedDistance implements Distance {                // logging proxy
    private final Distance real;
    LoggedDistance(Distance real) { this.real = real; }
    public int km(String from, String to) {
        System.out.println("LOG: API call " + from + " -> " + to);
        return real.km(from, to);
    }
}
class CachedDistance implements Distance {                // caching proxy
    private final Distance real;
    private final Map<String, Integer> saved = new HashMap<>();
    CachedDistance(Distance real) { this.real = real; }
    public int km(String from, String to) {
        return saved.computeIfAbsent(from + to, k -> real.km(from, to));
    }
}
public class Main {
    public static void main(String[] args) {
        Distance d = new LoggedDistance(new CachedDistance(new MapsApi()));   // log outside
        for (int i = 0; i < 3; i++) System.out.println(d.km("HSR", "BTM") + " km");
    }
}
LOG: API call HSR -> BTM
7 km
LOG: API call HSR -> BTM
7 km
LOG: API call HSR -> BTM
7 km

Neither order is wrong: decide what the log is for (counting paid calls vs. counting requests) and wrap in that order.

7. Remote proxy

A remote proxy represents an object that lives on another computer: it will "Represent an object located remotely, handling communication." Your code calls a method on a local object; the proxy turns the call into a network message (for example an HTTP request), sends it, waits for the reply and returns it as a normal result.

Your code Remote proxy (local) Server (real subject)
orders.place(o) turns the call into a request, sends it, decodes the reply does the real work

Examples: Java RMI (Remote Method Invocation) stubs, gRPC client stubs, and REST client libraries. Warning: it looks like a method call but it's a network call: slow, and it can fail. Good remote proxies use timeouts and throw clear exceptions.

8. Dynamic proxies: java.lang.reflect.Proxy

Writing a proxy class by hand for every interface is repetitive. Java can generate a proxy class while the program runs. You write one InvocationHandler: an interface with one method, invoke(proxy, method, args), that receives every call made on the proxy. Proxy.newProxyInstance(classLoader, interfaces, handler) creates an object that implements the given interfaces and dispatches every method call to the handler (with the proxy, a Method object naming the method, and an Object[] of arguments). A class loader is the part of the JVM that loads classes; Menu.class.getClassLoader() is the usual choice.

import java.lang.reflect.*;
import java.util.Arrays;

interface Menu { void deleteDish(String dish); int count(); }
class RealMenu implements Menu {
    public void deleteDish(String dish) { System.out.println("  deleted " + dish); }
    public int count() { return 42; }
}

public class Main {
    public static void main(String[] args) {
        Menu real = new RealMenu();
        InvocationHandler log = (proxy, method, params) -> {      // runs for EVERY method
            System.out.println("LOG: " + method.getName() + " " + Arrays.toString(params));
            return method.invoke(real, params);                    // then call the real object
        };
        Menu menu = (Menu) Proxy.newProxyInstance(
            Menu.class.getClassLoader(), new Class<?>[] { Menu.class }, log);
        menu.deleteDish("upma");
        System.out.println("  dishes: " + menu.count());
        RealMenu oops = (RealMenu) menu;                          // a proxy is not the class
    }
}
LOG: deleteDish [upma]
  deleted upma
LOG: count null
  dishes: 42
Exception in thread "main" java.lang.ClassCastException: class $Proxy0 cannot be cast to class RealMenu ($Proxy0 and RealMenu are in unnamed module of loader 'app')
    at Main.main(Main.java:21)
  • One handler logged every method, and would work for any interface.
  • count has no parameters, so params is null.
  • method.invoke(real, params) calls the same method on the real object. This uses reflection: inspecting and calling classes and methods at runtime by name.
  • The generated class is named $Proxy0. It implements Menu but is not a RealMenu, so the cast fails with ClassCastException. Always use the interface type.
  • JDK dynamic proxies work only for interfaces. Spring's documentation: "Spring AOP defaults to using standard JDK dynamic proxies for AOP proxies"; it uses CGLIB proxies when a class doesn't implement an interface. AOP (aspect-oriented programming) is Spring's feature for adding code (logging, security, transactions) around methods without editing them.

9. Proxy vs Decorator

Proxy Decorator
Interface same as the real object same as the wrapped object
Intent control access: when, whether, how often add behaviour
Who creates the inner object often the proxy itself (lazy) the client, building the stack
Layers usually one often many
Examples PhotoProxy, MenuGuard, CachedDistance, $Proxy0 Ginger, BufferedReader

In interviews, state the intent, not just the shape: the code can look identical.

Common mistakes

Mistake Exact message / symptom Why Fix
Heavy work in the constructor, for every object no error: 5 × loading … (5 MB), 1 photo shown Eager loading Virtual proxy: load on first use
No check in front of a dangerous method no error: masala dosa deleted by asha (customer) Nothing controls access Protection proxy checks the role
Casting a dynamic proxy to the class java.lang.ClassCastException: class $Proxy0 cannot be cast to class RealMenu The proxy only implements the interface Use the interface type
Clients create the real object directly no error: the guard is skipped Anyone can bypass the proxy Hand out only the proxy (a factory, episode 23)
Cache without expiry no error: stale distances forever Saved answers never refresh Store a timestamp, expire old entries
Lazy proxy shared by threads rare double loading Two threads see real == null at once Synchronize, or use the holder idiom (episode 22)

Mini project: a timing dynamic proxy

Write a generic method static <T> T timed(T real, Class<T> type) that returns a dynamic proxy which prints how long each method call took, in milliseconds. Use it on a Kitchen interface with cook(String dish) (sleeps 120 ms) and clean() (sleeps 30 ms).

Solution
import java.lang.reflect.*;

interface Kitchen { String cook(String dish); void clean(); }
class RealKitchen implements Kitchen {
    public String cook(String dish) { pause(120); return dish + " ready"; }
    public void clean() { pause(30); }
    static void pause(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } }
}

public class Main {
    @SuppressWarnings("unchecked")
    static <T> T timed(T real, Class<T> type) {
        InvocationHandler h = (proxy, method, params) -> {
            long start = System.nanoTime();
            Object result = method.invoke(real, params);
            long ms = (System.nanoTime() - start) / 1_000_000;
            System.out.println("  " + method.getName() + " took " + (ms >= 100 ? "100+" : "<100") + " ms");
            return result;
        };
        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] { type }, h);
    }
    public static void main(String[] args) {
        Kitchen k = timed(new RealKitchen(), Kitchen.class);
        System.out.println(k.cook("dosa"));
        k.clean();
    }
}
  cook took 100+ ms
dosa ready
  clean took <100 ms

(The real millisecond numbers change on every run, so this prints a range; print ms itself in your version.) timed works for any interface, which is exactly why frameworks use dynamic proxies.

Practice

1. In PhotoProxy, what happens if you move real = new HdPhoto(file) into the proxy's constructor?

Answer

It becomes eager again: every proxy loads its photo when created, and the proxy is pointless.

2. Write a LoggingDistance proxy and combine it with CachedDistance so that only real API calls are logged. Which wraps which?

Answer

new CachedDistance(new LoggingDistance(new MapsApi())). The cache is outside, so cached answers never reach the logger; only misses are logged.

3. Why should MenuGuard's constructor take a Menu, not create a RealMenu itself?

Answer

So it can guard any Menu (a test fake, a cached menu) and so the real object can be built in one place (dependency injection, episode 16). A factory then hands clients only the guarded menu.

4. Can Proxy.newProxyInstance proxy a class with no interface?

Answer

No. JDK dynamic proxies implement interfaces only. Libraries such as CGLIB or ByteBuddy generate subclasses for that; Spring uses CGLIB when a bean has no interface.

5. Name the proxy type: (a) an OrdersClient that sends HTTP requests to a server; (b) a wrapper that throws if the user isn't an admin; (c) a wrapper that remembers km("A","B").

Answer

(a) Remote proxy, (b) protection proxy, (c) caching proxy.

Quick quiz

Photo[] menu = new Photo[3];
for (int i = 0; i < 3; i++) menu[i] = new PhotoProxy("p" + i + ".jpg");
menu[2].show();
menu[2].show();
menu[0].show();

How many loading lines are printed? A. 0 B. 2 C. 3 D. 5

Answer

B, 2. p2 loads on its first show() only, p0 loads once, p1 is never shown so never loaded.

Interview questions

  1. What is the Proxy pattern? A structural pattern where a surrogate object with the same interface controls access to a real object.
  2. Name the participants. Subject, real subject, proxy, client.
  3. Kinds of proxies? Virtual (lazy creation), protection (access control), remote (network), caching, logging, smart reference (counting references, locking).
  4. What is lazy loading? Creating or loading something only when it's first needed.
  5. How does a JDK dynamic proxy work? Proxy.newProxyInstance generates a class implementing the given interfaces at runtime; every call goes to an InvocationHandler.invoke(proxy, method, args).
  6. Limitation of JDK dynamic proxies? Interfaces only; a cast to the concrete class fails with ClassCastException.
  7. Where are proxies used in real frameworks? Spring AOP (JDK dynamic proxies by default, CGLIB for classes), ORM lazy loading, RPC client stubs.
  8. Proxy vs Decorator? Same interface for both; Proxy controls access and often owns the real object; Decorator adds behaviour and is stacked by the client.
  9. Proxy vs Adapter? Proxy keeps the interface; Adapter changes it.
  10. How do you stop clients bypassing a proxy? Make the real class package-private or hide its constructor, and hand out proxies from a factory.

Glossary

Term Meaning, with an example
Proxy pattern A stand-in with the same interface that controls access to the real object. PhotoProxy
Subject The interface shared by proxy and real object. Photo
Real subject The object doing the real work. HdPhoto
Proxy Implements the subject, holds or creates the real subject, forwards calls
Surrogate / placeholder A substitute that acts for something else
Virtual proxy Creates or loads the real object only on first use
Lazy loading / lazy initialization Doing expensive work only when first needed
Eager loading Doing expensive work up front, needed or not
Protection proxy Checks permissions before forwarding. MenuGuard
Access control Deciding who may do what
Authentication / authorization Checking who you are / checking what you may do
Role A user's kind, which decides permissions: owner, customer
SecurityException Java's unchecked exception for a broken security rule
Caching proxy Saves answers and reuses them. CachedDistance
Cache A store of answers already obtained
computeIfAbsent Map method: return the saved value, or compute, save and return it
Logging proxy Logs each call, then forwards
Remote proxy A local object that forwards calls over the network to a real object on a server
RMI / gRPC stub Generated remote proxies in Java RMI and gRPC
Dynamic proxy A proxy class generated at runtime. Proxy.newProxyInstance(...)
java.lang.reflect.Proxy JDK class that creates dynamic proxy classes and instances
InvocationHandler Interface whose invoke(proxy, method, args) receives every call on a dynamic proxy
Reflection Inspecting and calling classes and methods at runtime. method.invoke(real, params)
Class loader The part of the JVM that loads classes
ClassCastException Thrown when an object is cast to a type it isn't
AOP Aspect-oriented programming: adding code around methods without editing them (Spring AOP)
CGLIB A library that generates subclasses at runtime; Spring uses it to proxy classes without interfaces
null "No object yet." real == null before the first show()

Summary

  • A proxy has the same interface as the real subject and stands in front of it, controlling access.
  • Virtual proxy: lazy loading on first use. Protection proxy: check, then forward. Caching and logging proxies: reuse answers, record calls. Remote proxy: hides a network call.
  • Dynamic proxies (Proxy.newProxyInstance + InvocationHandler) generate the proxy class at runtime for any interface; they implement interfaces only.
  • Proxy and Decorator look alike; Proxy controls access, Decorator adds behaviour.

Next episode: The Facade pattern.