LLD

Structural Patterns

Proxy pattern

Some objects should not be reached directly: a record only some people may read, or scans too slow to load until someone asks. We build an HR records service twice, once with checks and loading in every caller and once behind two proxies, and look at where each proxy has to sit.

An HR system keeps a file for every employee. The file has a profile (name, job title, manager) and a set of scanned documents: the offer letter, the PAN card, a degree certificate. The profile is a small row in a table. The scans are large, and reading them from the document archive takes a second or more.

Two rules apply to every file. Not everyone may open it: an employee may read their own, a manager their team's, and HR everyone's. And nobody should wait for the scans unless they open the documents tab.

The Proxy pattern puts an object in front of the real one, with the same interface, to control whether and when calls reach it. In this article we build the records service twice. In the first version every page checks permissions itself and every open reads every scan. In the second, two proxies do those jobs: one checks who is asking, and one loads the scans only when they are first needed. Then we look at where each proxy has to sit, what the pattern costs, and how it differs from a Decorator.

All the code is Java. The finished project compiles and runs, and its snippets have an Open file button that shows the whole file in a code browser. The first version's snippets come from a separate project that compiles.

The employee files we are building

The service must:

  1. Open an employee's file by id, and show the profile.
  2. Let an employee open their own file, a manager the files of their direct reports, and HR every file. Everyone else is refused.
  3. Read the scanned documents from the archive only when someone asks for them, and only once for each opened file, even when several threads ask at the same moment.
  4. If the archive fails, report the failure, and try again on the next request.
  5. Give every page (the profile page, the documents tab, a payslip export) the same interface, so no page has to know these rules exist.
Two proxies in front of the files
A page asks its access proxy to open a file (1). The proxy asks the record store, which reads only the profile and makes a stand-in for the file (2). The proxy checks the rule against that profile (3), so a refused caller never gets the file and no scan is read. An allowed caller gets the stand-in, which answers the profile at once (4). The first request for documents builds the real file from the archive (5), and later requests use it without asking again (6).A page asks its access proxy to open a file (1). The proxy asks the record store, which reads only the profile and makes a stand-in for the file (2). The proxy checks the rule against that profile (3), so a refused caller never gets the file and no scan is read. An allowed caller gets the stand-in, which answers the profile at once (4). The first request for documents builds the real file from the archive (5), and later requests use it without asking again (6).
One proxy decides who may open a file. The other decides when the scans are read. A page asks its access proxy to open a file (1). The proxy asks the record store, which reads only the profile and makes a stand-in for the file (2). The proxy checks the rule against that profile (3), so a refused caller never gets the file and no scan is read. An allowed caller gets the stand-in, which answers the profile at once (4). The first request for documents builds the real file from the archive (5), and later requests use it without asking again (6).

The first version: checks in every caller

The obvious way to write this has one store that opens a file completely, with the profile and every scan:

RecordStore.javalines 10–15 of 16
    public EmployeeRecord open(String employeeId) {        Profile profile = profiles.find(employeeId)                .orElseThrow(() -> new IllegalArgumentException("No employee " + employeeId));        // Every open reads every scan, even for a page that shows only the name.        return new EmployeeRecord(profile, archive.loadScans(employeeId));    }

Each page then checks permissions itself. Here is the profile page:

ProfilePage.javalines 8–17 of 18
    public String show(String viewerId, boolean viewerInHr, String employeeId) {        EmployeeRecord record = store.open(employeeId);        boolean allowed = viewerInHr                || viewerId.equals(employeeId)                || viewerId.equals(record.profile().managerId());        if (!allowed) {            return "Not allowed";        }        return record.profile().name() + ", " + record.profile().jobTitle();    }

And the documents tab:

DocumentsPage.javalines 10–15 of 16
    public List<Document> show(String viewerId, boolean viewerInHr, String employeeId) {        if (!viewerInHr && !viewerId.equals(employeeId)) {            throw new IllegalStateException("Not allowed");        }        return store.open(employeeId).documents();    }

For one page and one rule this would be fine. With three pages, it goes wrong in four ways.

The pages disagree. The profile page lets a manager read a report's file. The documents tab forgot that rule, so a manager can see Karan's name but not his offer letter. The two pages also refuse differently: one returns a string, the other throws.

A page can forget the check entirely. PayslipExport opens any file and prints the name, with no check at all. Any code that can call it can read any employee's details. Nothing in the store stops it, because the store has no idea who is asking.

The check runs after the expensive part. The profile page opens the file first and checks second. A refused request still reads every scan from the archive, and an unknown id gives "No employee E999" to anyone who asks, which tells them which ids exist.

Every open reads every scan. The profile page needs a name and a job title, and pays for every document anyway.

Rules in every caller
Each page talks to the store directly and carries its own copy of the access rule. The profile page checks after opening, the documents tab has no manager rule, and the payslip export has no check at all, shown in red. Every open reads every scan, shown by the amber arrows into the archive.Each page talks to the store directly and carries its own copy of the access rule. The profile page checks after opening, the documents tab has no manager rule, and the payslip export has no check at all, shown in red. Every open reads every scan, shown by the amber arrows into the archive.
Three pages, three versions of the rule, and every one of them reads the scans. Each page talks to the store directly and carries its own copy of the access rule. The profile page checks after opening, the documents tab has no manager rule, and the payslip export has no check at all, shown in red. Every open reads every scan, shown by the amber arrows into the archive.

The idea

The pattern works like this:

  • The real object and its stand-in implement the same interface. Here the store and the access proxy both implement EmployeeFiles, and the real file and its lazy stand-in both implement EmployeeFile.
  • The proxy holds a reference to the real object, or knows how to get it.
  • Every call goes to the proxy first. The proxy decides whether the call goes on, and when.
  • The caller cannot tell whether it holds the real object or a proxy.

The object behind the proxy is the real subject, and the shared interface is the subject. A protection proxy controls who may reach the real object. A virtual proxy stands in for an object that is expensive to create, and creates it only when it is first needed. A remote proxy stands in for an object on another machine: the client stub that a gRPC or RMI library generates is one, because calling it looks like a local call. This article builds the first two.

Building it, step by step

Step 1: one interface for every way in

Both proxies need an interface to share with what they stand in front of. There are two, because there are two things to stand in front of. The store opens files:

records/EmployeeFiles.javalines 3–5 of 5
public interface EmployeeFiles {    EmployeeFile open(String employeeId);}

And a file gives its profile and its documents:

records/EmployeeFile.javalines 5–9 of 9
public interface EmployeeFile {    Profile profile();     List<Document> documents();}

Pages depend on these two interfaces, the records they return, and the AccessDeniedException a refusal throws. A page that holds an EmployeeFiles has no way to know whether it is talking to the store or to a proxy in front of it.

Step 2: the protection proxy

The first proxy checks who is asking:

access/ProtectedFiles.javalines 10–43 of 43
public class ProtectedFiles implements EmployeeFiles {    private final EmployeeFiles inner;    private final Viewer viewer;     ProtectedFiles(EmployeeFiles inner, Viewer viewer) {        this.inner = Objects.requireNonNull(inner, "inner");        this.viewer = Objects.requireNonNull(viewer, "viewer");    }     @Override    public EmployeeFile open(String employeeId) {        Objects.requireNonNull(employeeId, "employeeId");        EmployeeFile file;        try {            file = inner.open(employeeId);        } catch (RecordNotFoundException e) {            if (viewer.inHr()) {                throw e;            }            // Staff cannot tell an unknown id from a file they may not open.            throw new AccessDeniedException(viewer, employeeId);        }        if (!mayOpen(file.profile())) {            throw new AccessDeniedException(viewer, employeeId);        }        return file;    }     private boolean mayOpen(Profile owner) {        return viewer.inHr()                || viewer.employeeId().equals(owner.employeeId())                || owner.reportsTo(viewer.employeeId());    }}

The proxy opens the file through the store first, on line 24. That is cheap: the store reads one profile and hands back a stand-in, and no scan is read. The proxy then checks the rule against the profile that stand-in carries (line 32), and either hands the file over or throws AccessDeniedException. A refused caller never gets the file, so nothing can be read from it and no scan is loaded for them.

The check uses the file's own profile on purpose, so the profile is read once and the check and the file always agree. A proxy that looked the profile up itself, and then asked the store to open the file, would read it twice. If Karan moved to another team between the two reads, Ravi could be handed a file that names his new manager.

mayOpen is the whole rule in one place: HR may open every file, anyone may open their own, and a manager may open the files of their direct reports. The rule covers direct reports only, so a manager's manager is refused unless they are in HR.

An unknown id gets the same refusal as a file the viewer may not open (lines 29 and 30). A staff member therefore cannot use the service to find out which ids exist. HR still gets RecordNotFoundException for an unknown id, because HR may open every file anyway.

Decision

How does the proxy know who is asking?

A viewer parameter on every method

open(viewer, employeeId) works, but the real store then takes a parameter it never reads, and every page has to pass it along. A page that passes the wrong viewer, or a made-up one, gets the wrong answer.

A thread-local holding the signed-in user

Nothing has to be passed, but the rule now depends on hidden state. A call made on another thread, such as a background export, sees no user or the wrong one.

One proxy per signed-in person, holding the viewerOur pick

The proxy is created when a person signs in, with their Viewer fixed inside it, and the page gets that proxy. The interface stays clean, the store never sees a viewer, and a page holding the proxy cannot ask on someone else's behalf. A proxy is a small object with two fields, so creating one per session costs little.

Decision

What does a refused call return?

An empty result, as if the file did not exist

Pages need no exception handling, but they also cannot tell "not allowed" from "not found". A bug in the rule then looks like missing data, and nobody notices.

An AccessDeniedExceptionOur pick

A refusal is a different answer from "not found", so it gets its own type. The page shows a "you do not have access" message, and the server can log refusals to spot misuse. The one place we blur the two is deliberate: staff asking for an unknown id are refused, so they learn nothing about which ids exist.

Only sign-in builds a proxy:

access/SignIn.javalines 7–18 of 18
public class SignIn {    private final EmployeeFiles store;     public SignIn(EmployeeFiles store) {        this.store = Objects.requireNonNull(store, "store");    }     // Called once per session, with the viewer the login system has vouched for.    public EmployeeFiles filesFor(Viewer viewer) {        return new ProtectedFiles(store, viewer);    }}

ProtectedFiles has a package-private constructor, so code outside the access package goes through SignIn, which is meant to be called with the viewer the login system has vouched for. Java cannot stop other code in the same program from creating its own RecordStore or SignIn, or calling Viewer.hr with any id it likes. What stops that is the wiring: the store, the profile table and the archive are created once at startup and handed only to SignIn, and pages are given the proxy it returns, never the parts behind it. A review that finds new RecordStore, new SignIn or Viewer.hr in page code has found a hole in the rule.

AccessDeniedException is a message for a person: the page catches it and shows it. A null id or a missing collaborator throws NullPointerException when the object is built or called, because that is a mistake in the code, not something a user did.

Step 3: the virtual proxy for the scans

The second proxy stands in for the real file. RecordStore.open reads the profile, which is cheap, and wraps it in a LazyFile. The real file is a LoadedFile, a record that holds the profile and the documents:

records/LoadedFile.javalines 6–11 of 11
record LoadedFile(Profile profile, List<Document> documents) implements EmployeeFile {    LoadedFile {        Objects.requireNonNull(profile, "profile");        documents = List.copyOf(documents);    }}

It is built only when someone first asks for the documents:

records/LazyFile.javalines 11–93 of 93
final class LazyFile implements EmployeeFile {    private final Profile profile;    private final DocumentArchive archive;    private final Duration maxWait;    private final AtomicReference<CompletableFuture<EmployeeFile>> inFlight = new AtomicReference<>();    private volatile EmployeeFile real;     LazyFile(Profile profile, DocumentArchive archive, Duration maxWait) {        this.profile = profile;        this.archive = archive;        this.maxWait = maxWait;    }     @Override    public Profile profile() {        return profile;    }     @Override    public List<Document> documents() {        EmployeeFile loaded = real;        if (loaded != null) {            return loaded.documents();        }        CompletableFuture<EmployeeFile> mine = new CompletableFuture<>();        CompletableFuture<EmployeeFile> running = inFlight.compareAndExchange(null, mine);        if (running == null) {            return loadAndShare(mine).documents();        }        return waitFor(running).documents();    }     // Only one thread loads. Threads that arrive meanwhile get its result, or the same exception.    private EmployeeFile loadAndShare(CompletableFuture<EmployeeFile> mine) {        try {            EmployeeFile file = new LoadedFile(profile, load());            real = file;            mine.complete(file);            return file;        } catch (Throwable failure) {            // Clear first, so a request arriving now starts a new attempt instead of reading this failure.            inFlight.compareAndSet(mine, null);            mine.completeExceptionally(failure);            throw failure;        }    }     private EmployeeFile waitFor(CompletableFuture<EmployeeFile> running) {        try {            return running.get(maxWait.toMillis(), TimeUnit.MILLISECONDS);        } catch (ExecutionException e) {            if (e.getCause() instanceof RuntimeException failure) {                throw failure;            }            if (e.getCause() instanceof Error error) {                throw error;            }            throw new IllegalStateException(e.getCause());        } catch (TimeoutException e) {            throw new IllegalStateException("Timed out waiting for the scans of " + profile.employeeId(), e);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();            throw new IllegalStateException("Interrupted while waiting for the scans of " + profile.employeeId(), e);        }    }     private List<Document> load() {        List<Document> scans = archive.loadScans(profile.employeeId());        if (scans == null) {            throw badAnswer("no list");        }        for (Document scan : scans) {            if (scan == null) {                throw badAnswer("a null entry");            }        }        return scans;    }     private IllegalStateException badAnswer(String what) {        return new IllegalStateException("The archive returned " + what + " for " + profile.employeeId());    }}

profile() answers at once from the profile the stand-in holds. documents() does the work. Once the real file exists, real holds it, and every call goes straight to it (lines 31 to 34).

The first call builds it. Several threads can make that first call together, for example a documents tab and a "download all" button opened at once, and the archive should be read only once. So the first thread to arrive claims the load by putting a CompletableFuture into inFlight (line 36). Only that thread calls the archive, in loadAndShare. Every thread that arrives while it runs finds the future already there, and waits on it in waitFor.

Three details make this safe:

  • When the load works, the loading thread stores the file in real and completes the future, so every waiting thread gets the same file.
  • When the load fails, for any reason, inFlight is cleared first (line 52), so a request that arrives now starts a new attempt. Then every waiting thread gets the same exception. loadAndShare catches Throwable, because a client library can throw a checked exception it never declared, and missing that would leave the attempt stuck for good. Ten threads that ask during one failing load hear back after one attempt.
  • A waiting thread gives up after maxWait, which the store is given (30 seconds in the demo), and it can be interrupted while it waits. The loading thread does not give up on its own: if the archive call hangs, the load hangs with it. The archive client therefore needs its own timeout, shorter than maxWait.

A simpler version puts a synchronized lock around the load. It also loads once, but after a failure each waiting thread takes the lock in turn and tries again, so ten threads wait for ten failures in a row.

real is volatile, so a thread that reads it sees either nothing or the finished file. load checks the archive's answer, and a missing list and a list with a null entry both raise IllegalStateException, the error for a bad answer from outside. LoadedFile keeps a copy made with List.copyOf, so a later change to the archive's list does not leak in, and no page can change it.

Decision

What happens when loading the scans fails?

Remember the failure, and fail every later call the same way

A broken archive is then not hit again for this file. But one timeout would break the file for as long as it is open, and the user would have to close it and open it again to retry.

Report it, and try again on the next callOur pick

If the archive throws, inFlight is cleared and real stays empty. The caller, and every thread waiting with it, sees the failure, and the next request tries the archive again. That is right for a one-off timeout. The cost is that an archive that is down for minutes is called again on every click, and each click waits for it to fail. A short cool-down, or a circuit breaker in front of the archive that fails at once for a while after several failures, stops that.

Step 4: the real store, and the order of the proxies

The store itself is now short:

records/RecordStore.javalines 21–27 of 28
    @Override    public EmployeeFile open(String employeeId) {        Objects.requireNonNull(employeeId, "employeeId");        Profile profile = profiles.find(employeeId)                .orElseThrow(() -> new RecordNotFoundException(employeeId));        return new LazyFile(profile, archive, maxWait);    }

It reads the profile, refuses an unknown id with RecordNotFoundException, and returns a new LazyFile. It has no access rule and no loading logic, and it is the only class that creates a LazyFile, which is package-private.

The two proxies have to sit in a particular order: the access check outermost, before any file is handed over, and the lazy loading behind it.

Decision

Where does the access check sit?

Inside each file, checked when the documents are first read

The store hands out a file to anyone, and the file checks before it loads the scans. But profile() needs no load, so the profile would go out unchecked.

Before the file is handed over, on the file's own profileOur pick

A refused caller never gets a file object, so there is nothing to read, pass on or load. One check covers the profile and the documents together, and it runs once per open.

That check is made once, when the file is opened, and it lasts as long as the file object. If Karan moves to Neha's team, Ravi's next open is refused, but a file Ravi opened before the move can still load Karan's documents. Pages should therefore hold a file for one request, not for a whole session. Where losing access must take effect at once, such as when someone leaves the company, the proxy can hand back its own EmployeeFile wrapper whose documents() checks again before it loads.

Decision

Should loaded scans be shared between opens?

Keep one loaded file per employee, shared by everyone who opens it

A file opened by many people reads the archive once. But the map grows with every employee ever opened, a newly uploaded scan does not show up, and the map has to sit behind the access check. If it sat in front, a file loaded for HR would be handed to the next person who asked, with no check at all.

A new file for every openOur pick

Each open gets a fresh profile and a fresh stand-in, so a new scan shows up on the next open, and memory is freed when the page lets go of the file. The cost is that two separate opens of the same employee read the scans twice, as steps 4 and 7 of the demo show.

One store serves the whole application, while each signed-in person gets their own access proxy in front of it.

The finished design

The finished design
ProtectedFiles and RecordStore both implement EmployeeFiles, and ProtectedFiles holds the store as its inner EmployeeFiles. SignIn creates one ProtectedFiles per signed-in person. RecordStore reads profiles through ProfileTable and creates one LazyFile per open. LazyFile and LoadedFile both implement EmployeeFile: LazyFile builds its LoadedFile from the DocumentArchive on the first documents() call and keeps it. Profile, Document, Viewer and LoadedFile are records.ProtectedFiles and RecordStore both implement EmployeeFiles, and ProtectedFiles holds the store as its inner EmployeeFiles. SignIn creates one ProtectedFiles per signed-in person. RecordStore reads profiles through ProfileTable and creates one LazyFile per open. LazyFile and LoadedFile both implement EmployeeFile: LazyFile builds its LoadedFile from the DocumentArchive on the first documents() call and keeps it. Profile, Document, Viewer and LoadedFile are records.
Each proxy implements the interface of the object it stands in front of, and holds that object. ProtectedFiles and RecordStore both implement EmployeeFiles, and ProtectedFiles holds the store as its inner EmployeeFiles. SignIn creates one ProtectedFiles per signed-in person. RecordStore reads profiles through ProfileTable and creates one LazyFile per open. LazyFile and LoadedFile both implement EmployeeFile: LazyFile builds its LoadedFile from the DocumentArchive on the first documents() call and keeps it. Profile, Document, Viewer and LoadedFile are records.

Here is one manager opening a report's file and reading the documents twice:

A manager opens a report's file
Ravi's page asks his access proxy to open E102 (1). The proxy asks the store (2), which reads Karan's profile from the table (3) and returns a stand-in holding only that profile. The proxy sees that Karan reports to Ravi and hands the stand-in over (4). The first documents() call reads the scans from the archive and keeps the real file (5). The second one returns the same list without asking (6).Ravi's page asks his access proxy to open E102 (1). The proxy asks the store (2), which reads Karan's profile from the table (3) and returns a stand-in holding only that profile. The proxy sees that Karan reports to Ravi and hands the stand-in over (4). The first documents() call reads the scans from the archive and keeps the real file (5). The second one returns the same list without asking (6).
The rule runs once, the scans load once, and the second read costs no archive call. Ravi's page asks his access proxy to open E102 (1). The proxy asks the store (2), which reads Karan's profile from the table (3) and returns a stand-in holding only that profile. The proxy sees that Karan reports to Ravi and hands the stand-in over (4). The first documents() call reads the scans from the archive and keeps the real file (5). The second one returns the same list without asking (6).

The whole project is below. Click any class name in the code to open that class.

accessProtectedFiles.java
package access; import java.util.Objects; import records.EmployeeFile;import records.EmployeeFiles;import records.Profile;import records.RecordNotFoundException; public class ProtectedFiles implements EmployeeFiles {    private final EmployeeFiles inner;    private final Viewer viewer;     ProtectedFiles(EmployeeFiles inner, Viewer viewer) {        this.inner = Objects.requireNonNull(inner, "inner");        this.viewer = Objects.requireNonNull(viewer, "viewer");    }     @Override    public EmployeeFile open(String employeeId) {        Objects.requireNonNull(employeeId, "employeeId");        EmployeeFile file;        try {            file = inner.open(employeeId);        } catch (RecordNotFoundException e) {            if (viewer.inHr()) {                throw e;            }            // Staff cannot tell an unknown id from a file they may not open.            throw new AccessDeniedException(viewer, employeeId);        }        if (!mayOpen(file.profile())) {            throw new AccessDeniedException(viewer, employeeId);        }        return file;    }     private boolean mayOpen(Profile owner) {        return viewer.inHr()                || viewer.employeeId().equals(owner.employeeId())                || owner.reportsTo(viewer.employeeId());    }}
Click a class name in the code to open its fileJava · 43 lines · 458 in the project

The demo in demo/Main.java signs in three people: Meena, an analyst; Ravi, her manager; and Asha, in HR. SignIn gives each one their own ProtectedFiles in front of one shared store. A fake archive counts how often it is read:

$ java demo.Main
1. Meena opens her own file
   Meena Iyer, Analyst  (archive loads: 0)
2. Meena opens her documents tab
   Offer letter, PAN card  (archive loads: 1)
3. Meena opens Karan's file
   refused: E101 may not open the file of E102
4. Ravi, Karan's manager, opens Karan's file and reads the documents twice
   Offer letter, Degree certificate  (archive loads: 2)
5. Ravi opens an id that does not exist
   refused: E100 may not open the file of E999
6. Asha, in HR, opens the same id
   not found: No employee E999
7. The archive times out once while Asha reads Karan's documents
   first try: Archive timed out loading E102
   second try: Offer letter, Degree certificate  (archive loads: 4)
8. Twenty threads read one opened file's documents at the same moment
   archive loads for that file: 1, different lists handed out: 1, failures: 0

Follow the archive count. Opening a file and showing the profile reads nothing (step 1). The first documents request reads once (step 2). Meena is refused Karan's file (step 3), and that refusal costs no archive read. Ravi reads Karan's documents twice and the count goes up by one (step 4). Ravi gets the same refusal for an unknown id as for a file outside his team (step 5), while Asha in HR is told the id does not exist (step 6). In step 7 Asha opens Karan's file again, which is a new open, and the archive times out once: the failed try and the retry are two reads, and the second one succeeds. In step 8 twenty threads read one opened file at once: the archive is read once, every thread gets the same list, and none of them fails.

What it costs

The pattern makes one kind of change cheap and another more expensive.

Changing a rule is cheap. Giving managers' managers access changes mayOpen, and the proxy's constructor and SignIn, because the proxy needs the profile table again to walk up the chain of managers. The walk must stop if it meets a loop: Profile stops a person managing themselves, not two people managing each other. A temporary-access rule needs a store of grants, which SignIn passes to each proxy. Either way no page changes, and every page gets the new rule at once.

Adding a method to an interface is more expensive. If EmployeeFiles gains search(name), the access proxy must decide what a search returns for each viewer, which is a real design question, and the store must implement it. A proxy that forwards a new method without thinking about it is a hole in the rule. A default method on the interface is a quieter version of the same hole: the proxy inherits it, and the compiler asks for no decision.

Which change is cheap
A rule that needs only what the proxy already holds (left) changes only ProtectedFiles, outlined in amber, and no page or store changes. A new search method (right) changes the EmployeeFiles interface, the access proxy, which must filter results per viewer, and the store, all outlined in amber.A rule that needs only what the proxy already holds (left) changes only ProtectedFiles, outlined in amber, and no page or store changes. A new search method (right) changes the EmployeeFiles interface, the access proxy, which must filter results per viewer, and the store, all outlined in amber.
A new rule changes one method. A new way in changes every class on that path. A rule that needs only what the proxy already holds (left) changes only ProtectedFiles, outlined in amber, and no page or store changes. A new search method (right) changes the EmployeeFiles interface, the access proxy, which must filter results per viewer, and the store, all outlined in amber.

There are smaller costs too:

  • Laziness moves the wait. Opening a file is fast, but the first click on the documents tab now takes the second the open used to take.
  • A first read can wait for someone else's load. Other threads reading the same file wait for the one archive call. Threads reading other files do not, because every file has its own attempt.

When a proxy is too much

With one page, the page can check the rule itself, and small, fast scans can simply load on open. A proxy earns its place when many callers need the same control, or the real object is expensive to create.

Proxy or Decorator?

The two have the same class diagram: a class implements an interface and holds another object of that interface. The Decorator pattern page draws the line by asking why the wrapper exists, and this page agrees with it.

DecoratorProxy
Why it existsTo add a job: retries, timing, bufferingTo stand in for the real object or control access to it: a remote stub, lazy loading, a permission check
Where the inner object comes fromPassed in by whoever builds the stackOften created or found by the proxy itself
How manySeveral, stacked in an order chosen where they are builtUsually one per job: access, lazy loading or a remote call
Who chooses itWhoever builds the stack, by choosing which layers to useOften fixed: the caller may not know a proxy is there

In this design LazyFile creates its real file itself, and ProtectedFiles is given the store by SignIn.

A short way to say it: a decorator adds something to an object, and a proxy controls the way to it. The line is blurry in practice, and the Decorator page's cache could fairly be called a caching proxy. Our access proxy could not be a decorator, though: it does not add a job around the answer, it decides whether there is an answer at all.

In an interview

Proxies appear inside many low-level design questions:

  • permission checks in front of a document store or a bank account;
  • lazy loading of large images, or of an object's related rows in a database layer;
  • a generated client stub for a remote call.

We suggest presenting it in this order:

  1. Say what the proxy controls: who may reach the object, when it is created, or where it lives. That names the kind of proxy.
  2. Write the shared interface, then the proxy with its inner field, and show the one place where it decides whether to call inner.
  3. Say where it sits and why. For an access check, that means in front of anything that holds data, including any cache.

Common mistakes:

  • Checking after the expensive work. A proxy that loads the scans and then checks has already paid for them, and may already have leaked them into a log or a cache.
  • A proxy with a second way around it. If pages can still create a RecordStore themselves and skip the proxy, the rule is only a suggestion. Here pages are given only what SignIn returns, and the store is created once at startup.
  • A lazy load that lets every thread load. Two threads that both see nothing loaded both read the archive, and they can end up holding two different lists for the same file.
  • Remembering a failure as an empty list. A timeout then looks like an employee with no documents, which is worse than an error.
  • Retrying a failed load inside a lock. The waiting threads then fail one after another, each paying for its own attempt.

Summary

  • Use a Proxy when every caller must go through the same control on the way to an object: who may reach it, or when it is created.
  • The proxy implements the real object's interface and holds it, so callers cannot tell the difference.
  • A protection proxy checks before handing anything over, and refuses before any expensive work is done. A virtual proxy creates the real object on first use, with one shared attempt that every waiting thread hears back from, and does not remember failures.
  • Order matters: an access check goes in front of anything that holds data.
  • Changing a rule is cheap. A new method on the interface needs a decision in every proxy.
  • A Decorator has the same shape but adds a job around the call. A Proxy controls the way to the object.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.