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

Singleton

Intent

Ensure one shared instance owns a resource and give every caller the same access point to it.

Motivation

An app writes audit events to a single log file. If each module opens its own writer, entries interleave, handles leak, and rotation breaks. A single coordinator that opens the file once and serializes writes removes that drift, but it only helps if every caller truly reaches the same coordinator.

Structure

flowchart LR
  CallerA --> GetInstance[Get Instance]
  CallerB --> GetInstance
  GetInstance --> Sole[The One Instance]
  Sole --> Resource[(Shared Resource)]
  • Client callers — request the instance instead of building their own.
  • Get Instance — single access point that creates once and returns the same handle.
  • The One Instance — holds shared state and guards it.
  • Shared Resource — file, registry, or connection pool behind the instance.

Adaptation note: in Elixir prefer a named GenServer or application config over a Java-style static holder; the lesson is single ownership, not a keyword.

Consequences

  • Benefit: one place controls lifecycle, cleanup, and ordering of a shared resource.
  • Cost: global reach hides dependencies, complicates tests, and invites overuse for things that should be passed explicitly.

Basic Recap

Singleton guarantees that one instance of a type exists within a defined scope and provides a common access point to it. It centralizes lifecycle and coordination for a resource whose independent copies would be incorrect. Its value comes from single ownership, not from making every dependency globally reachable. In practice, dependency injection, a process registry, or application composition can express the same constraint more explicitly.

Complex Scenario

An API gateway needs one process-wide token-bucket registry so all request handlers enforce the same per-client limits. Handlers may arrive on many worker threads, and creating a separate registry for each worker would multiply the allowed traffic. A singleton coordinator owns bucket creation, clock access, and cleanup, while the gateway’s composition root installs it during startup. Tests receive an explicitly scoped registry instead of resetting hidden production state.

Edge cases

  • Concurrency: Lazy initialization must publish exactly one fully initialized coordinator; token updates also need atomicity, because single construction alone does not make the instance’s methods thread-safe.
  • Memory pressure: Unlimited client keys grow buckets forever, so ownership includes expiry and capacity policy rather than merely shared access.
  • Partial failure: If clock or persistent snapshot initialization fails, callers must not receive a partially usable singleton that later fails in unpredictable places.

Define what “one” means: per process, per tenant, per test, or per cluster. A process singleton cannot by itself enforce a distributed rate limit.

Sketch (illustrative pseudocode, not runnable):

Gateway.start(config):
    registry = RateLimitRegistry.initializeOnce(
        clock = config.clock,
        snapshot = loadSnapshotOrFail(config.snapshot),
        eviction = config.bucketEviction
    )
    router = Router(rateLimits = registry)
    return Gateway(router)

Router.handle(request):
    decision = rateLimits.take(request.clientKey, request.cost)
    if decision.allowed:
        return upstream(request)
    return tooManyRequests(decision.retryAfter)

When to Use / When Not to Use

Use when:

  • Exactly one coordinator must exist (log writer, ID allocator, device handle).

Avoid when:

  • Callers could receive the dependency directly, tests need isolation, or lifetime differs per request.

Examples

  • examples/elixir/singleton/
  • examples/dart/singleton/
  • examples/go/singleton/
  • examples/rust/singleton/

Expected outcome: two requests for the instance return the same identity and one write counter reaches 2.

Anti-pattern / Failure Mode

  • Misuse: A singleton as a global grab-bag for unrelated state.

  • Review signal: Tests that must reset global state between cases, or order-dependent suites.

  • Misuse symptom: Singleton becomes a service locator for configuration, repositories, loggers, and business services simply to avoid passing arguments. Tests then depend on execution order, and request code conceals its real collaborators behind static access.

  • Review signal: Watch for global reset helpers in production paths, constructors replaced by static lookups, and mutable singleton fields without synchronization or eviction. A class called a singleton whose lifecycle is actually managed by a container should usually be injected as a normal scoped dependency instead.

Exercise

Add a reset operation that clears the counter. Decide who may call it and document why it stays test-only.

Self-check

  • How do you prove two callers share one instance?
    AnswerCompare identity (same pid, same object hash, pointer equality, or Once address) and observe shared counter.
  • Why is Singleton risky in tests?
    AnswerShared mutable state leaks between tests unless reset or injected.
  • What is the Elixir-idiomatic alternative?
    AnswerA named GenServer or supervised process registered once, not a static field.