Optimistic Lock Version Check

Implement optimistic locking with a version column, returning a typed conflict result when concurrent writers collide.

TypescriptData Integrity

Code

typescriptsnippet
19 lines
export interface Record { id: string; value: string; version: number; }
export type UpdateResult = { ok: true; record: Record } | { ok: false; conflict: true; current: Record };

export async function updateWithVersion(
  store: { load(id: string): Promise<Record | undefined>; save(record: Record, expectedVersion: number): Promise<boolean> },
  id: string,
  mutate: (value: string) => string,
): Promise<UpdateResult> {
  const current = await store.load(id);
  if (!current) throw new Error('record not found: ' + id);
  const next: Record = { id, value: mutate(current.value), version: current.version + 1 };
  const saved = await store.save(next, current.version);
  if (!saved) {
    const fresh = await store.load(id);
    if (!fresh) throw new Error('record vanished during update: ' + id);
    return { ok: false, conflict: true, current: fresh };
  }
  return { ok: true, record: next };
}

How it works

The working surface is the function updateWithVersion — everything else is wiring.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. When the guard condition holds, Error is thrown rather than a bogus value returned.

The result comes back as an object carrying false, true.

What to watch for

  • The guard !current short-circuits the flow with an early throw when its condition holds.

Using it

The primary signature is export async function updateWithVersion( store: { load(id: string)

Import updateWithVersion from the file and call it — the rest of the code is implementation detail.

The call returns false, true — destructure what you need at the call site.

Key statements

if (!fresh) throw new Error('record vanished during update: ' + id);
if (!current) throw new Error('record not found: ' + id);
const saved = await store.save(next, current.version);

Interactive Tools for This Topic

FAQ

Does `updateWithVersion` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
How are precondition violations signaled?
The code throws `Error` — the guard `!current` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `updateWithVersion` at load time.