Repository navigation
Releases
v0.6.1
This release removes a pause of tens of milliseconds from the first insert after many deletes. It also corrects three docs: how to restore a weighted cache, a case where saving silently drops struct fields, and the README's allocation claims. The exported API and the file format are unchanged: file.go changed only in doc comments, so v0.6.1 reads and writes the same data as v0.6.0. The fix makes inserts into a full cache slower on the CPU it was measured on (see Performance).
Fixed
- The first
Setafter many deletes no longer stalls.Deleteleaves its slot in the cache's FIFO order log. Once dead slots outnumbered live entries by more than 1,024, the next insert checked every slot in the log while holding the cache-wide queue lock. At a million entries that insert took tens of milliseconds, and every other insert of a new key waited behind it. Compaction now runs a few slots per insert, so the time an insert spends on the log no longer depends on the cache size.Deletestays O(1) amortized, and eviction order is unchanged. (#72, fixes #76)
Performance
Measured against v0.6.0 on a 16-vCPU AMD EPYC 7763 with Go 1.27.4:
- First
Setafter deleting 60% of a million entries: about 50 ms before, about 3 µs now. - Delete-and-insert churn at a million entries: the slowest
Setdrops from about 150 ms to about 100 ms. What remains is one growth of the log's buffer. The averageSetis about 15% slower. - Inserts into a full cache with no deletes: about 16% slower at a million entries and about 4% at 64K, although no compaction runs in that workload. Each changed line applied alone to v0.6.0 costs nothing, so this looks like a microarchitectural effect rather than added work. The exact cause hasn't been found.
- Memory: at a million entries under churn, the log is longer while a pass runs, which costs one more growth step. Its peak goes from 2.10M to 2.40M slots, and the heap from 158 MiB to 171 MiB.
- Everything else: the other 15 benchmarks in the same comparison, including
Get,Delete,Setreplacing a value and loading, showed no change.
Trade-offs
- A workload that never deletes pays the full-cache insert cost and gets nothing from the fix.
- The slowdown was measured only on that Zen 3 machine. Laptop runs on Apple Silicon were too noisy to confirm or rule it out.
Documentation
-
Restoring a weighted cache.
LoadFrom,LoadFromFileandLoadFromFileOrNewbuild the cache withNew, so a cache made byNewWeightedloads back without its weight bound. One made withmath.MaxIntasmaxEntries, the documented way to bound a cache by weight alone, loads back with no bound at all. The docs forNewWeighted, the three load functions and the package, and the README, now say so and give the way to restore one: make a new cache withNewWeightedand the same arguments, then pass itsSettoLoadFromFunc. The newExampleLoadFromFunc_weightedrestores a weighted cache from a file and shows that it still evicts. (#73)// LoadFromFile would drop the weight bound. cache, err := fastcache.NewWeighted(math.MaxInt, 64<<20, weigh) if err != nil { return err } f, err := os.Open(path) if err != nil { return err } defer f.Close() if err := fastcache.LoadFromFunc(f, cache.Set); err != nil { cache.Reset() // Drop the entries loaded before the error. return err }
-
Saving can't detect fields dropped from a struct that embeds a type with a
GobEncodeorMarshalBinarymethod, such astime.Time. The struct inherits the method, so gob encodes only the embedded value.SaveToandLoadFromboth return nil, and the struct's other fields load back as zero values. In a key, entries whose keys differed only in those fields load back as one entry. The save docs promised an error for any field gob would drop.SaveTonow describes this case and its fixes: give the embedded field a name, or, for values, convert them withSaveToFunc.SaveToFile,SaveToFileConcurrentandSaveToFuncpoint to it, andSaveToFuncadds that neither K nor S should embed such a type. The check itself can't be fixed: reflection can't tell an inherited method from one the struct declares, so it would also reject structs that declare their ownGobEncodeand save correctly. (#74, closes #77) -
The README's allocation claims are scoped. The README said
Getdoesn't allocate, which holds only for string keys. Hashing other key types boxes the key, so a struct key allocates once on everyGet, and so does anintkey of 256 or more. EverySetallocates the entry it stores, not only aSetthat replaces a value. The features list, the comparison table and the benchmark highlights now say so. The table's cell for the original fastcache now reads "Get with nil dst: 1 per hit. Set: 0". The highlights also explain why its allocs/op shows 0 fromGet/256up: some of thoseGetcalls miss, and the average, below 1, is truncated to an integer. (#75)
Internal
- The order log is compacted in place, at most
compactStep(8) slots per insert. The ring counts a pass's holes and unchecked slots from the newest end, sopushFrontis unchanged andpopstill inlines. When evictions have taken every slot a pass kept,popdrops the holes and ends the pass, and the next insert starts a new one if dead slots still outnumber live ones. (#72) TestCacheCompactsOrderLogInSmallStepschecks that an insert after mass deletes doesn't rewrite the whole log.TestSlotRingKeepsFIFOOrdernow runs compaction passes between pushes and pops, and the churn test bounds how much the log can grow while a pass runs. (#72)
Full changelog: v0.6.0...v0.6.1
v0.6.0
This release adds NewWeighted, which bounds a cache by the total weight of its entries, such as the bytes of their values, as well as by entry count. Caches made by New behave as before, but each entry now stores a weight, so some of their writes are slightly slower (see Performance). The file format is unchanged: weights aren't saved, and v0.6.0 reads and writes the same data as v0.5.1.
// At most 1,000 entries whose values add up to at most 64 MiB.
cache, err := fastcache.NewWeighted(1000, 64<<20, func(_ string, v []byte) int {
return len(v)
})Added
NewWeighted(maxEntries, maxWeight, weigh)returns a cache that holds at mostmaxEntriesentries whose weights add up to at mostmaxWeight. You supplyweigh, afunc(K, V) int, such as one that returns the length of the value. (#71, closes #70)- When a new or heavier value doesn't fit, the oldest entries are evicted until it does. A
Setthat makes a value heavier evicts only other entries, so its key stays in the cache and keeps its place in eviction order. - Each entry keeps the weight it was stored with, so the total can't drift if data that a value points to changes later.
- To bound a cache by weight alone, pass
math.MaxIntasmaxEntries. Storage is allocated as entries are stored, not up front.
- When a new or heavier value doesn't fit, the oldest entries are evicted until it does. A
ErrInvalidWeightis returned bySet,GetOrSetandSetIfAbsentin a weighted cache when a value's weight is negative or greater thanmaxWeight. The cache is left unchanged.GetOrSetandSetIfAbsentcheck the weight only when the key is absent. (#71)ErrInvalidMaxWeightis returned byNewWeightedwhenmaxWeightisn't positive.NewWeightedalso returns an error whenweighis nil, and the same errors asNewfor an invalidmaxEntries. (#71)
Saving and loading weighted caches
- Weighted caches save like any other cache. Their weights aren't saved.
LoadFrom,LoadFromFileandLoadFromFileOrNewreturn caches bounded only by entry count. To load saved entries into a weighted cache, pass itsSettoLoadFromFunc, which stops withErrInvalidWeightat the first saved value heavier thanmaxWeight. (#71)
Performance
Each entry now stores its weight, which makes it 8 bytes larger, in caches made by New too. Measured against v0.5.1 on an Apple M5 Pro:
Get: 1.5% slower (about 0.15 ns), with no change in allocations.- Updates of
[string, []byte], the type the README benchmarks: 3% slower, with no change in memory. - Small types such as
[string, string]and[int, int]: the extra 8 bytes move each entry up an allocation size class. Updates take 8% to 10% longer and allocate 16 B more, and each stored entry takes 16 B more memory. Inserts into a full[int, int]cache take 9% longer. - Benchmark suite (
GOMAXPROCS=4): the geomean is within 0.05% of v0.5.1's (48.52 ns against 48.50 ns), and the fork is still 2.4× faster than the original fastcache and otter.Setis 3% to 8% slower from 16 to 1,024 keys,SetGet1% to 8% slower up to 2,048 keys, andSetParallel5% to 6% slower at 1 and 16 keys. From 4,096 keys up there is no measurable change.
Trade-offs
- In a weighted cache, an update that makes a value heavier locks the cache-wide FIFO queue, as adding a key does, because it may have to evict. Updates that add no weight still lock only the key's shard. (#71)
- The benchmark suite measures only caches made by
New, notNewWeighted.
Documentation
- The README lists weighted capacity among the features and in the comparison with the original fastcache, and no longer lists "No size-based limits" under Limitations. (#71)
- The README's benchmark table was rerun on this release with the same settings. Its geomean now reads 48.5 ns against 116.2 ns for otter and 118.4 ns for the original. The changed
GetParallelranges reflect run-to-run spread, not the new code. (#71)
Internal
- Each entry records its weight, and the cache keeps a running total that inserts, updates, deletes, evictions and
Resetadjust. Eviction can skip the entry being updated and return it to the front of the queue. (#71)
Full changelog: v0.5.1...v0.6.0
v0.5.1
This release fixes four bugs in saving and loading: a goroutine leak after a failed save, a hang when saving into a pipe, damaged data that reached LoadFromFunc as wrong values, and errors that errors.Is couldn't match. The exported API and the file format are unchanged: v0.5.1 writes the same bytes as v0.5.0, and each loads what the other saves.
Warning
Behavior change:
- Loading checks the end of the saved data.
LoadFrom,LoadFromFile,LoadFromFuncandLoadFromFileOrNewnow read the end-of-stream chunk that minlz writes after the last entry, and reading it checks the stream's length. Data whose end chunk is missing or wrong, or that continues after the last entry, now fails to load. Before this release it loaded. Every successful save writes a valid end chunk, so only damaged or cut-off data is affected, such as a connection that closed right after the last entry.LoadFromFunchas already passed every entry to its function when it reports this error, andLoadFromFileOrNewreturns an empty cache, as it does for any file it can't load. (#67, fixes #64)
Fixed
- A failed save no longer leaves a goroutine running. The minlz writer runs a goroutine until it is closed, and saving closed it only when the save succeeded. Each
SaveTo,SaveToFile,SaveToFileConcurrentorSaveToFuncwhose writer failed partway, such as on a full disk or a closed connection, left one more goroutine waiting forever. (#65, fixes #61) SaveTointo a pipe returns once the other end has loaded the data.LoadFromandLoadFromFuncstopped reading at the last entry and never read the end chunk after it, so aSaveTointo anio.Pipeblocked forever writing that chunk. Loading now reads through the end chunk and stops there, without waiting for the writer to close. Because it no longer reads past the saved data, saves written one after another to the same stream also load one after another. In v0.5.0 the second load failed withminlz: corrupt input. (#67, fixes #64)- Damaged data no longer reaches
LoadFromFunc's function as a wrong value. One damaged byte could make minlz skip a whole compressed chunk without a check.LoadFromFuncthen passed the entry that spanned the gap, with different contents, and the error came only with a later entry. Loading now rejects such a chunk asminlz.ErrCorruptas soon as it reads it, so no entry decoded across the gap is passed on. (#68, fixes #63) - Save and load errors wrap their cause. They kept only the text of the error that caused them, so
errors.Iscouldn't tell a full disk or a closed connection from damaged data.errors.Isanderrors.Asnow match the writer's and reader's own errors, file-system errors fromSaveToFileandSaveToFileConcurrent, and gob and minlz errors such asminlz.ErrCorrupt, so those errors are now part of what the functions return. Data that ends after the capacity but before all the entries it promises reportsio.ErrUnexpectedEOF; only data that is empty from the start matchesio.EOF. (#66, fixes #62)
Performance
- Loading 100k entries takes the same time and memory as in v0.5.0. Saving runs the same code, apart from closing the writer on error paths.
Documentation
- The docs for
LoadFromandLoadFromFuncnow say that a successful load reads the reader to the end of the saved data and no further. (#67)
Internal
- Loading reads through a small reader in front of minlz that ends after the end chunk and rejects chunk types that saving never writes. (#67, #68)
Full changelog: v0.5.0...v0.5.1
v0.5.0
This release adds iterators that walk the cache in eviction order, and functions that select and convert entries when saving and loading. LoadFromFileOrNew now creates the cache with the capacity you pass it. The file format is unchanged: data saved by v0.4.0 loads in v0.5.0, and data saved by v0.5.0 loads in v0.4.0.
Warning
Breaking change:
LoadFromFileOrNewuses themaxEntriesyou pass, not the saved capacity. Before this release it usedmaxEntriesonly when the file failed to load, and otherwise returned a cache with the capacity it was saved with. Saving writes that capacity back, so a program that changed its cache size kept the old one on every run until the file was deleted. Now the cache always hasmaxEntriescapacity. When the file holds more entries than that, the cache keeps the newest and counts the others as evictions inStats. A missing or corrupted file still gives an empty cache. (#59, fixes #55)- A
maxEntriesthat isn't positive is now an error even when the file loads. (#59) - To keep the saved capacity, call
LoadFromFileand fall back toNew(maxEntries)when it returns an error.LoadFromFileandLoadFromstill restore the saved capacity.
Added
AllFIFO,KeysFIFOandValuesFIFOiterate oldest first, which is the order in which the cache evicts. Updating a key keeps its place; deleting a key and setting it again makes it the newest.All,KeysandValueskeep their faster, unordered iteration. (#57, closes #54)SaveToFuncsaves the entries that a function selects, as the values it returns, oldest first. Use it to save part of a cache, or to save values that gob can't encode, such as structs with unexported fields, by converting them to a type it can. The gob check applies to the returned type instead ofV. (#58, closes #56)LoadFromFuncpasses each saved entry, oldest first, to a function, such as theSetmethod of a cache you already have. It ignores the saved capacity and returns the first error that the function returns. It reads whatSaveTo,SaveToFileandSaveToFuncwrite, andLoadFromreads whatSaveToFuncwrites. (#58, closes #56)
Performance
SaveTois 4.8% faster on 500k entries, andSaveToFileConcurrentwith 8 workers is 3.9% faster, because the oldest-first sort moves smaller references. (#57)Get,Set,Delete,All,KeysandValuesrun the same code as in v0.4.0, and their benchmarks show no change.
Trade-offs
AllFIFO,KeysFIFOandValuesFIFOcopy and sort every entry before they yield the first one, and hold memory in proportion toLenuntil the loop ends. On 500k entries a full loop takes about 8× as long as withAll, and a loop that stops after 10 entries about 17,000× as long. (#57)SaveToFunckeeps the values it saves in memory until it writes them, because the format puts the entry count first. (#58)LoadFromFileOrNewwith amaxEntriessmaller than the file's entry count still decodes every entry, then evicts the extras. (#59)
Internal
- Saving and the FIFO iterators share one oldest-first snapshot. Its workers take every n-th shard instead of reading shard numbers from a channel. (#57)
- All save and load functions share one encoder and one decoder. (#58)
LoadFromno longer adds the entry's index to an error from inserting it. (#58)
Full changelog: v0.4.0...v0.5.0
v0.4.0
This release fixes several FIFO eviction and persistence bugs, cuts memory use, and makes Get lock-free. The exported API is unchanged.
Warning
Behavior changes:
- Saving rejects types it can't fully encode.
SaveTo,SaveToFileandSaveToFileConcurrentnow return an error, before writing anything, when K or V contains fields that gob drops: unexported struct fields, orchanandfuncfields. Before this release these values saved without an error and came back with those fields zeroed or nil. The error names the field and its path. To keep saving such a type, export its fields or implementgob.GobEncoderorencoding.BinaryMarshaler. The error isn't exported, soerrors.Iscan't match it. (#39, fixes #30) - Known gap: a struct that embeds a type that encodes itself, such as
time.Time, still loses its other fields without an error.
Fixed
Set,GetOrSetandSetIfAbsentno longer returnErrEvictionFailedon a full cache when a concurrentDeleteorGetAndDeleteremoves the entries being evicted. (#52, fixes #46)- A key that is deleted and then set again is no longer evicted ahead of older keys. (#35, fixes #28)
- A cache restored with
LoadFrom,LoadFromFileorLoadFromFileOrNewnow evicts in the original insertion order. Snapshots are written oldest entry first. (#38, fixes #29) SaveToFileandSaveToFileConcurrentflush the temporary file to disk before renaming it over the target. After a crash the target holds either the old snapshot or the complete new one, never a partial file. (#40, fixes #32)- Repeated
SetandDeletecalls on a cache below capacity no longer grow memory without bound. Two million Set/Delete pairs used to retain about 95 MiB. (#36, fixes #27) Newno longer allocates formaxEntriesup front. Storage grows as entries are stored, somaxEntriesworks purely as a cap. An emptyNew(1_000_000)used to take about 108 MB. (#37, fixes #31)Resetnow releases the memory of the eviction queue, as documented. (#48, fixes #44)
Performance
- Lock-free
Get.Getno longer takes a shard lock or writes shared memory, and its hit and miss counters are spread across CPUs. Concurrent Gets of one key on 18 CPUs take 2.3 ns each instead of 112 ns. Inserting into a full cache is 44% faster. (#50, closes #45) - Eviction no longer copies the queue. The eviction queue is now a ring buffer.
Seton a full cache of 4M entries takes about 240 ns instead of 1.7 µs. (#49, fixes #43)
Trade-offs
- Updating an existing key now allocates (48 B for a string key and value) and takes 11–20 ns longer, which is about twice as long for short keys. (#50)
- A
Getmiss takes about 5 ns longer. (#50) - Filling an empty cache is 7–23% slower, with occasional pauses while storage grows, since
Newno longer pays for it up front. (#37) - Saving 500k small entries takes about 1.85× as long, because entries are sorted into insertion order. (#38)
SaveToFileandSaveToFileConcurrenttake longer because of the added disk flush. (#40)
Documentation
- Fixed out-of-date mentions of snappy,
map[K]V, ring buffers and "lock-free" atomic operations. The docs now say which operations serialize on which lock. (#42, closes #34) - The README benchmarks were rerun on an Apple M5 Pro with
GOMAXPROCS=4. The previous numbers came from an AMD EPYC 7763, so the two sets can't be compared directly. (#50)
Internal
Full changelog: v0.3.1...v0.4.0