Quickstart
Create a cache with a loader and observe hits and batch loading.
Run the cache example
Use Go 1.27 or later. Install memo, save the complete example as main.go, and run go run .. From the memo source directory, run go run ./examples/loader.
go get github.com/luminyra/memo// Command loader backs a memo cache with a batch loader: concurrent misses for
// the same key share one load, GetMany loads all its misses in one call, and
// missing keys are cached too.
package main
import (
"context"
"fmt"
"maps"
"slices"
"sync"
"sync/atomic"
"time"
"github.com/luminyra/memo"
)
func main() {
ctx := context.Background()
// 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)
}
// 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())
// 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())
// 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())
}See when the loader runs
New accepts a Config with a capacity and a loader. Cache.Get returns a value, a presence flag, and an error. In the test below, two reads of the same user cause the loader to run once.
loadUsers := func(_ context.Context, ids []int) (map[int]string, error) {
fmt.Println("loading", ids)
users := make(map[int]string)
for _, id := range ids {
users[id] = fmt.Sprintf("user-%d", id)
}
return users, nil
}
cache, err := memo.New(memo.Config[int, string]{Capacity: 100, TTL: time.Minute, Loader: loadUsers})
if err != nil {
panic(err)
}
name, found, _ := cache.Get(context.Background(), 1)
fmt.Println(name, found)
name, found, _ = cache.Get(context.Background(), 1) // served from the cache
fmt.Println(name, found)loading [1]
user-1 true
user-1 trueContinue with batch reads using GetMany to see how one call handles multiple misses.