All my work / Distributed systems · by Ravindra Sawant

Tandem

Collaborative text editor on a sequence CRDT: offline edits, any delivery order, always converges.

Python 3.11+ · asyncio · websockets 15 · minimal HTML/JS 681 lines of core code source on GitHub ↗ CI status

4/4 core requirements 8 tests passing 3/3 benchmark targets

Verified 2026-11-28; CI re-runs the acceptance tests on every push.

The problem

Collaborative editing must converge when people edit concurrently, go offline and receive operations in any order. This is a sequence CRDT with stable character ids, tombstones, dependency buffering and a durable op log, plus a two-pane browser demo.

What I found

  • 180 randomized 3-5 replica histories with 15% dropped, 20% duplicated and shuffled delivery all converged to identical text after anti-entropy sync.
  • A replica restarted from its durable log restores its Lamport counter above every id it has seen, so it never reuses an operation id.
  • Local edit + render took 2.3 ms p95 on a 10,000-character document, well under the 50 ms stretch goal.

Architecture

browser textarea ─(prefix/suffix diff → {index, delete, insert})─► /ui/<name> ─► UIReplica
UIReplica: visible-position → atom IDs ─► Replica.local_insert/delete ─► op ─► DurableLog.append(fsync) ─► integrate
           ─(online)─► /relay {ops} ─► Relay: dedup by op id, store history, fan out to other clients (no ordering!)
remote op ─► Replica.apply: normalize/validate ─► seen? (same payload: ignore | different: reject) ─► Lamport counter
           ─► anchor/target present? integrate : buffer in pending[missing id] ─► drain dependents iteratively
render ─► iterative DFS from ROOT; children sorted by (counter, replica); newest sibling first; skip tombstones
reconnect ─► push full local log + sync_request{have: op ids} ─► sync_reply{missing ops}
restart ─► DurableLog.load() replays every op (persist=False) ─► counter = max observed ⇒ never reuses an id
  • Op shapes: ins {op_id, after, char} (op id = atom id) and del {op_id, target}; ids are [counter, replica].
  • Safety caps: one code point per insert, ids ≤ 64-char replica names, bounded messages (1 MiB, ≤ 5,000 ops), self-anchors rejected, unresolved (e.g. cyclic) ops capped and reported via unresolved().
  • Convergence hash = sha256(rendered text + every atom id with its tombstone flag).

Requirements → tests

ReqPriRequirement Proven byStatus
FR-01P0Character atoms with (replica, counter) IDs, predecessor anchors, tombstones; position<->ID; code pointsT01pass
FR-02P0Replicate ops via websocket relay or simulator; idempotent; duplicates, reordering, missing dependenciesT03, T05pass
FR-03P0Deterministic render with total sibling order; same op set => identical text in any orderT02, T05pass
FR-04P0Durable append-only op log + replica identity; replay on restart; no reused IDs; pending countT04pass
FR-05P1Two-browser demo with offline toggle, op log and convergence statusT04pass
TestWhat it provesResult
T01Local insert at start/middle/end, multi-char chains, delete, empty doc, Unicode code pointspass
T02Concurrent inserts at the same anchor, same-atom delete, insert under a deleted anchor; both delivery orderspass
T03Child before predecessor, delete before target, duplicates, delayed sync; colliding op id rejectedpass
T04Offline edits on both sides, restart from durable log, reconnect + full sync; no reused local idpass
T05Randomized 3-5 replica histories with shuffled/duplicated/dropped delivery (100+ seeds); cyclic/malformed cappedpass

Benchmark

Target (hypothesis from the spec)GoalActual
identical final text in every fully delivered runall converge8/8met
stretch: local edit + render p95 < 50 ms at 10K atoms< 50 ms2.905 msmet
tombstones grow sync size while visible text shrinks (50% deletes)observed1000: 16% tombstones; 1000: 34% tombstones; 10000: 2% tombstones; 10000: 5% tombstonesmet
  • edit_p95_ms@10K = 2.905
  • apply_p95_us@10K = 12.71
  • full_sync_bytes@10K = 723693

quick run · 2026-11-28T23:57:50+00:00 · Full traversal per edit (cached visible index invalidated on change).

Design questions

CRDT vs operational transformation?

CRDTs design operations/data so replicas converge under the stated delivery assumptions; OT transforms concurrent edits against each other, usually with a central revision history. Both need careful intent design.

Why stable IDs instead of positions?

Positions shift under concurrent edits; immutable atom IDs and anchors refer to the same logical element on every replica.

Why keep tombstones?

Deleted atoms remain anchors for late/concurrent inserts and stop resurrection when delayed ops arrive; safe GC needs causal stability.

What guarantees convergence?

A deterministic total sibling order, idempotent ops, stable identities and eventual delivery of dependencies give every replica the same state for the same op set.

What would production need?

Efficient sequence structures (runs/B-trees), version-vector incremental sync, durable relay, auth, presence/cursors, grapheme-aware editing and safe compaction.

Limitations

  • Single plain-text document, trusted local participants, no auth
  • No tombstone GC, rich text, undo or cursor presence
  • Concurrent insert order is deterministic but not intention-guaranteed

Run it

git clone https://github.com/ravirs/tandem.git && cd tandem
pip install -r requirements.txt
PYTHONPATH=src python -m crdtedit demo   # demo
PYTHONPATH=src python -m pytest -q   # test
PYTHONPATH=src python benchmarks/bench.py --quick   # bench

More systems I've built from scratch

Storage & data systems

  • Strata LSM-tree key-value storage engine: WAL, SSTables with Bloom filters, atomic manifest, compaction
  • Tidelog Kafka-style durable partitioned log broker: CRC'd records, offsets, generation-fenced consumer groups
  • Floe Iceberg-style table format: immutable Parquet, manifests, snapshots, time travel, compare-and-swap commits
  • Flint Spark-style batch engine: lazy lineage, stage planning, shuffles, broadcast and salted skew joins
  • Watermark Event-time stream processor: windows, watermarks, lateness, exactly-once checkpoints
  • Warden Data governance catalog: explainable grants, row filters, column masks, lineage impact
  • SnapshotDB MVCC transaction engine: snapshot isolation, the write-skew anomaly, a serializable mode

AI infrastructure

  • Nearline HNSW-style vector search index from scratch, measured against exact search
  • KVPager Paged KV cache with copy-on-write forks and prefix reuse (PagedAttention-style)
  • Batchwise LLM inference scheduler simulator: static vs continuous vs chunked-prefill batching
  • Steadyhand Durable AI agent runtime: allowlisted tools, approvals, budgets, crash recovery, replay
  • Toolgate Model Context Protocol gateway: curated tools, signed identity, tenant policy, approvals, audit

Distributed systems

  • Quorum Deterministic Raft consensus simulator with fault injection and an always-on invariant checker
  • Burrow Minimal Linux container runtime in Go: namespaces, pivot_root, cgroup v2 limits

← See all my work: apps, ML/AI and systems