Skip to content

mmostafa74/vector-clocks

Repository files navigation

Vector Clocks

A TypeScript example that demonstrates how vector clocks track causal relationships across replicas and identify concurrent updates.

What is a vector clock?

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.

Comparison results

  • 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

Why this project exists

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

Project files

  • vector-clocks.ts — vector clock implementation
  • replica.ts — replica model that stores versioned values and replicates them with HMAC verification
  • interfaces.ts — shared TypeScript types used across the project
  • simulate.ts — example script showing a simple replication and conflict scenario
  • utils.ts — helper to canonicalize clock state for signing

How it works

The example workflow is:

  1. Replica A writes a value.
  2. Replica A replicates the value to replica B.
  3. Replica B updates the same key while offline.
  4. Replica A updates the same key independently.
  5. Both replicas sync again and detect a conflict.
  6. 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.

Run the example

Install dependencies and run with npx tsx:

npm install
npx tsx simulate.ts

If you do not want to use tsx, compile first with TypeScript and run the generated JavaScript.

What to expect

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

Notes

  • 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.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors