luminyra
Guides

Eviction and expiration

Compare LRU, LFU, and FIFO on the same access sequence and distinguish capacity eviction from TTL.

Compare three eviction policies

Start with a capacity of three and insert A, B, and C. Read B several times, then read A. When Cache.Set inserts D, it needs to evict one entry.

PolicyRetains entries byEvicts in this example
LRUMost recent useB
LFUFrequency of use, with recency as the tiebreakerC
FIFOInsertion orderA
memo/examples/policy/main.go
for _, policy := range []memo.Policy{memo.LRU, memo.LFU, memo.FIFO} {
	cache, err := memo.New(memo.Config[string, int]{Capacity: 3, Policy: policy})
	if err != nil {
		panic(err)
	}

	// Write a, b and c in order, filling the cache.
	cache.Set("a", 1)
	cache.Set("b", 2)
	cache.Set("c", 3)

	// b is read three times (most frequent), c once, a once (most recent).
	for _, key := range []string{"b", "b", "b", "c", "a"} {
		cache.Get(ctx, key)
	}

	// Writing a fourth key evicts one entry; All iterates over the rest.
	cache.Set("d", 4)
	kept := slices.Sorted(maps.Keys(maps.Collect(cache.All())))
	fmt.Printf("%-4s keeps %v\n", policy, kept)
}
View on GitHub

Use shards for high concurrency

Each shard has its own lock. The cache uses a single shard by default. Set Config.Shards to distribute keys by hash across independently locked shards when multiple goroutines read and write concurrently.

memo/examples/shards/main.go
// Each shard has its own lock and holds Capacity/Shards entries (rounded
// up). Keys are assigned to shards by hash.
cache, err := memo.New(memo.Config[int, string]{
	Capacity: 100_000,
	Shards:   runtime.GOMAXPROCS(0),
})
if err != nil {
	panic(err)
}
View on GitHub

Writes from different goroutines are likely to take different locks when they use different keys.

memo/examples/shards/main.go
// Eight goroutines write different keys; most writes lock different shards.
var wg sync.WaitGroup
for worker := range 8 {
	wg.Go(func() {
		for i := range 1000 {
			cache.Set(worker*1000+i, fmt.Sprintf("user-%d", worker*1000+i))
		}
	})
}
wg.Wait()
fmt.Println("entries:", cache.Len())
View on GitHub

Each shard holds Capacity/Shards entries, rounded up, and runs its own eviction policy. Eviction order is exact within a shard. LRU and LFU update their order on each hit. FIFO hits leave the order unchanged, so FIFO scales best when eviction order is flexible.

Inspect entries and TTL

Cache.All iterates over a snapshot of fresh entries. Expired entries are removed lazily on access or eviction. Cache.Len can include expired entries that have yet to be cleaned up. Capacity eviction controls which entry to remove when full. Config.TTL controls when a value expires, and Config.Jitter spreads out expiration times.

memo/example_test.go
for _, policy := range []memo.Policy{memo.LRU, memo.LFU, memo.FIFO} {
	cache, _ := memo.New(memo.Config[string, int]{Capacity: 2, Policy: policy})
	cache.Set("a", 1)
	cache.Set("b", 2)
	cache.Get(context.Background(), "a") // a is now recently and frequently used
	cache.Set("c", 3)                    // evicts one entry

	kept := slices.Sorted(maps.Keys(maps.Collect(cache.All())))
	fmt.Println(policy, kept)
}
Expected output
LRU [a c]
LFU [a c]
FIFO [b c]
View on GitHub

On this page