Provide a substitute object with the same interface as a real subject, so you can control access to it: defer its creation, guard who may use it, cache its results, or hide that it lives on another machine.
A proxy is an object that has the same interface as another object and sits in front of it. Callers think they are talking to the real thing. The proxy decides when the real object is created, whether a request is allowed through, and whether it can answer from a cache without forwarding at all. In this guide you follow one system from start to finish: the scan viewer at Meridian Health, a regional hospital group. Its radiology viewer pulls 40 MB imaging studies from a remote archive server. You will see how a single proxy class adds a lazy connection, an LRU cache and a per-clinician access check, while the viewer code and the archive client stay unchanged. In interviews, Proxy questions usually test whether you can tell it apart from Decorator and Adapter, so that is covered too.
The problem
A situation where the obvious design starts to hurt.
Meridian Health's radiology viewer runs on about 300 workstations across four hospitals. Clinicians open imaging studies through a RemoteScanArchive class that talks to the central archive server at pacs.meridian.local. Each scan is roughly 40 MB, and a remote fetch takes around 800 ms on the hospital network.
Three complaints land on the viewer team in the same sprint. First, the viewer opens a TLS session to the archive as soon as it starts, even on workstations where nobody opens a scan for hours, and the archive's connection limit is being hit at shift change. Second, clinicians flip back and forth between the same two or three studies during a consultation, and every flip triggers another 800 ms download of the same 40 MB. Third, the compliance officer points out that any logged-in user can open any patient's scan by typing its ID; the archive server does not know which clinician is assigned to which patient.
The obvious fix is to edit RemoteScanArchive: add a lazy connect, bolt on a cache dictionary, and sprinkle assignment checks into fetchScan. But that class is generated from the archive vendor's protocol definition and is shared with the billing and research teams, who need neither the cache nor the clinician check. The other obvious fix is to put the checks into every screen of the viewer that opens a scan, which is six places today and growing. Either way, unrelated concerns pile into code that should do one thing.
The solution
What the pattern proposes.
Keep RemoteScanArchive exactly as it is and introduce a ScanArchive interface that both it and a new ScanArchiveProxy implement. The viewer depends only on ScanArchive, so it cannot tell whether it holds the real archive client or the proxy.
The proxy is created per clinician session with the clinician's ID and the set of patients they are assigned to. When the viewer calls fetchScan(patientId, scanId), the proxy does three things in order. It checks the patient against the assignment set and throws AccessDeniedError if the clinician is not on that patient's care team, so a forbidden request never reaches the network. It looks in a small LRU cache keyed by patient and scan ID and returns the cached scan if present. Only on a cache miss does it touch the real archive, and it creates the RemoteScanArchive (opening the TLS session) at that moment, not when the viewer starts.
Each concern lives in one place. The vendor-generated client still only knows how to talk to the archive. The viewer still only knows how to render a scan. The proxy owns the policy of when and whether to call through. Billing and research keep using RemoteScanArchive directly, and if radiology later wants a different cache size or an audit log, only the proxy changes.
An everyday analogy
The same idea, outside software.
Think of the reading room of a city archive with closed stacks. You never walk into the stacks yourself. You hand a request slip to the archivist at the desk. The archivist checks your reader card and refuses requests for restricted collections. If someone asked for the same box an hour ago, it is often still on the trolley behind the desk and you get it immediately. Otherwise the archivist goes down to the basement, which they only bother to unlock once the first request of the day comes in. From your side of the desk, you asked for a box and got a box; the archivist decided how.
Structure
The pieces and how they relate.
Participants
- ScanArchive (Subject interface)
- Declares
fetchScan(patientId, scanId). Both the real archive client and the proxy implement it, which is what lets the proxy be swapped in without the viewer noticing. - RemoteScanArchive (Real Subject)
- Does the actual work: opens a TLS session to the archive server and downloads scans. It knows nothing about clinicians, caching or when it should be created.
- ScanArchiveProxy (Proxy)
- Holds a reference to the real subject, created on demand. Enforces the clinician's patient assignments, serves repeated requests from an LRU cache and forwards everything else to the real archive.
- Viewer (Client)
- Works only with the
ScanArchiveinterface. It is handed a proxy at login and renders whatever scan it gets back, handling access errors. - Scan
- The value returned by the archive: scan ID, patient ID and size. The proxy stores these in its cache.
Pseudocode
The solution to the scenario, language-neutral.
interface ScanArchive
method fetchScan(patientId, scanId): Scan
class RemoteScanArchive implements ScanArchive
constructor(host)
open TLS session to host
method fetchScan(patientId, scanId)
download scan over the network
return scan
class ScanArchiveProxy implements ScanArchive
field host, clinicianId, allowedPatients, capacity
field real = null
field cache = ordered map, oldest entry first
method fetchScan(patientId, scanId)
if patientId not in allowedPatients
throw AccessDenied(clinicianId, patientId)
key = patientId + "/" + scanId
if cache contains key
move key to the newest position
return cache[key]
if real is null
real = new RemoteScanArchive(host)
scan = real.fetchScan(patientId, scanId)
cache[key] = scan
if cache.size > capacity
remove the oldest entry
return scan
// at login
archive = new ScanArchiveProxy("pacs.meridian.local", "dr-okafor", {"p-101", "p-102"}, 20)
viewer.openStudy(archive, "p-101", "s-1")The code
The same solution in TypeScript, Python and PHP.
interface Scan {
id: string;
patientId: string;
sizeMb: number;
}
interface ScanArchive {
fetchScan(patientId: string, scanId: string): Scan;
}
class RemoteScanArchive implements ScanArchive {
remoteCalls = 0;
constructor(private readonly host: string) {
console.log(`Opening TLS session to ${host}`);
}
fetchScan(patientId: string, scanId: string): Scan {
this.remoteCalls++;
console.log(`Remote fetch ${scanId} from ${this.host}`);
return { id: scanId, patientId, sizeMb: 40 };
}
}
class AccessDeniedError extends Error {
constructor(message: string) {
super(message);
this.name = "AccessDeniedError";
Object.setPrototypeOf(this, AccessDeniedError.prototype);
}
}
class ScanArchiveProxy implements ScanArchive {
private real: RemoteScanArchive | null = null;
private readonly cache = new Map<string, Scan>();
constructor(
private readonly host: string,
private readonly clinicianId: string,
private readonly allowedPatients: Set<string>,
private readonly capacity = 20,
) {}
fetchScan(patientId: string, scanId: string): Scan {
if (!this.allowedPatients.has(patientId)) {
throw new AccessDeniedError(`${this.clinicianId} is not assigned to ${patientId}`);
}
const key = `${patientId}/${scanId}`;
const cached = this.cache.get(key);
if (cached !== undefined) {
this.cache.delete(key);
this.cache.set(key, cached);
console.log(`Cache hit ${scanId}`);
return cached;
}
const scan = this.archive().fetchScan(patientId, scanId);
this.cache.set(key, scan);
if (this.cache.size > this.capacity) {
const oldest = this.cache.keys().next().value as string;
this.cache.delete(oldest);
}
return scan;
}
remoteCalls(): number {
return this.real === null ? 0 : this.real.remoteCalls;
}
private archive(): RemoteScanArchive {
if (this.real === null) {
this.real = new RemoteScanArchive(this.host);
}
return this.real;
}
}
function openStudy(archive: ScanArchive, patientId: string, scanId: string): void {
try {
const scan = archive.fetchScan(patientId, scanId);
console.log(`Rendering ${scan.id} (${scan.sizeMb} MB)`);
} catch (e) {
if (e instanceof AccessDeniedError) {
console.log(`Blocked: ${e.message}`);
} else {
throw e;
}
}
}
const proxy = new ScanArchiveProxy(
"pacs.meridian.local",
"dr-okafor",
new Set(["p-101", "p-102"]),
2,
);
console.log("Viewer started");
openStudy(proxy, "p-101", "s-1");
openStudy(proxy, "p-101", "s-1");
openStudy(proxy, "p-102", "s-7");
openStudy(proxy, "p-205", "s-9");
console.log(`Remote calls: ${proxy.remoteCalls()}`);from collections import OrderedDict
from dataclasses import dataclass
from typing import Optional, Protocol
@dataclass(frozen=True)
class Scan:
id: str
patient_id: str
size_mb: int
class ScanArchive(Protocol):
def fetch_scan(self, patient_id: str, scan_id: str) -> Scan: ...
class RemoteScanArchive:
def __init__(self, host: str) -> None:
self.host = host
self.remote_calls = 0
print(f"Opening TLS session to {host}")
def fetch_scan(self, patient_id: str, scan_id: str) -> Scan:
self.remote_calls += 1
print(f"Remote fetch {scan_id} from {self.host}")
return Scan(scan_id, patient_id, 40)
class AccessDeniedError(Exception):
pass
class ScanArchiveProxy:
def __init__(
self,
host: str,
clinician_id: str,
allowed_patients: set[str],
capacity: int = 20,
) -> None:
self._host = host
self._clinician_id = clinician_id
self._allowed_patients = allowed_patients
self._capacity = capacity
self._real: Optional[RemoteScanArchive] = None
self._cache: OrderedDict[str, Scan] = OrderedDict()
def fetch_scan(self, patient_id: str, scan_id: str) -> Scan:
if patient_id not in self._allowed_patients:
raise AccessDeniedError(
f"{self._clinician_id} is not assigned to {patient_id}"
)
key = f"{patient_id}/{scan_id}"
if key in self._cache:
self._cache.move_to_end(key)
print(f"Cache hit {scan_id}")
return self._cache[key]
scan = self._archive().fetch_scan(patient_id, scan_id)
self._cache[key] = scan
if len(self._cache) > self._capacity:
self._cache.popitem(last=False)
return scan
def remote_calls(self) -> int:
return 0 if self._real is None else self._real.remote_calls
def _archive(self) -> RemoteScanArchive:
if self._real is None:
self._real = RemoteScanArchive(self._host)
return self._real
def open_study(archive: ScanArchive, patient_id: str, scan_id: str) -> None:
try:
scan = archive.fetch_scan(patient_id, scan_id)
print(f"Rendering {scan.id} ({scan.size_mb} MB)")
except AccessDeniedError as e:
print(f"Blocked: {e}")
if __name__ == "__main__":
proxy = ScanArchiveProxy("pacs.meridian.local", "dr-okafor", {"p-101", "p-102"}, 2)
print("Viewer started")
open_study(proxy, "p-101", "s-1")
open_study(proxy, "p-101", "s-1")
open_study(proxy, "p-102", "s-7")
open_study(proxy, "p-205", "s-9")
print(f"Remote calls: {proxy.remote_calls()}")<?php
declare(strict_types=1);
final class Scan
{
public function __construct(
public readonly string $id,
public readonly string $patientId,
public readonly int $sizeMb,
) {}
}
interface ScanArchive
{
public function fetchScan(string $patientId, string $scanId): Scan;
}
final class RemoteScanArchive implements ScanArchive
{
public int $remoteCalls = 0;
public function __construct(private readonly string $host)
{
echo "Opening TLS session to {$host}\n";
}
public function fetchScan(string $patientId, string $scanId): Scan
{
$this->remoteCalls++;
echo "Remote fetch {$scanId} from {$this->host}\n";
return new Scan($scanId, $patientId, 40);
}
}
final class AccessDeniedException extends RuntimeException {}
final class ScanArchiveProxy implements ScanArchive
{
private ?RemoteScanArchive $real = null;
/** @var array<string, Scan> */
private array $cache = [];
/** @param string[] $allowedPatients */
public function __construct(
private readonly string $host,
private readonly string $clinicianId,
private readonly array $allowedPatients,
private readonly int $capacity = 20,
) {}
public function fetchScan(string $patientId, string $scanId): Scan
{
if (!in_array($patientId, $this->allowedPatients, true)) {
throw new AccessDeniedException("{$this->clinicianId} is not assigned to {$patientId}");
}
$key = "{$patientId}/{$scanId}";
if (isset($this->cache[$key])) {
$scan = $this->cache[$key];
unset($this->cache[$key]);
$this->cache[$key] = $scan;
echo "Cache hit {$scanId}\n";
return $scan;
}
$scan = $this->archive()->fetchScan($patientId, $scanId);
$this->cache[$key] = $scan;
if (count($this->cache) > $this->capacity) {
unset($this->cache[array_key_first($this->cache)]);
}
return $scan;
}
public function remoteCalls(): int
{
return $this->real === null ? 0 : $this->real->remoteCalls;
}
private function archive(): RemoteScanArchive
{
if ($this->real === null) {
$this->real = new RemoteScanArchive($this->host);
}
return $this->real;
}
}
function openStudy(ScanArchive $archive, string $patientId, string $scanId): void
{
try {
$scan = $archive->fetchScan($patientId, $scanId);
echo "Rendering {$scan->id} ({$scan->sizeMb} MB)\n";
} catch (AccessDeniedException $e) {
echo "Blocked: {$e->getMessage()}\n";
}
}
$proxy = new ScanArchiveProxy('pacs.meridian.local', 'dr-okafor', ['p-101', 'p-102'], 2);
echo "Viewer started\n";
openStudy($proxy, 'p-101', 's-1');
openStudy($proxy, 'p-101', 's-1');
openStudy($proxy, 'p-102', 's-7');
openStudy($proxy, 'p-205', 's-9');
echo "Remote calls: {$proxy->remoteCalls()}\n";When to use it
Situations where it pays off.
The real object is expensive to create or connect, and many sessions never actually use it.
A virtual proxy defers creation until the first real request. Meridian's workstations stop holding archive connections they never use, which is exactly what was exhausting the server at shift change.
You need to check permissions before a call reaches an object you cannot or should not modify.
A protection proxy puts the check in front of the real subject, so forbidden requests are rejected before any network or disk work. The real class stays shared and policy-free.
The same expensive request is repeated and the result is safe to reuse for a while.
A caching proxy answers repeats locally. Callers keep the same interface and do not have to know a cache exists, so you can add, tune or remove it in one place.
The real object lives in another process or on another machine.
A remote proxy makes a network service look like a local object, hiding serialisation, connection handling and addressing behind ordinary method calls.
You want logging, metrics or auditing around every use of a service without touching its code or its callers.
Because the proxy sees every call, it is a natural place to record who requested what and how long it took.
How to implement it
Steps to introduce it in existing code.
Identify the interface clients already use, or extract one from the real class if clients depend on the concrete type. Here that is
ScanArchivewithfetchScan(patientId, scanId).Change clients to depend on the interface instead of the concrete class. The viewer's
openStudytakes aScanArchive, not aRemoteScanArchive.Create the proxy class implementing the same interface. Give it whatever it needs to build the real subject later, such as the host name, rather than a ready-made instance if you want lazy creation.
Add a private accessor that creates the real subject on first use and reuses it afterwards.
Implement each interface method in the order that avoids wasted work: reject unauthorised calls first, then try the cache, then forward to the real subject and store the result.
Decide how the proxy is created and handed out. A login service or factory that returns a
ScanArchivekeeps callers from bypassing the proxy by constructing the real class themselves.Test the proxy against the real subject's contract: allowed calls must return the same results, denied calls must fail before any remote work, and repeated calls must not hit the network.
Pros and cons
What you gain and what you pay.
Pros
- Clients keep using the same interface, so you can introduce or remove a proxy without changing them.
- Access control, caching and lazy creation live in one class instead of being scattered across every caller.
- The real subject stays focused and reusable; other teams can use it without the extra policy.
- You can control the real object's lifecycle, creating it late and even releasing it when idle.
- Open/closed in practice: new policies are new proxies, not edits to the shared client.
Cons
- Each call goes through one more layer, and a cache miss still costs the full remote call plus the proxy's bookkeeping.
- A caching proxy can serve stale data unless you define when entries expire or are invalidated.
- Remote proxies make network calls look local, which tempts callers into chatty loops and hides failures and latency they should handle.
- Protection only works if clients cannot reach the real subject directly; you need to control how instances are created.
- Lazy creation moves the cost and the failure of initialisation to the first real call, which can surprise users and complicate error handling.
Relations with other guides
Patterns it's often confused or combined with.
- Decorator: Add Behaviour by Wrapping, the Way Middleware Does
Same shape: both wrap an object behind its own interface. A decorator adds behaviour and is usually stacked by the client; a proxy controls access to its subject and usually manages the subject's lifecycle itself.
- Adapter Pattern: Fit a Third-Party SDK Into Your Own Interface
An adapter gives a wrapped object a different interface so it fits a client. A proxy keeps exactly the same interface, so the client cannot tell it apart from the real subject.
- Facade Pattern: One Simple Entry Point to a Messy Subsystem
A facade also stands in front of something complex, but it defines a new, simpler interface over a whole subsystem. A proxy mirrors one object's interface.
- Cache-Aside: Invalidation, Stampedes, TTLs and Stale Reads
A caching proxy is the object-level version of cache-aside: check the cache, on a miss load from the source and store. The same invalidation and staleness questions apply.
- Circuit breaker: fail fast when a dependency is down
A remote proxy is a natural place to put a circuit breaker, so callers get a fast failure instead of waiting on an archive server that is already down.
- Timeouts and Deadline Propagation
Because a remote proxy hides the network, it should also own the timeout on each call; otherwise a slow server turns an innocent-looking method call into a hang.
Common questions
Short answers to the usual doubts.
What is the difference between Proxy and Decorator?
Structurally they are nearly identical: a wrapper implementing the subject's interface and forwarding calls. The difference is intent and control. A decorator adds behaviour, is typically composed by the client, and is often stacked several deep. A proxy controls access to one subject: it may create it lazily, refuse calls, or answer without forwarding, and it usually manages the subject's lifecycle so the client never sees the real object. In Meridian's viewer, the proxy decides whether the archive is contacted at all, which is the hallmark of a proxy.
Which kinds of proxy should I be able to name in an interview?
The common ones are the virtual proxy (lazy creation of an expensive object), the protection proxy (permission checks), the caching proxy (reusing results), the remote proxy (a local stand-in for an object in another process, as in RPC stubs) and the logging or smart-reference proxy (auditing, reference counting). The Meridian proxy combines virtual, protection and caching behaviour in one class, and RemoteScanArchive itself plays a remote-proxy role for the archive server.
Should one proxy do access control, caching and lazy loading, or should I split them?
For a small, stable set of rules, one proxy is easier to read and test. If the concerns change independently or need to be combined differently per client, split them into separate proxies that each wrap a ScanArchive, which makes the chain look a lot like stacked decorators. Order matters either way: the access check must run before the cache, or a denied clinician could receive a scan someone else cached.
What is the cost of the LRU cache in the example?
Lookups, inserts and evictions are O(1) on average. TypeScript's Map and PHP arrays preserve insertion order, so re-inserting a key on a hit moves it to the newest position and the first key is the oldest. Python's OrderedDict does the same with move_to_end and popitem(last=False). Memory is bounded by the capacity: at 20 scans of 40 MB, that is about 800 MB per session, which is why capacity is a constructor argument.
How do I stop callers from bypassing the proxy?
Do not let them construct the real subject. Hand out ScanArchive instances from a login service or factory that always returns a proxy, keep the real class in a module or namespace the viewer does not import, and type every dependency as the interface. Code review and dependency rules in the build can enforce the last part.