AlgoViz

Proxy pattern

medium 50 min

A 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

0:00 / 4:53

Proxy

1:05Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

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

  1. 1994

    The book Design Patterns describes Proxy and names remote, virtual and protection proxies and smart references.

  2. 2000

    PEP 205, weak references for Python, is written. The weakref module with proxy objects arrives in Python 2.1 in 2001.

  3. 2000

    Java 1.3 adds java.lang.reflect.Proxy: classes for a set of interfaces, made while the program runs.

  4. 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.

Step 1 of 3

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.

The page at the palace gate
z z zMarket: 8Market?

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

Python
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")          # 3
Run it. Opening an album loads all pictures, although only one is looked at. And each client repeats the fix.
Edit and run it in your browser

The album

100×50 MB=5 GB100×1 KB=100 KB100 \times 50\,\text{MB} = 5\,\text{GB} \qquad 100 \times 1\,\text{KB} = 100\,\text{KB}
Assumed: a proxy with name and size takes about 1 KB. 5 GB / 100 KB = 50,000 times less, until somebody looks.

The design that hurts

createsGallery+ show(): if not loaded+ layout(): loads allRealImage- pixels: 50 MB+ RealImage(): loads+ display()

1/3Creating is loading

The constructor does the expensive work, so whoever makes a list of images pays for all.

uses

The smell: the same 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

Client+ holds a Subject«interface»Subject+ request()

1/4Subject

One contract. The client is written against it and never learns more.

usesimplementshas (lives on)

In our code the proxy's field has the interface type where it can. A virtual proxy must know how to create the real one, so it holds a factory.

One request, with everything a proxy may do

No real proxy should do all of this. One job each.

The same in six steps

  1. 1

    The client calls

    subject.request(). It does not know who answers.

  2. 2

    Before

    The proxy checks permission, validates arguments, notes the call.

  3. 3

    Create if needed

    A virtual proxy makes the real object now, not earlier.

  4. 4

    Delegate

    The same method on the real object.

  5. 5

    Work

    The real object loads, queries, transfers.

  6. 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.

KindQuestion it answersNew danger
VirtualIs it needed now?The cost appears at a surprising moment
ProtectionMay this caller?A second door without a proxy
CachingDo I know that already?Old answers, memory
RemoteWhere is it?Slow, partial failure, unknown outcome
LoggingWho called what?Secrets in logs
Smart referenceWho still uses it?Counts that go wrong, cycles
SynchronizingWho may enter now?Holding the lock during long work

Virtual proxy, state by state

Cheap questions do not wake the real object. This only works if the proxy has the cheap answers, here from an index.

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
price may raise Unavailable, 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

PlaceKind
Lazy relations of Hibernatevirtual
@Transactional in Springinterception around a call
Proxy in JavaScript, reactivity in Vuedynamic, any method
A gRPC stubremote
nginx, an API gatewaythe same idea between machines: reverse proxy
weakref.proxy in Pythonsmart reference
A guard before an admin serviceprotection
Reverse proxies and gateways are system design: see API gateway.
TypeScript
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 2
JavaScript has proxies in the language. One handler for every property: this one counts reads.

Summary

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.

Sources