Files
skills/docs/foundation/flow/crdt/src/crdts/lww-register/lww-register.md
2026-05-29 08:20:56 +01:00

1.6 KiB

lww-register

(no submodules)

Purpose

Provides LWWRegister<T>, a Last-Write-Wins Register CRDT. The register holds a single value; when two replicas have different values, the one with the higher timestamp wins during merge. Ties are broken by node ID lexicographic order, ensuring deterministic convergence.

Features

  • set(value, timestamp?) — sets the value with optional explicit timestamp (defaults to Date.now())
  • get() — returns the current value or undefined
  • merge(state) — higher timestamp wins; tie-broken by nodeId lexicographic order
  • toJSON() / fromJSON() — serialization round-trip
  • clone() — deep copy

Usage: Basic Example

import { LWWRegister } from "@suaveplan/crdt";

const reg = new LWWRegister<string>("node-1");
reg.set("hello");
console.log(reg.get()); // "hello"

Usage: Advanced Example

import { LWWRegister } from "@suaveplan/crdt";

const a = new LWWRegister<number>("n1");
a.set(42, 1000);

const b = new LWWRegister<number>("n2");
b.set(99, 2000);

a.merge(b.state());
console.log(a.get()); // 99 (higher timestamp)

API Reference

LWWRegister<T>

  • constructor(nodeId, id?) — nodeId is required for tie-breaking
  • set(value, timestamp?) — sets value with timestamp
  • get(): T | undefined — current value
  • merge(state: LWWRegisterState<T>): void

Implementation Notes

Wall-clock timestamps from Date.now() can cause issues if clocks are not synchronized. For distributed deployments, use a monotonic or hybrid logical clock and pass the timestamp explicitly via set(value, timestamp).