Approval workflow engine
Design a workflow engine where companies define approval chains: a request moves through steps, approvers act, and the state survives restarts.
- 1A definition is versioned data, and an instance pins its version at the start, so a change never moves a running request.
- 2The instance row is the state and the lock. Each action locks it, so the approval count is exact and a step advances once.
- 3The row, the events, the tasks and the outbox rows commit in one transaction, so a crash leaves nothing half done.
- 4The engine holds no state. Timers are rows with a due time, and any engine can pick them up with SKIP LOCKED.
"Design a workflow engine where companies define approval chains: a request moves through steps, approvers act, and the state survives restarts."
| question | answer assumed |
|---|---|
| Who defines chains? | Each company's admin, as data, with no deploy. |
| What can a step do? | Run on a condition, ask one or several approvers, and need all or some of them. |
| What happens to a silent approver? | After a timeout, the open tasks move to an escalation target. |
| Can a chain change mid-request? | Yes for new requests. Running requests keep their version. |
| Can approvers hand off? | Yes, one task at a time, and never to the requester. |
| Do loops or arbitrary code run? | No. Steps run forward only. A rejection ends the request. |
| What does the audit need? | Who did what and when, kept for years, append-only. |
| requirement | target |
|---|---|
| A step advances | Exactly once, under concurrent approvals |
| Peak approvals | 308 a second |
| An action lands | Under 100 ms at peak |
| An engine restarts | No lost or repeated transition |
| Escalation fires | Within a minute of the due time |
| Audit trail | Rebuilds the state of every instance |
I keep each request on the chain version it started with. Every step advances once, and a restart loses nothing.
- people
- 10,000 companies × 1,000 = 10 million employees
- instances
- 10 million × 2 a month = 20 million a month
- actions
- 20 million × 4 approvals = 80 million a month
- average
- 80 million ÷ 2.6 million s ≈ 31 a second
- peak
- 31 × 10 in work hours ≈ 308 a second
- storage
- 240 million a year × 3.9 kB ≈ 936 GB a year
- timers
- At most one per open step; most never escalate
Bytes per instance were measured in the lab with indexes: 16 events, 4 tasks, 2 timers, 5 messages.
Approvals are a human workload: about 308 a second at peak. The hard part is correctness, not rate.
| call | result |
|---|---|
| POST /definitions/:key | 201 next version. 422 invalid chain. |
| POST /requests | 201 instance. Body has request_id; a repeat returns the same instance. |
| POST /requests/:id/actions | 200 new state. 403 requester or no task. 409 finished or step left. |
| POST /requests/:id/delegate | 200. 409 the delegate is on the step. |
| GET /requests/:id | State, open step, tasks, audit trail. |
| GET /inbox | 200 open tasks for the caller. |
The form carries an action_id, created when the page loads. Two clicks send the same id.
Every call that changes state carries a key from the client, so a retry or a double click lands once.
- tenancy
- company_id leads the definition key and scopes every request.
- growth
- Events grow fastest, at 16 rows per instance. Partition them by month.
- inbox
- A partial index holds open tasks only, so it stays small.
| table | written when | changes later? |
|---|---|---|
| definitions | An admin publishes | Never |
| instances | A request starts | Every transition |
| tasks | A step opens | Decision, delegation, escalation |
| events | Every transition | Never |
| timers | A step with a timeout opens | Fired once |
| outbox | Someone must be told | Marked sent once |
-- A definition is data. A change adds a version; nobody edits a version.
CREATE TABLE definitions (
company_id bigint NOT NULL,
key text NOT NULL, -- 'purchase'
version int NOT NULL,
body jsonb NOT NULL, -- steps, conditions, approvers, escalation
author text NOT NULL,
created_at timestamptz NOT NULL,
PRIMARY KEY (company_id, key, version)1
);
-- One request running one pinned version. This row is also the lock for the instance.
CREATE TABLE instances (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
company_id bigint NOT NULL,
def_key text NOT NULL,
def_version int NOT NULL,
request_id text NOT NULL, -- the caller's key: a second submit finds this row
requester text NOT NULL,
payload jsonb NOT NULL, -- the fields that conditions read
state text NOT NULL DEFAULT 'running'
CHECK (state IN ('running', 'approved', 'rejected')),
step int NOT NULL DEFAULT 0,
seq int NOT NULL DEFAULT 0, -- the last event number
started_at timestamptz NOT NULL,
finished_at timestamptz,
UNIQUE (company_id, request_id)2,
FOREIGN KEY (company_id, def_key, def_version) REFERENCES definitions
);
-- One row per approver slot on a step. The slot stays; the assignee can change.
CREATE TABLE tasks (
instance_id bigint NOT NULL REFERENCES instances,
step int NOT NULL,
slot text NOT NULL,
assignee text NOT NULL,
state text NOT NULL DEFAULT 'pending'
CHECK (state IN ('pending', 'approved', 'rejected', 'closed')),
acted_at timestamptz,
PRIMARY KEY (instance_id, step, slot)
);
-- An approver's inbox: only open tasks are in this index.
CREATE INDEX tasks_inbox ON tasks (assignee) WHERE state = 'pending'3;
-- The audit trail. Each transition adds a row in the transaction that made it.
CREATE TABLE events (
instance_id bigint NOT NULL REFERENCES instances,
seq int NOT NULL,
at timestamptz NOT NULL,
actor text NOT NULL,
type text NOT NULL,
step int NOT NULL,
subject text NOT NULL DEFAULT '',
action_id text,
PRIMARY KEY (instance_id, seq)
);
-- A double click sends the same action id. The second one finds this row.
CREATE UNIQUE INDEX events_action ON events (instance_id, action_id) WHERE action_id IS NOT NULL;
-- The backstop: a step completes once per instance, whatever the code does.
CREATE UNIQUE INDEX one_advance ON events (instance_id, step) WHERE type = 'step_completed'4;
-- A timer is never moved or cancelled. A timer for a step already left fires and does nothing.
CREATE TABLE timers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
instance_id bigint NOT NULL REFERENCES instances,
step int NOT NULL,
due_at timestamptz NOT NULL,
fired_at timestamptz
);
CREATE INDEX timers_due ON timers (due_at, id) WHERE fired_at IS NULL5;
-- Notifications commit with the transition that caused them.
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
instance_id bigint NOT NULL REFERENCES instances,
recipient text NOT NULL,
kind text NOT NULL,
body text NOT NULL,
sent_at timestamptz
);
CREATE INDEX outbox_unsent ON outbox (id) WHERE sent_at IS NULL;- 1A change adds a row. The definition is data, so a publish needs no deploy.
- 2A second submit with the same key finds the first instance.
- 3The inbox query reads only open tasks.
- 4The backstop: a second completion of a step fails, whatever the code does.
- 5The scan reads only unfired timers, oldest first.
An instance points at one definition version. It has a task per approver slot and an append-only event trail.
Step 1: Publish
- An admin saves a chain. The service validates it and adds the next version.
- A trigger refuses any later edit of that row.
If it fails
A step has no approvers, or an escalation has no target: the publish fails, and the author sees why.
API servers and timer engines hold no state. Postgres holds the rows, the events and the outbox, so any process can take over.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Postgres | SELECT FOR UPDATE on one row | Actions on one instance take turns; other instances never wait. | Balances, seat holds |
| Postgres | Multi-row transaction | Task, event, next step and notifications commit together. | Every state change |
| Postgres | Rollback when a connection ends | A killed process leaves no partial transition. | Batch workers |
| Postgres | Partial unique index | One action id per instance; one completion per step. | One active row per key |
| Postgres | ON CONFLICT DO NOTHING | A repeat submit creates nothing. | Idempotent APIs |
| Postgres | FOR UPDATE SKIP LOCKED | Engines and notifiers share due rows, each row to one process. | Job queues |
| Postgres | Row triggers that refuse changes | Published versions and events are append-only. | Ledgers, audit logs |
| Postgres | jsonb column | A chain is one document; its steps need no tables of their own. | Settings, rules |
| Service | Validation at publish time | A chain that could stall never reaches an approver. | Any rule editor |
| Notifier | Messages with stable ids | A resend after a crash is applied once. | Webhooks |
Postgres gives me a row lock to order actions, one transaction for state and events, and SKIP LOCKED for timers.
| where the chain lives | status |
|---|---|
| In code, one flow per company | Not approved |
| Editable rows, read at each step | Not approved |
| Versioned document, pinned at the start | Approved |
| Migrate running instances to a new version | Only on request |
| Full process language with loops and scripts | Only if asked |
| Conditions as data: field, operator, value | Approved |
| Conditions as scripts from customers | Not approved |
enter(instance, from):
FOR each step i from "from" onward, in the pinned version1:
IF step.when is false2 for the request: event step_skipped; next i
instance.step = i
add one task per approver; notify each approver
IF the step has a timeout: add a timer, due = now + timeout3
STOP
no step left: instance = approved; notify the requester- 1The instance reads its own version, so a later publish cannot change this loop.
- 2A condition reads the fields stored with the request. The skip is an event, so the audit explains it.
- 3The timer commits with the step, so a crash cannot leave a task without one.
Tested source Go: enter · SQL: publish, pin
// enter moves to the first step at or after from whose condition holds, opens one task per
// approver and sets the escalation timer. With no step left, the instance is approved.
func (r *run) enter(from int) error {
for i := from; i < len(r.def.Steps); i++ {
s := r.def.Steps[i]
if s.When != nil && !s.When.Holds(r.payload) {
if err := r.emit("engine", "step_skipped", i, s.Name, nil); err != nil {
return err
}
continue
}
r.step = i
if err := r.emit("engine", "step_entered", i, s.Name, nil); err != nil {
return err
}
for _, a := range s.Approvers {
if _, err := r.exec("add_task", r.id, i, a); err != nil {
return err
}
if err := r.emit("engine", "assigned", i, a, nil); err != nil {
return err
}
if err := r.notify(a, "task", s.Name); err != nil {
return err
}
}
if s.EscalateAfterS > 0 {
due := r.now.Add(time.Duration(s.EscalateAfterS) * time.Second)
if _, err := r.exec("add_timer", r.id, i, due); err != nil {
return err
}
}
return nil
}
return r.finish(Approved)
}
-- The next version of this definition. Two publishers at once: the second fails on the key.
INSERT INTO definitions (company_id, key, version, body, author, created_at)
SELECT $1, $2, coalesce(max(version), 0) + 1, $3, $4, $5
FROM definitions WHERE company_id = $1 AND key = $2
RETURNING version;
-- The version is pinned here. A later publish never changes this row.
INSERT INTO instances (company_id, def_key, def_version, request_id, requester, payload, started_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (company_id, request_id) DO NOTHING
RETURNING id;Tested: 12 definitions at validation, 3 request sizes through their chains, and an instance that keeps version 1 after version 2 appears.
A chain is a JSON document with a version. The instance stores the version, so a publish changes only new requests.
| state store | status |
|---|---|
| State in engine memory, saved now and then | Not approved |
| State row only, history in app logs | Not approved |
| Events only, replay on each read | With snapshots |
| State row plus events, in one transaction | Approved |
replay(events):
state = empty
FOR each event in seq order1:
apply it: assigned, delegated, escalated,
approved, rejected, step_completed, finished
RETURN state // must equal the rows2- 1The number comes from the instance row, so events have one order per instance.
- 2Every test run compares the two. A transition that forgets its event fails the test.
Tested source Go: replay · SQL: event numbering
// Replay rebuilds an instance from its events alone. A test compares the result with the rows
// after every run, so the audit trail cannot drift from what happened.
func Replay(events []Event) View {
v := View{Tasks: []Task{}}
each := func(step int, assignee string, f func(*Task)) {
for i := range v.Tasks {
t := &v.Tasks[i]
if t.State == Pending && (step < 0 || t.Step == step) && (assignee == "" || t.Assignee == assignee) {
f(t)
}
}
}
for _, ev := range events {
switch ev.Type {
case "started":
v.State = Running
case "step_entered":
v.Step = ev.Step
case "assigned":
v.Tasks = append(v.Tasks, Task{ev.Step, ev.Subject, ev.Subject, Pending})
case "delegated":
each(ev.Step, ev.Actor, func(t *Task) { t.Assignee = ev.Subject })
case "escalated":
each(ev.Step, "", func(t *Task) { t.Assignee = ev.Subject })
case Approved, Rejected:
each(ev.Step, ev.Actor, func(t *Task) { t.State = ev.Type })
case "step_completed":
each(ev.Step, "", func(t *Task) { t.State = Closed })
case "finished":
each(-1, "", func(t *Task) { t.State = Closed })
v.State = ev.Subject
}
}
slices.SortFunc(v.Tasks, func(a, b Task) int {
return cmp.Or(cmp.Compare(a.Step, b.Step), cmp.Compare(a.Slot, b.Slot))
})
return v
}
UPDATE instances SET seq = seq + 1 WHERE id = $1 RETURNING seq;
INSERT INTO events (instance_id, seq, at, actor, type, step, subject, action_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8);In the recorded run, all 17 events rebuild the final rows. A trigger refuses any UPDATE or DELETE on them.
The row says what is open now; the events say how it got there. One transaction writes both, and a test rebuilds the row from the events.
| step | row lock | completed | told | result |
|---|---|---|---|---|
| all of 2 | no | 0 | 0 | stuck: each counted 1 of 2, nobody advanced |
| any of 2 | no | 1 | 1 | deadlock: Postgres aborted 1 approval after 1 s |
| all of 2 | yes | 1 | 1 | advanced once |
| any of 2 | yes | 1 | 1 | advanced once |
act(action): // one transaction
lock the instance row1
IF action.id is in the events2: RETURN the current state
refuse IF finished, step left, requester, or no open task
mark the actor's task approved
count the approved tasks3 on this step
append the event, with action.id
IF count >= step.need:
close the open tasks; event step_completed4
enter(instance, step + 1)- 1Everything below runs one action at a time, per instance.
- 2A double click returns the current state, not an error.
- 3The lock makes this exact: every earlier action has committed.
- 4A unique index allows one per step, as a backstop for bugs.
Tested source Go: act and advance · SQL: lock, decide, count
// Act records one decision and advances the instance when the step is complete. Everything in
// it commits together: the task, the event, the next step's tasks and the notifications.
func (e *Engine) Act(ctx context.Context, a Action, now time.Time) (Result, error) {
var res Result
err := pgx.BeginFunc(ctx, e.DB, func(tx pgx.Tx) error {
r, err := e.load(ctx, tx, a.Instance, now) // locks the instance row
if err != nil {
return err
}
var seen bool
if err := tx.QueryRow(ctx, q["seen"], a.Instance, a.ID).Scan(&seen); err != nil {
return fmt.Errorf("look up action %s: %w", a.ID, err)
}
if seen {
res = Result{State: r.state, Step: r.step, Duplicate: true}
return nil
}
switch {
case r.state != Running:
return ErrFinished
case a.Step != r.step:
return ErrStale
case a.Actor == r.requester:
return ErrSelf
}
n, err := r.exec("decide", a.Instance, a.Step, a.Actor, a.Decision, now)
if err != nil {
return err
}
if n == 0 {
return ErrNotAssignee
}
if a.Decision == Rejected {
if err := r.emit(a.Actor, Rejected, a.Step, "", &a.ID); err != nil {
return err
}
err = r.finish(Rejected)
} else {
err = e.advance(r, a)
}
if err != nil {
return err
}
e.hook("act")
res = Result{State: r.state, Step: r.step}
return r.save()
})
if err != nil {
return Result{}, fmt.Errorf("act on instance %d: %w", a.Instance, err)
}
return res, nil
}
// advance completes the step if enough approvals exist, and enters the next one. The count is
// exact because every action on this instance holds its row lock.
func (e *Engine) advance(r *run, a Action) error {
var got int
if err := r.tx.QueryRow(r.ctx, q["approvals"], r.id, r.step).Scan(&got); err != nil {
return fmt.Errorf("count approvals on %d: %w", r.id, err)
}
e.hook("counted")
if err := r.emit(a.Actor, Approved, a.Step, "", &a.ID); err != nil {
return err
}
if got < r.def.Steps[r.step].Needed() {
return nil
}
if _, err := r.exec("close_open", r.id); err != nil {
return err
}
if err := r.emit("engine", "step_completed", r.step, r.def.Steps[r.step].Name, nil); err != nil {
return err
}
return r.enter(r.step + 1)
}
-- All actions on one instance take turns on this row. Other instances never wait.
SELECT i.requester, i.payload, i.state, i.step, d.body
FROM instances i
JOIN definitions d ON d.company_id = i.company_id AND d.key = i.def_key AND d.version = i.def_version
WHERE i.id = $1
FOR UPDATE OF i;
SELECT EXISTS (SELECT 1 FROM events WHERE instance_id = $1 AND action_id = $2);
UPDATE tasks SET state = $4, acted_at = $5
WHERE instance_id = $1 AND step = $2 AND assignee = $3 AND state = 'pending';
SELECT count(*) FROM tasks WHERE instance_id = $1 AND step = $2 AND state = 'approved';| method | status |
|---|---|
| Count without a lock | Not approved |
| Lock the instance row | Approved |
| Counter on the step, atomic decrement | Second source of truth |
| Serializable isolation with retries | Retry loop |
| Disable the button after a click | Not approved |
| Action id in a unique index | Approved |
Tested with the race detector: 2 to 32 approvers on one step, each clicking twice at once. Every step completed once, and the next approver was told once.
Each action locks the instance row, so the count sees every earlier approval. The action id makes a double click a no-op.
tick(now): // every engine, every few seconds
LOOP:
BEGIN
timer = next unfired timer WHERE due_at <= now
FOR UPDATE SKIP LOCKED1
IF no timer: STOP
lock the instance row
IF the instance is still on timer.step2:
move every open task3 to step.escalate_to
event escalated; notify the old and new assignee
timer.fired_at = now4
COMMIT- 1Engines take different timers and never wait for each other.
- 2The step may have ended. Then the timer changes nothing.
- 3The slot stays, so the step still needs the same count.
- 4This commits with the escalation, so a crash repeats neither.
Tested source Go: tick · SQL: next timer
// Tick fires every timer due at now, one transaction per timer, and returns how many open tasks
// it escalated. Any number of engines can run it. A timer for a step already left does nothing.
func (e *Engine) Tick(ctx context.Context, now time.Time) (int, error) {
escalated := 0
for {
more := false
err := pgx.BeginFunc(ctx, e.DB, func(tx pgx.Tx) error {
var timer, id int64
var step int
err := tx.QueryRow(ctx, q["next_timer"], now).Scan(&timer, &id, &step)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return fmt.Errorf("next timer: %w", err)
}
more = true
r, err := e.load(ctx, tx, id, now)
if err != nil {
return err
}
n := 0
if r.state == Running && r.step == step {
if n, err = e.escalate(r); err != nil {
return err
}
}
if _, err := r.exec("fire_timer", timer, now); err != nil {
return err
}
e.hook("tick")
escalated += n
return nil
})
if err != nil {
return escalated, fmt.Errorf("tick: %w", err)
}
if !more {
return escalated, nil
}
}
}
// escalate moves every open task on the current step to the step's target. The old assignee
// loses the task, so two people cannot answer the same slot.
func (e *Engine) escalate(r *run) (int, error) {
s := r.def.Steps[r.step]
rows, err := r.tx.Query(r.ctx, q["pending_on_step"], r.id, r.step)
if err != nil {
return 0, fmt.Errorf("open tasks on %d: %w", r.id, err)
}
from, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
return 0, fmt.Errorf("read open tasks on %d: %w", r.id, err)
}
if len(from) == 0 {
return 0, nil
}
if _, err := r.exec("escalate", r.id, r.step, s.EscalateTo); err != nil {
return 0, err
}
if err := r.emit("engine", "escalated", r.step, s.EscalateTo, nil); err != nil {
return 0, err
}
if err := r.notify(s.EscalateTo, "escalated", s.Name); err != nil {
return 0, err
}
for _, f := range from {
if err := r.notify(f, "moved", s.Name); err != nil {
return 0, err
}
}
return len(from), nil
}
-- Every engine runs this scan. SKIP LOCKED gives each one a different timer.
SELECT id, instance_id, step FROM timers
WHERE fired_at IS NULL AND due_at <= $1
ORDER BY due_at, id
LIMIT 1
FOR UPDATE SKIP LOCKED;
UPDATE timers SET fired_at = $2 WHERE id = $1;
UPDATE tasks SET assignee = $3 WHERE instance_id = $1 AND step = $2 AND state = 'pending';| delegation rule | why |
|---|---|
| The slot stays; the assignee changes | The step needs the same count. |
| Never to the requester | It removes the check. |
| Never to someone on the step | One person would fill 2 slots. |
| The old assignee loses the task | Two people cannot answer one slot. |
| timer method | status |
|---|---|
| Sleep in the engine | Not approved |
| Delayed message on a queue | Dual write |
| Due-time rows, partial index, SKIP LOCKED | Approved |
| Cancel the timer when the step ends | Not approved |
| Fire and check the step | Approved |
drain():
LOOP:
BEGIN
message = oldest unsent, FOR UPDATE SKIP LOCKED
IF no message: STOP
send message, with message.id1
message.sent_at = now
COMMIT
receiver: apply each message.id once2- 1A crash after the send repeats it. The id lets the receiver drop the copy.
- 2Delivery is at least once. The effect is once.
Tested source Go: drain · SQL: next message
// Drain sends unsent notifications, one transaction per message. A crash between the send and the
// commit sends that message again, so a receiver applies each message ID once.
func (e *Engine) Drain(ctx context.Context, now time.Time, send func(Message) error) (int, error) {
sent := 0
for {
more := false
err := pgx.BeginFunc(ctx, e.DB, func(tx pgx.Tx) error {
var m Message
err := tx.QueryRow(ctx, q["next_message"]).Scan(&m.ID, &m.Instance, &m.To, &m.Kind, &m.Body)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return fmt.Errorf("next message: %w", err)
}
more = true
if err := send(m); err != nil {
return fmt.Errorf("send message %d: %w", m.ID, err)
}
e.hook("sent")
if _, err := tx.Exec(ctx, q["mark_sent"], m.ID, now); err != nil {
return fmt.Errorf("mark message %d: %w", m.ID, err)
}
sent++
return nil
})
if err != nil {
return sent, fmt.Errorf("drain: %w", err)
}
if !more {
return sent, nil
}
}
}
SELECT id, instance_id, recipient, kind, body FROM outbox
WHERE sent_at IS NULL
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
UPDATE outbox SET sent_at = $2 WHERE id = $1;Tested: 4 engines on 200 due timers fired each one once. An unfired timer survived a process kill during its escalation.
A timer is a row with a due time. Engines scan with SKIP LOCKED, and a stale timer fires and does nothing.
Database after this step
- clock
- +0 h
- instance 1
- running, version 1
- events
- 3
- open timers
- 1
- outbox
- 1 unsent, 0 sent
- Manageropenmia: pending
- Finance and legalwaiting
- Directorwaiting
Engine A was a real process, stopped with SIGKILL while its transaction was open. The second view holds every state of this chain, for 2 request sizes.
The engine died inside an approval, and a new process finished it with the same action id. The step advanced once.
| event | result | why it is safe | saved by |
|---|---|---|---|
| An engine dies inside an approval | Its transaction ends. | Postgres rolls back. The retry carries the same action id and lands once. | Transaction |
| An engine dies during an escalation | The timer stays unfired. | The next scan takes it, and the task moves once. | SKIP LOCKED |
| An approver double-clicks | Two calls, one action id. | The second finds the id in the events. | Action id |
| Two approvers finish a step at once | The second waits. | The row lock orders them, so the second counts both. | Row lock |
| An approver acts on a step already left | 409. | The action names its step, and the engine compares it. | Step check |
| An admin publishes a bad chain | 422. | Validation runs before the row exists. | Validate |
| The approver has left the company | Nobody answers. | The timer moves the task to the target. | Timer |
| All engines are down for an hour | Timers wait. | Due rows stay in the table, and the first scan fires them late. | Due rows |
| The email service is down | Messages wait. | The outbox holds them, and approvals keep working. | Outbox |
| A notifier dies after a send | The message goes again. | The id is the same, and the receiver applies it once. | Message id |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One Postgres, N stateless engines. | About 1,370 approvals a second with 8 clients; 4,000 timers a second. | Inbox and audit reads take a large share of the primary. |
| 2 | Read replica for inboxes and reports. | Reads leave the primary. An inbox can lag by seconds; an action still goes to the primary. | Events pass memory; vacuum falls behind. |
| 3 | Partitions of events and tasks by month. | About 936 GB a year stays cheap. Old months move to slow storage. | Writes near the limit of one primary. |
| 4 | Shards by company. An instance never crosses a company. | Each shard adds its own rate. A large company can get its own shard. | Top of the ladder. |
Demand, derived: 80 million actions ÷ 2.6 million s × 10 ≈ 308 a second. Measured rates are orders of magnitude.
One Postgres takes about 1,370 approvals a second, above the 308 peak. I partition events by month, then shard by company.
| question | answer | deeper |
|---|---|---|
| How do you resolve "the requester's manager" as an approver? | Store a rule in the step, and resolve it to people when the step opens. The task keeps the person, so a later reorganisation does not move it. | D3 |
| Why not run this on a job scheduler? | A scheduler runs machine tasks with retries. Approvals wait days for people, so the state is a row that waits, not a job that runs. | C17 |
| What does the row lock block? | Other actions on the same instance. Readers never wait, and other instances never touch this row. | T4 |
| Would a stricter isolation level remove the lock? | Serializable detects this race and aborts one side, so the client must retry. The row lock queues the second action, which is simpler here. | T2 |
| How do notifications reach people? | The outbox feeds a notification service with channels, preferences and digests. The engine only writes a row. | C7 |
| What if an approved step must call another system? | Run it as a saga: an action step that writes to the outbox, with a compensating step if the call fails later. | T7 |
| How do you keep companies apart? | company_id scopes every query, and row-level security enforces it. A timer scan runs across companies as a separate service role. | O6 |
| Who may approve, and who may edit a chain? | A signed-in identity must match the task assignee. Editing a chain is an admin permission, and the audit trail records each publish. | O5 |
0 of 10 known
An admin changes a chain while 500 requests are running. Which chain do they follow?
One approver double-clicks. What stops a second approval?
Two approvers of an all-of-2 step click at the same moment, with no lock. What happens?
Why not just UPDATE the step with a WHERE step = n check?
Why does the timer never get cancelled when a step ends?
An engine is killed in the middle of an approval. What is left?
Why store a state row and events, and not only events?
Who decides when a task moves to the escalation target?
A delegate already holds a task on the step. May the task move to them?
A notification email fails after the transition has committed. Is the approval lost?
- approve
- About 290 a second with 1 client, 1,370 with 8.
- start
- About 260 a second with 1 client, 2,700 with 8.
- timers
- About 1,000 a second with 1 engine, 4,000 with 8.
- one instance
- 32 approvers at once: 450 approvals a second, worst wait 160 ms.
- storage
- About 3.9 kB per finished instance, 16 events.
- demand
- 308 approvals a second at peak for 10 million employees.
Postgres 16 on an 8-core laptop, durable commits, 4,000 instances per case. Other workloads shared the machine, so use these as orders of magnitude.