Proxy Design Pattern in Java
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
| Component | Responsibility | In the Basic Example |
|---|---|---|
| Subject | The interface shared by the proxy and the real object | RateProvider |
| Real Subject | Does the actual work | RemoteRateProvider |
| Proxy | Implements the subject, holds the real subject and controls access to it | CachingRateProvider |
| Client | Uses the subject interface, unaware of the proxy | main |
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.
- The client depends only on
RateProvider. - Both
CachingRateProviderandRemoteRateProviderimplement it, so either can be handed to the client. - The proxy holds exactly one real subject (solid navigable association) plus its own cache.
- The real subject knows nothing about the proxy or the cache.
5. Step-by-Step Execution Flow
- At startup, the application creates the
RemoteRateProvider, wraps it in aCachingRateProvider, and gives the proxy to clients as aRateProvider. - A client calls
rate("USD")on the proxy. - 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. - On a fresh hit, it returns the cached value without calling the remote service.
- Either way, the client receives a
BigDecimalthrough 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,@Asyncand 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.Proxygenerates proxies at runtime, and Java RMI client stubs are remote proxies.
7. Problem Without the Pattern
Two modules call a billed rate API directly:
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);
}
}
[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.
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
CachingRateProvideris the proxy;RemoteRateProvideris 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
Clockis injected, so the demo can move time forward and test expiry.
Expected output
[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
- The first USD and EUR lookups go to the remote service.
- Repeated USD lookups within five minutes come from the cache.
- After six minutes the USD entry is stale, so the proxy fetches it again: three remote calls in total.
Practical Example: Protection Proxy for Bank Accounts
Problem: customers may read only their own balance, and only fraud officers may freeze accounts. The core banking class should contain no security code.
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class ProtectionProxyDemo {
record User(String name, Set<String> roles, String ownAccount) { }
// Subject
interface AccountService {
BigDecimal balance(String accountId);
void freeze(String accountId);
}
// Real subject: pure banking logic, no security code
static final class CoreAccountService implements AccountService {
private final Map<String, BigDecimal> balances = new HashMap<>(Map.of(
"ACC-1", new BigDecimal("15200.50"),
"ACC-2", new BigDecimal("830.00")));
public BigDecimal balance(String accountId) { return balances.get(accountId); }
public void freeze(String accountId) { System.out.println(" [core] " + accountId + " frozen"); }
}
// Protection proxy: checks permissions, then delegates
static final class SecuredAccountService implements AccountService {
private final AccountService target;
private final User user;
SecuredAccountService(AccountService target, User user) {
this.target = target;
this.user = user;
}
@Override
public BigDecimal balance(String accountId) {
if (!accountId.equals(user.ownAccount()) && !user.roles().contains("TELLER")) {
throw new SecurityException(user.name() + " may not view " + accountId);
}
return target.balance(accountId);
}
@Override
public void freeze(String accountId) {
if (!user.roles().contains("FRAUD_OFFICER")) {
throw new SecurityException(user.name() + " may not freeze accounts");
}
target.freeze(accountId);
}
}
static void attempt(String label, Runnable action) {
try {
action.run();
} catch (SecurityException e) {
System.out.println(label + " -> DENIED: " + e.getMessage());
}
}
public static void main(String[] args) {
AccountService core = new CoreAccountService();
AccountService asOwner = new SecuredAccountService(core, new User("meera", Set.of("CUSTOMER"), "ACC-1"));
AccountService asOfficer = new SecuredAccountService(core, new User("vikram", Set.of("TELLER", "FRAUD_OFFICER"), null));
attempt("meera reads ACC-1", () -> System.out.println("meera reads ACC-1 -> " + asOwner.balance("ACC-1")));
attempt("meera reads ACC-2", () -> System.out.println("meera reads ACC-2 -> " + asOwner.balance("ACC-2")));
attempt("meera freezes ACC-2", () -> asOwner.freeze("ACC-2"));
attempt("vikram reads ACC-2", () -> System.out.println("vikram reads ACC-2 -> " + asOfficer.balance("ACC-2")));
attempt("vikram freezes ACC-2", () -> asOfficer.freeze("ACC-2"));
}
}
Important classes and methods
CoreAccountServiceis the real subject with pure banking logic.SecuredAccountServiceis the proxy. Each method checks the user, then delegates or throwsSecurityException.- One proxy is created per user, and both share the same core service.
Expected output
meera reads ACC-1 -> 15200.50
meera reads ACC-2 -> DENIED: meera may not view ACC-2
meera freezes ACC-2 -> DENIED: meera may not freeze accounts
vikram reads ACC-2 -> 830.00
[core] ACC-2 frozen
How it runs
- Meera reads her own account; the proxy lets the call through.
- Her attempts to read ACC-2 and to freeze it are stopped before reaching the core service.
- Vikram has the TELLER and FRAUD_OFFICER roles, so both of his calls reach the core service, which prints the freeze.
Real-World Enterprise Example: Retry with a JDK Dynamic Proxy
Problem: several clients, such as a payment gateway and an SMS sender, need the same retry policy for transient failures. Writing a hand-made proxy class for every interface does not scale.
import java.io.Serial;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class RetryProxyDemo {
// Marks failures that are worth retrying, such as timeouts
static final class TransientFailureException extends RuntimeException {
@Serial
private static final long serialVersionUID = 1L;
TransientFailureException(String message) { super(message); }
}
interface PaymentGateway {
String charge(String orderId, long amountInPaise);
}
interface SmsSender {
void send(String phone, String text);
}
// Real subjects
static final class FlakyPaymentGateway implements PaymentGateway {
private int attempts = 0;
public String charge(String orderId, long amountInPaise) {
attempts++;
if (orderId.equals("BAD")) throw new IllegalArgumentException("unknown order " + orderId);
if (attempts < 3) throw new TransientFailureException("gateway timeout"); // fails twice, then succeeds
return "PAY-" + orderId;
}
}
static final class ConsoleSmsSender implements SmsSender {
public void send(String phone, String text) { System.out.println(" [sms] " + phone + ": " + text); }
}
// Dynamic proxy: one handler adds retries to any interface, generated at runtime
static final class RetryHandler implements InvocationHandler {
private final Object target;
private final int maxAttempts;
RetryHandler(Object target, int maxAttempts) {
this.target = target;
this.maxAttempts = maxAttempts;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
for (int attempt = 1; ; attempt++) {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause(); // the exception the target really threw
if (!(cause instanceof TransientFailureException) || attempt == maxAttempts) {
throw cause; // non-retryable, or out of attempts
}
System.out.println(" [retry] " + method.getName() + " attempt " + attempt + " failed: " + cause.getMessage());
}
}
}
static <T> T wrap(Class<T> type, T target, int maxAttempts) {
Object proxy = Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, new RetryHandler(target, maxAttempts));
return type.cast(proxy);
}
}
public static void main(String[] args) {
PaymentGateway gateway = RetryHandler.wrap(PaymentGateway.class, new FlakyPaymentGateway(), 3);
SmsSender sms = RetryHandler.wrap(SmsSender.class, new ConsoleSmsSender(), 3);
System.out.println("Proxy class: " + (Proxy.isProxyClass(gateway.getClass()) ? "generated by java.lang.reflect.Proxy" : "plain class"));
String paymentId = gateway.charge("ORD-77", 249_900);
System.out.println("Charged: " + paymentId);
sms.send("+91-98xxxxxx10", "Payment " + paymentId + " received");
try {
gateway.charge("BAD", 100);
} catch (IllegalArgumentException e) {
System.out.println("Not retried: " + e.getMessage());
}
}
}
Important classes and methods
Proxy.newProxyInstance()generates a class at runtime that implements the given interface and sends every call toRetryHandler.invoke().invoke()calls the real method through reflection. Reflection wraps exceptions inInvocationTargetException, so the handler unwraps it and rethrows the original exception.- Only
TransientFailureExceptionis retried; other exceptions pass straight through. - The same handler wraps two unrelated interfaces. This is how Spring AOP applies one aspect to many beans.
Expected output
Proxy class: generated by java.lang.reflect.Proxy
[retry] charge attempt 1 failed: gateway timeout
[retry] charge attempt 2 failed: gateway timeout
Charged: PAY-ORD-77
[sms] +91-98xxxxxx10: Payment PAY-ORD-77 received
Not retried: unknown order BAD
How it runs
- The first two
charge()attempts time out and are retried; the third succeeds. - The SMS call goes through the same kind of proxy and succeeds first time.
- The "BAD" order throws
IllegalArgumentException, which is not retryable, so the client receives it immediately.
In production, add a backoff delay between attempts, and only retry operations that are idempotent, such as charges protected by an idempotency key.
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
InvocationTargetExceptionso 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
thisskips 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
@Cacheableor 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
finalor private methods.
13. Comparison with Similar Patterns
| Aspect | Proxy | Decorator | Adapter | Facade |
|---|---|---|---|---|
| Intent | Control access to an object | Add responsibilities to an object | Convert one interface into another | Simplify a subsystem |
| Interface | Same as the subject | Same as the component | Different from the adaptee | New, simpler interface |
| Who creates it | Often a framework or factory; the client may not know | Usually the client, layer by layer | The code that wires the adaptee in | The application |
| May skip the real call | Yes (cache hit, denied access) | Rarely; it normally always delegates | No | Not 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.