Reference counting and mark-and-sweep
Two ways to decide when shared data may be deleted: count who points at it and free it at zero, or periodically trace what is still reachable and sweep the rest. The choice shapes how a delete races an upload.
What it is
Reference counting stores, next to a shared resource, the number of references that point at it: an object in memory, a block on disk, a blob in a store. Each new reference adds one, each dropped reference subtracts one, and the resource is reclaimed when the count reaches zero. Its appeal is that space comes back as soon as the last reference goes, a little at a time, with no pause for a collection pass, and it is among the simplest schemes to build. Unix file systems work this way: unlink() removes one directory entry and lowers the file's link count, and the file's space is freed when the count becomes 0 and no process still has it open. If a process does have it open, the name disappears at once but the contents stay until the last descriptor is closed.
Mark-and-sweep doesn't trust a running count. A collector starts from the roots, the things known to be live (a user's photo records, a registry's manifests, a repository's branches and tags), marks everything it can reach from them, and then sweeps away whatever carries no mark. Git's gc removes objects that are unreachable from branches, tags, the index, remote-tracking branches and reflogs. Harbor frees no space when an image is deleted; a later garbage collection removes the blobs that no manifest references anymore. In memory managers the two are often paired: counting does the everyday work and a mark-sweep pass runs rarely to catch what counting misses.
In a deduplicated store the shared resource is the blob and the roots are the owner records that point at it, so either scheme applies. OpenZFS deduplication is a reference-counting design at block level: identical blocks are stored once, each unique block gets an entry in the dedup table, and that table is consulted on each write and on each free. The documentation suggests planning for at least 1.25 GiB of RAM per TiB stored, which shows the standing cost of counting synchronously on the write path.
The race both schemes face. A deleter and an uploader can act on the same blob at the same time. With counting, the uploader's dedup check finds the blob present and skips the upload, the deleter's decrement takes the count to zero and the bytes are removed, and then the uploader writes a link to bytes that are gone. With a sweep, the uploader stores the blob first and links to it second; a sweep that runs between those two steps sees an unreferenced blob and deletes it. The git-gc manual describes exactly this danger: a collector running beside another process can delete an object that process is using but hasn't yet referenced, and if the reference is added afterwards the repository is corrupt.
The defenses. First, order the writes: blob before link, and count before link, so a reference is visible before anything depends on it. Second, make count changes conditional: in a concurrent setting the count has to be updated with an atomic instruction such as compare-and-swap, so an increment from zero is refused, or revives a pending delete, rather than silently landing on a removed blob (see Atomic read-modify-write). Third, add a grace window. Git keeps any object whose modification time is newer than the prune date (two weeks by default, set by gc.pruneExpire) together with everything reachable from it, and most operations that add an object already present touch its modification time so the rule covers them. Harbor 2.15 skips any manifest or blob with a timestamp inside a two-hour window so that garbage collection can run while pushes continue. Even with these, Git's manual says the protection is not complete and concurrent users accept a small risk, so a strong design still keeps a repair pass for drift.
When to use it
Pick reference counting when space has to come back promptly and each reference is created and dropped through one code path you control, so the count and the link can change in the same transaction. It suits a flat graph, such as owners pointing at blobs, where no blob points back at an owner: the naive scheme can't reclaim a cycle, because each member of the cycle keeps the others' count above zero, and file systems with hard links often sidestep that by forbidding cycles. Counting is also used in file systems and distributed stores where tracing the whole object graph would take too long.
Pick mark-and-sweep when references are written by several services or by hand-run tools and you can't trust each one to adjust a counter, when a delayed reclaim is fine, or when the graph can contain cycles. The registry example above follows this shape: deletes are cheap metadata changes, and a scheduled or on-demand collection does the heavy work, with a dry run that lists what it would remove before anything is touched.
Our advice for a photo store: count on the hot path and sweep as the safety net. The count decides the common case in one transaction, and a periodic pass compares counts against the owner table to repair drift from crashed requests, in the spirit of a reconciliation job. The counting-plus-rare-sweep pairing is a known combination in memory management, where the sweep is run far less often than a pure tracing collector would be.
When not to
Skip a per-blob counter when one blob is shared by millions of owners: each new link is a write to the same row, and that row becomes a hot key. Think too about the standing cost of counting on each write. OpenZFS warns that dedup is its most resource-hungry feature, because each write is looked up in the dedup table before it lands and each free consults it again, and that a table too big for memory can leave a pool that won't import. For such blobs, a sweep that reads the owner table in bulk, or a sharded counter that is summed, is the lighter choice.
Don't run a sweep without a grace window or a quiet store. Git's --prune=now discards the window and raises the risk of corruption when another process is writing, and the registry's two-hour reserve exists so that pushes in progress aren't damaged. If you can't afford either a window or downtime, counting with conditional updates is the safer tool.
Neither scheme is needed when a blob has exactly one owner: delete it with the owner's record. For short-lived data, such as upload parts that were abandoned, an expiry by age does the job without any tracking of references.
Compared
| Approach | When space comes back | Cost per reference change | What breaks it | The right choice when |
|---|---|---|---|---|
Reference counting | At once, when the count hits zero | An atomic update to the count on each link and unlink | A missed or doubled update; cycles; a popular blob whose count row runs hot | References change through one transactional path and space must return quickly |
Mark-and-sweep | At the next collection pass | Little or none at write time in the simple form; a full walk of the roots at collection | Uploads in flight during the sweep, unless a grace window protects recent blobs | Many writers touch references, delays are acceptable, or cycles are possible |
Count plus periodic sweep | At once in the common case; drift is fixed at the next pass | Atomic count update, plus a walk that runs rarely | A sweep that trusts counts it should be checking | You want prompt reclaim but can't rule out lost updates from crashes |
In a picture
Step 1 of 4
Alice deletes
Her photo record is removed and the blob's count drops by one in the same transaction. Nothing touches the bytes yet.