00:00

Proxy Design Pattern in Java

Last updated:

The proxy design pattern in Java places a stand-in object in front of a real object. The proxy implements the same interface, so callers cannot tell the difference, and it decides when, whether and how each call reaches the real object: it can cache results, check permissions, load the object lazily or retry failures.

It matters because these concerns do not belong in business classes, yet every caller needs them. Without a proxy, each module writes its own cache or security check, or forgets to. It is a structural design pattern, and it is also the mechanism behind Spring's @Transactional, @Cacheable and @Async, which makes it a favourite interview topic.

1. What Is the Proxy Design Pattern?

The GoF intent is: "Provide a surrogate or placeholder for another object to control access to it."

The key word is control. A proxy implements the same interface as the real object, holds a reference to it, and runs its own logic before or after delegating. Because the interface is identical, a proxy can be swapped in without changing the client. The common kinds are:

  • Caching proxy: returns a stored result instead of repeating an expensive call.
  • Protection proxy: checks whether the caller may perform the operation.
  • Virtual proxy: delays creating an expensive object until it is first used.
  • Remote proxy: represents an object in another process and handles the network call.
  • Smart proxy: adds logging, metrics, retries or transactions around each call.

Proxies are written by hand or generated at runtime with java.lang.reflect.Proxy (interfaces) or CGLIB/ByteBuddy (classes). Either way, the real object keeps its single responsibility, and cross-cutting behaviour lives in the proxy.

2. Key Components

ComponentResponsibilityIn the Basic Example
SubjectThe interface shared by the proxy and the real objectRateProvider
Real SubjectDoes the actual workRemoteRateProvider
ProxyImplements the subject, holds the real subject and controls access to itCachingRateProvider
ClientUses the subject interface, unaware of the proxymain

The client calls the subject interface. The proxy runs its check or cache lookup, calls the real subject only when needed, and returns the result.

3. When Is a Proxy Useful?

  • Expensive remote calls: an exchange-rate API that is slow and billed per request.
  • Access control: bank customers may read only their own account, while fraud officers may freeze any account.
  • Reliability policies: retrying payment-gateway timeouts without touching the gateway code.

4. UML Class Diagram

The diagram shows the caching proxy from the Basic Example.

Proxy UML class diagram The Client uses the RateProvider interface. CachingRateProvider and RemoteRateProvider both implement RateProvider. CachingRateProvider holds a reference to RemoteRateProvider and delegates to it. Client uses «interface» RateProvider + rate(currency): BigDecimal Subject implements CachingRateProvider - remote: RemoteRateProvider - cache: Map<String, CachedRate> + rate(currency): BigDecimal Proxy delegates to 1 RemoteRateProvider + rate(currency): BigDecimal Real Subject
Proxy: the proxy and the real subject share one interface, and the proxy decides when to forward a call to the object it wraps.
  1. The client depends only on RateProvider.
  2. Both CachingRateProvider and RemoteRateProvider implement it, so either can be handed to the client.
  3. The proxy holds exactly one real subject (solid navigable association) plus its own cache.
  4. The real subject knows nothing about the proxy or the cache.

5. Step-by-Step Execution Flow

  1. At startup, the application creates the RemoteRateProvider, wraps it in a CachingRateProvider, and gives the proxy to clients as a RateProvider.
  2. A client calls rate("USD") on the proxy.
  3. The proxy checks its cache. On a miss, or when the entry is older than five minutes, it calls remote.rate("USD") and stores the answer with a timestamp.
  4. On a fresh hit, it returns the cached value without calling the remote service.
  5. Either way, the client receives a BigDecimal through the same method it would call on the real object.

6. Real-World Use Cases

  • E-commerce: caching product prices and stock levels from slow back-end systems.
  • Payments and banking: permission checks on account operations, and retry or circuit-breaker wrappers around gateways.
  • Notifications: a rate-limiting proxy in front of an SMS provider.
  • Spring Framework: @Transactional, @Cacheable, @Async and Spring Security's method security work by wrapping your bean in a proxy. Spring AOP uses JDK dynamic proxies for interfaces and CGLIB subclasses for classes; Spring Boot uses CGLIB by default (spring.aop.proxy-target-class=true).
  • JPA and Hibernate: lazy associations and getReference() return proxy objects that load the entity on first access, which is a virtual proxy.
  • The JDK: java.lang.reflect.Proxy generates proxies at runtime, and Java RMI client stubs are remote proxies.

7. Problem Without the Pattern

Two modules call a billed rate API directly:

RatesWithoutProxy.java
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RatesWithoutProxy {

    // Remote service: slow and billed per call
    static final class RemoteRateProvider {
        int calls = 0;

        BigDecimal rate(String currency) {
            calls++;
            System.out.println("  [remote] GET /rates/" + currency);
            return currency.equals("USD") ? new BigDecimal("83.20") : new BigDecimal("90.10");
        }
    }

    public static void main(String[] args) {
        RemoteRateProvider remote = new RemoteRateProvider();

        // Invoice module: calls the remote API for every line
        for (String currency : List.of("USD", "USD", "EUR", "USD")) {
            remote.rate(currency);
        }

        // Report module: wrote its own cache, with its own rules
        Map<String, BigDecimal> reportCache = new HashMap<>();
        for (String currency : List.of("USD", "EUR")) {
            reportCache.computeIfAbsent(currency, remote::rate);
        }
        System.out.println("Remote calls: " + remote.calls);
    }
}
Console
  [remote] GET /rates/USD
  [remote] GET /rates/USD
  [remote] GET /rates/EUR
  [remote] GET /rates/USD
  [remote] GET /rates/USD
  [remote] GET /rates/EUR
Remote calls: 6
  • Wasted calls: six paid requests for two distinct currencies.
  • Duplicated, inconsistent caching: invoicing has none, reporting has its own, and its entries never expire.
  • Mixed responsibilities: business modules now manage caching policy.

8. Solution Using the Pattern

Put one caching proxy in front of the remote provider and give every module the proxy, typed as RateProvider. The modules do not change, because the interface is the same.

Caching rules, including the five-minute expiry, now live in one class, and the report module can delete its private map. The Basic Example shows the remote calls dropping from six to three, including one refresh after expiry.

9. Proxy Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Caching Proxy for Exchange Rates

Problem: fix section 7 with a shared, expiring cache that callers do not have to know about.

CachingProxyDemo.java
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CachingProxyDemo {

    // Subject
    interface RateProvider {
        BigDecimal rate(String currency);
    }

    // Real subject: the slow remote call
    static final class RemoteRateProvider implements RateProvider {
        int calls = 0;

        @Override
        public BigDecimal rate(String currency) {
            calls++;
            System.out.println("  [remote] GET /rates/" + currency);
            return currency.equals("USD") ? new BigDecimal("83.20") : new BigDecimal("90.10");
        }
    }

    // Proxy: same interface, adds a time-limited cache in front of the real subject
    static final class CachingRateProvider implements RateProvider {
        private record CachedRate(BigDecimal value, Instant fetchedAt) { }

        private final RemoteRateProvider remote;
        private final Clock clock;
        private final Duration ttl;
        private final Map<String, CachedRate> cache = new ConcurrentHashMap<>();

        CachingRateProvider(RemoteRateProvider remote, Clock clock, Duration ttl) {
            this.remote = remote;
            this.clock = clock;
            this.ttl = ttl;
        }

        @Override
        public BigDecimal rate(String currency) {
            Instant now = clock.instant();
            return cache.compute(currency, (key, cached) ->            // atomic per key
                    cached != null && cached.fetchedAt().plus(ttl).isAfter(now)
                            ? cached
                            : new CachedRate(remote.rate(key), now)).value();
        }
    }

    // A clock the demo can move forward
    static final class TestClock extends Clock {
        private Instant now = Instant.parse("2026-11-02T09:00:00Z");
        void advance(Duration d) { now = now.plus(d); }
        @Override public Instant instant() { return now; }
        @Override public ZoneOffset getZone() { return ZoneOffset.UTC; }
        @Override public Clock withZone(ZoneId zone) { return this; }
    }

    public static void main(String[] args) {
        RemoteRateProvider remote = new RemoteRateProvider();
        TestClock clock = new TestClock();
        RateProvider rates = new CachingRateProvider(remote, clock, Duration.ofMinutes(5));   // clients get the proxy

        for (String currency : List.of("USD", "USD", "EUR", "USD")) {
            System.out.println(currency + " = " + rates.rate(currency));
        }

        clock.advance(Duration.ofMinutes(6));                          // cache entries are now stale
        System.out.println("After 6 minutes: USD = " + rates.rate("USD"));
        System.out.println("Remote calls: " + remote.calls);
    }
}

Important classes and methods

  • CachingRateProvider is the proxy; RemoteRateProvider is the real subject.
  • ConcurrentHashMap.compute() runs the check-and-refresh atomically for each key, so two threads cannot both fetch the same currency at once.
  • The Clock is injected, so the demo can move time forward and test expiry.

Expected output

Console
  [remote] GET /rates/USD
USD = 83.20
USD = 83.20
  [remote] GET /rates/EUR
EUR = 90.10
USD = 83.20
  [remote] GET /rates/USD
After 6 minutes: USD = 83.20
Remote calls: 3

How it runs

  1. The first USD and EUR lookups go to the remote service.
  2. Repeated USD lookups within five minutes come from the cache.
  3. After six minutes the USD entry is stale, so the proxy fetches it again: three remote calls in total.

10. Best Practices and Common Mistakes

Best practices

  • Keep each proxy focused on one concern; stack several proxies if needed.
  • Hand clients the interface, so the proxy can be added or removed through configuration.
  • In dynamic proxies, unwrap InvocationTargetException so callers see the real exception.
  • Thread safety: proxies are usually shared. Use concurrent structures for caches and counters, and make check-then-act steps atomic, as compute() does.

Common mistakes

  • Handing out the real object somewhere, which bypasses the proxy.
  • Expecting self-calls to be proxied: a method calling another method on this skips the proxy.
  • Caches without expiry or size limits, which grow forever or serve stale data.
  • Overengineering: hand-writing proxies for concerns your framework already provides, such as @Cacheable or Resilience4j.

11. When to Use and When Not to Use

Use it when a concern must apply to every call of an interface without changing its implementation, when the real object is expensive or remote, or when access must be checked in one place.

Avoid it for logic that is really part of the business rule, for cheap local objects where an extra layer only adds noise, and on hot paths where reflection-based proxies add measurable overhead.

12. Advantages and Disadvantages

Advantages

  • Transparent to clients: same interface, no code changes.
  • Separation of concerns: caching, security and retries stay out of business classes.
  • Reusable: dynamic proxies apply one policy to many interfaces.
  • Lazy loading and remote access become invisible to callers.

Disadvantages

  • Hidden behaviour: a plain-looking call may hit a cache or be refused.
  • Harder debugging: stack traces include generated classes.
  • Limits: JDK proxies need interfaces; class proxies cannot intercept final or private methods.

13. Comparison with Similar Patterns

AspectProxyDecoratorAdapterFacade
IntentControl access to an objectAdd responsibilities to an objectConvert one interface into anotherSimplify a subsystem
InterfaceSame as the subjectSame as the componentDifferent from the adapteeNew, simpler interface
Who creates itOften a framework or factory; the client may not knowUsually the client, layer by layerThe code that wires the adaptee inThe application
May skip the real callYes (cache hit, denied access)Rarely; it normally always delegatesNoNot applicable

Proxy and Decorator often look identical in code. Ask what the wrapper is for: if it decides whether and when the real object is reached, it is a Proxy; if it adds features and always delegates, it is a Decorator. Use an Adapter when the interface itself must change, and a Facade when many objects need one simple entry point.

14. Summary

  • The proxy design pattern in Java puts a stand-in with the same interface in front of a real object.
  • Purpose: control access for caching, security, laziness, remoting or retries.
  • Components: Subject, Real Subject, Proxy, Client.
  • The proxy runs its logic and decides whether to delegate; clients cannot tell the difference.
  • Used throughout Spring (@Transactional, @Cacheable), Hibernate lazy loading and RMI.
  • Benefits: transparency, separation of concerns and reuse through dynamic proxies.
  • Watch out for self-invocation, stale caches and thread safety in shared proxies.

15. Java Design Pattern Interview Questions and Answers

Q1. What is the difference between a JDK dynamic proxy and a CGLIB proxy?

A JDK dynamic proxy implements one or more interfaces, so the target must have an interface and callers must use it. CGLIB (or ByteBuddy) creates a subclass of the target class at runtime, so it works without an interface but cannot intercept final classes, final methods or private methods. Spring Boot uses CGLIB by default, which is why @Transactional on a final method silently does nothing.

Q2. Why does @Transactional not work when a method calls another method in the same class?

The transaction logic lives in the proxy, but a call such as this.save() goes straight to the target object and never passes through the proxy. Fixes include moving the method to another bean, injecting the bean's own proxy, or using TransactionTemplate for programmatic control.

@Service
class OrderService {
    public void importAll(List<Order> orders) {
        orders.forEach(this::save);      // bypasses the proxy: no transaction
    }
    @Transactional
    public void save(Order order) { ... }
}
Q3. What causes LazyInitializationException in Hibernate, and how does it relate to proxies?

A lazy association is a virtual proxy that loads data from the database on first access. If that first access happens after the persistence context is closed, for example in a controller after the transaction ended, the proxy has no session to load from and throws. Fix it by fetching what you need inside the transaction (a fetch join or entity graph) and returning DTOs.

Q4. Many threads miss the cache for the same key at the same moment. What happens, and how do you prevent it?

With a naive "get, then put on miss", every thread calls the expensive service: a cache stampede. Load each key atomically, as ConcurrentHashMap.compute() or computeIfAbsent() does, so other threads wait for the first load. For production caches, a library such as Caffeine adds this behaviour along with size limits and expiry.

Q5. How would you add timing metrics to every repository method in a large codebase without editing each class?

Wrap the repositories in a smart proxy that records the time around each call. In plain Java, one InvocationHandler can wrap every repository interface. In Spring, write an @Around aspect, which Spring applies through proxies, or rely on Micrometer's @Timed support. The repositories stay unchanged.