Optimistic concurrency for a collaborative document: revisions and field-level merges
by Chanan Braunstein, Owner
TripEagle is a group trip planner. Each trip has a draft: one JSON document with the trip's days, places, notes and travel between them. The organizer works on it in the studio on a laptop. A co-planner can work on it at the same time. Kestrel, the AI, writes to it when a planner accepts one of its proposals. And either planner can fix a day from their phone while they're on the trip, often with no signal, so the edit sits in the phone's outbox and reaches the server hours later.
That's a lot of writers for one document. This post is about how TripEagle keeps them from undoing each other: a revision on every write, a copy of every document a write replaced, a merge by field for an edit that arrives late, and an inbox for the fields two people really did change differently.
This is the seventh post in Techniques from TripEagle, after deterministic end-to-end tests. The code is simplified from the TripEagle monorepo so it stands on its own.
Last write wins, and why it loses data
The draft is stored whole in one jsonb column, and the natural first version of a write is: read the document, change it, write it back.
const {
rows: [trip],
} = await db.query('select draft_doc from trips where id = $1', [tripId])
const doc = renameDay(trip.draft_doc, 3, 'Ferry to Naxos')
await db.query('update trips set draft_doc = $2 where id = $1', [tripId, doc])
That's correct with one writer and wrong with two. The organizer opens the trip and renames day 3. A co-planner, who opened it a minute earlier, adds a place to day 5 and saves. Each wrote the whole document as they last read it, so whoever saved second wins, and the other's change is gone. Nobody sees an error, and nothing says it happened. The organizer finds out a week later, when the place they added isn't there.
This is the lost update, and with a document stored whole it doesn't need the two people to touch the same thing. Any two writes that overlap in time lose one of them.
There are three ways out, and TripEagle uses all three in different places:
- Refuse the stale write. Each write says which revision it read, and the server refuses it when the document has moved on. Nothing is lost, and the person whose write was refused sees the document as it now is and does their change again.
- Merge the stale write. When the server knows what the write was made against, it can tell which fields the write changed and which the other side changed since, and keep both.
- Ask a person. When both sides changed the same field differently, no rule can know which one is right. Keep both values and let a person choose.
Revision-guarded writes in SQL
The first is a counter and a copy. The trip has a revision that every write of the draft counts up, and a history table keeps the document each write replaced.
-- Counted up by every write of the draft. A trip's first draft is revision 1.
alter table trips add column draft_revision integer not null default 1;
-- The draft as it was before each write: undo's store, and a safety net.
-- A row is the draft as it stood at `revision`, and `written_by` the person
-- whose write replaced it with revision + 1.
create table draft_history (
trip_id uuid not null references trips (id),
revision integer not null,
doc jsonb not null,
written_by uuid,
written_at timestamptz not null,
primary key (trip_id, revision)
);
Every page that can change the draft is given the revision along with the document, and sends it back with the change. The write locks the trip's row, compares, keeps a copy and writes:
const historyKept = 50
type DraftWrite = { readRevision: number; doc: TripDocument; writtenBy: string | null; at: Date }
export async function writeDraft(tx: Transaction, tripId: string, write: DraftWrite) {
// Two writers that read the same revision queue here, and the second sees the first's.
const found = await tx.one(
'select draft_revision, draft_doc from trips where id = $1 for update',
[tripId],
)
if (found.draft_revision !== write.readRevision) {
// Moved on since they read it: they see it as it now is, and nothing is merged for them.
return { outcome: 'stale', revision: found.draft_revision, doc: found.draft_doc } as const
}
// Copied inside Postgres, so what is kept is the row exactly as it was.
await tx.query(
`insert into draft_history (trip_id, revision, doc, written_by, written_at)
select id, draft_revision, draft_doc, $2, $3 from trips where id = $1`,
[tripId, write.writtenBy, write.at],
)
await tx.query(
'update trips set draft_doc = $2, draft_revision = draft_revision + 1 where id = $1',
[tripId, write.doc],
)
await tx.query(
`delete from draft_history where trip_id = $1 and revision not in (
select revision from draft_history where trip_id = $1
order by revision desc limit $2)`,
[tripId, historyKept],
)
return { outcome: 'written', revision: write.readRevision + 1 } as const
}
select … for update is what makes the check safe. Under Postgres's default isolation, a second transaction that reaches the same row waits until the first commits, and then reads the revision the first wrote. Without the lock, both could read revision 7, both pass the check, and the second would overwrite the first, which is the lost update again.
The shorter version of this is a single compare-and-set: update trips set … where id = $1 and draft_revision = $2, then check that it updated a row. That's enough when the write is only the update. TripEagle's does more inside the same transaction (the copy into the history, and work the new draft queues up, such as routing a day whose places changed), and when the write is stale it answers with the draft as it now is, so the page can show it. Taking the lock first makes all of that read one consistent row.
On the page, a stale answer doesn't merge anything. The studio is a live page where the planner made one change a second ago, so it shows the draft as it now is, says it changed, and leaves them to do their change again. That costs a click. A merge the planner didn't see could cost a lot more.
Undo comes from the history
Every accept, reorder and delete in the studio shows a toast with an undo, because thumbs slip. The history table is what undo restores from, and the revision is what keeps it safe:
export async function undoDraft(
tx: Transaction,
tripId: string,
{ producedRevision, undoneBy, at }: { producedRevision: number; undoneBy: string | null; at: Date },
) {
const found = await tx.one('select draft_revision from trips where id = $1 for update', [tripId])
// Only the last write, while it is still the last: anything since ends the chance.
if (found.draft_revision !== producedRevision) return { outcome: 'changed-since' } as const
const before = await tx.maybeOne(
'select doc, written_by from draft_history where trip_id = $1 and revision = $2',
[tripId, producedRevision - 1],
)
if (!before) return { outcome: 'changed-since' } as const
// And only by the person who made it.
if (undoneBy === null || before.written_by !== undoneBy) return { outcome: 'not-yours' } as const
// The restore is a write like any other, so it is kept and can itself be undone.
const restored = await writeDraft(tx, tripId, {
readRevision: producedRevision,
doc: before.doc,
writtenBy: undoneBy,
at,
})
return { outcome: 'undone', revision: restored.revision } as const
}
The obvious alternative is to record each write's inverse and apply it to whatever the draft is now, which survives other people's edits in between. TripEagle doesn't, because a change to a list is written as the whole list. The inverse of "add a place to day 5" would put back day 5's old list of places, and if a co-planner had added a different place to day 5 in the meantime, the undo would quietly remove theirs too. Restoring a whole document is only safe while nothing has happened since, so that's the only time undo is offered.
It's deliberately narrow: the last write, by the person who made it, while it's still the last. The history is longer than undo needs (the last 50 drafts) because it's also the record of who changed the draft and when, which the conflict cards further down use for a conflict with the draft.
One operation lands every change
The revision check, the copy and the writer are the same for every kind of change: a planner's edit, a note, a proposal accepted from the Inbox, a picture landing in its slot, a write from a connected AI. The first version had a dozen callers do it by hand, and the writer was worked out in two places, once in JavaScript and once in SQL for the audit row, which could disagree. So now there's one function that does it, and each caller passes only what is particular to it: how to change the document, and what to record beside it once the write has landed.
type Applied<X, R> = { doc: TripDocument; extras: X } | { refused: R }
type Landing<X, R> = {
readRevision?: number
apply: (draft: TripDocument) => Applied<X, R> | Promise<Applied<X, R>>
then?: (revision: number, extras: X) => Promise<void>
writer: string | null
at: Date
}
export async function land<X, R>(tx: Transaction, tripId: string, landing: Landing<X, R>) {
const { readRevision, apply, then, writer, at } = landing
// The draft and its revision, read without a lock: writeDraft checks again under one.
let read = await readDraft(tx, tripId)
for (let attempt = 0; ; attempt++) {
if (readRevision !== undefined && read.revision !== readRevision) break
const applied = await apply(read.doc)
if ('refused' in applied) return { outcome: 'refused', refused: applied.refused } as const
const written = await writeDraft(tx, tripId, {
readRevision: read.revision,
doc: applied.doc,
writtenBy: writer,
at,
})
if (written.outcome === 'written') {
// Kept only if the write landed. One that throws rolls the write back.
await then?.(written.revision, applied.extras)
return { outcome: 'landed', revision: written.revision, extras: applied.extras } as const
}
// A person's stale revision is their "changed since", and never retried. A background
// job reading the draft as it is now meets a race once, and applies its change again.
if (readRevision !== undefined || attempt > 0) break
read = { revision: written.revision, doc: written.doc }
}
// The page then reads the draft as it now is, and shows it.
return { outcome: 'moved' } as const
}
Accepting one of Kestrel's proposals is then a few lines that say only what's particular to it:
const landed = await land(tx, tripId, {
readRevision: form.revision,
apply: (draft) => {
const doc = applyPatches(draft, proposal.patches)
return problemsInPlan(doc).length > 0 ? { refused: 'no-longer-fits' } : { doc, extras: null }
},
then: () => markAccepted(tx, proposal.id, now),
writer: planner.memberId,
at: now,
})
Undo is the landing's twin, undoDraft above with the same kind of then step, so clearing a proposal's acceptance also happens only if the restore landed. Two rules that used to be restated by every caller now live in the one function. A change is applied to the draft as it is when the planner acts, not as it was when the proposal was written, so a proposal that no longer fits is refused and can only be declined. And the proposal is marked accepted only if the write landed, in the same transaction.
Field-level merge for stale edits
Refusing works for the studio. It doesn't work for the phone.
A planner on day 4 of the trip opens the day on their phone, on a ferry with no signal. They fix the time of the boat back and rewrite a note. The app puts the edit in its outbox. Three hours later, back in signal, it sends it. In those three hours, the organizer, at home, renamed day 4 and published.
The first version refused that edit whole, and offered "send again against the newest" or "discard". Sending again overwrote the organizer's rename, and discarding lost the planner's fixes. Neither was right, and neither should have been needed, since the two changed different things.
A merge needs a base
To merge, you need three documents, not two:
- the base: the version the edit was made against;
- ours: the base with the edit applied;
- theirs: what the server has now.
With only ours and theirs, you can't tell "I changed the title" from "they changed the title": both look like the title is different. The base tells you who moved.
So the edit has to say what it was made against, and the server has to still have it. The phone's day page shows a published version, and every published version is kept, immutable, under its number. A day edit carries that number, and the server reads the base by it. If your documents aren't versioned like this, the history table above can do the same job for as far back as it reaches.
The rule, field by field
A day edit is a list of changes to one day: its title and summary, a place's note and time, the order of its places, a place removed. Each change sets one field, and each field is merged on its own:
theirs now holds | So |
|---|---|
| the base's value | only the edit changed it: write the edit's value |
| the edit's value | both made the same change: nothing to write |
| something else | both changed it, differently: a conflict, keep theirs |
| nothing: the field is gone | the day or place was removed: see below |
In code, simplified to a day's title and summary and each place's note and time:
type Place = { id: string; name: string; note: string; time: string | null }
type Day = { title: string; summary: string; places: Place[] }
type Field =
| { field: 'title' | 'summary' }
| { field: 'note' | 'time'; placeId: string }
type Value = string | null
type Change = Field & { value: Value }
type Conflict = Field & { value: Value }
/** A field's value on `day`, or undefined when the place it belongs to is gone. */
function valueOn(day: Day, f: Field): Value | undefined {
if (f.field === 'title' || f.field === 'summary') return day[f.field]
const place = day.places.find((p) => p.id === f.placeId)
return place && (f.field === 'note' ? place.note : place.time)
}
/** `day` with the field set to `value`. */
function withValue(day: Day, f: Field, value: Value): Day {
if (f.field === 'title' || f.field === 'summary') return { ...day, [f.field]: value }
const places = day.places.map((p) => (p.id === f.placeId ? { ...p, [f.field]: value } : p))
return { ...day, places }
}
export function mergeDayEdit(base: Day, theirs: Day, changes: Change[]) {
const conflicts = new Map<string, Conflict>()
let was = base
let day = theirs
for (const change of changes) {
const key = 'placeId' in change ? `${change.field}:${change.placeId}` : change.field
const before = valueOn(was, change)
const now = valueOn(day, change)
// A second change to the same field is compared with what the first one set.
was = withValue(was, change, change.value)
if (now === change.value) {
conflicts.delete(key) // they already made this change
} else if (now !== undefined && now === before) {
day = withValue(day, change, change.value) // only we changed it
conflicts.delete(key)
} else if (change.value === valueOn(base, change)) {
conflicts.delete(key) // a later change put back the base's value: only they moved it
} else {
conflicts.set(key, change) // both changed it, or they removed it: theirs stands for now
}
}
return { day, conflicts: [...conflicts.values()] }
}
In the ferry example, the planner's time and note merge, the organizer's rename stays, and the edit publishes at once as a new version. No one is asked anything, because there was nothing to choose.
The same merge runs a second time onto the studio's draft, with the draft as theirs, so the organizer's next Publish doesn't take the phone's fix back out. A field already in conflict with the published version is left out of that second pass, so one disagreement makes one card, not two.
Lists and removals need their own rules
A field that's a string compares with ===. A day's order of places doesn't, and a naive comparison makes everything a conflict.
Say the planner moved the museum before lunch. Meanwhile the organizer added a café to the same day. Now the base's order, the edit's order and the server's order are three different lists, and a whole-list comparison calls it a conflict, although nobody reordered the same places differently. So two orders count as the same when the places they both hold come in the same order:
/** The same order, as far as two lists hold the same places. */
function sameOrder(a: string[], b: string[]): boolean {
const common = (xs: string[], ys: string[]) => xs.filter((id) => ys.includes(id))
return common(a, b).join() === common(b, a).join()
}
And a reorder is stored as what the person did ("move the museum to position 2"), not as the list it produced, so it can be replayed on the server's list, its position clamped to the list's length. It's a conflict only when the other side reordered too.
Removals are the other case. If the planner rewrote the note on a place the organizer has since removed, writing the note would bring the place back, and dropping it would lose the note. So the conflict is over the place itself (the simplified code above records it under the note it was about), and the card offers "keep it, with its note" or "leave it removed". Removed on both sides is no change at all. And an edit to a day the trip no longer has publishes nothing and makes no card, since there's nothing left to choose for; the answer to the phone lists it as skipped, with why.
None of this works if places are named by their position. "Set the note on the third place" means a different place once someone has added one before it. Each place in the document has a stable id, given when it's written, and every edit names places by it.
Surfacing true conflicts to a human
What's left after the merge is a short list of fields where two people really disagree. TripEagle doesn't pick. Neither value is lost: the other side's value stays in the document, and the edit's value is kept as a row.
-- Simplified: the real table also names the day's split and the place's name.
create table day_edit_conflicts (
trip_id uuid not null,
id uuid not null,
day_edit_id uuid not null, -- who made the edit, and when
met text not null check (met in ('published', 'draft')),
day_n integer not null,
field text not null check (field in ('title', 'summary', 'transport', 'order', 'note', 'time', 'place')),
place_id text,
value jsonb not null, -- the edit's value, the one that didn't win
settled text check (settled in ('chosen', 'kept')),
settled_by uuid,
settled_at timestamptz,
primary key (trip_id, id)
);
Each open row is a card in the trip's Inbox, shown to every planner, not only the one whose edit conflicted. The other planner is as much a party to it, and the Inbox is the trip's, not a person's. The card shows both values, who set each and when. The edit's author and time come from the day edit. Who set the value it met comes from walking the kept versions back to where the field last changed.
A card compares with now
A card isn't a snapshot. It reads the field as it is when the card is shown:
/** A conflict as it stands now, or undefined when there's nothing left to choose. */
export function conflictStanding(day: Day | undefined, conflict: Conflict) {
if (!day) return undefined // the day itself is gone: nothing left to choose for
// undefined when the place was removed: the choice is then over the place itself.
const current = valueOn(day, conflict)
if (current === conflict.value) return undefined
return { current }
}
If someone has since set the field to the edit's value anyway, or the day is gone, the card goes away by itself. And choosing never writes a value someone stored hours ago over whatever is there now, which would be a lost update of its own.
Choosing is the field's own write. Picking the edit's value makes a one-field edit, published and laid onto the draft by the same rules, with the same undo toast as any other write. Keeping the other value writes nothing and settles the card.
A conflict isn't a refusal
The server answers a stale day edit with 200, not 409: here's the version it published (if anything merged), what it skipped and why, and which fields are waiting in the Inbox. The phone's outbox entry is done, whatever conflicted, and the day page says how many changes clash and links to the Inbox. The person on the ferry doesn't have to do anything else, and the one at home sees a card, not a mystery.
It's tempting to fold conflicts into Kestrel's proposals, since both are cards in the same Inbox. TripEagle keeps them apart. A proposal is written by something other than a planner, and is accepted or declined whole. A conflict is two planners' values, and is settled by choosing one. Folding them together would stretch the proposal's one rule, that it changes nothing until it's accepted.
Why not a CRDT?
Conflict-free replicated data types (CRDTs), as in Automerge or Yjs, are the other well-known answer. Every replica records operations, any two replicas that have seen the same operations hold the same document, and there are never conflicts to resolve. For some products that's exactly right. TripEagle doesn't use one, for reasons that come down to what it needs:
- "No conflicts" means something picked for you. When two people set a title to different strings, a CRDT still converges, by a rule such as "the write with the higher clock wins". That's last write wins for that field, applied silently. What TripEagle wants for exactly that case is to keep both and ask.
- Converged isn't the same as valid. A trip has rules a merged document has to pass: days numbered with no gap, every day in a region the trip has, no traveler in two of a day's splits at once. A CRDT guarantees every replica ends with the same document, not that the document passes your checks. TripEagle checks every write against them, which needs a server that can refuse.
- There's already a server, and it's the authority. Every write goes through it to be checked and audited. CRDTs earn their keep when there's no single authority, as with peer-to-peer apps or long offline work on every device. Here the only offline writer is a phone editing one day, and a base version is enough to merge that.
- Not every writer is a person typing. An accepted proposal, a background job and a connected AI each replace part of the document in one go. Writing those as a stream of fine-grained operations would be its own project, for no gain.
- The cost is real. The document would carry its operation history or tombstones, every client would need the library, and the stored JSON would no longer be the plain thing every other part of the app reads.
Where a CRDT would pay for itself is live, character-by-character co-editing of the same long text, with two cursors in one paragraph. TripEagle's text fields are a title and a few sentences of a note, and people edit them a minute or a day apart, not a keystroke apart. If that changes, a CRDT for that one field, beside revision-guarded writes for the rest, would be the move, not a CRDT for the whole document.
What to take from this
- A whole-document write without a check loses updates, even when the two people changed different things.
- Give the document a revision, and refuse a write that names an old one. Check it under
select … for update, or with a compare-and-set update, so two writers can't both pass. - Keep what each write replaced. It makes undo a restore that's safe while nothing has happened since, records who changed what, and is a safety net for a bad change after the toast has gone.
- Put the guard, the writer and "record it only if it landed" in one function, and let each kind of change pass in only how it changes the document.
- Refuse on a live page, merge for an offline device. One costs a click, and the other would cost the edit.
- Merge three ways, field by field. Without the base you can't tell who moved. Name list items by a stable id, compare lists by the items both hold, and treat an edit to something removed as a conflict over the thing itself.
- Keep real conflicts as rows, show them to everyone, and compare them with now when they're shown, so choosing never overwrites a later change.
- Reach for a CRDT when you need live co-editing of the same text without a central authority. When you have a server, rules a document must pass, and conflicts people should see, revisions and a three-way merge are less to build and keep both values.
