How-To Guide

How to Implement Copy-on-Write Data Structures

Share immutable snapshots safely across readers and writers using copy-on-write, so readers never block and mutations stay consistent.

On this page

  1. Introduction
  2. The Core Idea: Never Mutate Shared Data
  3. Why Readers Never Block
  4. Structural Sharing for Large Structures
  5. Atomic Publication and Memory Ordering
  6. Garbage Collection and Retention
  7. Where It Fits and Where It Does Not
  8. Common Pitfalls and Conclusion

Introduction

Some data is read constantly and written rarely: configuration, routing tables, feature flags, caches, in-memory indexes. A lock around such data serialises reads that never conflict and turns every writer into a stall for all readers. Copy-on-write solves this by never mutating shared data in place: a writer builds a new version and atomically swaps a reference, while readers keep using the old version they already hold. Readers never block, writers never corrupt a read in progress, and the only coordination is the atomic pointer swap.

The Core Idea: Never Mutate Shared Data

In copy-on-write, the published value is immutable. A writer copies it, applies its change to the copy, and replaces the reference with the new copy in a single atomic operation. Readers grab the current reference once and use that snapshot for the whole read; a concurrent swap does not affect them, because they are holding the old object.

The invariant is that a published snapshot is never modified. If a writer could mutate a published object, a reader mid-read would see a half-updated value. Making snapshots immutable by convention, or by type as readonly, is what guarantees the reader’s view stays consistent.

interface Config { readonly maxRetries: number; readonly timeoutMs: number; }

class ConfigStore {
  private current: Config = { maxRetries: 3, timeoutMs: 1000 };

  // Readers: take the snapshot once, use it consistently.
  get(): Config { return this.current; }

  // Writers: build a new immutable value, swap atomically.
  update(patch: Partial<Config>): void {
    this.current = { ...this.current, ...patch }; // new object, no mutation
  }
}
// Node.js assignment of an object reference is atomic, so no lock is needed.

Why Readers Never Block

A reader performs exactly one operation on shared state: it reads the reference. In JavaScript, assigning or reading an object reference is atomic, so there is no interleaving that produces a torn read. The reader then works with its own snapshot, and every other reader does the same, independently. There is no shared lock to contend for.

This is why copy-on-write is ideal for read-heavy data. Reads scale with cores and threads because they touch no contended resource. A traditional lock would serialise them; copy-on-write removes the shared mutability that the lock existed to protect.

// Every request reads the same snapshot for its whole lifetime.
function handleRequest(store: ConfigStore) {
  const cfg = store.get();          // one atomic read
  return withRetry(cfg.maxRetries, () => fetchWithTimeout(cfg.timeoutMs));
  // a concurrent store.update(...) does not change cfg for this request
}

Structural Sharing for Large Structures

Copying a large object on every write is expensive if the object is big. The trick is structural sharing: copy only the path from the root to the changed node, and reuse the untouched subtrees by reference. This is what persistent data structures such as immutable maps and lists do, turning an O(n) copy into O(log n).

For a configuration object or a routing table that changes a few keys at a time, a shallow copy that shares the unchanged subtrees is enough. For a large collection, use a persistent map library so writes stay cheap while readers still see an immutable snapshot.

// Structural sharing: copy only the changed path, share the rest.
interface Tree { left?: Tree; right?: Tree; value: number; }

function insert(node: Tree | undefined, value: number): Tree {
  if (!node) return { value };
  if (value < node.value) {
    return { ...node, left: insert(node.left, value) }; // share right subtree
  }
  return { ...node, right: insert(node.right, value) };  // share left subtree
}

Atomic Publication and Memory Ordering

The correctness of copy-on-write depends on publishing the new reference atomically and on readers seeing a fully initialised object. Build the new object completely before you publish it; never publish a reference to an object you are still filling in. In a language with a memory model and multiple threads, publication must also establish ordering, which is what an atomic or volatile write provides.

In single-threaded Node.js the concern is simpler: because JavaScript runs one thing at a time and object-reference assignment is atomic, a swap is always seen consistently. The discipline remains: finish building the snapshot, then assign it, and never hand out a partial object through a shared reference.

# publication order (multi-threaded flavor)
1. allocate new snapshot
2. fully initialise every field (no reader can see it yet)
3. atomic store of the root reference (release semantics)
# reader: atomic load of the root reference (acquire semantics)
# => reader sees either the whole old snapshot or the whole new one

Garbage Collection and Retention

Old snapshots are kept alive as long as some reader still holds them, and released when the last reader drops its reference. In a garbage-collected runtime that is automatic, but it means memory can spike if a long-running reader holds an old snapshot while writers produce many new ones. Retroactive readers, such as a background job iterating a large structure for minutes, are the usual cause.

Bound the lifetime of readers that hold snapshots. A streaming reader should re-fetch the snapshot periodically rather than holding one for hours, so the old versions can be collected. For very long-lived processes, monitor the number of retained snapshots as a memory signal, because a slow reader coupled with frequent writes is a leak in disguise.

# retention: snapshot lives while any reader references it
snapshot v1  <- reader A holds
publish v2, v3, v4 ...
v1 stays alive until A drops it  => a long reader pins old versions
# mitigation: readers re-fetch periodically; don't pin a snapshot for hours

Where It Fits and Where It Does Not

Copy-on-write fits read-heavy, write-light data: configuration, feature flags, route tables, lookup indexes, caches that are rebuilt rather than edited. It gives lock-free reads and consistent snapshots, which is exactly what those workloads want. It also gives you versioning for free: a snapshot is a version you can compare or roll back to.

It does not fit data with frequent, in-place updates where the working set is large, such as a hot counter incremented thousands of times per second; copying on every increment would be prohibitive. For those, use a mutable structure with fine-grained synchronisation, or batch the updates and publish a new snapshot periodically.

# good fits
config / feature flags   rarely written, read on every request
routing tables           rebuilt on change, read constantly
in-memory lookup indexes read-heavy, refreshed in bulk
# poor fits
hot per-key counters     write-heavy; copy per write is too costly
large mutable buffers    in-place updates dominate

Common Pitfalls and Conclusion

Do not publish a snapshot before it is fully built. Do not mutate a published snapshot “just once”. Do not let a long-running reader pin old versions indefinitely. Do not use copy-on-write for write-heavy data. And do not forget that a shallow copy shares nested mutable objects, so a deep change needs either a deep copy or structural sharing; a shallow copy that still mutates a nested object silently breaks the invariant.

Copy-on-write replaces locks on read-heavy data with immutable snapshots and an atomic swap. Readers take a snapshot once and never block, writers build a new version and publish it atomically, structural sharing keeps writes cheap for large structures, and bounded reader lifetimes keep old versions collectable. It is the simplest way to get consistent, lock-free reads.

Test the invariant by attempting a mutation of a published snapshot and confirming it is rejected.

Sources: Wikipedia: Copy-on-write, Clojure: Persistent data structures, Immutable.js: Structural sharing.

FAQ

Is copy-on-write safe without any lock in Node.js?
Yes, for the reference swap: reading and writing an object reference is atomic, and JavaScript runs one task at a time. The remaining discipline is to never mutate a published snapshot, so a reader that holds it always sees a consistent value.
When is copy-on-write the wrong choice?
When the data is written frequently relative to reads, such as a hot counter updated thousands of times a second. Copying on every write is too expensive; use a mutable structure with fine-grained synchronisation or batch updates instead.

Related Examples