O que faz
- Cinco políticas de eviction, entre elas LRU, Clock e TinyLFU
- Expiração por tempo e invalidação em O(1)
- Loader protegido contra thundering herd, nunca chamado com o lock adquirido
Medido
- Release, MSVC 19.51, i7-6700. Zero alocações em cem mil leituras e cem mil inserções. 256 threads, e o loader é chamado uma única vez
- TinyLFU vs. LRU: taxa de acerto de 35,0% vs. 26,5%
- Leitura com acerto: 20,7 ns. Meta de 20 ns não cumprida
- Vazão de leitura de 1 a 8 threads: 2x. Meta de 10x de 1 a 16 threads não cumprida (4 núcleos físicos)
Limites conhecidos
- A vazão de leitura escala 2x de 1 a 8 threads em 4 núcleos, abaixo da meta de 10x
The cache is complete and measured. Open-addressing table over a preallocated slab, five eviction policies, expiry, O(1) invalidation, loading with stampede protection, and the sharded variant. Two spec targets are not reached, and the sections "The 20 ns" and "Scaling" say how far off they are, why, and what would have to change. Read those two sections before relying on this module's performance.
---
What this module is
CCache< ETL_UINT64, std::string > C;
SCacheParams P;
P.uMaxEntries = 10000u;
P.ePolicy = EEviction::eTinyLfu;
ETL_UNUSED( C.Init( P ) );
ETL_UNUSED( C.Put( 42u, "forty-two" ) );
std::string s;
if( C.Get( 42u, &s ) )
...For several threads, CShardedCache with the same interface, without GetRef, and with eClock instead of eLru. Both reasons are in ethereal/cpp/cache/sharded.hpp and are repeated below.
---
The four decisions that govern everything
"A cache exists to be faster than the thing it caches. If lookup costs more than a few tens of nanoseconds it stops earning its place."
Open addressing, no chained buckets. A chained table makes each read follow pointers across different cache lines. In a cache that is what costs: computing the hash is one multiplication, and a cache miss is two hundred cycles. Power-of-two capacity, a mask instead of a modulo (more than twenty cycles versus one).
Robin Hood solves the variance, and the mean stays the same. Whoever has been probing longer pushes out whoever has been probing for less time. The median read stays the same. What changes is the variance: the worst read stops being catastrophic as the table fills up.
The bucket stores the short hash. Eight bytes per bucket, eight buckets per cache line. Comparing the short hash resolves almost every probe step without touching the slab. Only when it matches does the code go fetch the key there, and then the cache miss was worth it.
No tombstones. Removing a key does a backward shift. A table full of tombstones is walked as if it were full even when it is empty, and one day the search for a key that is there does not find it. There is a test that inserts and removes twenty thousand times in the same 64-slot table and requires that all of them be found.
---
Three things the API does not let you work around
GetRef does not exist in the concurrent variant
Returning a pointer into a cache that another thread may evict the next instant is a use after free waiting to happen, and no comment makes that safe. In the single-threaded variant it exists, with the borrow documented as valid until the next operation.
eLru is not the recommended policy for several threads
A strict list is modified by every read, and in a cache reads are almost everything. That is a write where there should only be a read. eClock does the same job with one bit per entry, and the bit is only written when it is clear: reading and comparing leaves the cache line shared, and writing takes it away from every other core.
The difference was measured and is in the table below: 22.9 ns versus 20.7 ns per read, on one thread.
The loader never runs with the lock held
"A popular key expires. A thousand concurrent requests all miss, and all call the loader, and the backend that the cache existed to protect gets a thousand simultaneous requests."
The database goes down because of the cache, and at the worst moment. The first thread that misses writes the key to a list of in-flight keys and releases the lock. The others find it there and wait on a condition variable instead of calling the loader.
There is a test with 256 threads missing the same key at the same time, with a gate so they all start together, and it requires the loader to run once.
---
The 20 ns
"Single-threaded hit: under 20 ns."
| measured | |
|---|---|
read that hits, eClock | 20.7 ns |
read that hits, eLru | 22.9 ns |
**It falls two tenths short of the target with eClock, and does not get there with eLru.** Release, MSVC 19.51, x64, Intel i7-6700.
What remains in a read, after everything that was taken out: the key's bit mixing (three multiplications, inline, see below), one probe step, the key comparison, the timestamp and the copy of the value. There is no identifiable fat left here to cut. What is missing is the size of the measurement noise.
One thing was cut because of this: a trivially copyable key of eight bytes or fewer (the most common cache key) no longer goes to HashBytes, which is a call that is not inlined, and now has its hash computed inline. That took ~4.6 ns off each read in the sharded variant (43.5 → 38.9 ns).
---
Scaling
"Concurrent hit: under 40 ns at 16 threads on 16 cores. Concurrent scaling: throughput scales at least 10x from 1 to 16 threads on a read-heavy workload."
| threads | ns per read (throughput) | scaling |
|---|---|---|
| 1 | 37.7 | 1.00x |
| 2 | 30.6 | 1.23x |
| 4 | 22.9 | 1.65x |
| 8 | 18.9 | 1.99x |
The 40 ns target is met with room to spare. The scaling target is not: the measured value is 2x, and the target is 10x.
What the number means, and what it does not
The machine has four physical cores and eight logical. From four to eight threads what is added are hyperthreading siblings, which share the execution ports. The spec target is about sixteen cores, and this report cannot say what would happen there. It can say that here, from one to four real threads, the scaling is 1.65x, far from 4x.
The cause, measured
Two measurements point to the same place:
- The lock was half the cost of a sharded read. Replacing MSVC's
std::mutexwithstd::shared_mutex(which relies directly on SRWLOCK) brought the single-thread read down from 52.4 to 43.5 ns. Nine nanoseconds, just from changing the lock, with everything else the same. - In Debug, the same cache scales 3.38x. In Debug each read does much more work, and the serialized part weighs relatively less. That is the signature of a bottleneck in the shared part (the lock and the cache lines that every thread dirties), and the work of each read is ruled out as the cause.
The number of shards was also measured: with four per thread the scaling was 1.76x, with many more it was 2.63x. The default value became eight per thread, with the safeguard of never leaving a shard with fewer than 64 entries. Below that each shard evicts on its own and the hit rate drops.
What it would take to get there
A read that takes a lock and writes four words does not scale linearly, however many shards are added. For 10x it would take a lock-free read path (a sequence stamp per entry, with the read confirming that the entry did not change during the copy) and sampled counters instead of exact ones. That is a different design, which is not here. A tweak of this one is not enough.
---
What was measured, and is verified
| allocations on a read that hits | zero, over one hundred thousand |
| allocations on a read that misses | zero, over one hundred thousand |
allocations on a steady-state Put | zero, over one hundred thousand |
| memory use | the same number after three hundred thousand operations |
| capacity | ten thousand inserts into a cache of one hundred: never exceeds one hundred |
| cost ceiling | never exceeded, and filled up to near it |
| capacity under concurrency | eight threads writing, never exceeded |
| stampede | 256 threads, same key, loader called once |
| eviction notification | runs outside the lock, and calls the cache again without deadlock |
| expiry | expires on the instant, with a manual clock |
| TinyLFU versus LRU | 35.0% versus 26.5% hit rate |
| invalidation of a thousand entries | 100 ns |
The allocation counter fails the test: the spec asks for zero "always", and a read that allocates memory is not a cache read. The global allocation functions are replaced, the complete set including the nothrow variants.
Twenty-four-hour memory use is not verified in a test suite. What is verified in its place is the reason it is flat: the slab and the table are sized in Init and never change size again. The number is the same after three hundred thousand operations.
---
The coarse timestamp, and what it costs
The clock is read once every sixteen operations. Between reads, expiry is compared against the last value read.
**The real drift is the wall-clock time of fifteen operations, not uCoarseClockMs.** In a cache with traffic that is nanoseconds. In a cache with one read per minute it is fifteen minutes, and an entry with a one-minute expiry would be served long after it had died.
**A low-traffic cache uses uCoarseClockMs = 0**, and then the clock is always read and there is no drift. That is what the expiry tests do, with the manual clock.
---
How this was verified
tests/cache.cpp, 71 checks, green in Debug and Release.
Three defects the benchmark itself caught:
- The CLOCK test was written backward. It failed the first time, and rightly so: a new entry comes in with the reference bit set. That is classic CLOCK, it has just been referenced. Right after filling up, the four bits were set and reading three of them did not distinguish them from the fourth. The second chance only appears after a sweep has cleared the bits, and that is what the test now sets up.
- The scaling measured the warmup. The single-thread round was the first to touch the freshly filled slab and paid for the page faults. The eight-thread round already found it warm. It gave 1.8x, a number that said the cache did not scale when what did not scale was the benchmark.
- The same configuration measured 18.3 ns and 27.3 ns on consecutive runs. More than fifty percent difference, without changing a line. The benchmark now runs each case three times and keeps the best round, and the numbers stabilized within ±2%.
No timing number is a gate, for the same reason and with the same decision as the Resilience test suite: with this variation, any threshold placed here is a coin toss, and a failure nobody believes stops being a failure. In Debug the benchmark runs one hundredth of the rounds. The number is worthless, on purpose. The benchmark keeps compiling and running, and that keeps the benchmark code from rotting.
---
C layer
Header ethereal/c/cache/cache.h (source src/c/cache/cache.cpp), 13 ETLC_Cache* functions. The template is fixed at CShardedCache< std::string, std::string >: key and value are blocks of bytes copied on the way in and on the way out, with zero bytes in the middle without problem, and the handle can be shared between threads. ETLC_CacheConfigInit fills in the C++ defaults, and the struct exposes the five policies, capacity, cost budget, default and idle TTL, coarse timestamp, LFU aging, number of shards and a manual clock (ETLC_CacheAdvanceClock). The cost of each entry is the size of the key plus that of the value, so uMaxCostBytes counts real bytes. There are put, get into a caller buffer (required size on a short buffer), contains, remove, clear, invalidation by generation, size and statistics.
Left out are the eviction callback, the loader (GetOrLoad) and GetRef: in C the value only comes out by copy, and a callback with the key and the value in bytes would cost one copy per eviction.
Tests cache.cabi.c11 and cache.cabi.c17 (tests/cache_c_abi.c): LRU order with one shard, bytes with zeros, short buffer, TTL through the manual clock, byte budget, the five policies and the null handle on each entry point.
---
What is missing
- The sanitizers. ASan, UBSan and TSan are a row in the acceptance table and do not run on this machine. MSVC ships ASan but not TSan, and TSan is the one that would matter here. The complete set of
operator deleteis replaced precisely so that ASan does not reportalloc-dealloc-mismatchwhen someone runs it. - **The
IMetricSinkextension point**, for the Stats module to consume the counters without depending on the cache. - A lock-free read path in the sharded variant. See "Scaling".
- The seeded hash. The third template parameter accepts a custom hash, but there is no hash here randomized at initialization ready to use. Whoever has keys coming from outside (HTTP headers, file names requested by a client) needs it: the default is fast and non-cryptographic, and whoever can choose the keys can manufacture collisions.