The Singleton Pattern: Ruby Rabbit and the Bakery's One Price Board

updated 2026-10-07 · 12 min


ONELINE

A Singleton works only when everyone reaches the same object through the same path — and the moment that object is created cannot be raced, or two different parts of the program end up holding two different "the" objects.

METAPHOR

One Price Board on one hook by the door, and exactly one key to the cabinet where a new board gets written, so only one pair of hands is ever allowed to check-and-maybe-write at a time.

Cheat sheet: the bakery map

StorySystem
Ruby RabbitThe application (one running process)
Ruby's bakeryThe process the Singleton lives inside
The Price BoardThe Singleton instance — state meant to exist as exactly one shared object within that process
The hook by the doorThe one global access point — a get_instance() classmethod everyone must go through
Checking the hook before writing a new boardThe lazy if _instance is None check
Two staff reaching for the hook at the same moment, each hanging their own boardThe race: two callers both observe "nothing exists yet" before either finishes constructing
The one cabinet keyA lock guarding only the check-then-create critical section
A second bakery across town with its own boardA different process — a Singleton is one-per-process, not one-in-the-world

Keep these at separate levels: Ruby is the whole application, not the board. The board is the one piece of shared state; the hook is how anyone reaches it; the key guards only the instant it's created, never every later visit to read it.

What problem is a Singleton actually solving?

Not "make sure only one of these ever exists, anywhere, forever." The scope matters: a Singleton guarantees one instance within some defined boundary — here, one running bakery, one running process — and gives every part of that process the same way of reaching it. A bakery across town keeping its own separate board isn't a crack in the rule; it's simply a different process, with its own scope.

The actual problem is narrower and more common than "uniqueness" sounds: when several different parts of a program each need the same shared state — a config, a connection pool, a price list — letting each part construct its own copy on demand means those copies can quietly drift apart. The fix isn't "ask everyone nicely to share." It's making the one object reachable through a single path that itself refuses to produce a second one.

The apprentice and the second board

Ruby Rabbit's bakery ran on one Price Board, chalked up fresh every morning and nailed by the door: the price of every loaf, roll, and seeded special, for anyone in the bakery to read.

Ruby had just taken on Clover, a new delivery apprentice, to shadow Finn for the week before running deliveries on her own. Nobody had told Clover where the shared board was — only that she needed a price before she could quote a delivery. So on her first morning, working from the price list she half-remembered from her interview, she chalked up her own board on a scrap of slate and tacked it up by the delivery desk, while Finn was busy elsewhere.

It was close. Not exact. By midmorning, a customer who'd been quoted one price for the seeded loaf at the front counter got a delivery invoice for a different price entirely. Pepper, working the counter, hadn't done anything wrong — she'd read the real board. Clover hadn't exactly done anything wrong either — she'd just never been told there was only supposed to be one.

NAPKIN — Tech translation

Story: Clover didn't ignore a rule — there wasn't yet a rule telling her where the one shared board was, so she built her own from memory. The two boards didn't start out wrong; they just had no reason to agree with each other.

Python: This is what happens without a Singleton at all: if any part of the code is free to construct its own PriceBoard() whenever it needs one, you don't get one shared object — you get as many independent copies as there are call sites, each able to drift from the others the moment either one changes.

One hook by the door

Ruby fixed it the way it looks obvious to fix: one hook by the door, and one rule. Before writing any price board, check the hook first. If a board's already hanging there, read it — don't write a new one. If nothing's hanging, write one and hang it.

It worked, for weeks. Whoever opened the bakery each morning checked the hook, found it bare, chalked up the one board, and hung it. Everyone after that just read it. One board, one hook, no more disagreeing invoices.

NAPKIN — Tech translation

Story: The hook is the one place everyone is told to look — never build your own, always check there first.

Python: This is lazy initialization through a single access point: a get_instance() classmethod that checks a class attribute (cls._instance) and constructs the object only if it's still None, handing back that same object to every caller from then on.

The festival morning

Clover learned the hook rule fast, and by the time she was running deliveries on her own, she never got the price wrong again. Months later, the harvest festival meant triple the orders, so for the first time, Ruby had both Finn and Pepper open the bakery together, before dawn, each rushing to get their own station ready before the doors opened.

Pepper checked the hook at the same instant Finn checked it from across the room. Both saw nothing hanging there — because at that instant, nothing was. Both, within the same breath, picked up chalk and started writing a board of their own.

Pepper finished first, four minutes of chalking, and hung hers on the hook. Finn, who'd started a fraction of a second after her but worked a little slower that morning, finished his four minutes and change later — and hung his board right over hers.

Nothing about either board was wrong. The problem was that there were now two of them, in two pairs of hands that morning, and the hook — the one thing everyone else was told to trust — ended up pointing at whichever one got hung last. Pepper kept right on quoting customers from the board she'd made and never let go of. It simply wasn't the board anyone checking the hook after her would ever see again.

Checking and creating had looked like one action to both of them. They were two — and nothing in the rule stopped a second pair of hands from finishing the first action before either of them finished the second.

NAPKIN — Tech translation

Story: Checking and writing look like one action to Pepper and Finn — "see if it's there, and if not, make it" — but they're two separate actions, and nothing stopped a second person from doing the first one before either of them finished the second.

Python: if cls._instance is None: cls._instance = cls() looks like one action, but it's a check followed by a creation. Two threads can both see None before either finishes creating — the GIL doesn't turn that whole sequence into one atomic step, so creation still needs its own synchronization. The result: two live PriceBoard objects, with cls._instance left pointing at whichever one finished last.

Two callers both check before either finishes constructing Pepper starts building a board, and while she's still building, Finn checks the hook, finds nothing, and starts building his own. Pepper finishes first; Finn finishes shortly after and becomes the one the hook now points to. Pepper checks, then starts building hangs her board Finn checks while Pepper is still building — sees nothing hangs his board — hook points here now both checks land inside this overlap building a board
Finn's check happens while Pepper's board is still being built — nothing was there to see, so he builds one too.

Ruby's board is unique inside her own bakery, not unique across the whole forest. A second bakery in Rivertown keeping its own separate board, with its own hook and its own key, isn't a crack in the rule. It's a different process entirely; the rule only ever promised one board per bakery.

The one key to the cabinet

Ruby's fix wasn't "write faster" or "check more carefully." It was closing the gap between checking and writing so nothing could happen in between. She had one key made for the board cabinet. From then on: whoever wants to check the hook and possibly write a new board must hold the key first. Only one pair of hands can hold it at a time. Everyone else waits their turn before they're even allowed to look.

The next time two staff opened together, the second one to reach for the key simply waited. By the time the key was free, the first one to get it had already checked, found nothing, written the one board, hung it, and handed the key back. The second person took the key, checked, found a board already there, and never wrote one at all.

NAPKIN — Tech translation

Story: The key doesn't protect the board once it's hanging — anyone can walk up and read it anytime. It only protects the narrow moment of deciding whether to write a new one.

Python: This is a lock (threading.Lock()) making check-and-create one protected step: take the lock, check again, create only if still absent, then release. A common optimization — checking once before taking the lock, then again after, in case someone else finished while you waited — is called double-checked locking. The name matters less than the requirement underneath it: check and create have to happen as one critical section.

WATCHOUT

The key's job is narrow: it protects only the moment of deciding whether to create the board, not every later visit to read it. Locking on every read is a common overcorrection that slows everyone down for no safety benefit.

  • Lazy, no lock — fast, but unsafe the instant two callers can race on creation
  • Lazy, lock around check-and-create only — safe, pays the lock's cost once, at first creation
  • Eager, created up front — safe with no lock at all, because the cost is paid unconditionally, whether or not that run ever actually needs it

RECALL

If Ruby had given out two keys to the cabinet instead of one — say, a spare in case the first got lost — would the race from the festival morning still be possible? What exactly would the second key have to be able to do for it to actually close the gap?

ASIDE

There's a simpler option this lesson hasn't dramatized: print the board before the bakery even opens, every morning, instead of waiting for whoever happens to need it first. In Python terms, the shared object can be created when its module is first loaded, and every later import just reuses that same object — no lock required, because there's no check to race. The tradeoff is that construction happens whether or not the program ever actually needs it, which is why the lazy, lock-guarded version in this lesson still matters for anything expensive enough that you'd rather not build until asked for.

Putting it together: the board, written once

Here's the naive version Ruby's bakery effectively ran the morning of the festival — the exact shape that let Pepper and Finn race:

class PriceBoard:
    _instance = None

    def __init__(self):
        self.prices = self._load_from_ledger()

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

Two threads calling PriceBoard.get_instance() close together can both pass the if cls._instance is None check before either one finishes running cls() — exactly Pepper and Finn, each hanging a board the other can't see. (This simplified version shows the shared access path and the race in it; it doesn't stop anyone from calling PriceBoard() directly — a production Singleton usually blocks that too, commonly by overriding __new__.) Here's one thread-safe implementation, with a lock doing the cabinet key's job:

import threading

class PriceBoard:
    _instance = None
    _lock = threading.Lock()

    def __init__(self):
        self.prices = self._load_from_ledger()

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = cls()
        return cls._instance

Pepper's thread calls get_instance() first, finds the lock free, and starts building. Finn's thread calls it moments later, finds _instance still None, and tries for the lock — but Pepper already holds it, so Finn waits:

The lock serializes the two calls instead of letting them overlap Pepper's thread holds the lock while it builds the board. Finn's thread arrives shortly after, waits for the lock the entire time Pepper holds it, and once it's released, re-checks, finds the board already built, and returns it immediately with no construction of its own. Pepper holds the key while creating Finn waits until the key is released key released Finn re-checks, finds a board already there, returns it — no extra construction
Only one construction happens — Finn waits, then re-checks and reuses the board.

Finn waits until Pepper releases the lock, acquires it himself, checks cls._instance again — this time it isn't None — and returns Pepper's board directly, with no construction of his own. Exactly one PriceBoard is created through get_instance().

Closing distinction: enforced by the class, or enforced by the container?

One cost of the classic Singleton is that callers depend on a global access path rather than receiving the dependency explicitly. That hidden coupling can make tests harder, because replacing the shared instance with a fake means reaching into PriceBoard itself.

A GoF Singleton answers one question, baked into the class itself:

"Is it even possible to construct a second one?"

A dependency-injection container's "singleton scope" answers a related but different one:

"Does this particular container choose to hand out the same one?"

A classic Singleton puts the uniqueness rule inside the class itself. A dependency-injection container can instead keep the class ordinary and configure the container to reuse one instance within its own scope. Same shared-instance outcome, different place where the rule lives — which is also why a DI-managed service is easy to swap for a fake in a test, and a GoF Singleton isn't.

Next lesson Caching: Ferron Fox and the Long Ride to Oakhollow