System Design

C26

Approval workflow engine

Design a workflow engine where companies define approval chains: a request moves through steps, approvers act, and the state survives restarts.

Not startedSaved in this browser only.
  1. 1A definition is versioned data, and an instance pins its version at the start, so a change never moves a running request.
  2. 2The instance row is the state and the lock. Each action locks it, so the approval count is exact and a step advances once.
  3. 3The row, the events, the tasks and the outbox rows commit in one transaction, so a crash leaves nothing half done.
  4. 4The engine holds no state. Timers are rows with a due time, and any engine can pick them up with SKIP LOCKED.
C26
    A

    The prompt and requirements

    questions first, then numbers
    "Design a workflow engine where companies define approval chains: a request moves through steps, approvers act, and the state survives restarts."
    questionanswer 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.
    sequentialparallel, all of 2conditionalManagermia · 1 of 1Finance · finLegal · legDirectordan · 1 of 1amount ≥ 5,000else skip≥ 50,000else skipafter 48 hafter 24 hOpen tasks move to dan when the timer fires. The step keeps its slots.The chain is JSON in one row, version 1. A change adds version 2.
    requirementtarget
    A step advancesExactly once, under concurrent approvals
    Peak approvals308 a second
    An action landsUnder 100 ms at peak
    An engine restartsNo lost or repeated transition
    Escalation firesWithin a minute of the due time
    Audit trailRebuilds 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.

    B

    Estimates

    arithmetic shown
    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.

    C

    API

    methods, bodies, status codes
    callresult
    POST /definitions/:key201 next version. 422 invalid chain.
    POST /requests201 instance. Body has request_id; a repeat returns the same instance.
    POST /requests/:id/actions200 new state. 403 requester or no task. 409 finished or step left.
    POST /requests/:id/delegate200. 409 the delegate is on the step.
    GET /requests/:idState, open step, tasks, audit trail.
    GET /inbox200 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.

    D

    Data model

    entities, then SQL
    definitionsPKcompany_idPKkeyPKversionbodyjsonbtrigger: never updatedinstancesPKidFKdef_versionpinnedUQrequest_idstate3 statesstepopen stepseqlast eventrow lock orders actionstasksPKinstance_idPKstepPKslotassigneecan changestatepending …inbox: partial indextimersPKidFKinstance_idstepdue_atscannedfired_atpartial index on unfiredeventsPKinstance_idPKseqactor, type, stepUQaction_iddouble clickUQ one step_completed a stepoutboxPKidFKinstance_idrecipient, kindsent_atcommits with the transition
    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.
    tablewritten whenchanges later?
    definitionsAn admin publishesNever
    instancesA request startsEvery transition
    tasksA step opensDecision, delegation, escalation
    eventsEvery transitionNever
    timersA step with a timeout opensFired once
    outboxSomeone must be toldMarked sent once
    definitions, instances, tasks, events, timers, outboxsql
    -- 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;
    1. 1A change adds a row. The definition is data, so a publish needs no deploy.
    2. 2A second submit with the same key finds the first instance.
    3. 3The inbox query reads only open tasks.
    4. 4The backstop: a second completion of a step fails, whatever the code does.
    5. 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.

    E

    The architecture

    click a step; its path lights up
    Adminedits chainsPeoplesubmit, approveWorkflow APIN, no stateTimer enginesN, scan with skipPostgresrows, events, outboxNotifieremail, chat

    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.

    F

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    PostgresSELECT FOR UPDATE on one rowActions on one instance take turns; other instances never wait.Balances, seat holds
    PostgresMulti-row transactionTask, event, next step and notifications commit together.Every state change
    PostgresRollback when a connection endsA killed process leaves no partial transition.Batch workers
    PostgresPartial unique indexOne action id per instance; one completion per step.One active row per key
    PostgresON CONFLICT DO NOTHINGA repeat submit creates nothing.Idempotent APIs
    PostgresFOR UPDATE SKIP LOCKEDEngines and notifiers share due rows, each row to one process.Job queues
    PostgresRow triggers that refuse changesPublished versions and events are append-only.Ledgers, audit logs
    Postgresjsonb columnA chain is one document; its steps need no tables of their own.Settings, rules
    ServiceValidation at publish timeA chain that could stall never reaches an approver.Any rule editor
    NotifierMessages with stable idsA 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.

    G

    Deep dive: definitions as versioned data

    pin at the start; never edit
    where the chain livesstatus
    In code, one flow per companyNot approved
    Editable rows, read at each stepNot approved
    Versioned document, pinned at the startApproved
    Migrate running instances to a new versionOnly on request
    Full process language with loops and scriptsOnly if asked
    Conditions as data: field, operator, valueApproved
    Conditions as scripts from customersNot approved
    enter a steppseudo code
    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
    1. 1The instance reads its own version, so a later publish cannot change this loop.
    2. 2A condition reads the fields stored with the request. The skip is an event, so the audit explains it.
    3. 3The timer commits with the step, so a crash cannot leave a task without one.
    Tested source Go: enter · SQL: publish, pin
    Go: entergo
    
    // 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)
    }
    
    SQL: publish, pinsql
    -- 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.

    H

    Deep dive: durable state and the audit trail

    a row for now, events for history
    submitrunningstep n opentasks pending, timer set✓ approved✕ rejectedlast stepcompleteone rejectapprove · delegate · escalate · next stepeach arrow: one transaction, row + events + outbox
    state storestatus
    State in engine memory, saved now and thenNot approved
    State row only, history in app logsNot approved
    Events only, replay on each readWith snapshots
    State row plus events, in one transactionApproved
    rebuild from eventspseudo code
    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
    1. 1The number comes from the instance row, so events have one order per instance.
    2. 2Every test run compares the two. A transition that forgets its event fails the test.
    Tested source Go: replay · SQL: event numbering
    Go: replaygo
    
    // 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
    }
    
    SQL: event numberingsql
    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.

    I

    Deep dive: concurrent approvals and double clicks

    one row lock; one action id
    ✕ no lock: each counts only itself✓ row lock: they take turnsfinlegfinlegset own taskset own taskcount = 1 of 2count = 1 of 2commitcommitstep stuck: both tasks approvedlock instancewait for the lockset task; 1 of 2commitlock; set task2 of 2: advancecommitstep completes once
    steprow lockcompletedtoldresult
    all of 2no00stuck: each counted 1 of 2, nobody advanced
    any of 2no11deadlock: Postgres aborted 1 approval after 1 s
    all of 2yes11advanced once
    any of 2yes11advanced once
    actpseudo code
    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)
    1. 1Everything below runs one action at a time, per instance.
    2. 2A double click returns the current state, not an error.
    3. 3The lock makes this exact: every earlier action has committed.
    4. 4A unique index allows one per step, as a backstop for bugs.
    Tested source Go: act and advance · SQL: lock, decide, count
    Go: act and advancego
    
    // 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)
    }
    
    SQL: lock, decide, countsql
    -- 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';
    methodstatus
    Count without a lockNot approved
    Lock the instance rowApproved
    Counter on the step, atomic decrementSecond source of truth
    Serializable isolation with retriesRetry loop
    Disable the button after a clickNot approved
    Action id in a unique indexApproved

    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.

    J

    Deep dive: timers, delegation and notifications

    due rows; one transaction each
    escalation scanpseudo code
    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
    1. 1Engines take different timers and never wait for each other.
    2. 2The step may have ended. Then the timer changes nothing.
    3. 3The slot stays, so the step still needs the same count.
    4. 4This commits with the escalation, so a crash repeats neither.
    Tested source Go: tick · SQL: next timer
    Go: tickgo
    
    // 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
    }
    
    SQL: next timersql
    -- 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 rulewhy
    The slot stays; the assignee changesThe step needs the same count.
    Never to the requesterIt removes the check.
    Never to someone on the stepOne person would fill 2 slots.
    The old assignee loses the taskTwo people cannot answer one slot.
    timer methodstatus
    Sleep in the engineNot approved
    Delayed message on a queueDual write
    Due-time rows, partial index, SKIP LOCKEDApproved
    Cancel the timer when the step endsNot approved
    Fire and check the stepApproved
    outboxpseudo code
    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
    1. 1A crash after the send repeats it. The id lets the receiver drop the copy.
    2. 2Delivery is at least once. The effect is once.
    Tested source Go: drain · SQL: next message
    Go: draingo
    
    // 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
        }
      }
    }
    
    SQL: next messagesql
    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.

    K

    See it: step through an instance

    recorded from Postgres; every state came from the engine
    step 1 of 16

    Database after this step

    clock
    +0 h
    instance 1
    running, version 1
    events
    3
    open timers
    1
    outbox
    1 unsent, 0 sent
    1. Manageropenmia: pending
    2. Finance and legalwaiting
    3. 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.

    L

    Failure cases

    what breaks, and why the request is safe
    eventresultwhy it is safesaved by
    An engine dies inside an approvalIts transaction ends.Postgres rolls back. The retry carries the same action id and lands once.Transaction
    An engine dies during an escalationThe timer stays unfired.The next scan takes it, and the task moves once.SKIP LOCKED
    An approver double-clicksTwo calls, one action id.The second finds the id in the events.Action id
    Two approvers finish a step at onceThe second waits.The row lock orders them, so the second counts both.Row lock
    An approver acts on a step already left409.The action names its step, and the engine compares it.Step check
    An admin publishes a bad chain422.Validation runs before the row exists.Validate
    The approver has left the companyNobody answers.The timer moves the task to the target.Timer
    All engines are down for an hourTimers wait.Due rows stay in the table, and the first scan fires them late.Due rows
    The email service is downMessages wait.The outbox holds them, and approvals keep working.Outbox
    A notifier dies after a sendThe message goes again.The id is the same, and the receiver applies it once.Message id
    M

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1One Postgres, N stateless engines2+ read replica for inboxes3+ partitions by month4+ shards by companymore load →
    Capacity against the peak101001k10k100kDemand, peak approvals: 308 actions per secondDemand, peak approvals308Approve, 1 client: 290 actions per secondApprove, 1 client290Approve, 8 clients: 1,370 actions per secondApprove, 8 clients1,370Timers, 8 engines: 4,000 actions per secondTimers, 8 engines4,000actions per second, log scale
    stepaddit handlesmove up when you see
    1One 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.
    2Read 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.
    3Partitions 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.
    4Shards 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.

    N

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    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
    O

    Drill

    predict, then reveal

    0 of 10 known

    1. An admin changes a chain while 500 requests are running. Which chain do they follow?

    2. One approver double-clicks. What stops a second approval?

    3. Two approvers of an all-of-2 step click at the same moment, with no lock. What happens?

    4. Why not just UPDATE the step with a WHERE step = n check?

    5. Why does the timer never get cancelled when a step ends?

    6. An engine is killed in the middle of an approval. What is left?

    7. Why store a state row and events, and not only events?

    8. Who decides when a task moves to the escalation target?

    9. A delegate already holds a task on the step. May the task move to them?

    10. A notification email fails after the transition has committed. Is the approval lost?

    P

    Numbers to say

    measured in the lab
    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.