Transactions
Sharing data is not enough to build a distributed system: two nodes that read, decide and write can both decide. A transaction closes the gap.
import clusterio
@clusterio.transaction
def claim(job_id, worker):
owners = clusterio.dict("owners")
if job_id in owners:
return False
owners[job_id] = {"worker": worker, "at": clusterio.now()}
return True
print(claim("nightly-report", "host-a")) # True
print(claim("nightly-report", "host-b")) # False: exactly one claim winsWhat a transaction is#
A transaction is a function that runs as one entry of the log. Every node runs it, in log order, with the same arguments, against the same state, so every node gets the same result. Calling it returns that result once the calling node has applied the entry.
Inside a transaction:
clusterio.dict,clusterio.listand files read and write the state as of its entry, directly, with no network round trip;clusterio.now()is the time stamped on the entry, the same on every node;- calling another transaction runs it as part of this one.
An exception undoes the transaction's writes and is raised to the caller, on the node that called it.
Rules#
A transaction must compute the same thing on every node, so:
- It depends only on its arguments, the shared state and
clusterio.now(). Nottime.time(),random, environment variables or the local disk; pass those in as arguments. - Its arguments and result are JSON values. A result that is not raises
TypeErrororValueErrorand undoes the transaction's writes. - It is a plain function defined at the top level of a module, not a generator, coroutine, method, lambda or
functools.partial, and every node has the same code. A transaction is named bymodule:qualname; a node that cannot find one stops applying the log rather than diverge. - It does not wait. It runs while the log waits for it; keep it short, and do I/O outside it.
wait_forandstatus()raiseRuntimeErrorin a transaction;sync()returns at once.
Whatever it raises, even a BaseException such as KeyboardInterrupt, is its outcome: its writes are undone on every node, and the caller gets the exception, or a RuntimeError naming it if the caller cannot make it again.
Traps#
Code that looks deterministic can still differ between nodes:
- Iterating a
setorfrozensetof strings. Python randomizes string hashes per process, so two nodes iterate the same set in different orders. Sort it first:for x in sorted(s). Adictkeeps insertion order and is safe, and so isclusterio.set, whose order every node shares. hash(),id(),uuid.uuid4(),os.getpid(),random. Each differs per process. Make the value outside and pass it in.- Module-level state. A global counter or cache in the transaction's module holds what this process did, not what the log did. Keep state in
clusterio.dictandclusterio.list. - Different code on different nodes. Upgrading a transaction's code while nodes run changes what later entries compute on the upgraded nodes only. Give a changed transaction a new name, and keep the old one until no entry calls it.
- Catching exceptions from the environment.
MemoryError,RecursionErrornear the limit, or aKeyErrorfrom a local file can happen on one node and not another. Read only shared state.
Patterns#
Compare-and-set:
import clusterio
@clusterio.transaction
def compare_and_set(key, prev, value):
kv = clusterio.dict("kv")
if kv.get(key) != prev:
return False
kv[key] = value
return True
print(compare_and_set("leader", None, "host-a"))A counter:
import clusterio
@clusterio.transaction
def incr(name, by=1):
counters = clusterio.dict("counters")
counters[name] = counters.get(name, 0) + by
return counters[name]
print(incr("visits"))Take one job from a list, so each job goes to one worker, as clusterio.queue does:
import clusterio
@clusterio.transaction
def take():
jobs = clusterio.list("jobs")
return jobs.pop(0) if jobs else None
clusterio.list("jobs").append({"id": 1})
print(take(), take()) # {'id': 1} NoneA lease, which is what clusterio.lock is built from:
import clusterio
@clusterio.transaction
def lease(name, owner, ttl):
leases = clusterio.dict("leases")
held = leases.get(name)
if held and held["owner"] != owner and held["expires"] > clusterio.now():
return False
leases[name] = {"owner": owner, "expires": clusterio.now() + ttl}
return True
print(lease("primary", "host-a", 10))clusterio.now()#
Outside a transaction, clusterio.now() is time.time(). Inside one, it is the time the calling node stamped on the entry, so every node that applies the entry sees the same time. Use it for expiry, scheduling and timestamps in shared state.