AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Watch lesson4:52

Beyond one process

Ten processes, ten instances: count the connections, guard the single job.

The point: the pattern ends at the edge of the process. Say so before the interviewer does.

Numbers

The pool that multiplied

One per process

6 processes×20 connections=120>1006 \text{ processes} \times 20 \text{ connections} = 120 > 100
The limit of 100 is the usual default of PostgreSQL's max_connections. It is for all clients together. Size the pool from the limit: 100, minus 10 kept free for people and jobs, divided by 6 processes is 15.

During a rolling start

(6+2)×15=120>100;⇒;⌊90/8⌋=11(6 + 2) \times 15 = 120 > 100 ;\Rightarrow; \lfloor 90 / 8 \rfloor = 11
While two new processes run beside the six old ones there are eight pools. Plan with the highest number of processes, not with the usual one.

What is one, and where

Three different problems with the same name. Only the first one is this pattern.
Python
def try_lead(db, me, now, seconds=30):    row = db.execute(        """UPDATE lease SET owner = ?, expires = ?, fence = fence + 1           WHERE name = 'nightly' AND expires < ?           RETURNING fence""",        (me, now + seconds, now),    ).fetchone()    return row[0] if row else None      # a number: you may work, and show itdef write_result(db, fence, value):    done = db.execute(        "UPDATE result SET value = ?, fence = ? WHERE name = 'nightly' AND fence <= ?",        (value, fence, fence),    ).rowcount    if done == 0:        raise RuntimeError("somebody newer leads")
A job that must run in one process only. The row is the one thing, not the class. UPDATE ... WHERE is atomic in the database.

Failure walk: the leader that slept

  1. 1

    Process 1 leads

    It gets fence 7 and the lease until 10:00:30. Then it stops for a minute, for example in a long garbage collection.

  2. 2

    Process 2 leads

    At 10:00:31 the lease is over. Process 2 gets fence 8 and writes its result.

  3. 3

    Process 1 wakes up

    It still believes that it leads, and writes with fence 7. The condition fence <= 7 does not match 8. Refused.

Without the number, the late write would win. Time limits alone can not make a job unique, because a process can not know that it slept. A store that gives out such leases is Apache ZooKeeper.

A value that all processes share

WayCostUse it for
Read at start, restart to changeSlow changeMost settings
Poll a store every 30 secondsUp to 30 seconds of mixed valuesFlags
Push on change, poll as a safety netA channel to runSwitches for incidents
Ask the store on every useA network call each timeMoney limits that must be exact