Batch loading
Load several missing keys with GetMany and avoid repeated reads for concurrent requests and absent data.
Configure a loader
A Loader accepts a batch of keys and returns the values it finds, so the lookup can use one database round trip. Loaders must support concurrent calls. Config.Capacity is enough to create a cache. Add a loader for misses and set the lifetime with Config.TTL.
// The Loader receives a batch of keys, like SELECT ... WHERE id IN (...).
var loads atomic.Int32
loadUsers := func(_ context.Context, ids []int) (map[int]string, error) {
loads.Add(1)
time.Sleep(50 * time.Millisecond) // a slow query
users := make(map[int]string)
for _, id := range ids {
if id <= 100 { // only users 1 to 100 exist
users[id] = fmt.Sprintf("user-%d", id)
}
}
return users, nil
}
// Only Capacity is required; the zero value of every other field turns
// its feature off.
cache, err := memo.New(memo.Config[int, string]{
Capacity: 1000,
TTL: time.Minute,
Loader: loadUsers,
CacheMissing: true, // remember missing keys instead of querying again
})
if err != nil {
panic(err)
}Coalesce concurrent reads
Ten goroutines call Cache.Get for the same uncached key. They share one load and the call count is one. If one caller cancels its wait, the others can still wait for the shared load.
// Ten goroutines read the same uncached key; it is loaded once.
var wg sync.WaitGroup
for range 10 {
wg.Go(func() {
if _, _, err := cache.Get(ctx, 1); err != nil {
panic(err)
}
})
}
wg.Wait()
fmt.Println("10 concurrent reads, loads:", loads.Load())Batch reads with GetMany
Cache.GetMany returns hits directly and sends the remaining keys through one load call. If the load fails, it returns any values already found along with the error. Callers can handle partial results and the failure separately.
// GetMany returns cached keys directly and loads the rest (2, 3, 999) in
// a single call.
users, err := cache.GetMany(ctx, []int{1, 2, 3, 999})
if err != nil {
panic(err)
}
for _, id := range slices.Sorted(maps.Keys(users)) {
fmt.Println(id, users[id])
}
fmt.Println("after GetMany, loads:", loads.Load())loadUsers := func(_ context.Context, ids []int) (map[int]string, error) {
fmt.Println("one loader call for", ids)
return map[int]string{2: "bob", 3: "carol"}, nil
}
cache, _ := memo.New(memo.Config[int, string]{Capacity: 100, Loader: loadUsers})
cache.Set(1, "alice")
users, _ := cache.GetMany(context.Background(), []int{1, 2, 3, 404})
for _, id := range slices.Sorted(maps.Keys(users)) {
fmt.Println(id, users[id])
}one loader call for [2 3 404]
1 alice
2 bob
3 carolCache missing keys and serve stale values briefly
Config.CacheMissing remembers keys omitted by the loader. Looking up the missing key again in the example leaves the load count unchanged. With a TTL and loader configured, Config.StaleWhileRevalidate can return expired values for a specified window while reloading them in the background.
// 999 is now cached as missing, so reading it again does not load.
_, found, _ := cache.Get(ctx, 999)
fmt.Println("read 999:", found, "loads:", loads.Load())