← Engineering

Project report / Workflow integrity

Making a multi-stage review safe when many people touch one record

How I used PostgreSQL leases, versioned decisions, and a transactional outbox to keep a two-stage approval workflow consistent, without building a distributed system.

Sole engineerTypeScript · PostgreSQLProject report
01 / The problem

One record, four kinds of writers.

I built a web platform for a public-sector institution that moves applicants through a multi-stage accreditation process. Applicants submit details and documents, two independent review stages assess them, and an approved applicant receives a numbered PDF credential. I was the only engineer, and I owned the architecture, data model, background processing, and deployment. The institution’s stakeholders owned the business rules, such as eligibility criteria and deadlines.

Kinds of writers on one record
4
Independent review stages
2
Review lease
15 min
Transaction per decision
1

On paper this is forms and an approval chain. The difficulty is that the same application is written to by actors working on very different timescales, and each decision has consequences that are hard to take back.

Who writes to it
Shared stateOne application recordStatus, documents, and a version number
Writers
ReviewersTwo stages working shared queues. A review takes minutes, not milliseconds.
The applicantMay replace a document at almost any point before the final decision.
AdministratorsReassign work, correct data, and repair workflow state.
Background workersSend email and render the credential after a decision.

A naive implementation reads the record, shows a form, and writes the new status. That fails in two ways. Two reviewers approve the same file, or a reviewer approves evidence that was replaced two minutes earlier. Or a side effect disagrees with the database: an email goes out for a decision that then rolls back, or a decision commits and its email is never sent.

The question I designed around was how to let many people work on the same records, keep every decision explainable, and keep side effects consistent with committed state. My answer was to make PostgreSQL do the coordination.

02 / One decision

Every decision is one guarded transaction.

A review decision does four things inside a single database transaction. It checks that the reviewer still holds the lease and is looking at current evidence. It advances the application with a compare-and-set update. It writes the decision record along with every consequence. Then it commits.

Decision transaction
01 / FenceCheck lease and versionOwner, token, lease version, expiry, and the application version the reviewer sawFails fast with a clear message
02 / AdvanceCompare-and-set the statusUpdate the application only where its version still matchesOne row, or roll back
03 / RecordWrite the consequencesVersioned review record, history entry, outbox rows, in-app notice, lease completionSame transaction
04 / CommitCommit, then logThe operational audit entry is written just after the commitBest effort

Decisions are records, not just a status change. Each review is keyed to the application and a review version, and it stores the application version it was made against. The checklist answers behind it carry the version of the rules in force. That is what lets me reconstruct a decision later: who made it, against which evidence, and under which rules.

Side effects never run inside that transaction. The decision inserts email and credential-rendering jobs into an outbox table, and a worker delivers them afterwards. If the transaction rolls back, so do the jobs. If it commits, the jobs exist and will be retried until they succeed or hit a cap.

Delivery path
01 / OutboxMessage rowInserted with the decision under a deterministic idempotency keyDuplicate keys collapse
02 / ClaimWorker takes a rowA short transaction using SKIP LOCKED, then marks it processingOne worker at a time
03 / SendCall the providerAn email send or a PDF render, outside any transactionMay repeat on retry
04 / SettleDelivered or retryCapped exponential backoff. Stale processing rows are reclaimed.Retries, then stops
03 / Concurrency

The lease keeps people apart. The version keeps the data right.

Reviewers take a lease on a review before they start. A lease is a row per application and stage with an owner, a random token, a version, and a 15-minute expiry. Claiming one is serialized with a transaction-scoped advisory lock, and every change appends to an event log. A second reviewer who tries to claim the same review is refused with a specific message.

Two reviewers, one file
  1. Reviewer A → DatabaseClaim the review
  2. Database → Reviewer ALease granted, expires in 15 minutes
  3. Reviewer B → DatabaseClaim the same review
  4. Database → Reviewer BRefused: claimed by another officer
  5. DatabaseA’s lease lapses and B claims it in the instant between A’s lease check and A’s write. Both now hold application version 7.
  6. Reviewer A → DatabaseApprove at version 7 (update where version = 7)
  7. Database → Reviewer AOne row changed. Commit. Version is now 8.
  8. Reviewer B → DatabaseApprove at version 7
  9. Database → Reviewer BNo row matches. Roll back: this application changed.

It is tempting to say the lease is what keeps reviewers apart. That is only half true. Inside the decision transaction the lease is read, not locked, so in principle it can lapse and be claimed by a colleague in the milliseconds between my check and my commit. That still cannot produce two decisions, because the compare-and-set is the real serialization point. PostgreSQL row-locks the application during the first update. The second update waits, re-evaluates its condition against the committed row, matches nothing, and rolls back.

Illustrative example, not production sourceUPDATE application
   SET status  = 'APPROVED',
       version = version + 1
 WHERE id      = :id
   AND version = :version_the_reviewer_saw;

-- 1 row changed  -> this decision won
-- 0 rows changed -> the record moved on; roll back

The same version protects against the applicant. If they replace a document after approval, the version increments, the earlier approval is cleared, and any open lease on that application is released. A reviewer still working from the old page then fails the version check.

Evidence changes mid-review
Status check onlyA reviewer’s decision after the evidence changed.
Reviewer opens the fileReads the evidence as it stands.
Applicant replaces a documentNothing tells the open review page.
Reviewer approvesThe write succeeds against a status that still looks valid.
WrongAn approval is recorded against evidence nobody reviewed.
Versioned evidenceWhat the platform does.
Reviewer opens the fileThe page carries application version 7.
Applicant replaces a documentVersion becomes 8, the approval is cleared, and open leases are released.
Reviewer approves at version 7The compare-and-set matches no row.
ContainedThe stale decision is rejected and the new evidence returns to review.

I did not use plain row locks or serializable isolation for the whole review, because a database lock cannot sensibly be held across ten minutes of human reading. Optimistic concurrency on its own is correct, but it lets two people do the same work and then discards one reviewer’s effort. The lease avoids the wasted work, and the version keeps correctness intact. Each layer has a distinct job.

Layer by layer
LeaseCoordination. Makes conflicts rare, visible, and attributable, and gives administrators something to reassign.Read, not locked, inside the decision. It cannot guarantee exclusion alone.
Fencing checkFails fast with a specific message when a lease expired, moved, or was completed.A read, so it can be true at check time and stale a moment later.
Version compare-and-setThe guarantee. At most one decision commits per version of the evidence.The loser’s work is discarded, and the conflict surfaces as an error.
Database constraintsA backstop for paths I did not anticipate, such as one active application per person.Guards only what the schema can express.
04 / Delivery

What “exactly once” does and does not mean.

It is easy to describe a transactional outbox as giving exactly-once side effects. It does not, and the precise version is more useful. The outbox moves the question from “did the decision and the email agree?” to “did the worker finish?”. It cannot make the external call itself transactional.

Guarantees
Decision, history, outbox rows, in-app noticeAtomic: all commit or none do.One database transaction.
Applying the same decision twiceAt most once per version.Compare-and-set, and a completed lease rejects a resubmission.
Enqueuing the same message twiceCollapsed to one row.Unique idempotency key. The upsert is a no-op on conflict.
A worker picking up a messageOne worker at a time, while its claim is fresh.SKIP LOCKED, then a processing marker with a staleness timeout.
Sending an emailAt least once. A duplicate is possible.The send is an external call outside any transaction.
Rendering a credential PDFSafe to repeat.Deterministic storage path, skipped if already recorded.
Operational audit logBest effort.Written after commit. A crash in the gap loses the entry, not the decision.

The duplicate window is narrow but real. If a worker sends an email and crashes before recording it as delivered, the row is reclaimed after a timeout and the email can be sent again. I accepted that for this workload because a repeated notice is a nuisance, while a lost one is not. Forwarding the outbox key to the email provider as an idempotency key would narrow it.

05 / Trade-offs

Decide the guarantee first, then pick the mechanism.

Most of the design came from asking what must never happen, and what is merely annoying. Two decisions on one version of the evidence must never happen. A slow handover is annoying. That ordering is why the version is the hard guarantee and the lease is a convenience.

01

Leases without heartbeats

An abandoned lease blocks colleagues until it expires, up to 15 minutes. Administrators can reassign it, and deactivating an account releases its leases, but there is no heartbeat.

02

Polling, not a broker

The outbox adds a few seconds of latency and sends one message per transaction. That suits this volume and needs nothing beyond PostgreSQL, but it is a ceiling for a larger system.

03

Errors for conflicts

A stale decision currently surfaces as a generic error instead of an inline “this changed, reload” message. It is correct but not graceful, and it is the first thing I would improve.

If I continued, I would add concurrency tests that run against a real database: two reviewers racing to claim, an expired lease re-claimed, evidence replaced mid-review, and a double-submit, each asserting exactly one outcome. I would also collapse the repeated status-transition pattern into a single helper so the compare-and-set, history entry, and version bump cannot drift apart between code paths.

Continue readingAll engineering writing