Singleton
medium 60 minOne 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
During a rolling start
What is one, and where
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")UPDATE ... WHERE is atomic in the database.Failure walk: the leader that slept
- 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
Process 2 leads
At 10:00:31 the lease is over. Process 2 gets fence 8 and writes its result.
- 3
Process 1 wakes up
It still believes that it leads, and writes with fence 7. The condition
fence <= 7does 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
| Way | Cost | Use it for |
|---|---|---|
| Read at start, restart to change | Slow change | Most settings |
| Poll a store every 30 seconds | Up to 30 seconds of mixed values | Flags |
| Push on change, poll as a safety net | A channel to run | Switches for incidents |
| Ask the store on every use | A network call each time | Money limits that must be exact |