A TypeScript example that demonstrates how vector clocks track causal relationships across replicas and identify concurrent updates.
A vector clock is a way for distributed systems to track the order of updates without using a single global time.
Each node keeps a counter for every node: A: 2, B: 1, C: 0
- When a node makes a change, it increments its own counter.
- When nodes exchange data, they also exchange these counters.
- BEFORE → one update is older than the other
- AFTER → one update is newer than the other
- EQUAL → both updates are the same version
- CONCURRENT → both updates happened independently
This repo demonstrates:
- how vector clocks store causal history
- how replicas exchange versioned values
- how concurrent updates are detected
- how simple HMAC-based authentication can protect signed replicas
- how a conflicted update can preserve the local value while merging clock history
vector-clocks.ts— vector clock implementationreplica.ts— replica model that stores versioned values and replicates them with HMAC verificationinterfaces.ts— shared TypeScript types used across the projectsimulate.ts— example script showing a simple replication and conflict scenarioutils.ts— helper to canonicalize clock state for signing
The example workflow is:
- Replica
Awrites a value. - Replica
Areplicates the value to replicaB. - Replica
Bupdates the same key while offline. - Replica
Aupdates the same key independently. - Both replicas sync again and detect a conflict.
- A conflict is resolved by merging clock history and preserving the local value.
Each replica signs its own update with a shared HMAC secret. The receiver verifies that the incoming version was produced by the claimed signer before accepting it.
Install dependencies and run with npx tsx:
npm install
npx tsx simulate.tsIf you do not want to use tsx, compile first with TypeScript and run the generated JavaScript.
The output shows:
- each local write and its vector clock
- replication steps between replicas
- whether a remote version is newer, older, equal, or concurrent
- signature verification for incoming replicas
- conflict detection and merged clock history
- a final summary of each replica's state
- This example uses HMAC-based signatures instead of public/private key cryptography.
- Each node signs its own update, and other replicas verify the signer via a shared secret.
- The focus is on learning vector clock behavior and simple authenticated replication.