Optimistic Locking With Version

Implement optimistic concurrency control with version numbers for conflict-free updates.

TypescriptData Integrity

Code

typescriptsnippet
1 line
export interface Versioned<T>{data:T;version:number;}export async function updateWithVersion<T>(load:()=>Promise<Versioned<T>>,save:(v:Versioned<T>)=>Promise<boolean>,transform:(data:T)=>T,{maxRetries=3}={}):Promise<T>{for(let i=0;i<maxRetries;i++){const current=await load();const newData=transform(current.data);const saved=await save({data:newData,version:current.version+1});if(saved)return newData;}throw new Error('optimistic lock failed after retries');}

How it works

All of the logic lives in the function updateWithVersion.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. There is no validation gate in front of the Error — the throw fires whenever its line runs.

Points of care

  • The guard saved short-circuits the flow with an early return when its condition holds.

Putting it to use

updateWithVersion is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Does the code guard against bad input?
The snippet does not validate input. `Error` is thrown unconditionally at its throw site — nothing guards it.
Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `updateWithVersion` at load time.