← Notebook

Designing maker–checker workflows

Stopping people approving their own changes is the easy part. An approval must cover exactly what was read, and count exactly once.

approvalsstate machinesconcurrency

An approval flow usually starts with two rules: nobody approves their own change, and nothing takes effect until someone else has. Enforce both on the server and the flow looks finished. It still fails in three ordinary ways.

  • A reviewer opens a change, reads it, and clicks Approve. In the minute between reading and clicking, the author fixed a typo and added a zero. What was approved is not what was read.
  • Two reviewers click Approve on the same change at the same moment. Both requests pass every check, and whatever an approval triggers happens twice.
  • The author clicks Publish and the request times out. The app's retry logic, or the author, sends it again. The first attempt had in fact worked, so the retry either publishes a second time or is refused, and the author sees an error for something that succeeded.

None of these is a missing permission check. Each is a gap between the moment something was checked and the moment it was acted on. This note closes all three. It assumes you already check permissions on the server, as server-enforced authorization describes, and that you have not built a multi-step approval before.

Why two people#

The two-person rule says a consequential change needs two different people: one to make it and one to check it. In this pattern they are called the maker and the checker. Banks use it for payments, operations teams for production deployments, and regulated publishers for anything that goes out under the company's name.

It exists because one person can be wrong, can be pressured, or can have had their account taken over. Requiring a second, independent person means no single mistake and no single bad actor is enough on its own.

That guarantee holds only if the checker's approval covers exactly what takes effect. Every technique in this note protects that one property.

States are not screens#

The usual first version has an approve endpoint that sets status = 'approved'. From which status? Whatever it happened to be. Can an approved change still be edited? Nobody decided, so the answer is whatever the code happens to do.

A state machine settles those questions up front. It is a fixed list of states an item can be in, and a fixed list of moves between them, called transitions. A move that is not on the list cannot happen. The screens come later, and only display it.

Write the list as data, so it reads as a specification:

ts
type Actor = { id: string; roles: string[] };

type Status = "draft" | "awaiting_review" | "approved" | "published";
type Action = "edit" | "submit" | "approve" | "reject" | "publish";

// Every move the workflow allows. Anything not listed cannot happen.
const transitions: Record<Status, Partial<Record<Action, Status>>> = {
  draft: {
    edit: "draft",
    submit: "awaiting_review"
  },
  awaiting_review: {
    edit: "awaiting_review",
    approve: "approved",
    reject: "draft"
  },
  approved: {
    edit: "awaiting_review",
    publish: "published"
  },
  published: {}
};

Read the edit moves across the states. Editing a draft leaves it a draft. Editing something under review keeps it under review, though the reviewer is now looking at an older version; the next sections deal with that. Editing something already approved sends it back to review, because an approval does not survive a change to what was approved. Published has no moves at all: a later change is a new item, reviewed from the start.

Notice what else the table says. Approved does not mean live. Publishing is its own step, so it can fail and be retried without anyone approving again.

Approve a revision, not a record#

An approval is a statement about content: I have read this, and it is right. If the content can change afterwards, the statement quietly becomes about something else.

So content is immutable: once written, it is never changed. An edit does not overwrite the old content. It adds a new revision, numbered, alongside the old ones, and the item records which revision is current:

sql
CREATE TABLE items (
  id         text PRIMARY KEY,
  author_id  text NOT NULL,
  status     text NOT NULL DEFAULT 'draft',
  revision   integer NOT NULL DEFAULT 0,
  digest     text NOT NULL DEFAULT '',
  version    integer NOT NULL DEFAULT 1
);

-- Every revision ever written. Rows are added, never changed.
CREATE TABLE revisions (
  item_id   text NOT NULL REFERENCES items (id),
  revision  integer NOT NULL,
  content   jsonb NOT NULL,
  digest    text NOT NULL,
  PRIMARY KEY (item_id, revision)
);

Content is stored as jsonb, PostgreSQL's JSON type. An item starts empty at revision 0; its first edit is revision 1. The digest and version columns are explained below. Nothing in this schema yet stops an UPDATE on revisions; the note on audit trails shows how to make the database itself refuse one.

A fingerprint of what was reviewed#

When the checker's page loads, it receives the content and a fingerprint of it. When they click Approve, the page sends the fingerprint back. The server compares it with the fingerprint of the current revision. If they differ, the content changed while the checker was reading, and the approval is refused.

The fingerprint is a digest, made by a hash function. The same input always gives the same output; any change to the input gives a completely different output; and it is not feasible to construct two different inputs with the same output. SHA-256 is the standard choice:

ts
import { createHash } from "node:crypto";

type Content = { title: string; body: string; amount: number };

export function digest(content: Content): string {
  // Hash the fields in a fixed order. An object's keys come out in
  // the order they were added, so equal content could otherwise hash
  // two different ways.
  const canonical = JSON.stringify([
    content.title,
    content.body,
    content.amount
  ]);
  return createHash("sha256").update(canonical).digest("hex");
}

For the example change used in the tests below, with an amount of 7,500, the digest begins 0651cf64. Change the amount to 75,000 and it begins 75771efb. Nothing about the second suggests it is close to the first, which is the point.

A revision number would also notice the change. The digest does one more thing: anyone holding the stored content can recompute it later and confirm that what was approved is exactly what is stored.

The guards#

Now the decision itself. A guard is a condition checked before a move is allowed. The table says which moves exist; the guards say who may make them, and on what:

ts
type Item = {
  id: string;
  authorId: string;
  status: Status;
  revision: number; // which content: goes up on every edit
  digest: string;   // fingerprint of that content
  version: number;  // which write: goes up on every change to the row
};

type Command =
  | { itemId: string; action: "edit"; content: Content }
  | { itemId: string; action: "submit" | "publish" }
  | {
      itemId: string;
      action: "approve" | "reject";
      reviewedDigest: string; // the digest the checker's page showed
    };

type Decision =
  | { ok: true; to: Status }
  | { ok: false; status: 403 | 404 | 409; error: string };

function refuse(status: 403 | 404 | 409, error: string): Decision {
  return { ok: false, status, error };
}

export function transition(
  item: Item,
  command: Command,
  actor: Actor
): Decision {
  // A draft is private to its author, as in the previous note.
  if (item.status === "draft" && actor.id !== item.authorId) {
    return refuse(404, "not_found");
  }

  // Not in the table means not possible, even for a status or an
  // action this code has never seen. Object.hasOwn looks only at the
  // table's own entries: a plain lookup would also find names every
  // object inherits, so an action called "constructor" would pass.
  const row = Object.hasOwn(transitions, item.status)
    ? transitions[item.status]
    : undefined;
  const to = row && Object.hasOwn(row, command.action)
    ? row[command.action]
    : undefined;
  if (!to) {
    return refuse(409, `cannot_${command.action}_when_${item.status}`);
  }

  if (command.action === "approve" || command.action === "reject") {
    // The two-person rule: whoever wrote it cannot also check it.
    const isReviewer = actor.roles.includes("reviewer");
    if (!isReviewer || actor.id === item.authorId) {
      return refuse(403, "needs_a_second_person");
    }
    // The decision has to be about the content as it is now.
    if (command.reviewedDigest !== item.digest) {
      return refuse(409, "changed_since_review");
    }
  } else if (actor.id !== item.authorId) {
    return refuse(403, "only_the_author");
  }

  return { ok: true, to };
}

The first guard is the view rule from the previous note: someone else's unsubmitted draft is reported as not found, so its existence does not leak. The two-person rule is a single comparison of stable IDs: not names, not email addresses, and not a disabled button. It applies even when the author also holds the reviewer role, which in a small team they usually will.

The two kinds of refusal are deliberate. 403 Forbidden means this person may never do this. 409 Conflict means the request was reasonable but the item has moved on: someone edited it, or it is no longer awaiting review. The right next step differs too: after a 403 there is nothing to retry, and after a 409 the person should reload and look again.

Put two rules together and they prove something. An approval must name the digest of the current revision, and any edit moves an approved item back to review. So whenever an item's status is approved, its current revision is the one that was approved, and publishing never needs to check the content again. That holds only if nothing can change between the check and the write, which is the next problem.

Two reviewers at once#

Each request so far reads the item, decides, then writes. When two requests for the same item arrive together, the gap between reading and writing is where things go wrong. This is a race condition: the outcome depends on the timing of two things happening at once.

Chen and Omar both click Approve. Both requests read the item: awaiting review, version 7. Both run the guards, and both pass, because each is right about what it read. Both write approved. Every check was correct when it ran. What was wrong was assuming the item still looked that way when the write happened.

There are two standard fixes. Pessimistic concurrency locks the row while you decide, so the second request waits its turn. Optimistic concurrency assumes conflicts are rare, lets both decide, and makes the write conditional: update the row only if its version is still the one I read, adding one to the version as you do. The first write succeeds and moves the version to 8. The second asks for version 7, matches no row, and changes nothing. This holds even when both writes arrive in the same instant: by default, PostgreSQL makes the second update wait for the first to finish, then checks its condition again against the row as it now is.

Optimistic concurrency suits approvals: two people acting on the same item in the same instant is rare, so it is not worth locking rows on every request to guard against it. The rare loser waits only for the other write to finish, then gets a clear 409.

The write also does several things — update the item, store a new revision, record the outcome — and they must happen together or not at all. That is what a transaction is for. On one database connection, BEGIN starts it, COMMIT makes everything in it take effect at once, and ROLLBACK discards all of it. The examples use node-postgres, the most widely used PostgreSQL driver for Node; the pattern is the same in any driver:

ts
import type { Pool, PoolClient } from "pg";

export async function inTransaction<T>(
  pool: Pool,
  work: (tx: PoolClient) => Promise<T>
): Promise<T> {
  // A transaction lives on one connection.
  const tx = await pool.connect();
  try {
    await tx.query("BEGIN");
    const result = await work(tx);
    await tx.query("COMMIT");
    return result;
  } catch (error) {
    // Something failed, so none of it happened.
    await tx.query("ROLLBACK");
    throw error;
  } finally {
    tx.release();
  }
}

The same request twice#

Networks fail in an awkward way: a request can succeed on the server and its response still never arrive. The app's retry logic, or the person, tries again. The server receives the same request twice and cannot tell a retry from a second intention.

An operation is idempotent when doing it twice has the same effect as doing it once. Approving and publishing are not idempotent by nature, so you make them so with an idempotency key: a unique value the client creates when the person first asks for an action, and sends with every attempt at it until an answer arrives — including when the person clicks again after a timeout, usually in an Idempotency-Key header. The server stores the outcome of each change it makes under that change's key. A request whose key is already stored gets the stored outcome back, and nothing runs a second time. A refused request changes nothing and stores nothing, so a retry of one is simply decided again.

sql
-- One stored outcome per key, per person.
CREATE TABLE commands (
  actor_id  text NOT NULL,
  key       text NOT NULL,
  outcome   jsonb NOT NULL,
  PRIMARY KEY (actor_id, key)
);

Two details matter. The key belongs to a person, so nobody can read another user's outcome by guessing their key. And the outcome is stored in the same transaction as the change it describes. Stored separately, a crash between the two leaves either a change with no key, which a retry repeats, or a key with no change, which tells a retry that something happened when it did not.

One request, start to finish#

Here is the whole path. It reads and decides outside the transaction, then writes inside it, and only if nothing has changed since the read:

ts
type Outcome = { status: number; body: Record<string, unknown> };

export async function perform(
  pool: Pool,
  actor: Actor,
  command: Command,
  key: string
): Promise<Outcome> {
  const refused = (status: number, error: string): Outcome =>
    ({ status, body: { error } });

  // The outcome already stored under this key, if there is one. Inside
  // the transaction, ask on that connection rather than taking another.
  const stored = async (db: Pool | PoolClient = pool) => {
    const { rows } = await db.query<{ outcome: Outcome }>(
      "SELECT outcome FROM commands WHERE actor_id = $1 AND key = $2",
      [actor.id, key]
    );
    return rows[0]?.outcome;
  };

  // 1. A key seen before means a retry: answer it the same way.
  const seen = await stored();
  if (seen) return seen;

  // 2. Read the item and decide.
  const { rows: [item] } = await pool.query<Item>(
    `SELECT id, author_id AS "authorId", status, revision, digest,
            version
       FROM items WHERE id = $1`,
    [command.itemId]
  );
  if (!item) return refused(404, "not_found");

  const decision = transition(item, command, actor);
  if (!decision.ok) {
    // A twin of this request may have succeeded since step 1.
    return (await stored()) ?? refused(decision.status, decision.error);
  }

  // An edit adds a revision; every other action keeps the current one.
  const next =
    command.action === "edit"
      ? { revision: item.revision + 1, digest: digest(command.content) }
      : { revision: item.revision, digest: item.digest };
  const outcome: Outcome = {
    status: 200,
    body: { id: item.id, status: decision.to, ...next }
  };

  // 3. Write it all at once, and only if the item is still the version
  //    that step 2 read.
  try {
    return await inTransaction(pool, async (tx) => {
      const updated = await tx.query(
        `UPDATE items
            SET status = $1, revision = $2, digest = $3,
                version = version + 1
          WHERE id = $4 AND version = $5
          RETURNING id`,
        [decision.to, next.revision, next.digest, item.id, item.version]
      );
      if (updated.rows.length === 0) {
        // Someone changed the item first. If it was this request's
        // twin, the outcome it stored is the right answer.
        return (await stored(tx)) ?? refused(409, "changed_since_read");
      }

      if (command.action === "edit") {
        await tx.query(
          `INSERT INTO revisions (item_id, revision, content, digest)
           VALUES ($1, $2, $3, $4)`,
          [item.id, next.revision, command.content, next.digest]
        );
      }
      await tx.query(
        `INSERT INTO commands (actor_id, key, outcome)
         VALUES ($1, $2, $3)`,
        [actor.id, key, outcome]
      );
      return outcome;
    });
  } catch (error) {
    // A twin stored this key after step 1, so this attempt's writes
    // were rolled back. The twin's outcome is the answer.
    const keyTaken =
      (error as { constraint?: string }).constraint === "commands_pkey";
    const twin = keyTaken ? await stored() : undefined;
    if (twin) return twin;
    throw error;
  }
}

Follow the two reviewers through it. Both find no stored key, both read version 7, both pass the guards. Inside its transaction, one moves the item to version 8 and stores its outcome. The other's update matches no row. RETURNING id makes an update report the rows it changed, so an empty result means the version had moved on, and the request writes nothing and returns 409.

A request can race its own duplicate in the same way: two attempts with one key, sent together, before either has stored anything. One wins, and the other fails in one of three ways. Its update can match no row; the guards can refuse it, if it read the item after the winner finished; or, for an edit, which the table allows again, its own writes can run and then collide with the key the winner stored, so the database rolls them back. Each would answer with an error for something that worked, which is the third failure from the start of this note. So in each case perform looks the key up again before answering, and returns the winner's outcome. The winner has always committed by then: the loser's update, or its insert of the same key, waited for exactly that. Inside the transaction the lookup uses the transaction's own connection, tx; taking a second one from the pool there would deadlock once every connection was held by a request waiting for another. With those checks in place, step 1 is only the fast path: it answers an ordinary retry without touching the item at all.

Prove it#

Each failure from the start of this note becomes a test against a real database, with every step sent through perform as a real request would be:

ts
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import pg from "pg";

const pool = new pg.Pool({
  connectionString: process.env.DATABASE_URL
});

// All three are reviewers. Maya also writes the changes.
const reviewer = (id: string): Actor =>
  ({ id, roles: ["reviewer"] });
const maya = reviewer("maya");
const chen = reviewer("chen");
const omar = reviewer("omar");

const draft: Content = {
  title: "Raise the transfer limit",
  body: "Daily limit for business accounts.",
  amount: 7_500
};
const read = digest(draft); // what a reviewer's page received

// Each step is a separate request with its own key.
const send = (actor: Actor, command: Command) =>
  perform(pool, actor, command, randomUUID());
const approve = (actor: Actor, itemId: string) =>
  send(actor, { itemId, action: "approve", reviewedDigest: read });

async function inReview(id: string) {
  await pool.query(
    "INSERT INTO items (id, author_id) VALUES ($1, $2)",
    [id, maya.id]
  );
  await send(maya, { itemId: id, action: "edit", content: draft });
  await send(maya, { itemId: id, action: "submit" });
}

// The author cannot check their own work, even as a reviewer.
await inReview("c1");
assert.equal((await approve(maya, "c1")).status, 403);

// Maya adds a zero while Chen reads. Chen's approval is refused.
await inReview("c2");
const zero = { ...draft, amount: 75_000 };
await send(maya, { itemId: "c2", action: "edit", content: zero });
assert.equal((await approve(chen, "c2")).status, 409);

// Chen and Omar approve at once. Exactly one succeeds, every time.
for (let i = 0; i < 100; i++) {
  await inReview(`race-${i}`);
  const both = await Promise.all([
    approve(chen, `race-${i}`),
    approve(omar, `race-${i}`)
  ]);
  assert.deepEqual(both.map((r) => r.status).sort(), [200, 409]);
}

// A retried publish reuses its key, and gets the stored outcome back.
const key = randomUUID();
const publish: Command = { itemId: "race-0", action: "publish" };
const first = await perform(pool, maya, publish, key);
const retry = await perform(pool, maya, publish, key);
assert.equal(first.status, 200);
assert.deepEqual(retry, first);

// Editing after approval sends the item back to review.
await inReview("c3");
await approve(chen, "c3");
const retitle: Command = {
  itemId: "c3",
  action: "edit",
  content: { ...draft, title: "Raise the limit" }
};
const edited = await send(maya, retitle);
assert.equal(edited.body.status, "awaiting_review");

await pool.end();

The race runs a hundred times because once proves almost nothing. On a single attempt the first request often finishes before the second has even opened its database connection; the guard then refuses the second, and the test passes without any concurrency having happened. Repeated, most attempts genuinely overlap. In a longer run of 300 races against PostgreSQL, none approved twice: the version check stopped the second approval in all but a handful, and the guards stopped the rest, where the requests had not overlapped. With it removed from the UPDATE, nearly every run approved twice, and this test fails.

What it costs#

Every consequential action now waits for a second person. That is the price of the guarantee, and it is worth paying only where one mistake is expensive. Put maker–checker on everything and reviewers learn to approve without reading, which is worse than having no checker at all.

The state machine has to keep pace with how the business actually works. When someone needs a move the table does not allow, the answer is to change the table on purpose, not to add a back door around it.

Optimistic concurrency hands conflicts to people: whoever loses a race sees a 409 and has to look again. Idempotency keys pile up, so keep them as long as a retry could plausibly arrive — a day is common — and delete them after. A complete implementation also stores each request with its key and refuses a key reused for a different request.

None of this shows when everything goes right. It exists for the minute between reading and clicking, the two people who click at once, and the response that never arrived.

An approval is worth something only if it covers exactly what takes effect, exactly once.