Optimistic Locking With Version
Implement optimistic concurrency control with version numbers for conflict-free updates.
Code
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
savedshort-circuits the flow with an earlyreturnwhen 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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.UUID Version DetectorValidate the 8-4-4-4-12 UUID layout and read its version (v1 to v8) and variant nibbles per RFC 9562, with full field decomposition.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.