Polski

Article · Proxy · Decorator

Proxy – a stand-in that controls access to the real object

Proxy has the same interface as the real object and stands in front of it, deciding when – and whether – to pass a call on. An invoice archive example with access control and a lazy connection in C#, TypeScript, Java, Go and Python.

By · · 11 min read

Sometimes you do not want the client to talk to an object directly: the object is expensive to create, lives on another server, or not everyone should have access to it. Proxy is a stand-in with an identical interface. The client sees no difference, while the proxy can check permissions, create the real object only on first use, cache the result or send the call over the network.

The problem: an invoice archive for everyone, right away

The course platform stores PDF invoices in cloud file storage. The CloudInvoiceArchive class opens a connection and authenticates when it is created, which takes a few hundred milliseconds. The code looked like this:

invoices-controller.ts
const archive = new CloudInvoiceArchive(); // connects on every request, even if unused

app.get("/invoices/:path(*)", async (req, res) => {
  // every developer has to remember this check – and one endpoint forgot it
  if (!req.user.isAccountant && !req.params.path.startsWith(`${req.user.name}/`)) {
    return res.status(403).end();
  }
  res.send(await archive.fetch(req.params.path));
});

Permission checks are scattered across controllers, and one of them skipped it – a student could download someone else's invoice by guessing the path. And the storage connection is opened even when the request is going to be rejected anyway.

The solution: a stand-in with the same interface

We create a SecuredInvoiceArchive that implements the same InvoiceArchive interface. The proxy knows the current user and a function that creates the real archive. On every fetch() it checks permissions first, and it creates the real archive only on the first allowed call. Controllers receive the proxy and do not have to remember anything.

Diagram: The proxy has the same interface as the real object and manages its creation
Diagram: A denial opens no connection; the first allowed call creates the real archive
RoleIn the exampleResponsibility
SubjectInvoiceArchivethe common interface of the original and the proxy
Real subjectCloudInvoiceArchivethe actual work – fetching a file from storage
ProxySecuredInvoiceArchiveaccess control and lazy creation of the original
Clientthe invoice controlleruses the interface, unaware of the proxy

Kinds of proxies

KindWhat it doesReal-life example
Virtualcreates an expensive object only on first uselazy loading of entities in an ORM
Protectionchecks permissions before delegatingour invoice archive
Remotehides network communication behind a local interfacea client generated from gRPC or OpenAPI
Cachingreturns a remembered result instead of asking the originalcaching responses of an expensive API
Smart referencecounts references, logs, measurescall counters, access audit

Implementation in five languages

The example combines two kinds: protection and virtual. Look at the output – the access denial opens no connection, which is created only on the first allowed call. Lazy creation is thread-safe thanks to Lazy<T> in C#, a synchronized method in Java and sync.OnceValue in Go; in Python we used functools.cached_property.

SecuredInvoiceArchive

Invoices.cs
var ola = new User("ola", IsAccountant: false);
IInvoiceArchive archive = new SecuredInvoiceArchive(() => new CloudInvoiceArchive(), ola);

try { archive.Fetch("jan/2026-11.pdf"); } // denied before any connection is opened
catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); }

Console.WriteLine($"{archive.Fetch("ola/2026-11.pdf").Length} bytes"); // connects now

public sealed record User(string Name, bool IsAccountant);

public interface IInvoiceArchive
{
    byte[] Fetch(string path);
}

// Real subject: expensive to create (opens a connection) and to call.
public sealed class CloudInvoiceArchive : IInvoiceArchive
{
    public CloudInvoiceArchive() => Console.WriteLine("connecting to cloud storage...");

    public byte[] Fetch(string path) => new byte[1024]; // pretend this is a PDF
}

// Proxy: same interface; checks access and creates the real archive only when needed.
public sealed class SecuredInvoiceArchive(Func<IInvoiceArchive> createReal, User user) : IInvoiceArchive
{
    private readonly Lazy<IInvoiceArchive> _real = new(createReal); // thread-safe lazy creation

    public byte[] Fetch(string path)
    {
        if (!user.IsAccountant && !path.StartsWith($"{user.Name}/", StringComparison.Ordinal))
            throw new UnauthorizedAccessException($"{user.Name} cannot read {path}");
        return _real.Value.Fetch(path);
    }
}
invoices.ts
interface User {
  name: string;
  isAccountant: boolean;
}

interface InvoiceArchive {
  fetch(path: string): Promise<Uint8Array>;
}

// Real subject: expensive to create (opens a connection) and to call.
class CloudInvoiceArchive implements InvoiceArchive {
  constructor() {
    console.log("connecting to cloud storage...");
  }

  async fetch(path: string): Promise<Uint8Array> {
    return new Uint8Array(1024); // pretend this is a PDF
  }
}

// Proxy: same interface; checks access and creates the real archive only when needed.
class SecuredInvoiceArchive implements InvoiceArchive {
  private real?: InvoiceArchive;

  constructor(private readonly createReal: () => InvoiceArchive, private readonly user: User) {}

  async fetch(path: string): Promise<Uint8Array> {
    if (!this.user.isAccountant && !path.startsWith(`${this.user.name}/`)) {
      throw new Error(`${this.user.name} cannot read ${path}`);
    }
    this.real ??= this.createReal(); // virtual proxy: connect on first allowed call
    return this.real.fetch(path);
  }
}

const archive: InvoiceArchive = new SecuredInvoiceArchive(() => new CloudInvoiceArchive(), {
  name: "ola",
  isAccountant: false,
});

archive
  .fetch("jan/2026-11.pdf")
  .catch((e: Error) => console.log(e.message)) // denied before any connection is opened
  .then(() => archive.fetch("ola/2026-11.pdf"))
  .then((pdf) => console.log(`${pdf.length} bytes`));
Invoices.java
import java.util.function.Supplier;

record User(String name, boolean isAccountant) {}

interface InvoiceArchive {
    byte[] fetch(String path);
}

// Real subject: expensive to create (opens a connection) and to call.
class CloudInvoiceArchive implements InvoiceArchive {
    CloudInvoiceArchive() { System.out.println("connecting to cloud storage..."); }
    public byte[] fetch(String path) { return new byte[1024]; } // pretend this is a PDF
}

// Proxy: same interface; checks access and creates the real archive only when needed.
final class SecuredInvoiceArchive implements InvoiceArchive {
    private final Supplier<InvoiceArchive> createReal;
    private final User user;
    private InvoiceArchive real;

    SecuredInvoiceArchive(Supplier<InvoiceArchive> createReal, User user) {
        this.createReal = createReal;
        this.user = user;
    }

    public byte[] fetch(String path) {
        if (!user.isAccountant() && !path.startsWith(user.name() + "/"))
            throw new SecurityException(user.name() + " cannot read " + path);
        return realArchive().fetch(path);
    }

    private synchronized InvoiceArchive realArchive() {
        if (real == null) real = createReal.get(); // virtual proxy: connect on first allowed call
        return real;
    }
}

public class Invoices {
    public static void main(String[] args) {
        InvoiceArchive archive = new SecuredInvoiceArchive(CloudInvoiceArchive::new, new User("ola", false));
        try {
            archive.fetch("jan/2026-11.pdf"); // denied before any connection is opened
        } catch (SecurityException e) {
            System.out.println(e.getMessage());
        }
        System.out.println(archive.fetch("ola/2026-11.pdf").length + " bytes");
    }
}
invoices.go
package main

import (
	"fmt"
	"strings"
	"sync"
)

type User struct {
	Name         string
	IsAccountant bool
}

type InvoiceArchive interface {
	Fetch(path string) ([]byte, error)
}

// CloudInvoiceArchive is the real subject: expensive to create and to call.
type CloudInvoiceArchive struct{}

func NewCloudInvoiceArchive() InvoiceArchive {
	fmt.Println("connecting to cloud storage...")
	return CloudInvoiceArchive{}
}

func (CloudInvoiceArchive) Fetch(string) ([]byte, error) { return make([]byte, 1024), nil }

// SecuredInvoiceArchive is the proxy: same interface, access check and lazy creation.
type SecuredInvoiceArchive struct {
	user User
	real func() InvoiceArchive
}

func NewSecuredInvoiceArchive(create func() InvoiceArchive, user User) *SecuredInvoiceArchive {
	return &SecuredInvoiceArchive{user: user, real: sync.OnceValue(create)}
}

func (p *SecuredInvoiceArchive) Fetch(path string) ([]byte, error) {
	if !p.user.IsAccountant && !strings.HasPrefix(path, p.user.Name+"/") {
		return nil, fmt.Errorf("%s cannot read %s", p.user.Name, path)
	}
	return p.real().Fetch(path) // the real archive is created on the first allowed call
}

func main() {
	archive := NewSecuredInvoiceArchive(NewCloudInvoiceArchive, User{Name: "ola"})
	if _, err := archive.Fetch("jan/2026-11.pdf"); err != nil {
		fmt.Println(err) // denied before any connection is opened
	}
	pdf, _ := archive.Fetch("ola/2026-11.pdf")
	fmt.Println(len(pdf), "bytes")
}
invoices.py
from collections.abc import Callable
from dataclasses import dataclass
from functools import cached_property
from typing import Protocol


@dataclass(frozen=True)
class User:
    name: str
    is_accountant: bool = False


class InvoiceArchive(Protocol):
    def fetch(self, path: str) -> bytes: ...


class CloudInvoiceArchive:
    """Real subject: expensive to create (opens a connection) and to call."""

    def __init__(self) -> None:
        print("connecting to cloud storage...")

    def fetch(self, path: str) -> bytes:
        return bytes(1024)  # pretend this is a PDF


class SecuredInvoiceArchive:
    """Proxy: same interface; checks access and creates the real archive only when needed."""

    def __init__(self, create_real: Callable[[], InvoiceArchive], user: User) -> None:
        self._create_real = create_real
        self._user = user

    @cached_property
    def _real(self) -> InvoiceArchive:  # virtual proxy: built on first access
        return self._create_real()

    def fetch(self, path: str) -> bytes:
        if not self._user.is_accountant and not path.startswith(f"{self._user.name}/"):
            raise PermissionError(f"{self._user.name} cannot read {path}")
        return self._real.fetch(path)


if __name__ == "__main__":
    archive: InvoiceArchive = SecuredInvoiceArchive(CloudInvoiceArchive, User("ola"))
    try:
        archive.fetch("jan/2026-11.pdf")  # denied before any connection is opened
    except PermissionError as e:
        print(e)
    print(len(archive.fetch("ola/2026-11.pdf")), "bytes")

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step by step
  • When to use it and when not to
  • Related patterns
  • In practice
  • Quick check
  • Summary

Create a free account · Sign in