Write-Ahead Step Record
A write-ahead step record is a row saved by a workflow engine before it performs a step’s external side effect. The row says that the step is about to run and captures whatever the engine will later need to judge whether the effect happened, usually a snapshot of the target system’s state. If the process dies, the engine reads that row on restart and learns that the step is in an uncertain state, not an untouched one.
The gap it covers
A step that changes another system does three things in order: it decides to act, it calls the other system, and it records that it did. No transaction spans a local database and a remote service, so a crash can fall between any two of these. After a crash before the call, repeating the step is correct. After a crash between the call and the record, repeating it duplicates the effect. A local table that holds only pending and done cannot tell these two situations apart, because both look like pending.
The record adds a third state, started, committed before the call. On restart the three possibilities separate: pending means the call was never attempted, done means it finished and was recorded, and started means the call may or may not have happened. Only the last needs investigation.
What the record contains
- A status. Typically
pending,started,done, and a terminal state for failures that were refused or abandoned. - A baseline. A fact about the external system that the effect would change and that can be read later: the number of shipments on an order, the balance of an account, the highest version of a document. Taking it before the call is what makes the comparison possible afterward.
- An attempt count and the operation identity. Whatever key or reference the downstream system accepts, saved before use, so that a retry reuses it instead of inventing a new one.
Resolving a started step
On finding a started step, the engine asks the target system what exists now and compares it with the baseline. A higher shipment count means the effect happened and the step can be marked done with no further call. An unchanged count permits a retry only after the earlier attempt has definitely stopped and the query reliably reflects its completed effects. A timed-out call may still be running, and a stale read may hide its effect. If the target cannot be queried, or someone else could have changed it in the meantime, the engine has no sound way to decide, and the step should stop in an unknown state for a person or a reconciliation job to settle.
The following simulation models an order system that has no idempotency key but can report how many shipments an order has. Two helpers hold the writes the record depends on: begin commits started together with the baseline, and finish marks the step done.
class OrderSystem: # external system: no idempotency key, but it can be queried
def __init__(self): self.shipments = []
def create_shipment(self, order): self.shipments.append(order)
def count(self, order): return self.shipments.count(order)
def begin(db, ext, order):
# commit the intent and the baseline BEFORE the external call
db.execute("UPDATE step SET status='started', baseline=? WHERE id=1", (ext.count(order),))
db.commit()
def finish(db):
db.execute("UPDATE step SET status='done' WHERE id=1")
db.commit()
run_step places them around the external call. At the top, the restart check reads the row. A done row returns immediately. A started row with a shipment count above the baseline means the effect already happened, so the step is marked done with no second call. Otherwise the step runs begin, makes the call, and runs finish. The comment in the check states what it assumes: in this single-process toy the earlier call has ended, the count is immediate, and nobody else writes. The write_ahead=False switch skips begin to give the comparison without the record, and the crash hook is where the harness interrupts the step.
def run_step(db, ext, order, crash=lambda point: None, write_ahead=True):
status, baseline = db.execute("SELECT status, baseline FROM step WHERE id=1").fetchone()
if status == "done":
return "already done"
# restart check: a previous attempt may or may not have reached the external system
if status == "started" and ext.count(order) > baseline:
# safe in this toy: the previous call ended; count is immediate; no concurrent writers
finish(db)
return "resolved: effect found, marked done"
if write_ahead:
begin(db, ext, order)
crash("before")
ext.create_shipment(order)
crash("after_effect")
finish(db)
crash("after_record")
return "ok"
The harness crashes the step at each of the three points, restarts it, and counts shipments, once with the record and once without. It uses Python’s sqlite3 and standard library (Python 3.12.14, macOS 26.7.1); the right column of the output is the run without the record.
import sqlite3
class Crash(Exception): pass
def crash_at(point):
def hook(p):
if p == point: raise Crash()
return hook
def trial(point, write_ahead):
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE step(id INTEGER, status TEXT, baseline INTEGER)")
db.execute("INSERT INTO step VALUES(1,'pending',NULL)"); db.commit()
ext = OrderSystem()
try: run_step(db, ext, "O-1", crash_at(point), write_ahead)
except Crash: pass
msg = run_step(db, ext, "O-1", write_ahead=write_ahead) # restart and resume
return ext.count("O-1"), msg
print(f"{'crash point':<14}{'with record':<56}{'without record'}")
for c in ("before", "after_effect", "after_record"):
a, am = trial(c, True); b, bm = trial(c, False)
print(f"{c:<14}{str(a)+' shipment(s); '+am:<56}{b} shipment(s); {bm}")
crash point with record without record
before 1 shipment(s); ok 1 shipment(s); ok
after_effect 1 shipment(s); resolved: effect found, marked done 2 shipment(s); ok
after_record 1 shipment(s); already done 1 shipment(s); already done
The crash before the call and the crash after the record are harmless in both columns. The crash between the call and the record produces a second shipment when no record exists, because the restarted step only sees pending. With the record, the engine finds started, reads a shipment count above the baseline, and marks the step done.
Conditions and limits
- The check must be a sound inference. The count comparison assumes nobody else created a shipment between the baseline and the check, the previous attempt has ended, and the query reflects its effects. A timeout alone does not establish that the remote work stopped. If concurrent actors are possible, the comparison can adopt someone else’s effect as its own, and the step belongs in
unknownfor review. - The record must be committed before the call. If the status update and the call are issued together, or the update is buffered, the crash window reopens.
- A downstream key is a stronger guard where it exists. If the receiver honors an idempotency key, a resumed step can repeat the call with the same key and receive the recorded result, and the record is then mainly bookkeeping. The record earns its place for calls that have no key.
- It does not undo anything. Steps that completed before a later permanent failure still need a saga or compensating transaction.
- Two engines on one workflow need exclusive ownership. The record does not stop two processes from picking up the same step. A lease can hand the step to one engine at a time, but a lease that has expired does not stop the engine that held it: after a long pause it can resume and make its external call. The target therefore has to protect itself, either by rejecting a call that carries an outdated fencing token or by using the operation identity to discard the duplicate.
The name echoes write-ahead logging in databases, which writes recovery information before changing data pages, but the two are separate mechanisms: the step record is an application-level table that guards one external call. It is one ingredient of durable execution, whose engines persist progress in their own history and still depend on idempotent steps or a resolution check for effects that may have been repeated. Differences that remain after a restart can be classified by reconciliation.
References
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
