Skip to content

Proxy Pattern: Control Access with a Stand-In Object

Learn the Proxy pattern through a hospital scan viewer that adds lazy connection, caching and access checks without touching the remote archive client.

13 min readDesign patternStructural

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.

The viewer depends on ScanArchive. ScanArchiveProxy implements the same interface and lazily creates and wraps RemoteScanArchive.Viewer calls ScanArchive (fetchScan). RemoteScanArchive implements ScanArchive. ScanArchiveProxy implements ScanArchive. ScanArchiveProxy creates RemoteScanArchive (on first miss). ScanArchiveProxy calls RemoteScanArchive (forwards misses). RemoteScanArchive creates Scan. ScanArchiveProxy has a Scan (cache).VieweropenStudy(archive,patientId, scanId)«interface»ScanArchivefetchScan(patientId,scanId): ScanRemoteScanArchivereal subject, talksto the serverScanArchiveProxyaccess check, LRUcache, lazy realScanid, patientId,sizeMbProxy order ofchecksdeny, then cache,then create real an…fetchScanon first missforwards missescache
The viewer depends on ScanArchive. ScanArchiveProxy implements the same interface and lazily creates and wraps RemoteScanArchive.

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 ScanArchive interface. 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()}`);

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.

  1. Identify the interface clients already use, or extract one from the real class if clients depend on the concrete type. Here that is ScanArchive with fetchScan(patientId, scanId).

  2. Change clients to depend on the interface instead of the concrete class. The viewer's openStudy takes a ScanArchive, not a RemoteScanArchive.

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

  4. Add a private accessor that creates the real subject on first use and reuses it afterwards.

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

  6. Decide how the proxy is created and handed out. A login service or factory that returns a ScanArchive keeps callers from bypassing the proxy by constructing the real class themselves.

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

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.