On this page

Proxy

A proxy is an object that stands in for another object and has exactly the same interface. Callers think they're talking to the real thing. In between, the proxy gets to decide whether, when and how the real object is reached: it can delay creating it, refuse the call, answer from a cache, send the call across a network or write a log line first.

The structural patterns overview introduces Proxy with a short caching example. This page goes further. It covers the five kinds of proxy you'll meet in real code, the dynamic proxies that frameworks generate for you, the self-invocation trap that catches almost every Spring developer once, and how to tell a proxy apart from a decorator when an interviewer asks.

Intent

Provide a surrogate for another object so you can control access to it, without the caller knowing or caring that the surrogate is there.

Three words in that sentence do the work:

  • Surrogate. The proxy implements the same interface as the real object (the subject), so it can be passed anywhere the real one could.
  • Control. The point of a proxy is a policy about access: lazy creation, permission, location, caching, auditing. If the wrapper adds new features to the result instead, you're probably looking at a decorator.
  • Without the caller knowing. Client code doesn't change when a proxy is added or removed. That's what makes proxies a good home for cross-cutting concerns.

The problem

Here's a reporting module in an internal admin tool. WarehouseReports is expensive to construct (it opens a connection pool and compiles templates), some reports are restricted to the finance team, and rendering is slow enough that people want caching. The first version puts all of those concerns into the HTTP endpoint.

import java.util.*;

class WarehouseReports {
    static int instances = 0;
    WarehouseReports() { instances++; }               // pretend: opens a pool, compiles templates
    String render(String id) { return "report:" + id; }
}

class ReportEndpoint {
    private WarehouseReports reports;                  // built lazily
    private final Map<String, String> cache = new HashMap<>();
    final List<String> log = new ArrayList<>();

    String get(String id, Set<String> roles) {
        log.add("GET " + id);                                           // logging
        if (id.startsWith("finance/") && !roles.contains("FINANCE"))    // access control
            throw new SecurityException("denied: " + id);
        String hit = cache.get(id);                                     // caching
        if (hit != null) return hit;
        if (reports == null) reports = new WarehouseReports();          // lazy creation
        String out = reports.render(id);
        cache.put(id, out);
        return out;
    }
}

class NightlyExportJob {
    // A second caller. It forgot the access check and the cache,
    // and builds its own expensive instance.
    String export(String id) { return new WarehouseReports().render(id); }
}

class Demo {
    public static void main(String[] args) {
        ReportEndpoint endpoint = new ReportEndpoint();
        assert endpoint.get("sales/q3", Set.of()).equals("report:sales/q3");
        assert endpoint.get("sales/q3", Set.of()).equals("report:sales/q3");
        assert WarehouseReports.instances == 1;

        new NightlyExportJob().export("finance/q3");   // no check at all
        assert WarehouseReports.instances == 2;        // and a second pool
        System.out.println("before: works, but every caller re-implements the policies");
    }
}
class WarehouseReports:
    instances = 0

    def __init__(self) -> None:
        WarehouseReports.instances += 1        # pretend: opens a pool, compiles templates

    def render(self, report_id: str) -> str:
        return f"report:{report_id}"


class ReportEndpoint:
    def __init__(self) -> None:
        self._reports: WarehouseReports | None = None
        self._cache: dict[str, str] = {}
        self.log: list[str] = []

    def get(self, report_id: str, roles: set[str]) -> str:
        self.log.append(f"GET {report_id}")                                  # logging
        if report_id.startswith("finance/") and "FINANCE" not in roles:      # access control
            raise PermissionError(f"denied: {report_id}")
        if report_id in self._cache:                                         # caching
            return self._cache[report_id]
        if self._reports is None:                                            # lazy creation
            self._reports = WarehouseReports()
        out = self._reports.render(report_id)
        self._cache[report_id] = out
        return out


class NightlyExportJob:
    def export(self, report_id: str) -> str:
        return WarehouseReports().render(report_id)   # no check, no cache, new pool


endpoint = ReportEndpoint()
assert endpoint.get("sales/q3", set()) == "report:sales/q3"
assert endpoint.get("sales/q3", set()) == "report:sales/q3"
assert WarehouseReports.instances == 1
NightlyExportJob().export("finance/q3")
assert WarehouseReports.instances == 2
print("before: works, but every caller re-implements the policies")

The code works, and that's the trap. Look at what's wrong with it:

  1. Four policies are tangled in one method. Logging, access control, caching and lazy creation each have their own reasons to change, so the endpoint changes for all of them. That's a single responsibility problem.
  2. Every new caller has to remember every policy. NightlyExportJob forgot two of them. One of the forgotten ones is a security check. Nothing in the type system stops this, because WarehouseReports is directly reachable.
  3. The policies can't be tested alone. To test caching you have to go through the access check. To test the access check you have to build the real reports engine.
  4. Ordering is implicit. Is the check before the cache on purpose? (It is, and it matters, as we'll see later.) Nobody can tell from reading the code.

What we want: one object that callers can't get around, with the same render method as the real thing, so the policies live in front of the real object rather than inside each caller.

Structure

classDiagram
    direction LR
    class Client
    class ReportService {
        <<interface>>
        +render(reportId) String
    }
    class WarehouseReportService {
        +render(reportId) String
    }
    class ReportServiceProxy {
        -inner ReportService
        +render(reportId) String
    }
    Client --> ReportService : uses
    ReportService <|.. WarehouseReportService
    ReportService <|.. ReportServiceProxy
    ReportServiceProxy o--> ReportService : controls access to

The proxy holds a reference to the subject interface (or, for a virtual proxy, a way to create the real subject later). Because the proxy also is a ReportService, proxies can wrap other proxies. That gives you a chain, with each link owning one policy:

sequenceDiagram
    participant C as Client
    participant A as AccessControlProxy
    participant K as CachingProxy
    participant L as LazyProxy
    participant R as WarehouseReportService
    C->>A: render("finance/q3")
    A->>A: check caller has FINANCE role
    A->>K: render("finance/q3")
    K->>K: cache miss
    K->>L: render("finance/q3")
    L->>R: create on first use, then render
    R-->>L: report
    L-->>K: report
    K->>K: store in cache
    K-->>A: report
    A-->>C: report

On the second call for the same report, the chain stops at CachingProxy, and the real service never hears about it.

Participants

ParticipantRole in the exampleResponsibility
SubjectReportServiceThe interface that both the real object and the proxy implement. Clients depend only on this.
Real subjectWarehouseReportServiceDoes the actual work. Knows nothing about proxies.
ProxyLazyReportService, AccessControlledReportService, CachingReportServiceImplements the subject, holds (or can create) a reference to the real subject, and applies one access policy before, after or instead of delegating.
ClientThe endpoint and the export jobCalls the subject interface. Gets a proxy from wiring code (a constructor, a factory or a DI container) and can't tell the difference.

The interface is the important part. If clients depend on the concrete WarehouseReportService class, you can't put anything in front of it without a framework generating a subclass for you (which is exactly what CGLIB does for Spring, more on that below).

The five kinds of proxy

The structure is always the same. What changes is the policy:

KindControlsTypical triggerExample
VirtualWhen the real object is createdThe real object is expensive and often not neededHibernate lazy associations, image placeholders
ProtectionWhether the caller may use itDifferent callers have different rightsRole checks, read-only views
RemoteWhere the real object livesThe real object is in another process or machinegRPC stubs, Java RMI, xmlrpc.client.ServerProxy
CachingWhether the real object needs to be called at allResults are expensive and safe to reuseMemoising a slow lookup
Logging / monitoringWhat gets recorded around each callAuditing, metrics, tracingMethod timing, audit trails

Some authors add a "smart reference" proxy (one that counts references or locks the object during a call). It's the same idea with a different policy.

Implementation

The implementation below builds the three most common proxies (virtual, protection and caching) and stacks them. The client code at the bottom only sees ReportService.

import java.util.*;
import java.util.function.Supplier;

interface ReportService {
    String render(String reportId);
}

// Real subject: expensive to build, slow to call.
final class WarehouseReportService implements ReportService {
    static int instances = 0;
    int renders = 0;

    WarehouseReportService() { instances++; }

    @Override public String render(String reportId) {
        renders++;
        return "report:" + reportId + ":run" + renders;
    }
}

// Virtual proxy: builds the real subject on first use.
final class LazyReportService implements ReportService {
    private final Supplier<? extends ReportService> factory;
    private ReportService real;

    LazyReportService(Supplier<? extends ReportService> factory) { this.factory = factory; }

    @Override public synchronized String render(String reportId) {
        if (real == null) real = factory.get();
        return real.render(reportId);
    }
}

record User(String name, Set<String> roles) {}

// Protection proxy: refuses calls the current user isn't allowed to make.
final class AccessControlledReportService implements ReportService {
    private final ReportService inner;
    private final Supplier<User> currentUser;

    AccessControlledReportService(ReportService inner, Supplier<User> currentUser) {
        this.inner = inner;
        this.currentUser = currentUser;
    }

    @Override public String render(String reportId) {
        User user = currentUser.get();
        if (reportId.startsWith("finance/") && !user.roles().contains("FINANCE")) {
            throw new SecurityException(user.name() + " may not read " + reportId);
        }
        return inner.render(reportId);
    }
}

// Caching proxy: answers repeated calls without touching the real subject.
final class CachingReportService implements ReportService {
    private final ReportService inner;
    private final Map<String, String> cache = new HashMap<>();

    CachingReportService(ReportService inner) { this.inner = inner; }

    @Override public synchronized String render(String reportId) {
        return cache.computeIfAbsent(reportId, inner::render);
    }

    synchronized void invalidate(String reportId) { cache.remove(reportId); }
}

class Demo {
    public static void main(String[] args) {
        User[] current = { new User("asha", Set.of("FINANCE")) };
        WarehouseReportService[] realRef = new WarehouseReportService[1];

        CachingReportService cache = new CachingReportService(
                new LazyReportService(() -> realRef[0] = new WarehouseReportService()));
        ReportService service = new AccessControlledReportService(cache, () -> current[0]);

        // Virtual: nothing expensive happens at wiring time.
        assert WarehouseReportService.instances == 0;

        // Caching: the second call never reaches the real subject.
        String first = service.render("finance/q3");
        assert service.render("finance/q3").equals(first);
        assert WarehouseReportService.instances == 1;
        assert realRef[0].renders == 1;

        // Protection: a user without the role is refused before the cache is consulted.
        current[0] = new User("ben", Set.of("SALES"));
        try {
            service.render("finance/q3");
            throw new AssertionError("ben should have been refused");
        } catch (SecurityException expected) { }
        assert service.render("sales/q3").equals("report:sales/q3:run2");

        // Invalidation forces a fresh render.
        cache.invalidate("sales/q3");
        assert service.render("sales/q3").equals("report:sales/q3:run3");

        // The wrong order: cache OUTSIDE the access check leaks data.
        current[0] = new User("asha", Set.of("FINANCE"));
        ReportService leaky = new CachingReportService(
                new AccessControlledReportService(new WarehouseReportService(), () -> current[0]));
        leaky.render("finance/q3");                       // asha fills the cache
        current[0] = new User("ben", Set.of("SALES"));
        String leaked = leaky.render("finance/q3");       // ben is served from the cache
        assert leaked.startsWith("report:finance/q3");
        System.out.println("proxy chain ok, and the wrong order leaks: " + leaked);
    }
}
import threading
from dataclasses import dataclass
from typing import Callable, Protocol


class ReportService(Protocol):
    def render(self, report_id: str) -> str: ...


class WarehouseReportService:
    """Real subject: expensive to build, slow to call."""
    instances = 0

    def __init__(self) -> None:
        WarehouseReportService.instances += 1
        self.renders = 0

    def render(self, report_id: str) -> str:
        self.renders += 1
        return f"report:{report_id}:run{self.renders}"


class LazyReportService:
    """Virtual proxy: builds the real subject on first use."""

    def __init__(self, factory: Callable[[], ReportService]) -> None:
        self._factory = factory
        self._real: ReportService | None = None
        self._lock = threading.Lock()

    def render(self, report_id: str) -> str:
        if self._real is None:
            with self._lock:
                if self._real is None:          # another thread may have won the race
                    self._real = self._factory()
        return self._real.render(report_id)


@dataclass(frozen=True)
class User:
    name: str
    roles: frozenset[str]


class AccessControlledReportService:
    """Protection proxy: refuses calls the current user isn't allowed to make."""

    def __init__(self, inner: ReportService, current_user: Callable[[], User]) -> None:
        self._inner = inner
        self._current_user = current_user

    def render(self, report_id: str) -> str:
        user = self._current_user()
        if report_id.startswith("finance/") and "FINANCE" not in user.roles:
            raise PermissionError(f"{user.name} may not read {report_id}")
        return self._inner.render(report_id)


class CachingReportService:
    """Caching proxy: answers repeated calls without touching the real subject."""

    def __init__(self, inner: ReportService) -> None:
        self._inner = inner
        self._cache: dict[str, str] = {}
        self._lock = threading.Lock()

    def render(self, report_id: str) -> str:
        with self._lock:
            if report_id not in self._cache:
                self._cache[report_id] = self._inner.render(report_id)
            return self._cache[report_id]

    def invalidate(self, report_id: str) -> None:
        with self._lock:
            self._cache.pop(report_id, None)


if __name__ == "__main__":
    current = [User("asha", frozenset({"FINANCE"}))]
    real_ref: list[WarehouseReportService] = []

    def build() -> WarehouseReportService:
        real_ref.append(WarehouseReportService())
        return real_ref[0]

    cache = CachingReportService(LazyReportService(build))
    service: ReportService = AccessControlledReportService(cache, lambda: current[0])

    assert WarehouseReportService.instances == 0            # virtual: nothing built yet

    first = service.render("finance/q3")
    assert service.render("finance/q3") == first             # caching
    assert WarehouseReportService.instances == 1
    assert real_ref[0].renders == 1

    current[0] = User("ben", frozenset({"SALES"}))
    try:
        service.render("finance/q3")
        raise AssertionError("ben should have been refused")
    except PermissionError:
        pass                                                 # protection
    assert service.render("sales/q3") == "report:sales/q3:run2"

    cache.invalidate("sales/q3")
    assert service.render("sales/q3") == "report:sales/q3:run3"

    # The wrong order: cache OUTSIDE the access check leaks data.
    current[0] = User("asha", frozenset({"FINANCE"}))
    leaky = CachingReportService(
        AccessControlledReportService(WarehouseReportService(), lambda: current[0]))
    leaky.render("finance/q3")
    current[0] = User("ben", frozenset({"SALES"}))
    leaked = leaky.render("finance/q3")
    assert leaked.startswith("report:finance/q3")
    print("proxy chain ok, and the wrong order leaks:", leaked)
import assert from "node:assert/strict";

interface ReportService {
  render(reportId: string): string;
}

// Real subject: expensive to build, slow to call.
class WarehouseReportService implements ReportService {
  static instances = 0;
  renders = 0;
  constructor() {
    WarehouseReportService.instances++;
  }
  render(reportId: string): string {
    this.renders++;
    return `report:${reportId}:run${this.renders}`;
  }
}

// Virtual proxy: builds the real subject on first use.
class LazyReportService implements ReportService {
  private real: ReportService | null = null;
  constructor(private readonly factory: () => ReportService) {}
  render(reportId: string): string {
    this.real ??= this.factory();
    return this.real.render(reportId);
  }
}

interface User {
  readonly name: string;
  readonly roles: ReadonlySet<string>;
}

class AccessDenied extends Error {}

// Protection proxy: refuses calls the current user isn't allowed to make.
class AccessControlledReportService implements ReportService {
  constructor(
    private readonly inner: ReportService,
    private readonly currentUser: () => User,
  ) {}
  render(reportId: string): string {
    const user = this.currentUser();
    if (reportId.startsWith("finance/") && !user.roles.has("FINANCE")) {
      throw new AccessDenied(`${user.name} may not read ${reportId}`);
    }
    return this.inner.render(reportId);
  }
}

// Caching proxy: answers repeated calls without touching the real subject.
class CachingReportService implements ReportService {
  private readonly cache = new Map<string, string>();
  constructor(private readonly inner: ReportService) {}
  render(reportId: string): string {
    let hit = this.cache.get(reportId);
    if (hit === undefined) {
      hit = this.inner.render(reportId);
      this.cache.set(reportId, hit);
    }
    return hit;
  }
  invalidate(reportId: string): void {
    this.cache.delete(reportId);
  }
}

let current: User = { name: "asha", roles: new Set(["FINANCE"]) };
let real: WarehouseReportService | undefined;

const cache = new CachingReportService(
  new LazyReportService(() => (real = new WarehouseReportService())),
);
const service: ReportService = new AccessControlledReportService(cache, () => current);

assert.equal(WarehouseReportService.instances, 0); // virtual: nothing built yet

const first = service.render("finance/q3");
assert.equal(service.render("finance/q3"), first); // caching
assert.equal(WarehouseReportService.instances, 1);
assert.equal(real?.renders, 1);

current = { name: "ben", roles: new Set(["SALES"]) };
assert.throws(() => service.render("finance/q3"), AccessDenied); // protection
assert.equal(service.render("sales/q3"), "report:sales/q3:run2");

cache.invalidate("sales/q3");
assert.equal(service.render("sales/q3"), "report:sales/q3:run3");

// The wrong order: cache OUTSIDE the access check leaks data.
current = { name: "asha", roles: new Set(["FINANCE"]) };
const leaky = new CachingReportService(
  new AccessControlledReportService(new WarehouseReportService(), () => current),
);
leaky.render("finance/q3");
current = { name: "ben", roles: new Set(["SALES"]) };
const leaked = leaky.render("finance/q3");
assert.ok(leaked.startsWith("report:finance/q3"));
console.log("proxy chain ok, and the wrong order leaks:", leaked);

Walking through it

Each proxy owns one policy. LazyReportService knows nothing about roles. CachingReportService knows nothing about laziness. You can test each with a fake inner service, and you can drop one from the chain without touching the others.

The wiring decides the policy, not the caller. The composition root (where the objects are built) is the only place that knows the chain exists. The endpoint and the export job both receive a ReportService. If the real WarehouseReportService is only ever constructed inside the lazy proxy's factory, no caller can reach it without going through the access check. That fixes the bug in NightlyExportJob structurally rather than by code review.

Order matters, and the demo proves it. The last block wraps the cache around the access check. Asha's request fills the cache, and Ben's request is answered from it without ever reaching the check. The rule of thumb: put checks that depend on the caller outside anything that shares results between callers. If you really need the cache outermost (because the check itself is expensive), the cache key has to include whatever the check depends on, such as the user or their role set.

Thread safety is the proxy's job. A virtual proxy that two threads hit at once can build two real objects. The Java version uses synchronized, and the Python version uses a lock with a second check inside it. The TypeScript version doesn't need one because a single JavaScript event loop runs synchronous code to completion. The caching proxy has the same issue. Note that Java's computeIfAbsent on a plain HashMap isn't thread-safe by itself, hence the synchronized. In a real service you'd use ConcurrentHashMap or a cache library such as Caffeine, and you'd think about expiry, because a cache without eviction is a memory leak with good intentions. The caching strategies page covers that side.

A remote proxy

A remote proxy makes an object in another process look local. The client calls stockLevel("SKU-1"). The proxy (usually called a stub) turns that into a message, sends it, waits for the reply and turns the reply back into a return value. Generated gRPC clients, Java RMI stubs and Python's xmlrpc.client.ServerProxy all work this way.

The example below fakes the network with a Transport that fails on its first attempt, so the stub's retry logic is exercised. The TypeScript version is asynchronous, because real network calls in JavaScript are.

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.*;

interface InventoryApi {
    int stockLevel(String sku);
}

// The real object, which in production lives in another process.
final class InventoryServer {
    private final Map<String, Integer> stock = Map.of("SKU-1", 7, "SKU-2", 0);

    String handle(String request) {
        String[] parts = request.split(" ", 2);
        if (!parts[0].equals("stockLevel")) return "ERR unknown-method";
        return "OK " + stock.getOrDefault(parts[1], 0);
    }
}

interface Transport {
    String send(String request) throws IOException;
}

// Remote proxy (stub): same interface as a local object, hides the wire.
final class InventoryStub implements InventoryApi {
    private final Transport transport;
    private final int maxAttempts;

    InventoryStub(Transport transport, int maxAttempts) {
        this.transport = transport;
        this.maxAttempts = maxAttempts;
    }

    @Override public int stockLevel(String sku) {
        IOException last = null;
        for (int attempt = 1; attempt <= maxAttempts; attempt++) {
            try {
                String reply = transport.send("stockLevel " + sku);   // marshal the call
                if (!reply.startsWith("OK ")) throw new IllegalStateException(reply);
                return Integer.parseInt(reply.substring(3));        // unmarshal the result
            } catch (IOException e) {
                last = e;                                           // safe to retry: it's a read
            }
        }
        throw new UncheckedIOException("inventory unreachable after " + maxAttempts + " attempts", last);
    }
}

class Demo {
    public static void main(String[] args) {
        InventoryServer server = new InventoryServer();
        int[] calls = {0};
        Transport flaky = request -> {
            calls[0]++;
            if (calls[0] == 1) throw new IOException("connection reset");
            return server.handle(request);
        };

        InventoryApi inventory = new InventoryStub(flaky, 3);
        assert inventory.stockLevel("SKU-1") == 7;
        assert calls[0] == 2;                     // first attempt failed, second succeeded

        Transport down = request -> { throw new IOException("no route to host"); };
        try {
            new InventoryStub(down, 2).stockLevel("SKU-1");
            throw new AssertionError("expected failure");
        } catch (UncheckedIOException e) {
            assert e.getMessage().contains("after 2 attempts");
        }
        System.out.println("remote proxy ok");
    }
}
from typing import Callable, Protocol


class InventoryApi(Protocol):
    def stock_level(self, sku: str) -> int: ...


class InventoryServer:
    """The real object, which in production lives in another process."""

    def __init__(self) -> None:
        self._stock = {"SKU-1": 7, "SKU-2": 0}

    def handle(self, request: str) -> str:
        method, _, arg = request.partition(" ")
        if method != "stock_level":
            return "ERR unknown-method"
        return f"OK {self._stock.get(arg, 0)}"


Transport = Callable[[str], str]


class InventoryStub:
    """Remote proxy (stub): same interface as a local object, hides the wire."""

    def __init__(self, transport: Transport, max_attempts: int) -> None:
        self._transport = transport
        self._max_attempts = max_attempts

    def stock_level(self, sku: str) -> int:
        last: Exception | None = None
        for _ in range(self._max_attempts):
            try:
                reply = self._transport(f"stock_level {sku}")    # marshal the call
            except ConnectionError as e:
                last = e                                         # safe to retry: it's a read
                continue
            if not reply.startswith("OK "):
                raise RuntimeError(reply)
            return int(reply[3:])                                # unmarshal the result
        raise ConnectionError(f"inventory unreachable after {self._max_attempts} attempts") from last


if __name__ == "__main__":
    server = InventoryServer()
    calls = 0

    def flaky(request: str) -> str:
        global calls
        calls += 1
        if calls == 1:
            raise ConnectionResetError("connection reset")
        return server.handle(request)

    inventory: InventoryApi = InventoryStub(flaky, max_attempts=3)
    assert inventory.stock_level("SKU-1") == 7
    assert calls == 2

    def down(request: str) -> str:
        raise ConnectionRefusedError("no route to host")

    try:
        InventoryStub(down, max_attempts=2).stock_level("SKU-1")
        raise AssertionError("expected failure")
    except ConnectionError as e:
        assert "after 2 attempts" in str(e)
    print("remote proxy ok")
import assert from "node:assert/strict";

interface InventoryApi {
  stockLevel(sku: string): Promise<number>;
}

// The real object, which in production lives in another process.
class InventoryServer {
  private readonly stock = new Map([["SKU-1", 7], ["SKU-2", 0]]);
  handle(request: string): string {
    const [method, arg = ""] = request.split(" ", 2);
    if (method !== "stockLevel") return "ERR unknown-method";
    return `OK ${this.stock.get(arg) ?? 0}`;
  }
}

type Transport = (request: string) => Promise<string>;

class TransportError extends Error {}

// Remote proxy (stub): same interface as a local object, hides the wire.
class InventoryStub implements InventoryApi {
  constructor(
    private readonly transport: Transport,
    private readonly maxAttempts: number,
  ) {}

  async stockLevel(sku: string): Promise<number> {
    let last: unknown;
    for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
      let reply: string;
      try {
        reply = await this.transport(`stockLevel ${sku}`); // marshal the call
      } catch (e) {
        if (!(e instanceof TransportError)) throw e;
        last = e; // safe to retry: it's a read
        continue;
      }
      if (!reply.startsWith("OK ")) throw new Error(reply);
      return Number(reply.slice(3)); // unmarshal the result
    }
    throw new TransportError(`inventory unreachable after ${this.maxAttempts} attempts`, {
      cause: last,
    });
  }
}

async function main(): Promise<void> {
  const server = new InventoryServer();
  let calls = 0;
  const flaky: Transport = async (request) => {
    calls++;
    if (calls === 1) throw new TransportError("connection reset");
    return server.handle(request);
  };

  const inventory: InventoryApi = new InventoryStub(flaky, 3);
  assert.equal(await inventory.stockLevel("SKU-1"), 7);
  assert.equal(calls, 2);

  const down: Transport = async () => {
    throw new TransportError("no route to host");
  };
  await assert.rejects(new InventoryStub(down, 2).stockLevel("SKU-1"), /after 2 attempts/);
  console.log("remote proxy ok");
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});

Remote proxies are where the "caller doesn't know" promise starts to strain. A local call takes nanoseconds and either works or throws a bug. A remote call takes milliseconds, can time out, and can fail after the other side has done the work. The classic paper on this, A Note on Distributed Computing (Waldo, Wyant, Wollrath and Kendall, Sun Microsystems, 1994), argues that pretending remote objects are local is a mistake because partial failure and latency can't be hidden. That's why modern stubs return futures or promises, take deadlines, and only retry calls that are safe to repeat. The stub above retries only because stockLevel is a read. For writes, see idempotency before adding a retry loop.

Dynamic proxies: one proxy class for every interface

Hand-writing a proxy is fine for one interface with two methods. For a logging proxy that should wrap every service, writing one class per interface is busywork. All three languages let you build a proxy at runtime that intercepts any method call:

  • Java has java.lang.reflect.Proxy, which creates a class at runtime that implements the interfaces you list and sends every call to an InvocationHandler.
  • Python can do it with __getattr__, which is called when normal attribute lookup fails, so a wrapper with no methods of its own sees every method access.
  • JavaScript has a built-in Proxy object with traps for get, set, has, deleteProperty, apply and more.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.*;

interface PriceCatalog {
    long priceCents(String sku);
    List<String> skus();
}

final class InMemoryCatalog implements PriceCatalog {
    public long priceCents(String sku) {
        if (!sku.startsWith("SKU-")) throw new IllegalArgumentException("bad sku " + sku);
        return 1999;
    }
    public List<String> skus() { return List.of("SKU-1", "SKU-2"); }
}

final class Logged {
    // Works for any interface, not just PriceCatalog.
    static <T> T wrap(Class<T> iface, T target, List<String> log) {
        Object proxy = Proxy.newProxyInstance(
                iface.getClassLoader(),
                new Class<?>[] { iface },
                (self, method, args) -> {
                    String call = method.getName() + Arrays.toString(args == null ? new Object[0] : args);
                    try {
                        Object result = method.invoke(target, args);
                        log.add(call + " -> " + result);
                        return result;
                    } catch (InvocationTargetException e) {
                        log.add(call + " threw " + e.getCause().getClass().getSimpleName());
                        throw e.getCause();     // rethrow the real exception, not the reflection wrapper
                    }
                });
        return iface.cast(proxy);
    }
}

class Demo {
    public static void main(String[] args) {
        List<String> log = new ArrayList<>();
        PriceCatalog catalog = Logged.wrap(PriceCatalog.class, new InMemoryCatalog(), log);

        assert catalog.priceCents("SKU-1") == 1999;
        assert catalog.skus().size() == 2;
        try {
            catalog.priceCents("oops");
            throw new AssertionError("expected IllegalArgumentException");
        } catch (IllegalArgumentException expected) { }

        assert log.equals(List.of(
                "priceCents[SKU-1] -> 1999",
                "skus[] -> [SKU-1, SKU-2]",
                "priceCents[oops] threw IllegalArgumentException"));
        assert Proxy.isProxyClass(catalog.getClass());
        assert !(catalog instanceof InMemoryCatalog);   // a JDK proxy only implements the interface
        System.out.println("dynamic proxy ok: " + log);
    }
}
from typing import Any


class InMemoryCatalog:
    def price_cents(self, sku: str) -> int:
        if not sku.startswith("SKU-"):
            raise ValueError(f"bad sku {sku}")
        return 1999

    def skus(self) -> list[str]:
        return ["SKU-1", "SKU-2"]


class Logged:
    """Wraps any object. __getattr__ only runs for names Logged itself doesn't define."""

    def __init__(self, target: Any, log: list[str]) -> None:
        self._target = target
        self._log = log

    def __getattr__(self, name: str) -> Any:
        attr = getattr(self._target, name)
        if not callable(attr):
            return attr

        def call(*args: Any, **kwargs: Any) -> Any:
            label = f"{name}{list(args)}"
            try:
                result = attr(*args, **kwargs)
            except Exception as e:
                self._log.append(f"{label} threw {type(e).__name__}")
                raise
            self._log.append(f"{label} -> {result}")
            return result

        return call


if __name__ == "__main__":
    log: list[str] = []
    catalog = Logged(InMemoryCatalog(), log)

    assert catalog.price_cents("SKU-1") == 1999
    assert len(catalog.skus()) == 2
    try:
        catalog.price_cents("oops")
        raise AssertionError("expected ValueError")
    except ValueError:
        pass

    assert log == [
        "price_cents['SKU-1'] -> 1999",
        "skus[] -> ['SKU-1', 'SKU-2']",
        "price_cents['oops'] threw ValueError",
    ]
    assert not isinstance(catalog, InMemoryCatalog)   # identity checks see through nothing
    print("dynamic proxy ok:", log)
import assert from "node:assert/strict";

interface PriceCatalog {
  priceCents(sku: string): number;
  skus(): string[];
}

class InMemoryCatalog implements PriceCatalog {
  priceCents(sku: string): number {
    if (!sku.startsWith("SKU-")) throw new RangeError(`bad sku ${sku}`);
    return 1999;
  }
  skus(): string[] {
    return ["SKU-1", "SKU-2"];
  }
}

// Works for any object type T, and the result is still typed as T.
function logged<T extends object>(target: T, log: string[]): T {
  return new Proxy(target, {
    get(obj, prop, receiver) {
      const value = Reflect.get(obj, prop, receiver);
      if (typeof value !== "function") return value;
      return function (this: unknown, ...args: unknown[]) {
        const label = `${String(prop)}${JSON.stringify(args)}`;
        try {
          const result = Reflect.apply(value, this, args);
          log.push(`${label} -> ${JSON.stringify(result)}`);
          return result;
        } catch (e) {
          log.push(`${label} threw ${(e as Error).name}`);
          throw e;
        }
      };
    },
  });
}

const log: string[] = [];
const catalog = logged<PriceCatalog>(new InMemoryCatalog(), log);

assert.equal(catalog.priceCents("SKU-1"), 1999);
assert.equal(catalog.skus().length, 2);
assert.throws(() => catalog.priceCents("oops"), RangeError);

assert.deepEqual(log, [
  'priceCents["SKU-1"] -> 1999',
  'skus[] -> ["SKU-1","SKU-2"]',
  'priceCents["oops"] threw RangeError',
]);
// Unlike Java's JDK proxies, a JS Proxy passes instanceof checks for the target's class.
assert.ok(catalog instanceof InMemoryCatalog);
console.log("dynamic proxy ok:", log);

A few details in that code are easy to get wrong:

  • Unwrap reflection exceptions. In Java, method.invoke wraps whatever the target threw in an InvocationTargetException. If you let that escape, callers who catch IllegalArgumentException will miss it. Rethrow getCause().
  • JDK proxies only implement interfaces. catalog instanceof InMemoryCatalog is false. Code that casts to the concrete class breaks the moment a JDK proxy is introduced. That's one reason Spring Boot switched its default to class-based (CGLIB) proxies, which subclass the target.
  • __getattr__ doesn't see dunder methods. Python looks up special methods such as __len__ or __iter__ on the type, not the instance, so len(Logged(some_list)) fails even though some_list has a length. Python-level proxies that need to support operators must define those dunders explicitly.
  • JavaScript traps must respect invariants. A Proxy can't report a non-configurable, read-only property as having a different value than the target has. The engine throws a TypeError if a trap lies about it.

JavaScript Proxy beyond logging

The JavaScript Proxy object is more powerful than a hand-written wrapper because it intercepts property access, not just method calls. That makes some proxies possible that would be awkward in Java or Python:

  • Validation on write. A set trap can reject order.quantity = -1 at the moment of assignment.
  • Change tracking. A set trap can record which fields changed, which is the core of how Vue 3's reactivity system knows what to re-render and how Immer builds an immutable copy from "mutations" on a draft.
  • Defaults and missing keys. A get trap can return a default for unknown properties instead of undefined.
  • Revocation. Proxy.revocable(target, handler) returns a proxy plus a revoke() function. After revoking, every operation on the proxy throws. That's a protection proxy whose permission you can withdraw, useful when handing an object to plugin code that shouldn't keep using it after a callback ends.
import assert from "node:assert/strict";

interface OrderLine {
  sku: string;
  quantity: number;
}

// Validates writes and records which fields changed.
function tracked(line: OrderLine, dirty: Set<keyof OrderLine>): OrderLine {
  return new Proxy(line, {
    set(obj, prop, value, receiver) {
      if (prop === "quantity" && (!Number.isInteger(value) || value < 1)) {
        throw new RangeError(`quantity must be a positive integer, got ${value}`);
      }
      dirty.add(prop as keyof OrderLine);
      return Reflect.set(obj, prop, value, receiver);
    },
  });
}

const dirty = new Set<keyof OrderLine>();
const line = tracked({ sku: "SKU-1", quantity: 1 }, dirty);
line.quantity = 3;
assert.throws(() => {
  line.quantity = 0;
}, RangeError);
assert.equal(line.quantity, 3);
assert.deepEqual([...dirty], ["quantity"]);

// Revocable access: the plugin can use the object only until we revoke it.
const { proxy: pluginView, revoke } = Proxy.revocable({ sku: "SKU-1", quantity: 3 }, {});
assert.equal(pluginView.quantity, 3);
revoke();
assert.throws(() => pluginView.quantity, TypeError);
console.log("JS Proxy traps ok");

The cost: every property access on a Proxy goes through a trap, which is slower than a plain property read and harder for engines to optimise. Use it at boundaries (configuration objects, reactive state, plugin APIs), not on the hot inner loop of a numeric routine.

Spring AOP proxies and the self-invocation gotcha

Spring's @Transactional, @Cacheable, @Async, @Retryable and method-level security annotations all work through proxies. When the container creates a bean that has one of these annotations, it doesn't hand you the bean. It hands you a proxy that wraps the bean. The proxy starts the transaction (or checks the cache, or submits to an executor) and then calls your method on the real object.

Spring builds that proxy in one of two ways:

MechanismHow it worksLimits
JDK dynamic proxyImplements the bean's interfaces with java.lang.reflect.ProxyOnly interface methods are intercepted. You can't inject it as the concrete class.
CGLIB proxyGenerates a subclass of the bean's class at runtime and overrides its methodsCan't intercept final methods or private methods. The class can't be final.

Spring Boot defaults to CGLIB (spring.aop.proxy-target-class=true) since Boot 2.0, so most applications get class-based proxies even when the bean implements an interface. Plain Spring Framework without Boot still uses a JDK proxy when the bean has interfaces, unless told otherwise.

The gotcha

With either mechanism, the proxy and the real bean are two different objects. The proxy receives the outside call and delegates to the real bean. Once execution is inside the real bean, this refers to the real bean, not the proxy. So when one method of a bean calls another method of the same bean, the call doesn't pass through the proxy, and the annotation on the second method does nothing.

The classic example: placeOrder() isn't annotated, and it calls this.saveOrder(), which is @Transactional. The caller goes through the proxy into placeOrder, which is not intercepted. Then saveOrder is called on the real object directly, so no transaction is ever started. Writes happen in auto-commit mode, and a failure halfway through leaves partial data. A variant: an @Transactional(propagation = REQUIRES_NEW) method called from inside the same bean silently joins the outer transaction instead of starting a new one. The same goes for @Async (the method runs synchronously on the caller's thread) and @Cacheable (the cache is never consulted).

The program below reproduces the mechanism without Spring. A "transaction proxy" records which methods it intercepted. The real object's internal call to saveOrder never shows up. The same code then shows the most common fix: move the annotated method into a separate bean so the call crosses a proxy boundary.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.*;

interface OrderService {
    void placeOrder(String id);
    void saveOrder(String id);          // imagine @Transactional on the implementation
}

interface OrderWriter {
    void saveOrder(String id);          // imagine @Transactional here
}

final class Tx {
    // A stand-in for the proxy Spring would generate around a @Transactional bean.
    static <T> T proxy(Class<T> iface, T target, List<String> intercepted) {
        return iface.cast(Proxy.newProxyInstance(iface.getClassLoader(), new Class<?>[] { iface },
                (self, method, args) -> {
                    intercepted.add("tx:" + method.getName());
                    try { return method.invoke(target, args); }
                    catch (InvocationTargetException e) { throw e.getCause(); }
                }));
    }
}

// The bug: an internal call bypasses the proxy.
final class SelfCallingOrderService implements OrderService {
    final List<String> saved = new ArrayList<>();
    public void placeOrder(String id) { this.saveOrder(id); }   // 'this' is the real object
    public void saveOrder(String id) { saved.add(id); }
}

// The fix: the transactional work lives in another bean, reached through its own proxy.
final class OrderWriterImpl implements OrderWriter {
    final List<String> saved = new ArrayList<>();
    public void saveOrder(String id) { saved.add(id); }
}

final class DelegatingOrderService implements OrderService {
    private final OrderWriter writer;   // injected proxy
    DelegatingOrderService(OrderWriter writer) { this.writer = writer; }
    public void placeOrder(String id) { writer.saveOrder(id); }
    public void saveOrder(String id) { writer.saveOrder(id); }
}

class Demo {
    public static void main(String[] args) {
        List<String> intercepted = new ArrayList<>();
        SelfCallingOrderService real = new SelfCallingOrderService();
        OrderService buggy = Tx.proxy(OrderService.class, real, intercepted);

        buggy.placeOrder("o-1");
        assert real.saved.equals(List.of("o-1"));                  // the work happened
        assert intercepted.equals(List.of("tx:placeOrder"));      // but saveOrder was never intercepted

        intercepted.clear();
        OrderWriterImpl writerImpl = new OrderWriterImpl();
        OrderWriter writerProxy = Tx.proxy(OrderWriter.class, writerImpl, intercepted);
        OrderService fixed = Tx.proxy(OrderService.class, new DelegatingOrderService(writerProxy), intercepted);

        fixed.placeOrder("o-2");
        assert writerImpl.saved.equals(List.of("o-2"));
        assert intercepted.equals(List.of("tx:placeOrder", "tx:saveOrder"));
        System.out.println("self-invocation reproduced and fixed");
    }
}
from typing import Any


class TxProxy:
    """A stand-in for a framework-generated proxy: records each method it intercepts."""

    def __init__(self, target: Any, intercepted: list[str]) -> None:
        self._target = target
        self._intercepted = intercepted

    def __getattr__(self, name: str) -> Any:
        attr = getattr(self._target, name)

        def call(*args: Any, **kwargs: Any) -> Any:
            self._intercepted.append(f"tx:{name}")
            return attr(*args, **kwargs)

        return call


class SelfCallingOrderService:
    def __init__(self) -> None:
        self.saved: list[str] = []

    def place_order(self, order_id: str) -> None:
        self.save_order(order_id)           # self is the real object, not the proxy

    def save_order(self, order_id: str) -> None:
        self.saved.append(order_id)


class OrderWriter:
    def __init__(self) -> None:
        self.saved: list[str] = []

    def save_order(self, order_id: str) -> None:
        self.saved.append(order_id)


class DelegatingOrderService:
    def __init__(self, writer: Any) -> None:
        self._writer = writer               # injected proxy

    def place_order(self, order_id: str) -> None:
        self._writer.save_order(order_id)


if __name__ == "__main__":
    intercepted: list[str] = []
    real = SelfCallingOrderService()
    buggy = TxProxy(real, intercepted)
    buggy.place_order("o-1")
    assert real.saved == ["o-1"]
    assert intercepted == ["tx:place_order"]          # save_order bypassed the proxy

    intercepted.clear()
    writer = OrderWriter()
    fixed = TxProxy(DelegatingOrderService(TxProxy(writer, intercepted)), intercepted)
    fixed.place_order("o-2")
    assert writer.saved == ["o-2"]
    assert intercepted == ["tx:place_order", "tx:save_order"]
    print("self-invocation reproduced and fixed")
import assert from "node:assert/strict";

class OrderService {
  saved: string[] = [];
  placeOrder(id: string): void {
    this.saveOrder(id);
  }
  saveOrder(id: string): void {
    this.saved.push(id);
  }
}

// Style 1: the proxy calls methods ON THE TARGET (like Spring and most hand-written wrappers).
function delegatingProxy<T extends object>(target: T, intercepted: string[]): T {
  return new Proxy(target, {
    get(obj, prop) {
      const value = Reflect.get(obj, prop);
      if (typeof value !== "function") return value;
      return (...args: unknown[]) => {
        intercepted.push(`tx:${String(prop)}`);
        return Reflect.apply(value, obj, args); // 'this' inside the method = target
      };
    },
  });
}

// Style 2: the proxy forwards the receiver, so 'this' inside the method = the proxy.
function receiverProxy<T extends object>(target: T, intercepted: string[]): T {
  return new Proxy(target, {
    get(obj, prop, receiver) {
      const value = Reflect.get(obj, prop, receiver);
      if (typeof value !== "function") return value;
      return function (this: unknown, ...args: unknown[]) {
        intercepted.push(`tx:${String(prop)}`);
        return Reflect.apply(value, this, args);
      };
    },
  });
}

const a: string[] = [];
const viaTarget = delegatingProxy(new OrderService(), a);
viaTarget.placeOrder("o-1");
assert.deepEqual(a, ["tx:placeOrder"]); // the internal call bypassed the proxy

const b: string[] = [];
const viaReceiver = receiverProxy(new OrderService(), b);
viaReceiver.placeOrder("o-2");
assert.deepEqual(b, ["tx:placeOrder", "tx:saveOrder"]); // the internal call went through it
assert.deepEqual(viaReceiver.saved, ["o-2"]);
console.log("self-invocation depends on what 'this' is bound to");

The TypeScript version shows the root cause from a different angle. Whether an internal call is intercepted depends only on what this points to inside the method. A JavaScript Proxy that forwards the receiver keeps this pointing at the proxy, so internal calls are intercepted too. A delegating proxy (Spring's JDK and CGLIB proxies, Python's __getattr__ wrapper, any hand-written wrapper class) calls the method on the target, so this is the target and internal calls escape.

Fixes, in the order you should reach for them

  1. Move the method to another bean. If saveOrder needs its own transaction, it probably belongs in its own class anyway (an OrderWriter or repository). This is the cleanest fix and the one the demo shows.
  2. Put the annotation on the outer method. If the whole placeOrder flow should be one transaction, annotate placeOrder instead. Often the "bug" is that the annotation was on the wrong method.
  3. Use programmatic control. Spring's TransactionTemplate runs a lambda inside a transaction with no proxy involved: transactionTemplate.executeWithoutResult(status -> saveOrder(id)). It's explicit, and it works from anywhere.
  4. Inject the bean into itself. A field such as @Lazy @Autowired OrderService self gives you the proxy, and self.saveOrder(id) goes through it. It works, but it reads oddly and hides a circular dependency.
  5. AopContext.currentProxy(). With @EnableAspectJAutoProxy(exposeProxy = true), a bean can fetch its own proxy at runtime. This ties your domain code to Spring AOP and is best avoided.
  6. Switch to AspectJ weaving. Compile-time or load-time weaving rewrites the bytecode of the class itself, so there's no separate proxy object and internal calls are advised too. It's a bigger build change, so most teams pick option 1.

Two related traps come from the same cause. Private methods are never intercepted: a JDK proxy can't see them and a CGLIB subclass can't override them. And calls made from the constructor or from @PostConstruct run on the real object before (or outside of) the proxy, so annotations on methods called from there don't apply. Since Spring Framework 6.0, class-based proxies can also intercept protected and package-private methods for @Transactional. Earlier versions only honoured public methods. The Spring AOP page covers pointcuts and advice types in more detail.

Real-world uses

JDK and Java ecosystem

  • java.lang.reflect.Proxy is the JDK's built-in dynamic proxy factory, used directly by many frameworks to implement interfaces at runtime.
  • Java RMI generates remote proxies (stubs) that implement a Remote interface and send calls to another JVM.
  • Hibernate / JPA lazy loading. EntityManager.getReference() returns an uninitialised proxy that only hits the database when you read a non-id field. Lazy @ManyToOne associations are usually proxies too. That's why accessing one after the session closes throws LazyInitializationException: the virtual proxy tries to load and finds its connection gone.
  • Spring AOP. @Transactional, @Cacheable, @Async and @PreAuthorize are applied by proxies, as described above. Spring Data repositories are interfaces you never implement: Spring creates a JDK proxy for each one at startup.
  • Collections.unmodifiableList and friends return wrappers that reject mutation, which is a protection proxy by intent (some authors file it under Decorator, a good example of how blurry the line is).

Python standard library

  • types.MappingProxyType wraps a dict in a read-only view. Class __dict__ attributes are exposed through it. It's a protection proxy: same mapping interface, writes refused, and changes to the underlying dict still show through.
  • weakref.proxy returns an object that behaves like the referent without keeping it alive. Using it after the referent is collected raises ReferenceError.
  • xmlrpc.client.ServerProxy is a remote proxy: ServerProxy(url).some_method(1, 2) turns into an XML-RPC request.
  • multiprocessing managers hand out proxy objects that forward method calls to an object living in the manager's server process.

JavaScript and Node.js

  • The built-in Proxy and Reflect objects (ES2015) are the language-level mechanism.
  • Vue 3's reactivity system wraps state objects in Proxy so it can track which properties a component reads and re-render when they're written.
  • Immer gives you a Proxy-based draft to "mutate" and produces a new immutable object from the recorded changes.
  • MobX 6 uses Proxy for observable objects by default.
  • Generated API clients (gRPC clients, many OpenAPI-generated SDKs) are remote proxies with a local method per remote endpoint.

Note the word clash: an HTTP reverse proxy such as Nginx, or a forward proxy in a corporate network, is a network component. It shares the idea (a stand-in that controls access) but isn't an object-level design pattern. In an interview, it's worth saying you know the difference.

When NOT to use it

When nothing needs controlling. A proxy that only forwards calls is pure overhead and one more class to read. If the policy is "call the real object", call the real object.

When the policy belongs in the object. If the real subject should never be used without the check (an Account that must refuse overdrafts), that's an invariant, and it lives inside the class. Proxies are for policies that vary by context: who's calling, where the object lives, whether caching is acceptable here.

When callers need to know. Remote calls fail in ways local calls don't. A cache can return stale data. Lazy loading can throw LazyInitializationException far from where the object was fetched. If hiding the proxy makes callers write wrong code, expose the difference in the interface instead: return a CompletableFuture, accept a deadline, name the method cachedPrice.

When identity matters. A proxy is a different object from its target. proxy == target is false, equals and hashCode may be forwarded or may not, and JDK proxies fail instanceof checks for the concrete class. Code that uses objects as map keys, compares them by reference or inspects their class can behave differently once a proxy appears.

When the indirection is in a hot path. Each layer adds a virtual call, and dynamic proxies add reflection or trap dispatch on top. That rarely matters for a service call that does I/O. It can matter inside a tight loop called millions of times. Measure before and after if you're unsure.

When a framework already does it. If you're in Spring and want caching, use @Cacheable rather than hand-writing a caching proxy, and know its rules (including self-invocation). Two caching layers that don't know about each other are worse than one.

The costs, in one list: an extra type per subject (unless dynamic), debugging through generated classes and stack frames, surprises around identity and this, ordering bugs when several proxies are stacked, and policies that become invisible to anyone reading only the client code.

PatternSame interface as the wrapped object?Main purposeWho usually creates the wrapped object
ProxyYesControl access: when, whether, whereOften the proxy itself (virtual) or the wiring code
DecoratorYesAdd behaviour or responsibilitiesThe client, which stacks decorators explicitly
AdapterNo, it converts to a different interfaceMake an incompatible interface fitSomeone else, it already exists
FacadeNo, it offers a new, simpler interfaceSimplify a whole subsystemThe facade, over many objects
FlyweightNot a wrapperShare state to save memoryA factory

Decorator vs Proxy

This is the most common pattern comparison in interviews, because the class diagrams are identical: both implement the subject interface and hold a reference to another implementation. The difference is intent, and it shows up in a few concrete ways:

  • What the wrapper changes. A decorator adds something to the result or the behaviour: compression, buffering, extra formatting, a retry. A proxy controls access to the same behaviour: maybe it's delayed, refused, cached or sent elsewhere, but when it does go through, the real object's result comes back unchanged.
  • Who knows about the wrapping. Decorators are usually stacked by the client on purpose: new BufferedReader(new InputStreamReader(in)). Proxies are usually inserted by wiring code or a framework so the client doesn't know. Nobody calls new TransactionProxy(service) in Spring application code.
  • Lifecycle of the wrapped object. A decorator is handed an existing object. A virtual proxy often creates the real object itself, and a remote proxy never holds the real object at all.
  • Stacking. Decorators are designed to be combined in any order the client likes (though order can matter). A proxy is usually one layer, or a fixed chain decided at configuration time.

The honest answer is that some classes are both. A caching wrapper is a proxy if you see it as "skip the real call when we can" and a decorator if you see it as "add caching". In an interview, say which intent you mean and why. That's what the question is testing.

Proxy vs Adapter and Facade

An adapter changes the interface: the client wants charge(Money), the SDK offers createPaymentIntent(map). A proxy keeps the interface identical. A facade puts one simple interface over several objects. A proxy sits in front of one object with the same interface it has. If you notice your "proxy" exposing new methods or hiding some of the subject's methods, it has turned into an adapter or facade, which is fine, but name it accordingly.

Other neighbours

  • Chain of Responsibility also passes a request through a sequence of handlers. The difference is that in a chain, any handler may handle and stop, and handlers usually share a generic handler interface. A stack of proxies all implement the domain interface and each normally forwards.
  • Singleton and lazy initialisation are often confused with virtual proxies. A lazy singleton delays creating the one instance. A virtual proxy delays creating the instance behind this reference, and there can be many.
  • Dependency injection is what makes proxies painless. If clients receive their collaborators through constructors, the composition root can slip a proxy in. If clients call new WarehouseReports() themselves, no proxy can help.

The smell that suggests it

You might want a proxy when you see one of these:

  • The same guard at the top of many methods or many callers. if (!user.hasRole(...)) throw copied across a service, or log.info("calling X") before every call to X. The policy is about access, not about the work, and it wants to live in one place in front of the object.
  • Expensive construction that most code paths don't need. A constructor that opens connections, loads files or warms caches, in an object that only some requests use. Startup is slow and memory is wasted on things that are never called.
  • A "check, then call" pattern that some callers forget. Like NightlyExportJob above. If forgetting the check is a security bug, the check should be unavoidable, and a proxy that is the only reference callers can get makes it so.
  • Network or persistence details leaking into business code. Serialisation, retries and connection handling sprinkled through code that should only care about stockLevel(sku). A remote proxy pulls that into one class.
  • Ad-hoc memoisation in callers. Several callers each keep a little Map of results from the same slow service, with different expiry rules and different bugs.
  • Tests that can't exercise a policy alone. If testing the cache requires a real database and a logged-in user, the policies are tangled with the work.

And the counter-smell: if your proxy's methods start doing domain work (computing totals, enforcing business invariants), it's no longer a proxy. Move that logic into the real subject.

Interview questions

  1. "What's the difference between Proxy and Decorator? Their class diagrams look the same." They are the same shape, and the difference is intent. A proxy controls access to the subject (lazy creation, permissions, remoteness, caching) and returns the subject's own result. A decorator adds behaviour or responsibilities and is usually stacked by the client. A good concrete tell: a virtual or remote proxy often creates or locates the real object itself, while a decorator is always given an existing one.

  2. "Why does @Transactional sometimes do nothing in Spring?" The usual cause is self-invocation. Spring applies the annotation through a proxy, and a call from one method of a bean to another method on the same bean goes through this, which is the real object, not the proxy. Other causes are annotating a private method, calling it from a constructor or @PostConstruct, or the bean not being managed by Spring (created with new). Fixes: move the method to another bean, annotate the outer method, or use TransactionTemplate.

  3. "JDK dynamic proxy vs CGLIB: what's the difference, and which does Spring Boot use?" A JDK proxy implements the target's interfaces using java.lang.reflect.Proxy, so only interface methods can be intercepted and the proxy can't be cast to the concrete class. CGLIB generates a subclass at runtime, so it works without interfaces but can't intercept final or private methods and can't proxy a final class. Spring Boot defaults to CGLIB since 2.0.

  4. "Design a virtual proxy for a large image in a document editor. What about threads?" The proxy implements the Image interface, stores the file path and the cheap metadata (width and height from the header), and loads the pixel data the first time draw() is called. With multiple threads, two can call draw() at once and both load the file. Guard the creation with a lock (or synchronized, or a holder idiom), check again inside the lock, and make the reference safely published (volatile in Java if you use double-checked locking).

  5. "You have a caching proxy and an authorisation proxy. Which goes outside?" Authorisation outside. If the cache is outside, a result fetched by an authorised user is served to the next caller without the check running. If performance forces the cache outside, the cache key must include everything the authorisation decision depends on (user, role set, tenant).

  6. "Is a remote proxy a good idea? Shouldn't remote calls look local?" The structure is useful because it keeps marshalling and connection handling out of business code. But a remote call can't fully look local: it has latency, can time out, and can fail after the server did the work. Good remote proxies are honest about this. They return futures, accept deadlines, retry only idempotent calls and surface distinct exception types for transport failures.

  7. "How would you add timing metrics to every method of 30 service interfaces?" Not with 30 hand-written proxies. Use a dynamic proxy (java.lang.reflect.Proxy with one InvocationHandler, a JavaScript Proxy, a Python __getattr__ wrapper or decorator applied in a loop), or in Spring an aspect with a pointcut. Mention the costs: reflection overhead, unwrapping InvocationTargetException, and self-invocation not being measured.

  8. "How is JavaScript's Proxy different from a wrapper class?" It intercepts fundamental operations on any object (property get and set, in, delete, function calls, construction) without you writing a method per member, and it preserves instanceof because the prototype lookup goes to the target. If the trap forwards the receiver, this inside methods is the proxy, so even internal calls are intercepted. The costs are trap overhead on every access and some invariants the engine enforces.

  9. "Where have you seen the Proxy pattern in libraries you use?" Good answers: Hibernate lazy-loaded entities and LazyInitializationException; Spring Data repositories and @Transactional; gRPC or OpenAPI-generated clients; Python's types.MappingProxyType or weakref.proxy; Vue 3 reactivity or Immer on top of JavaScript Proxy.

  10. "When would you not add a proxy?" When it only forwards calls; when the rule is an invariant of the object and belongs inside it; when hiding the extra behaviour misleads callers (stale caches, remote failures); when code depends on object identity; and when a framework feature already provides the same policy.