Proxy pattern
medium 50 minA proxy stands in for another object, with the same interface, and controls access to it: it creates it late, checks the caller, remembers results, or reaches it over a network.
Video lesson · Chapter 1 of 6
Make a prediction
Proxy
1:05Reel
More reels
One idea each, a minute or less.
Decorator vs proxy
0:32Reel
Theory
Read or listen first. About 2 min.
What it is
Proxy is a structural design pattern. A proxy implements the interface of another object, the real subject, and stands before it. Clients talk to the proxy and can not tell by the interface.
The proxy decides whether, when and how the real subject is reached. It may create it at first use (virtual), check the caller (protection), keep results (caching) or carry the call to another process (remote).
The real subject does its work and knows nothing about any of this.
Why it exists
Rules about access, such as load once, only administrators, at most one call a second, are the same for every client. Written into clients they are copied and forgotten.
In a proxy each rule has one home, and neither the clients nor the real class change.
Frameworks use it everywhere: lazy relations, transactions by annotation, stubs of remote calls. Who knows the pattern understands why a self call loses the transaction.
A short history
1994
The book Design Patterns describes Proxy and names remote, virtual and protection proxies and smart references.
2000
PEP 205, weak references for Python, is written. The weakref module with proxy objects arrives in Python 2.1 in 2001.
2000
Java 1.3 adds
java.lang.reflect.Proxy: classes for a set of interfaces, made while the program runs.2015
ECMAScript 2015 puts Proxy objects with traps into JavaScript.
Words to know
- Subject
- The interface shared by proxy and real subject.
- Real subject
- The object that does the work.
- Virtual proxy
- Creates the real subject at first use.
- Protection proxy
- Checks the caller first.
- Caching proxy
- Keeps results.
- Remote proxy, stub
- Stands here for an object in another process.
- Smart reference
- Does something when the object is referred to: counts, locks, checks that it still lives.
- Dynamic proxy
- A proxy generated at run time for any interface.
- Self-invocation
- An object calling itself, past its proxy.
- Invalidation
- Telling a cache that an answer is no longer right.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Client calls. The subject's interface
Understand it
Start here
Somebody who answers in your place
Some objects are expensive, far away, or not for everybody. A 50 MB picture. A service on another continent. A bank account. The Proxy pattern puts a stand-in before such an object. It has the same methods, and it decides when, whether and how the real object is asked.
Every visitor asks in the same way. What the page does with the question is the page's business.
You also know it from the guard before an office (checks the badge, writes down the visit, then lets you in) and the bodyguard of a celebrity (fans deal with the bodyguard). Both show the protection kind. The page shows that there are others.
Four roles
Subject
The common interface:
Image,Account. The client knows only this.Real subject
RealImage,RealAccount. Does the work and knows nothing of the proxy.Proxy
ImageProxy,AccountProxy. Same methods. Reaches the real subject, or does not.Client
Gallery, a banking app. Receives a subject from someone else and can not tell which.
Why
What goes wrong without it
class RealImage: loaded_mb = 0 def __init__(self, name): RealImage.loaded_mb += 50 self.name = name def display(self): return "showing " + self.namealbum = [RealImage(f"photo{i}.jpg") for i in range(100)]print(album[0].display(), "after loading", RealImage.loaded_mb, "MB") # 5000# The usual fix, copied into every client:RealImage.loaded_mb = 0names = [f"photo{i}.jpg" for i in range(100)]cache = {}def show(i): # the gallery has this if i not in cache: cache[i] = RealImage(names[i]) return cache[i].display()def print_photo(i): # printing forgot it return RealImage(names[i]).display()show(0); show(0); print_photo(0); print_photo(0)print("one photo, loaded", RealImage.loaded_mb // 50, "times") # 3The album
The design that hurts
1/3Creating is loading
The constructor does the expensive work, so whoever makes a list of images pays for all.
uses
if before the same call, in many clients.A proxy guards
- One place for the rule
- No way around it, if clients only get proxies
- Clients call a method and nothing else
- The real class does its one job
Each client guards
- Rules about access are copied
- One forgotten check is a hole
- Clients know that creating is expensive
- The real class grows flags and roles
The idea
Same interface, controlled access
The Proxy pattern in general
1/4Subject
One contract. The client is written against it and never learns more.
usesimplementshas (lives on)
One request, with everything a proxy may do
The same in six steps
- 1
The client calls
subject.request(). It does not know who answers. - 2
Before
The proxy checks permission, validates arguments, notes the call.
- 3
Create if needed
A virtual proxy makes the real object now, not earlier.
- 4
Delegate
The same method on the real object.
- 5
Work
The real object loads, queries, transfers.
- 6
After
The proxy may store the result or record time and outcome, and returns it.
Kinds
Four jobs, and some more
Virtual
Creates an expensive object at first use. Pictures, documents, lazy relations of an object-relational mapper.
Protection
Checks who calls before passing on. Accounts, admin functions.
Caching
Keeps results and answers repeated questions. Price lists, API responses.
Remote
Stands here for an object in another process. Stubs of remote procedure calls.
| Kind | Question it answers | New danger |
|---|---|---|
| Virtual | Is it needed now? | The cost appears at a surprising moment |
| Protection | May this caller? | A second door without a proxy |
| Caching | Do I know that already? | Old answers, memory |
| Remote | Where is it? | Slow, partial failure, unknown outcome |
| Logging | Who called what? | Secrets in logs |
| Smart reference | Who still uses it? | Counts that go wrong, cycles |
| Synchronizing | Who may enter now? | Holding the lock during long work |
Virtual proxy, state by state
Protection proxy
Honest
How transparent is it?
The interface is the same. The behaviour of time and failure is not. A call that used to be a field read may now load 50 MB or cross an ocean. Good proxies make this visible: in the name of the type, in an error the interface knows, or by being asynchronous.
A remote service should be used through the interface of the local one: price(sku). How do you design the proxy?
BreaksHide the distance
- How
- Same signature, blocking, errors become null.
- Limit
- A loop over 1,000 products becomes 1,000 round trips. A lost network looks like a product without a price.
- Choose when
- Never.
WorksSame method, own errors, timeouts
- How
pricemay raiseUnavailable, each call has a time limit.- Limit
- Callers must handle an error that the local class never raised, so it must be in the contract from the start.
- Choose when
- Few calls per request.
StrongAn interface made for distance
- How
prices(skus)in one call, asynchronous, with a deadline and typed failures. The local class implements it as well.- Limit
- The local case looks heavier than necessary.
- Choose when
- Whenever the far side is the normal case.
Choosing
When to use it and when not
Use it when
- Creating is expensive and often not needed
- Access depends on the caller
- Results repeat
- The object lives elsewhere
- Use must be counted or logged
- Clients must not change
Leave it when
- The object is simple and cheap
- Direct access is fine
- Callers must see the cost: make it explicit
- The proxy is slower than the work
- One client needs it: put it there
Which kind?
Where you meet proxies
| Place | Kind |
|---|---|
| Lazy relations of Hibernate | virtual |
@Transactional in Spring | interception around a call |
Proxy in JavaScript, reactivity in Vue | dynamic, any method |
| A gRPC stub | remote |
| nginx, an API gateway | the same idea between machines: reverse proxy |
weakref.proxy in Python | smart reference |
| A guard before an admin service | protection |
const reads = new Map<PropertyKey, number>();const user = new Proxy({ name: "Asha", city: "Pune" }, { get(target, key, receiver) { reads.set(key, (reads.get(key) ?? 0) + 1); return Reflect.get(target, key, receiver); },});console.log(user.name, user.name, reads.get("name")); // Asha Asha 2Summary
The whole topic in one minute.
Same interface, controlled access. Virtual creates late, protection checks, caching remembers, remote travels. One job per proxy, and the real subject stays clean.
Answer cheap questions without the real object, create it once, deny by default, guard every method, and give nobody the real one.
In production: lock the creation, bound and age what you remember, use versions against slow reads, put request ids on remote calls, wrap what you return, and watch for self calls and one query per row.
- Same interface, and control over whether, when and how the real object is reached.
- Virtual, protection, caching, remote: one job per proxy.
- A virtual proxy needs the cheap answers from somewhere else.
- Protection works only if nobody gets the real object.
- The interface can be transparent. Time and failure never are.