← Concepts

阅读中文版本

Copy-on-Write

Copy-on-write defers duplication until a shared page or object is modified: forks share physical pages, snapshots stay cheap, and immutable structures clone in O(changes) instead of O(size).

performance

Definition

Copy-on-write marks shared pages or objects read-only and traps the first write to materialize a private copy. Process fork shares the entire address space this way; B-tree and MVCC snapshots clone by versioning pages; immutable data structures persist structure sharing. The win: copying proportional to mutation, not to size.

Context and scope

Used in fork-based servers (Redis, Python preloaded workers), ZFS and Btrfs snapshots, MVCC page versioning, persistent data structures, and JS structuredClone alternatives.

Common misconceptions

  • COW makes copying free — it makes reading free; writes pay the copy plus the fault, so write-heavy workloads degrade
  • Snapshots with COW are free forever — each snapshot pins the blocks it shares; space grows with divergence, not with snapshot count alone
  • COW and fork remove the cost of preforking — memory overcommit and page-fault storms during copy waves are the real cost curve

Anti-patterns

  • Forking from a huge-heap process and hitting a page-fault storm as every touched page copies
  • Keeping long snapshot chains on write-heavy datasets and inflating space as every block diverges everywhere
  • Assuming Redis BGSAVE is free while the fork copies pages under a write-heavy workload

Related concepts

Related examples

Authoritative source

https://en.wikipedia.org/wiki/Copy-on-write

What it is

Copying is usually wasted: most data never changes after duplication. COW defers the copy to the moment of first modification — sharing until then, paying only for what actually diverges.

How it works

The kernel or runtime marks shared structures read-only. A write faults; the handler allocates a private copy, updates references, and resumes. Forked processes share physical pages marked COW. MVCC databases version pages so readers see consistent snapshots without blocking writers. Persistent data structures rebuild only the path from the change to the root.

When to exploit it

Snapshotting large states, fork-based worker model from a warmed parent, immutable value sharing across threads, and delta-based replication. The economics shine when read sharing dominates mutation.

Pitfalls

Copy waves: a workload that touches all pages right after fork pays the full copy with fault overhead on top. Overcommit-dependent fork fails unpredictably when memory accounting is strict — containers deny the fork mid-flight. Snapshot chains on churny datasets multiply divergence space; schedule consolidation.