Design Patterns

Pattern 12 of 23, Structural family

Proxy

Also known as: Surrogate

Provide a stand-in that controls access to an object: caching, lazy loading, security, logging…

The problem

A remote video service takes 800 ms to respond. The same videos are requested thousands of times and you cannot modify the third-party client.

The solution

Create a Proxy that implements the same interface as the real service, intercepts calls, adds its own logic (here a cache) and delegates to the real service only when needed.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. The client thinks it is talking to the real service: same interface.
  2. Empty cache: the proxy delegates to the real service (≈ 800 ms).
  3. YouTubeApi (slow) → CachedVideoProxy: video 42
  4. The proxy stores the result.
  5. CachedVideoProxy → Client: video 42
  6. Second identical call…
  7. CachedVideoProxy → cache {42}: get(42)
  8. cache {42} → CachedVideoProxy: hit!
  9. …served from the cache: the real service is never called.

An analogy

A bank card: it stands in for cash, and adds checks (PIN, spending limit) before touching the account.

When to use it

  • Caching / memoization
  • Lazy loading (ORMs, heavy images)
  • Access control, rate limiting, logging
  • Remote objects (RPC, gRPC stubs)

Pros and cons

Pros

  • Transparent to the client (same interface)
  • Adds control without touching the service
  • Open/Closed

Cons

  • Possible extra latency
  • Cache consistency to manage (invalidation)

Implementations

The same example, written idiomatically in each language.

Proxy in Python

proxy.py 28 lines
import time
from typing import Protocol


class VideoService(Protocol):
    def get_video(self, vid: int) -> str: ...


class YouTubeApi:
    def get_video(self, vid: int) -> str:
        time.sleep(0.8)                      # slow network call
        return f"video-{vid}"


class CachedVideoProxy:
    def __init__(self, real: VideoService):
        self._real = real
        self._cache: dict[int, str] = {}

    def get_video(self, vid: int) -> str:
        if vid not in self._cache:
            self._cache[vid] = self._real.get_video(vid)
        return self._cache[vid]


svc = CachedVideoProxy(YouTubeApi())
svc.get_video(42)   # slow
svc.get_video(42)   # instant

Proxy in TypeScript

proxy.ts 23 lines
interface VideoService {
  getVideo(id: number): Promise<string>;
}

class YouTubeApi implements VideoService {
  async getVideo(id: number) {
    const res = await fetch("https://api.example.com/videos/" + id);
    return res.text();
  }
}

class CachedVideoProxy implements VideoService {
  private cache = new Map<number, Promise<string>>();

  constructor(private real: VideoService) {}

  getVideo(id: number) {
    if (!this.cache.has(id)) this.cache.set(id, this.real.getVideo(id));
    return this.cache.get(id)!;
  }
}

// JS also has a native Proxy: new Proxy(target, { get(t, key) { … } })

Proxy in Java

proxy.java 21 lines
interface VideoService { String getVideo(int id); }

class YouTubeApi implements VideoService {
    public String getVideo(int id) {
        /* slow HTTP call */
        return "video-" + id;
    }
}

class CachedVideoProxy implements VideoService {
    private final VideoService real;
    private final Map<Integer, String> cache = new ConcurrentHashMap<>();

    CachedVideoProxy(VideoService real) { this.real = real; }

    public String getVideo(int id) {
        return cache.computeIfAbsent(id, real::getVideo);
    }
}

// Spring (@Transactional, @Cacheable) is built on dynamic proxies

Proxy in C#

proxy.cs 13 lines
interface IVideoService { Task<string> GetVideoAsync(int id); }

class YouTubeApi(HttpClient http) : IVideoService
{
    public Task<string> GetVideoAsync(int id) => http.GetStringAsync($"/videos/{id}");
}

class CachedVideoProxy(IVideoService real) : IVideoService
{
    private readonly ConcurrentDictionary<int, Task<string>> _cache = new();

    public Task<string> GetVideoAsync(int id) => _cache.GetOrAdd(id, real.GetVideoAsync);
}

Proxy in PHP

proxy.php 24 lines
interface VideoService { public function getVideo(int $id): string; }

final class YouTubeApi implements VideoService
{
    public function getVideo(int $id): string
    {
        usleep(800_000);              // slow call
        return "video-$id";
    }
}

final class CachedVideoProxy implements VideoService
{
    private array $cache = [];

    public function __construct(private VideoService $real) {}

    public function getVideo(int $id): string
    {
        return $this->cache[$id] ??= $this->real->getVideo($id);
    }
}

// Doctrine / Eloquent use proxies to lazy-load relations

Proxy in Go

proxy.go 26 lines
type VideoService interface {
    GetVideo(id int) (string, error)
}

type CachedVideoProxy struct {
    real  VideoService
    mu    sync.RWMutex
    cache map[int]string
}

func (p *CachedVideoProxy) GetVideo(id int) (string, error) {
    p.mu.RLock()
    v, ok := p.cache[id]
    p.mu.RUnlock()
    if ok {
        return v, nil
    }
    v, err := p.real.GetVideo(id)
    if err != nil {
        return "", err
    }
    p.mu.Lock()
    p.cache[id] = v
    p.mu.Unlock()
    return v, nil
}

Frequently asked questions

What is the Proxy design pattern?

Provide a stand-in that controls access to an object: caching, lazy loading, security, logging… Create a Proxy that implements the same interface as the real service, intercepts calls, adds its own logic (here a cache) and delegates to the real service only when needed.

When should you use the Proxy pattern?

Caching / memoization; Lazy loading (ORMs, heavy images); Access control, rate limiting, logging; Remote objects (RPC, gRPC stubs).

What are the pros and cons of the Proxy pattern?

Pros: Transparent to the client (same interface); Adds control without touching the service; Open/Closed. Cons: Possible extra latency; Cache consistency to manage (invalidation).