Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Proxy

Intent

Stand a lightweight stand-in in front of a costly object so loading, access, or bookkeeping happens only when actually needed.

Motivation

A gallery shows thumbnails for large photos. Loading every full image up front stalls the page, yet skipping the load breaks the display step callers expect. An image proxy offers the same display step, loads the real file on the first view, and serves later views from its cached copy — so scrolling back is instant and the disk is touched exactly once.

Structure

flowchart LR
  Gallery --> Photo[Photo Contract]
  Photo --> Proxy[Image Proxy]
  Photo --> Real[Real Image]
  Proxy --> Real
  • Subject (Photo) — the shared display contract.
  • Real subject (Real Image) — the costly file load plus display.
  • Proxy — holds the same contract, loads the real image lazily on first display, caches afterward.
  • Client (Gallery) — displays through the contract, unaware of the lazy load.

Consequences

  • Benefit: expensive work is deferred and done once — startup stays fast and repeats are free.
  • Cost / trade-off: first access still pays full price (a visible pause), and caching adds staleness risk if the file changes.

Basic Recap

Proxy stands in for another object while preserving its interface, adding a reason for indirection such as lazy loading, access control, remote access, or resource management. Clients can use the proxy as they would the real subject, subject to the proxy’s documented failure and lifecycle behavior. The real subject may be created or contacted only when needed. Transparency has limits: network errors and initialization cost cannot always be hidden honestly.

Complex Scenario

An ORM session returns a proxy for a customer’s large preference document rather than fetching it with every customer row. The proxy exposes the same document methods and loads the real value on first property access. Authorization is checked before the fetch, and successful initialization is reused within the session. This delays expensive work, but the boundary between an in-memory property and a database operation must remain visible to performance tooling.

Edge cases

  • Concurrency: Two threads accessing an uninitialized proxy should trigger at most one load, or use an explicit single-flight policy, without publishing a partially filled document.
  • Partial failure: Access after the session closes cannot lazy-load; the proxy should report that lifecycle error rather than opening a hidden session.
  • Retries: Retrying a timed-out query must be bounded and must not discard an already committed initialization while another caller is consuming it.

Initialization failure should leave a coherent state that either permits a controlled retry or consistently reports the same terminal failure.

Sketch (illustrative pseudocode, not runnable):

DocumentProxy.read(field):
    assertSessionOpen()
    assertReadAllowed(currentPrincipal)

    document = loader.loadOnce(documentKey)
    return document.read(field)

Loader.loadOnce(key):
    if initialized:
        return realDocument
    return singleFlight(key, function:
        loaded = repository.fetchDocument(key)  # bounded policy
        publishAtomically(loaded)
        return loaded
    )

When to Use / When Not to Use

Use when:

  • Construction or loading is costly and often unnecessary (large images, remote resources).
  • You need access control, counting, or caching around an object without changing its callers.

Avoid when:

  • The object is cheap — the stand-in adds indirection for no gain.
  • Freshness matters more than speed and cached copies would silently go stale.

Examples

Links to runnable code (same scenario, four languages):

  • examples/elixir/proxy/
  • examples/dart/proxy/
  • examples/go/proxy/
  • examples/rust/proxy/

Expected outcome: the first display loads the file from disk; the second display is served from cache.

Anti-pattern / Failure Mode

  • Misuse: A proxy that duplicates the subject’s logic instead of delegating.

  • Review signal: Proxies stacked so latency and failure modes are opaque.

  • Misuse symptom: Proxies surround every property and repository call, making routine object access perform hidden queries, authorization changes, or remote retries. Lazy proxies returned beyond their session lifetime turn ordinary reads into unpredictable runtime failures.

  • Review signal: Watch for interfaces whose proxy adds surprising checked failures, double-checked initialization without safe publication, and loops that touch one lazy property per entity. Query counts growing with row count, repeated load exceptions, and closed-session errors are strong operational evidence that the proxy boundary is being ignored.

  • Decorator — control access vs add duties.
  • Adapter — same interface with control vs translated interface.
  • Zero Trust — verify on every access, including through proxies.

Exercise

Add an access check: displaying a photo named private.png must print a denial line and never load the file, while normal photos keep the load-once behavior.

Self-check

  • When does the disk get touched?
    AnswerOnce, on the first display through the proxy — later displays use the cache.
  • Proxy vs Decorator: what differs?
    AnswerProxy manages access to the real object (lazy load, cache); Decorator adds features around it.
  • What is the staleness risk?
    AnswerIf the underlying file changes, the proxy keeps serving its cached copy unless invalidated.