Git Deep Dive: Content Hashing, Immutable Objects and Mutable Names
By Edward Grundy, Bay Information Systems. Published . In Architecture & Deployment.
The first version of git, committed by Linus Torvalds on 7 April 2005, was seven small programs. One created an empty store, three wrote data (file contents, directory listing, and a snapshot record); two read things back, and the last compared files with the Unix diff tool. No branches, no history browser, no merge and no network commands.
Everything git has gained in the twenty years since rests on three design choices: Data is named by a hash of its content; Data is immutable, and a small set of mutable names points into the store. Those names are the only part that changes. The properties people value in git (integrity, cheap snapshots, deduplication, offline work, merging work from many machines) follow from those choices.
In this article wx describe each choice in turn, and how comparing and merging fit in. We also describe the same design in data and distributed systems. Git’s own terms appear in brackets, for readers who want to find the commands.
Content hashing
A hash function reads any sequence of bytes and returns a fixed-length number. The same bytes always give the same number; a single changed byte gives an unrelated one. Git uses the hash of each piece of content as its name, and stores the content in a file named after the hash. (Git has used SHA-1 since 2005; SHA-256 is planned as the default for spring 2027.)
Identical content is stored once. Two copies of file in different directories, or one file left unchanged across a thousand snapshots, hash to the same value and occupy one entry.
Content can be checked on arrival. A machine receiving an object recomputes its hash; if the result differs from the expected value, the object is corrupt or has been altered. No checksum file or trusted server is involved.
Names need no coordination. Two machines that have never communicated, storing the same bytes and use same name. A central counter handing out identifiers would have to be reachable from every machine at every write; a hash is computed locally. This lets git work offline, and lets any copy of a repository be a source for any other.
Immutable storage
An object named by its hash cannot be edited in place, since editing it would change its name. A change to a file writes a new object under a new name; the old object is preserved.
Immutability makes stored data safe to copy and cache. A cached object can never go stale, because no newer version of that object will exist; a newer version is a different object with a different name. Readers never see a half-written state, because objects are written whole and become reachable only once complete.
The cost is space, which git recovers in a second, physical layer. New objects are written individually (loose objects). Periodically, and whenever data crosses the network, git gathers objects into a single file (a packfile) and stores similar objects as differences against each other (delta compression). Text history compresses well this way; images and archives do not. The packing is invisible to the logical model, in which every object is still a complete copy, so storage efficiency becomes a separate problem with its own solution and the model stays simple.
Structure from references
Git stores three kinds of object.
The first holds the bytes of a file (a blob), with no name, path or permissions attached. The second is a directory listing (a tree): each entry gives a name, a file mode, and the hash of either a file’s contents or another listing, for a subdirectory. The third is a snapshot record (a commit): the hash of one top-level listing, the hashes of the snapshots it was based on, the author and committer, timestamps and a message. The top-level listing is the snapshot itself. The record adds who, when, why, and what came before.
Every reference is a hash, and every hash covers the content it names, so the hash of a top-level listing covers every file and directory beneath it. A change anywhere changes the hash of everything above it, up to the top. This structure is known as a Merkle tree.
A change to one file therefore writes a small, predictable set of new objects: the file’s new contents, a new listing for each directory containing that file, and a new snapshot record. Everything else is shared with the previous snapshot by hash.
We can trace this through a small repository holding a README and a docs directory with two files, a.md and b.md. After the first snapshot, a.md is edited and a second snapshot recorded:
snapshot 1 snapshot 2 (based on snapshot 1)
top listing 8b54af7 top listing 71e470f new
README ce01362 README ce01362 shared
docs/ e163519 docs/ b6d670e new
a.md 5626abf a.md 762d0e5 new
b.md f719efd b.md f719efd shared
The second snapshot wrote four objects: the new contents of a.md, the new docs listing, the new top-level listing and the snapshot record. (In git, git cat-file -p HEAD prints the latest snapshot record and git cat-file -p HEAD^{tree} its top-level listing.)
This layout follows the Unix filesystem: A Unix directory maps names to inode numbers, and the inode locates a file’s data; a git listing maps names to hashes, and the hash locates the content. A Unix filesystem updates its directories and data blocks in place. The filesystems that share git’s approach are the copy-on-write designs, ZFS (from Sun Microsystems) and btrfs (started by Chris Mason at Oracle). Both write changes to new blocks, rewrite the path up to a new root, and share unchanged blocks between snapshots. ZFS also stores each block’s checksum in the pointer its parent holds, which makes it a Merkle tree in the same sense as git.
History as links, change as a computation
Nothing in the store links one version of a file to a previous version. Each version is a set of bytes under its own hash. History lives only in the snapshot records, each naming the snapshot or snapshots it followed. Following those links backwards gives the history of the project; a snapshot with no predecessor is a standalone starting point.
Despite common belief, change is not stored. It is computed on request by walking two top-level listings side by side. Where an entry has the same hash in both, the whole subtree beneath it is identical and is skipped. Only entries with different hashes need comparing.
When we find a file which has changed we compare them: Given two sequences of lines, find the longest common subsequence. Lines outside it are deletions from the first file or insertions into the second, and together they make the shortest set of edits that turns one into the other. The original Unix diff, by James Hunt and Douglas McIlroy at Bell Labs in 1976, solved this. Eugene Myers’ algorithm of 1986, used by GNU diff and as git’s default, treats it as a shortest path through a grid of one file against the other, and runs fastest when the files are similar. Hashing appears here too, in a supporting role: each line is first reduced to a number, so that comparing two lines costs one integer comparison. (Git also offers the patience and histogram algorithms, which anchor on lines that occur once in each file and tend to keep blocks of code aligned.)
Names: the only mutable part
A bare hash is hard to type or remember, and a store of immutable objects has no way to say “the latest version”. Git supplies both with names (refs). A name holds one hash, usually as a one-line file under .git/refs/ whose path is the name (or as a line in a shared file, or an entry in a reftable). Within the object model, moving a name is the only operation that changes existing state. Everything else adds.
Git tells names apart by the folder they sit in. Names under refs/heads/ are branches: git expects them to point at snapshot records and, when updated by a push, to move forward, each new position descending from the last (in data structure teams, these are heads of a linked list). Names under refs/tags/ are tags, which git expects never to move. Any other folder under refs/ is valid and git applies no rules to it, which is how hosting services keep their own names for pull requests and review comments inside ordinary repositories. One special name, HEAD, holds another name in place of a hash, and records which branch is current.
Because names are the only moving part, they are where concurrent writers meet, and git updates them by compare-and-swap: move this name from hash A to hash B, provided it still holds A. If another writer has moved it in the meantime, the update fails and the writer has to look again. (git update-ref <name> <new> <old> does this locally; git push --force-with-lease asks a server to do it.) Several names can be moved in one transaction, all or none.
An object is retained in storage while it can be reached by following references from some name (or from git’s log of where names recently pointed). Deleting a name leaves any objects that only it reached unreachable. Garbage collection removes them after a grace period.
The store holds an unbounded amount of immutable data that any machine can copy, cache and verify. The names hold a few dozen bytes each. Only names need agreement between machines.
Merging
Merging two lines of work is done in three steps.
The first finds the merge base: the most recent common ancestor of the two candidates, found by walking the predecessor links back from each side until they meet (git merge-base). Unix had no standard tool for this step, having no history graph to walk.
The second walks three top-level listings side by side (the base, ours and theirs) and compares hashes path by path. If all three agree, the file is unchanged. If only one side differs from the base, that side changed it alone, and its version is taken. Only when both sides differ from the base, and from each other, does anything need to look inside the file. In most merges, most paths are settled by comparing hashes.
The third merges the contents of files changed on both sides. diff3, from Unix in 1979, compares the base against each side and sorts every changed region into one of three cases: changed on one side only (take that change), changed identically on both (take it once), or changed differently on each (a conflict, marked in the file for a person to resolve). Git’s first merge script in 2005 reached this logic through the merge command from RCS; git later built it in (git merge-file). An edit to line 1 on one side and line 4 on the other merges cleanly. Two different edits to line 2 produce a conflict:
a
<<<<<<< ours
B1
||||||| base
b
=======
B2
>>>>>>> theirs
c
d
The merge works on lines and knows nothing of what they mean. One side can rename a function while the other adds a call to the old name on a different line, and the merge completes without complaint. Catching that is a job for the tests.
The design choices
The three choices carry over to data work with little translation. Raw datasets are stored under the hash of their content and never overwritten. A manifest listing the files of a training set is itself stored by hash. A name such as “current training set” points at a manifest, and moves by compare-and-swap. A model trained on that set records the manifest’s hash, and the question of what data it was trained on has an exact answer years later. Two teams can still disagree about which dataset a name should point at, but the disagreement is a recorded change to one pointer, and neither team’s data has been altered by the other. The append-only raw layer of a medallion architecture applies the same rule to a database table. (For a review of how a project’s data is stored and versioned, get in touch; the data maturity checklist is a quicker start.)
Several established tools already work this way. Container images are addressed by the digest of their layers, as the Docker deep dive shows by unpacking one. DVC keeps dataset files in a cache keyed by content hash and commits only small pointer files to git. Apache Iceberg tables keep immutable data and metadata files, and commit by atomically swapping a catalogue’s pointer to the current metadata file. Nix stores every build output under a hash of the inputs that produced it.
For distributed systems where the issue is coordination, content addressing removes the need to agree on names. Immutability removes the need to agree on whether a cached copy is current. What remains is a small set of pointers, and a pointer can be kept consistent with a single compare-and-swap, on one machine or across a replicated service. (The large git hosts are moving repositories into cloud storage along the same line, as Git at Scale describes.)
Git’s first version could store snapshots, list them and read them back. Branches, merging, network transfer and hosting for millions of repositories all came later, and none of them required a change to the store. Data named by its content and never changed gives every later feature a foundation it can rely on, and reduces agreement between machines to the movement of a few names.