Skip to content

coins: store spent dbcache entries compactly - #37038

Open
LarryRuane wants to merge 6 commits into
bitcoin:masterfrom
LarryRuane:2026-07-compact-spents
Open

LarryRuane wants to merge 6 commits into
bitcoin:masterfrom
LarryRuane:2026-07-compact-spents

Conversation

@LarryRuane

@LarryRuane LarryRuane commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

This PR makes IBD (and -reindex and -reindex-chainstate) faster and less resource-intensive.

When a coin in the cache (dbcache) is spent and was created since the last flush to the chainstate database (disk), it can be erased from memory immediately. But if the coin had been flushed, it must be marked as spent in memory and retained until the next cache synchronization with the database (a flush or sync event), so the unspent version of the coin can be erased from the database.

Such a spent coin still occupies a full cacheCoins map entry, about 128 bytes plus its share of the bucket array. During IBD, a large part of the cache holds spent coins. All that's needed to record a spent coin is its outpoint (the map key); the coin data isn't used.

This PR periodically moves spent coin entries out of the map into a sorted vector of COutPoints (36 bytes each), with a small blocked bloom filter in front of it (2-4 bytes per entry). This cuts the memory per spent coin from about 140 bytes to about 40. The cache can hold more total coins between flushes, so there are fewer cache-full flushes, fewer cache misses, and fewer chainstate (LevelDB) reads and writes. More coins are created and spent within a single flush cycle, so they never reach the chainstate database at all.

Compaction runs when the number of spent entries in the map reaches a threshold, about 1M for default dbcache, scaled with the cache size. The spents are sorted and merged into a new vector as they're removed from the map. As the cache continues to fill, when the number of spent coins in the map reaches 20% of the vector size, we run another compaction cycle. Each cycle adds to the vector but frees space from the map, for a net space gain. The 20% choice balances avoiding many uncompacted spents in the map versus the overhead of updating (adding to) the vector. It's a fixed percentage because we want the space savings to scale with the overhead of vector growing and sorting. A minor tweak is that if the growth would exceed the initial threshold, we limit it to the threshold (we don't want the number of spents in the map to ever exceed the threshold). During a single flush cycle, compaction may run about 10 times (3 to 18 in my runs).

The downside of compacting spents is that when a coin isn't found in the map, we must now check the compacted spents list before looking in the chainstate (disk) database. Checking the spents list has two parts. First, we check the bloom filter. If the filter returns false (not found), then we go directly to disk. This happens most of the time. If the filter returns true, it could be a false positive (measured rate 0.025%), so we must binary-search the vector. (If found there, it's treated the same as finding a spent coin in the map. If not found, we go to disk.) This filter check is fast since it accesses a single CPU cache line (much faster than binary search of a large vector).

At flush or sync, the vector is passed to BatchWrite() along with the cursor (used to iterate the map's dirty entries). BatchWrite() treats the vector's outpoints the same as spent coins in the map (they're erased from the chainstate).

Compaction is enabled only for the main coins cache (CoinsTip()). The per-block cache, mempool views, and other CCoinsViewCache instances are unchanged. There's no new config option.

Wall-clock time reduction isn't the only or even necessarily the biggest benefit of this patch. It reduces disk writes, which reduces SSD wear. The lower disk I/O and CPU use reduce resource competition with other services running on the same system. It's just a more efficient use of memory, and thus I/O bandwidth and CPU.

Results, mainnet -reindex-chainstate, dbcache=1000:

hardware wall-clock improvement
Raspberry Pi 4, USB SSD (UAS off), to height 600k −12.6% (54.6 h vs 62.4 h)
Raspberry Pi 4, USB SSD (UAS), to height 600k −14.7% (7.9 h vs 9.2 h)
SATA HDD, to height 974k −5.3% (8:14 vs 8:42) 1
NVMe SSD, to height 974k −2.1% (2:22 vs 2:25)

On the NVMe SSD, CPU time is 8% lower and SMART-measured device writes are 15% lower (678 vs 798 GB). On the desktop runs, flushes drop by about 30%. LevelDB reads drop 11% on the NVMe SSD and 6% (UAS off) and 12% (UAS) on the Pi. The wall-clock advantage is largest on the Pi, where both I/O and CPU are limited, since each avoided read costs more there. Details are in 2.

Crash safety: the erases are still part of the same atomic batch write, so the on-disk invariant is unchanged. If a compacted coin is re-created (in a reorg), the map entry takes precedence, and RemoveShadowedSpents() removes the stale vector entry before each BatchWrite(). feature_dbcrash.py caught this case in an earlier version.

Concurrency with #35295's prevout fetchers: the new lookup paths are read-only, and the vector and filter are only modified after StopFetching() has joined the workers.

Summary of commits:

  1. coins: track spent cache entries on a separate linked list lets spent entries be gathered without scanning the map. No behavior change.
  2. coins: add sorted outpoint vector to hold spent cache entries is the core change: compaction, lookups, the BatchWrite() spents parameter, and RemoveShadowedSpents(). It's disabled by default.
  3. test, fuzz: exercise spent-coin compaction aggressively. The fuzz targets now read a compaction threshold from the input, so existing qa-assets seeds for these targets are interpreted differently.
  4. validation: enable spent-coin compaction for the coins tip cache sets the threshold from the dbcache size, and caps the large-cache flush trigger at 95% to leave room for a compaction.
  5. coins: add a blocked bloom filter in front of compact-spents lookups cuts the cost of a lookup for a coin that isn't in the map (avoids binary search).
  6. validation: log estimated in-use coins cache memory in UpdateTip is optional. With compaction, the cache= figure in the log steps up and then plateaus, because freed map nodes stay in the pool's free lists. This adds a cache_used= estimate alongside it.

Footnotes

  1. Master was run twice (8:45 and 8:39, a 1.2% difference). The master time shown is the mean. ↩

  2. full benchmark results ↩

Currently, coins cache entries that are either DIRTY or FRESH (or both)
are kept on a "flagged entry" linked list so they can be enumerated
quickly (by `Sync()`/`Flush()`), without needing to enumerate the entire
`cacheCoins` map.

A later commit will need to identify only the spent entries in this
list. To avoid having to enumerate the full list, this commit splits the
list in two, unspents and spents. This is done by having two sentinels
instead of one. Because these two sentinels are often needed at the same
time, this commit packages them into a new struct, `CoinsSentinel`.

The number of entries in the spent list is maintained in a new counter,
`m_spent_count`.

Most of this commit is the logic to keep the coins on the correct list,
including by moving them when necessary (transitioning between spent and
unspent states).

When a cache's `BatchWrite()` runs, it iterates the child cache's
flagged entries using the passed-in cursor's `Begin()`, `End()`, and
`NextAndMaybeErase()` methods. Both unspent and spent entries must be
returned (in any order). Implementing these methods is simpler if
there's a single linked list, so this commit modifies the cursor's
constructor to merge the spent list into the unspent list, which can
then be iterated as before. (Merging the other way would work too.
Either way, one list's name is briefly wrong. The distinction between
unspent and spent is no longer needed, since the spents are all deleted
anyway once the flush or sync completes.)

`SanityCheck()` verifies both lists' integrity, that spent entries are
DIRTY and not FRESH, and checks `m_spent_count`'s value.

No change in behavior.
Add `m_compact_spents`, a vector of `COutPoint`s, to `CCoinsViewCache`
to hold spent coins in a more memory-efficient way. It can be considered
an extension of the existing `cacheCoins` map; a spent coin can be in
either place.

After a coin in the cache is spent, its `Coin` fields are unused (except
its output's `nValue` is set to -1). So we only need to store a spent
coin's outpoint. (The `CCoinsCacheEntry`'s flags are always `DIRTY` and
`!FRESH`, so those don't need to be stored.) Using memory more
efficiently means we can fit more coins in the cache, which increases
the cache hit ratio and reduces the frequency of cache flushes. It's
equivalent to increasing the size of the cache.

Storing a spent coin as an element of a vector requires 36 bytes (the
minimum possible), versus about 128 bytes for a `cacheCoins` map entry.

When looking for a coin in the cache, we must now look in two places,
first the map, and, if not found, the compact spents vector. (In reorg
scenarios, it's possible the coin could be in both places; the map takes
precedence. Similarly, the same spent coin could end up in the compact
list more than once, which is harmless.)

To speed up the compact spents lookup, we keep the vector sorted to
enable binary search. (A later commit improves on this further.) It
would be inefficient to re-sort the vector with every new spent coin.
Instead, we store spent coins in the map, as in the past. When there's a
significant number of them, we migrate them from the map to the vector,
then sort the vector. This amortizes the overhead of the sort over many
cache operations. This frees space in the map, more than the space used
by the vector.

We can gather these spent coins in the map efficiently because they're
on a separate linked list.

When the number of spents in the map again becomes significant, we
migrate them to the vector. Optimization: Instead of adding this group
of N new spents to the end of the sorted vector of E existing spents,
and then sorting the entire vector, we use a two-step process. We write
the new spents to a temporary vector, sort it, and then _merge_ the two
vectors (one step of a merge sort), which has complexity
O(N*log(N) + (E+N)), rather than O((E+N)*log(E+N)).

The merge writes into a newly allocated vector, so memory use briefly
exceeds the cache budget by about the size of the vector (as already
happens when the map's bucket array is resized). This lasts only as long
as the sort and merge (about 0.3 seconds on a desktop with a vector of
10M entries). It may push some unrelated memory out to swap, but that's
very different from steadily using memory beyond the budget.

`BatchWrite()` is given the compact spents list (`m_compact_spents`) in
addition to the cursor (map). The map can also contain spent coins;
spents from either source should be processed the same way. Before
`BatchWrite()` is called (by `Flush()` or `Sync()`), the caller must
remove all spent coins from the list that are also in the map, that is,
that are "shadowed" by the map. (Shadowing rarely happens, but could
following a reorg.) The method `RemoveShadowedSpents()` does this.
This is needed because otherwise a stale spent in the list could delete
the unspent coin the map holds for the same outpoint.

A coin isn't marked FRESH if its outpoint is in the compact spents
vector, for the same reason it isn't when a spent coin is in the map.

Compaction is opt-in via `SetCompactSpentsThreshold()` (default:
disabled). It's intended only for the main cache (not the per-block
caches). It will be enabled in the next commit.
Set the compaction threshold in the coins fuzz targets
(`coinscache_sim`, `coins_view`, `coins_view_db`, `coins_view_overlay`
and `coins_view_stacked`) from the fuzz input, in the range 0 to 4. Small
thresholds compact often but still leave some spent coins in the map
between operations, and 0 disables compaction.

The existing simulation unit tests (`SimulationTest` and
`updatecoins_simulation_test`) now set a random threshold of 0 to 3 on
each cache in their stack. This mixes compacting and non-compacting
caches.

Add three unit tests. `compact_spents_lookup` checks that compacted
spent coins aren't found by any lookup, even though the base view still
holds them unspent, and that a flush erases them from the base.
`compact_spents_shadowed_purged` checks that a coin spent and then
re-created isn't passed to the base's `BatchWrite()` as spent.
`compact_spents_sync` checks that the cache stays consistent after a
`Sync()`, which clears the vector but keeps unspent map entries.
Enable compaction for the main coins cache only, sized from the actual
dbcache. For example, with dbcache=1024 (1 GiB, the usual default),
compact when the cache has accumulated about 1M spent map entries
(roughly 1/8th of the total cache capacity). This is scaled down
proportionally on memory-constrained nodes and up with larger caches.
The threshold is set in `InitCoinsCache()` and updated on
`ResizeCoinsCaches()`. Every other `CCoinsViewCache` (mempool validation
views, the per-block `ConnectBlock` overlay, RPC helpers, tests) doesn't
set the threshold, and compaction is disabled by default.

Also clamp `LargeCoinsCacheThreshold()` at 95% of total space. The fixed
10 MiB headroom assumed cache usage grows smoothly per block. But a
compaction run can raise the measured usage by 36 bytes per compacted
entry (up to ~3.5% of the cache) within a single block. So the headroom
must scale with the cache. For caches below ~200 MiB, the pre-existing
terms already provide at least this much headroom, so behavior there is
unchanged. Without the clamp, benchmarked reindexes hit
`CoinsCacheSizeState::CRITICAL` (cache over budget) up to 12 times. With
it, zero (same as master).

In debug builds, run `CCoinsViewCache::SanityCheck()` at every flush
boundary (compiled out of release builds).
This commit is a performance-only improvement.

Whenever a coin is looked up, there's a good chance we'll find it
unspent in the cache, especially if the cache is large or the coin
was recently created.

But if it's not found in the cache, previous commits require a binary
search of the compact spents list (vector). Only if it's not found
there (which is almost always the case, or this would be a double-spend
attempt) do we search for the coin on disk (base view), where there's a
good chance it will be found (or else the input is invalid).

A binary search of a large vector (the compact spents vector can have
millions of entries) is bad from a CPU cache perspective, since almost
every probe is a cache miss.

To mitigate this problem, this commit adds `CompactSpentsFilter`, a
blocked bloom filter, so that a negative lookup usually needs only a
single 64-byte cache-line read. We only need to binary search if we
get a positive bloom filter result (in practice, rarely). The false
positive rate is at most about 0.1%, and the measured average was
around 1 in 4,000.

A bloom filter can't give false negatives, and correctness depends on
that, so when a debug build gets a negative filter result, it verifies
that the binary search fails.

`CompactSpents()`, which moves all spent coins from the map to the
vector, is the only place the vector is added to (or created), so it
maintains the filter. The vector only grows within a flush cycle, so
`CompactSpents()` inserts just the new entries unless the filter must
grow. The filter doubles when it grows, so it's rebuilt only a few times
per flush cycle, at the new size (known exactly). It's cleared along
with the vector at each flush.

We don't touch the filter when `RemoveShadowedSpents()` runs, because
a stale filter entry can only cause a false positive.

The filter takes about 2-4 bytes per 36-byte entry, which is counted
in `DynamicMemoryUsage()`.

The block and bit positions come from the outpoint (whose txid is
already uniform) mixed with a per-instance salt. A peer that grinds
txids could at worst raise the false positive rate, which degrades to
the binary search. The hash's intentional integer wraparound is added to
the ubsan suppressions, as `CBloomFilter::Hash` is.

; Conflicts:
;	src/test/coins_tests.cpp
;	src/validation.h
The `cache=` figure in the UpdateTip log line includes the pool memory
resource's free lists. Map nodes freed by compaction stay there for
reuse, so `cache=` doesn't drop when spents are compacted. It steps up
instead, by the size of the vector.

Add `cache_used=`, an estimate of the memory actually in use, so the
effect of compaction is visible. The map node size is implementation
defined, so it's estimated. `cache=` is unchanged.
@DrahtBot

DrahtBot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #37094 (validation: validate assumeutxo snapshots with a single chainstate by fjahr)
  • #36904 (log: Remove trailing and embedded newlines from log messages by maflcko)
  • #36603 (Improve loadtxoutset performance by ajtowns)
  • #36496 (coins: avoid redundant prevout preparation allocations by l0rinc)
  • #34864 (coins: tighten cache entry state invariants by l0rinc)
  • #34778 (logging: rewrite macros to enforce restrictions at compile-time, improve efficiency and usability by ryanofsky)
  • #34132 (coins,dbwrapper: make database point-read failures fatal by l0rinc)
  • #29256 (log, refactor: Allow log macros to accept context arguments by ryanofsky)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • src/test/coins_tests.cpp: base.AddCoin(outpoint, Coin{CTxOut{i + 1, CScript{}}, 1, false}, false)
  • src/test/coins_tests.cpp: base.AddCoin(recreated, Coin{CTxOut{1, CScript{}}, 1, false}, false)
  • src/test/coins_tests.cpp: base.AddCoin(spent, Coin{CTxOut{2, CScript{}}, 1, false}, false)
  • src/test/coins_tests.cpp: base.AddCoin(spent.back(), Coin{CTxOut{1, CScript{}}, 1, false}, false)
  • src/test/coins_tests.cpp: base.AddCoin(kept.back(), Coin{CTxOut{2, CScript{}}, 1, false}, false)
  • src/test/coins_tests.cpp: cache.AddCoin(spent[0], Coin{CTxOut{3, CScript{}}, 2, false}, false)

2026-12-01 23:58:55

@LarryRuane

LarryRuane commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Benchmark details

All runs: mainnet -reindex-chainstate, dbcache=1000, base e211dd0, networking off, txindex and blockfilterindex off, page cache dropped before each run. Desktop runs stop at height 974000, Pi runs at 600000.

Desktop: AMD Ryzen 9 5950X, 64 GB RAM.

NVMe SSD (Samsung 980 PRO 2 TB):

master branch change
wall clock 2:25:20 2:22:20 −2.1%
user CPU 17,895 s 16,468 s −8.0%
system CPU 2,117 s 1,854 s −12.4%
device writes (SMART) 798 GB 678 GB −15.0%
flushes 157 108 −31%
LevelDB lookups 681.9M 606.0M −11.1%

SATA HDD (Seagate ST4000DM004 4 TB), master run twice:

master (mean) branch change
wall clock 8:42:09 (8:45:12, 8:39:05) 8:14:29 −5.3%
user CPU 17,936 s 17,004 s −5.2%
system CPU 2,126 s 2,010 s −5.5%
flushes 157 108 −31%

Raspberry Pi 4 (4 GB RAM), 1 TB SATA SSD (APS-SL3N-1T) in a USB 3 enclosure with UAS disabled:

master branch change
wall clock 62:26:39 54:34:58 −12.6%
user CPU 33,752 s 32,232 s −4.5%
system CPU 30,916 s 26,763 s −13.4%
flushes 79 69 −13%
LevelDB lookups 182.8M 171.8M −6.0%

The same Pi and SSD with UAS enabled, so the drive can queue many reads at once (queue depth 29 instead of 1), and the prevout fetch threads can overlap them. With UAS, the kernel picked a 64 MB readahead for this enclosure, which thrashed the page cache, so read_ahead_kb was set to 128 (the usual default). Same binaries as above:

master branch change
wall clock 9:13:27 7:52:18 −14.7%
user CPU 30,239 s 27,783 s −8.1%
system CPU 20,036 s 15,647 s −21.9%
flushes 43 30 −30%
LevelDB lookups 202.8M 179.1M −11.7%

Raspberry Pi 4, 4 TB HDD over USB. Master ran for 24 hours and reached height 449741, then the branch ran to the same height. Times are to the UpdateTip for that height:

master branch change
wall clock 24:00:08 21:50:52 −9.0%
user CPU 11,574 s 11,202 s −3.2%
system CPU 4,197 s 3,801 s −9.4%
flushes 33 30 −9%
LevelDB lookups 78.9M 74.4M −5.7%

Desktop NVMe SSD again, with -dbcache=40000. The cache peaked at about 29.8 GB, so it never filled. The only writes were two periodic syncs and the one at shutdown, and compaction never triggered:

master branch change
wall clock 2:37:02 2:36:43 −0.2%
user CPU 12,130 s 12,137 s +0.1%
system CPU 1,171 s 1,229 s +5.0%
device writes (SMART) 161 GB 158 GB −1.9%

@LarryRuane

LarryRuane commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Non-required reading: Some of my earlier attempts to use cache memory more efficiently by optimizing spent coin representation. These didn't work out:

  • Writing spent coins to LevelDB early, ahead of the regular flush. This naive attempt breaks crash consistency, since the chainstate on disk has to match its best block.
  • Changing CCoinsCacheEntry to hold a Coin* (null for spent). Elegant, but the gain was small, because most of a spent entry's cost is the map node itself. It also needed twice as many allocations (although the pool allocator makes them cheap) and an extra CPU cache line fetch on every coin access (which is a bigger problem).
  • Moving each coin into a separate std::unordered_set as soon as it's spent. This needs no thresholds or batching, but too much code (especially test code) depends on spent entries being able to exist in the map, and I never got it working. I also measured a set in place of this PR's vector and filter (keeping spent coins in the map). It would take about 60 bytes per spent coin vs about 38 here.
  • Writing spent outpoints to a separate LevelDB table that's cleared at startup and applied at flush time (each entry becomes an erase in the main table). LevelDB writes need large batches to perform well, so like this PR it batched spents once a threshold was reached. It worked for -reindex-chainstate, but it was slower than keeping them in memory and got slower as the sync went on.

@l0rinc

l0rinc commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Hey Larry, welcome back.

I checked out the code and took it for a spin: storing pending deletions separately from the main map could make sense if we can do it simply and safely. This version adds a lot of state to consensus-critical code for the gain I measured.
On my Raspberry Pi 5 with an SSD and 16 GB of RAM, reindexing the chainstate was barely 1% faster in wall-clock time. I suspect avoiding disk reads buys less on this setup now that parallel prevout fetching can overlap them. HDDs, SD cards, and network-attached storage may benefit more.

It doesn't just depend on me of course, but if we can do this in a much simpler way (e.g. a separate map and dbcache hidden behind an interface) that doesn't affect anything else (and we can see meaningful improvements on weaker systems at least), I could be for this change.

Issued flagged by my local AIs during review
  • A failed Bloom filter allocation can expose an already-spent coin if the caller recovers from the exception.
  • With a small -dbcache, unused mempool space can let the spent vector grow while the batch cap stays small, so each small batch copies the whole growing vector.
  • The merge buffers can push peak memory well above what the cache budget accounts for.
  • The debug SanityCheck() runs after flush or sync has already cleared the spent state it's meant to check.
  • Shrinking the cache can trigger compaction just before a forced flush discards the result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants