Skip to content
goforjPublic

About

Go caching library with local, distributed, and SQL-backed drivers, plus typed helpers, locks, counters, and rate limits.

Topics

Resources

Security policy

Stars

6 stars

Watchers

0 watching

Forks

Latest commit

 

History

194 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

cache logo

One cache API for Go, from in-process memory to shared backends.

Go Reference License: MIT Go version Latest tag Codecov Unit tests (passing count) Local integration tests (passing count)

Quick Start · Drivers · Behavior · API

Quick Start

go get github.com/goforj/cache
package main

import (
	"context"
	"fmt"
	"log"
	"strconv"
	"time"

	"github.com/goforj/cache"
)

// main loads and caches a price in cents.
func main() {
	// Create an in-memory cache store.
	c := cache.NewCache(cache.NewMemoryStore(context.Background()))

	// Load the price on a cache miss and keep it for one minute.
	price, err := c.Remember("product:42:price", time.Minute, func() (int, error) {
		return strconv.Atoi("4900")
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Desk lamp costs %d cents\n", price)
	// Output: Desk lamp costs 4900 cents
}

Get, Set, and Delete

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/goforj/cache"
)

// main shows direct cache operations for a piece of product inventory.
func main() {
	// Create an in-memory cache store.
	c := cache.NewCache(cache.NewMemoryStore(context.Background()))
	const key = "stock:desk-lamp"

	// Cache the stock count for one minute.
	if err := c.Set(key, 12, time.Minute); err != nil {
		log.Fatal(err)
	}

	// Read the count as an int. A cache miss sets found to false.
	stock, found, err := c.Get[int](key)
	if err != nil || !found {
		log.Fatalf("read stock: found=%t, error=%v", found, err)
	}
	fmt.Printf("Cached stock: %d\n", stock)
	// Output: Cached stock: 12

	// Delete the entry and verify the next read misses.
	if err := c.Delete(key); err != nil {
		log.Fatal(err)
	}
	_, found, err = c.Get[int](key)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Cached after delete: %t\n", found)
	// Output: Cached after delete: false
}

Drivers

Memory, file, and null are included in the root module. Install only the additional driver modules you use.

Backend Use and limits
Memory In-process cache. Values, locks, and counters are local to each process.
File Local files that survive restarts. Use a dedicated directory. Locks are process-local.
Null Disable caching. Drops writes and admits every lock.
Redis Shared cache with native counters. Counter expiry has one-second resolution.
Memcached Shared, ephemeral cache. Keys route to a stable peer. TTL resolution is one second.
NATS JetStream KV Uses an existing JetStream KV bucket with per-key or bucket-wide TTL.
DynamoDB Shared cache using a DynamoDB table. Item limits include encoded values and metadata.
SQLite Embedded SQL cache. Use a dedicated file or database.
PostgreSQL Shared SQL cache backed by PostgreSQL. Requires access to a cache table.
MySQL Shared SQL cache backed by MySQL. Requires access to a cache table.
go get github.com/goforj/cache/driver/rediscache
go get github.com/goforj/cache/driver/memcachedcache
go get github.com/goforj/cache/driver/natscache
go get github.com/goforj/cache/driver/dynamocache
go get github.com/goforj/cache/driver/sqlitecache
go get github.com/goforj/cache/driver/postgrescache
go get github.com/goforj/cache/driver/mysqlcache

See Driver Configs for construction examples and the Production Guide for connection ownership and rollout.

Supported Go versions

Modules Minimum Go version
Root cache 1.27.0
cachecore, cachetest, driver/sqlcore 1.24.4
DynamoDB, Memcached, MySQL, and Redis drivers 1.24.4
PostgreSQL and SQLite drivers 1.25.0
NATS driver 1.26.0

The generic method API requires Go 1.27 or newer. Projects on Go 1.26 can pin the root at v0.4.0 and select independently published drivers that support their toolchain. Documentation, examples, and integration tooling use Go 1.27.

Config Options

Cache uses explicit config structs throughout, with shared fields embedded via cachecore.BaseConfig.

Shared config (embedded by root stores and optional drivers):

type BaseConfig struct {
	DefaultTTL    time.Duration
	Prefix        string
	Compression   CompressionCodec
	MaxValueBytes int
	EncryptionKey []byte
}

Root-backed stores use cache.StoreConfig:

type StoreConfig struct {
	cachecore.BaseConfig
	MemoryCleanupInterval time.Duration
	FileDir               string
}

Typical root constructor usage:

store := cache.NewMemoryStoreWithConfig(ctx, cache.StoreConfig{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL: 5 * time.Minute,
		Prefix:     "app",
	},
	MemoryCleanupInterval: time.Minute,
})

Optional backends use driver-local config types that embed the same cachecore.BaseConfig plus backend-specific fields.

Example shapes:

// rediscache.Config (abridged)
type Config struct {
	cachecore.BaseConfig
	Client rediscache.Client
}
// sqlitecache.Config (abridged)
type Config struct {
	cachecore.BaseConfig
	DSN   string
	Table string
}

See the API Index Driver Configs section for per-driver defaults and compile-checked examples for: rediscache, memcachedcache, natscache, dynamocache, sqlitecache, postgrescache, mysqlcache, and sqlcore.

Value Shaping And Rollout

Built-in and optional drivers share the same settings for compression, encryption, and value limits.

Capability What it does
Gzip compression Set Compression to CompressionGzip to write values in a versioned CMP1 envelope.
AES-GCM encryption Set EncryptionKey to a 16-, 24-, or 32-byte key to protect values in an ENC1 envelope.
Payload limits Set MaxValueBytes to bound writes and reads, including decompressed output. Use 0 to disable the limit. Negative values are invalid.
Atomic counters Increment and Decrement bypass shaping so drivers can update raw counters atomically.

When both are enabled, encryption runs first and gzip wraps the result as CMP1(ENC1(plaintext)). Upgraded readers also accept existing raw values.

Important

Upgrade all cache readers before enabling shaped writes. Optional drivers from before v0.4 cannot decode compressed or encrypted values. During a rolling upgrade, pause writes until every reader is upgraded. Migration checklist

Behavior Semantics

For precise runtime semantics, see Behavior Semantics:

  • TTL/default-TTL matrix by operation/helper
  • stale and refresh-ahead behavior and edge cases
  • lock and rate-limit guarantees (process-local vs distributed scope)

Production Guidance

For deployment defaults and operational patterns, see Production Guide:

  • recommended defaults and tuning
  • key naming/versioning conventions
  • payload size limits by backend
  • TTL jitter and miss-storm mitigation
  • observability instrumentation patterns

Memoized reads

Create a NewMemoStore per request when a short-lived read snapshot is useful.

memoStore := cache.NewMemoStore(store)
memoRepo := cache.NewCache(memoStore)

Memoization holds up to 256 hits or misses for up to one second. Use the backing store directly when you need its exact TTL or immediate visibility of writes made through another handle.

Testing

For contributors, the module manifest lists the published drivers and repository tooling.

Unit tests cover the public helpers. See Integration coverage for the shared store contract, driver-specific checks, and suite scope. Run the cross-driver suite from the integration module:

cd integration
go test -tags=integration ./all

Use INTEGRATION_DRIVER=sqlitecache (comma-separated) to select which fixtures run, or use the repo helper:

bash scripts/test-all-modules.sh

scripts/check-quality.sh runs tidy-diff, vet, and tests independently in every module. CI also enforces a 97.0% root package statement-coverage floor with scripts/check-coverage.sh. The quick start runs in CI and its output is checked.

Benchmarks

The charts show a recorded benchmark snapshot. Rerun the benchmarks on the release and backend versions you plan to deploy.

cd docs
go test -tags benchrender ./bench -run TestRenderBenchmarks -count=1 -v

Note: NATS numbers can look slower than Redis/memory because the NATS driver preserves per-operation TTL semantics by storing per-key expiry metadata (envelope encode/decode) and may do extra compare/update steps for some operations. Generic helper benchmarks (Get[T] / Set[T]) use the default JSON codec, so compare them against GetBytes / SetBytes (and GetString / SetString) when evaluating convenience vs raw-path performance.

Note: DynamoDB is intentionally omitted from these local charts because emulator-based numbers are not representative of real AWS latency.

NATS variants in these charts:

  • nats: per-key TTL semantics using a binary envelope (magic/expiresAt/value). This preserves per-key expiry parity with other drivers, with modest metadata overhead.
  • nats_bucket_ttl: bucket-level TTL mode (natscache.Config.BucketTTL), raw value path; faster but different expiry semantics.

Latency (ns/op)

Cache benchmark latency chart

Iterations (N)

Cache benchmark iteration chart

Allocated Bytes (B/op)

Cache benchmark bytes chart

Allocations (allocs/op)

Cache benchmark allocs chart

API reference

The API section below is autogenerated; do not edit between the markers. Bind request context with c.WithContext(ctx). Package-level typed helpers remain available alongside generic Cache methods.

API Index

Group Functions
Constructors NewFileStore · NewFileStoreWithConfig · NewMemoryStore · NewMemoryStoreWithConfig · NewNullStore · NewNullStoreWithConfig
Core Cache.WithContext · Driver · Inspector · NewCache · NewCacheWithTTL · Ready · Store
Driver Configs Shared BaseConfig · DynamoDB Config · Memcached Config · MySQL Config · NATS Config · Postgres Config · Redis Config · SQL Core Config · SQLite Config
Invalidation Cache.Pull · Delete · DeleteMany · Flush · PullBytes
Locking Acquire · Block · Lock · NewLockHandle · Release · TryLock · Unlock
Memoization NewMemoStore
Observability OnCacheOp · WithObserver
Other
Rate Limiting RateLimit
Read Through Cache.Remember · Cache.RememberStale · RememberBytes · RememberStaleBytes
Reads BatchGetBytes · Cache.Get · Cache.GetJSON · GetBytes · GetString · ListPage
Refresh Ahead Cache.RefreshAhead · Cache.RefreshAheadValueWithCodec · RefreshAheadBytes
Testing Helpers AssertCalled · AssertNotCalled · AssertTotal · Cache · Count · New · Reset · Total
Writes Add · BatchSetBytes · Cache.Set · Cache.SetJSON · Decrement · Increment · SetBytes · SetString

Examples assume ctx := context.Background() and c := cache.NewCache(cache.NewMemoryStore(ctx)) unless shown otherwise.

Constructors

NewFileStore

NewFileStore is a convenience for a filesystem-backed store.

ctx := context.Background()
store := cache.NewFileStore(ctx, "/tmp/my-cache")
fmt.Println(store.Driver()) // file

NewFileStoreWithConfig

NewFileStoreWithConfig builds a filesystem-backed store using explicit root config.

ctx := context.Background()
store := cache.NewFileStoreWithConfig(ctx, cache.StoreConfig{
	BaseConfig: cachecore.BaseConfig{
		EncryptionKey: []byte("01234567890123456789012345678901"),
		MaxValueBytes: 4096,
		Compression:   cache.CompressionGzip,
	},
	FileDir: "/tmp/my-cache",
})
fmt.Println(store.Driver()) // file

NewMemoryStore

NewMemoryStore is a convenience for an in-process store using defaults.

ctx := context.Background()
store := cache.NewMemoryStore(ctx)
fmt.Println(store.Driver()) // memory

NewMemoryStoreWithConfig

NewMemoryStoreWithConfig builds an in-process store using explicit root config.

ctx := context.Background()
store := cache.NewMemoryStoreWithConfig(ctx, cache.StoreConfig{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL:  30 * time.Second,
		Compression: cache.CompressionGzip,
	},
	MemoryCleanupInterval: 5 * time.Minute,
})
fmt.Println(store.Driver()) // memory

NewNullStore

NewNullStore is a no-op store useful for tests where caching should be disabled.

ctx := context.Background()
store := cache.NewNullStore(ctx)
fmt.Println(store.Driver()) // null

NewNullStoreWithConfig

NewNullStoreWithConfig builds a null store with shared wrappers (compression/encryption/limits).

ctx := context.Background()
store := cache.NewNullStoreWithConfig(ctx, cache.StoreConfig{
	BaseConfig: cachecore.BaseConfig{
		Compression:   cache.CompressionGzip,
		MaxValueBytes: 1024,
	},
})
fmt.Println(store.Driver()) // null

Core

Cache.WithContext

WithContext returns a derived cache handle that binds ctx to subsequent operations.

Driver

Driver reports the underlying store driver.

Inspector

Inspector returns the optional browsing interface for the underlying store.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
inspector, ok := c.Inspector()
fmt.Println(ok, inspector.Capabilities().CanList) // true true

NewCache

NewCache creates a cache facade bound to a concrete store. NewCache panics when store is nil because a cache cannot operate without its required backend.

ctx := context.Background()
s := cache.NewMemoryStore(ctx)
c := cache.NewCache(s)
fmt.Println(c.Driver()) // memory

NewCacheWithTTL

NewCacheWithTTL lets callers override the default TTL applied when ttl <= 0. NewCacheWithTTL panics when store is nil because accepting invalid wiring would defer failure to the first operation.

ctx := context.Background()
s := cache.NewMemoryStore(ctx)
c := cache.NewCacheWithTTL(s, 2*time.Minute)
fmt.Println(c.Driver(), c != nil) // memory true

Ready

Ready checks whether the underlying store is ready to serve requests.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
fmt.Println(c.Ready() == nil) // true

Store

Store returns the underlying store implementation.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
fmt.Println(c.Store().Driver()) // memory

Driver Configs

Optional backend config examples (compile-checked from generated examples and driver New(...) docs).

Shared cachecore.BaseConfig

Shared fields are embedded via cachecore.BaseConfig on every driver config:

  • DefaultTTL: defaults to 5*time.Minute when zero in all optional drivers
  • Prefix: defaults to "app" when empty in all optional drivers
  • Compression: gzip writes a versioned CMP1 envelope; the zero value leaves bytes uncompressed
  • MaxValueBytes: bounds writes and decoded reads; 0 disables the limit
  • EncryptionKey: AES-GCM writes a versioned ENC1 envelope; nil disables encryption
  • Increment and Decrement: bypass shaping so backend-native counters remain atomic

DynamoDB

Defaults:

  • Region: "us-east-1" when empty
  • Table: "cache_entries" when empty
  • DefaultTTL: 5*time.Minute when zero
  • Prefix: "app" when empty
  • Client: auto-created when nil (uses Region and optional Endpoint)
  • Endpoint: empty by default (normal AWS endpoint resolution)
ctx := context.Background()
store, err := dynamocache.New(ctx, dynamocache.Config{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL: 5 * time.Minute,
		Prefix:     "app",
	},
	Region: "us-east-1",
	Table:  "cache_entries",
})
if err != nil {
	panic(err)
}
fmt.Println(store.Driver()) // dynamo

Memcached

release them through io.Closer. Addresses are treated as a fixed peer set. A failed peer returns an error for its keys so locks never fail over to another peer.

Defaults:

  • Addresses: []string{"127.0.0.1:11211"} when empty
  • DefaultTTL: 5*time.Minute when zero
  • Prefix: "app" when empty
  • AllowServerFlush: false, unless every server is dedicated to this cache
store := memcachedcache.New(memcachedcache.Config{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL: 5 * time.Minute,
		Prefix:     "app",
	},
	Addresses: []string{"127.0.0.1:11211"},
})
fmt.Println(store.Driver()) // memcached

MySQL

Defaults:

  • DefaultTTL: 5*time.Minute when zero
  • Prefix: "app" when empty
  • Table: "cache_entries" when empty
  • DSN: required
store, err := mysqlcache.New(mysqlcache.Config{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL: 5 * time.Minute,
		Prefix:     "app",
	},
	DSN:   "user:pass@tcp(127.0.0.1:3306)/app?parseTime=true",
	Table: "cache_entries",
})
if err != nil {
	panic(err)
}
fmt.Println(store.Driver()) // sql

NATS

Defaults:

  • DefaultTTL: 5*time.Minute when zero
  • Prefix: "app" when empty
  • BucketTTL: false (TTL enforced in value envelope metadata)
  • KeyValue: required for real operations (nil allowed, operations return errors)
var kv natscache.KeyValue // provided by your NATS setup
store := natscache.New(natscache.Config{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL: 5 * time.Minute,
		Prefix:     "app",
	},
	KeyValue:  kv,
	BucketTTL: false,
})
fmt.Println(store.Driver()) // nats

Postgres

Defaults:

  • DefaultTTL: 5*time.Minute when zero
  • Prefix: "app" when empty
  • Table: "cache_entries" when empty
  • DSN: required
store, err := postgrescache.New(postgrescache.Config{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL: 5 * time.Minute,
		Prefix:     "app",
	},
	DSN:   "postgres://user:pass@localhost:5432/app?sslmode=disable",
	Table: "cache_entries",
})
if err != nil {
	panic(err)
}
fmt.Println(store.Driver()) // sql

Redis

Defaults:

  • DefaultTTL: 5*time.Minute when zero
  • Prefix: "app" when empty
  • Addr: empty by default (no client auto-created unless Addr is set)
  • Client: optional advanced override (takes precedence when set)
  • Client overrides must also implement Eval to use ownership-safe locking
  • If neither Client nor Addr is set, operations return errors until a client is provided
store := rediscache.New(rediscache.Config{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL: 5 * time.Minute,
		Prefix:     "app",
	},
	Addr: "127.0.0.1:6379",
})
fmt.Println(store.Driver()) // redis

SQL Core (advanced/shared implementation)

the store and can release its database pool through io.Closer.

Defaults:

  • Table: "cache_entries" when empty
  • DefaultTTL: 5*time.Minute when zero
  • Prefix: "app" when empty
  • DriverName: required
  • DSN: required
store, err := sqlcore.New(sqlcore.Config{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL: 5 * time.Minute,
		Prefix:     "app",
	},
	DriverName: "sqlite",
	DSN:        "file::memory:?cache=shared",
	Table:      "cache_entries",
})
if err != nil {
	panic(err)
}
fmt.Println(store.Driver()) // sql

SQLite

Defaults:

  • DefaultTTL: 5*time.Minute when zero
  • Prefix: "app" when empty
  • Table: "cache_entries" when empty
  • DSN: required
store, err := sqlitecache.New(sqlitecache.Config{
	BaseConfig: cachecore.BaseConfig{
		DefaultTTL: 5 * time.Minute,
		Prefix:     "app",
	},
	DSN:   "file::memory:?cache=shared",
	Table: "cache_entries",
})
if err != nil {
	panic(err)
}
fmt.Println(store.Driver()) // sql

Invalidation

Cache.Pull

Pull reads a typed JSON value and then deletes its key. The operations are separate.

type Token struct { Value string `json:"value"` }
ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
_ = c.Set("preview:banner:42", Token{Value: "abc"}, time.Minute)
tok, ok, err := c.Pull[Token]("preview:banner:42")
fmt.Println(err == nil, ok, tok.Value) // true true abc

Delete

Delete removes a single key.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
_ = c.SetBytes("a", []byte("1"), time.Minute)
fmt.Println(c.Delete("a") == nil) // true

DeleteMany

DeleteMany removes multiple keys.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
fmt.Println(c.DeleteMany("a", "b") == nil) // true

Flush

Flush clears all keys for this store scope.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
_ = c.SetBytes("a", []byte("1"), time.Minute)
fmt.Println(c.Flush() == nil) // true

Pull

Pull reads a typed JSON value and then deletes its key. The operations are separate. It remains available for compatibility; new code can use Cache.Pull.

PullBytes

PullBytes reads a value and then deletes its key. The operations are separate. Concurrent readers can receive the same value.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
_ = c.SetString("preview:banner:42", "abc", time.Minute)
body, ok, _ := c.PullBytes("preview:banner:42")
fmt.Println(ok, string(body)) // true abc

Locking

Acquire

Acquire attempts to acquire the lock once (non-blocking).

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
lock := c.NewLockHandle("job:sync", 10*time.Second)
locked, err := lock.Acquire()
fmt.Println(err == nil, locked) // true true

Block

Block waits up to timeout to acquire the lock, runs fn if acquired, then releases.

retryInterval <= 0 falls back to the cache default lock retry interval.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
lock := c.NewLockHandle("job:sync", 10*time.Second)
locked, err := lock.Block(500*time.Millisecond, 25*time.Millisecond, func() error {
	// do protected work
	return nil
})
fmt.Println(err == nil, locked) // true true

Lock

Lock waits until this Cache instance and the backend can begin a lock lifecycle or timeout elapses.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
locked, err := c.Lock("job:sync", 10*time.Second, time.Second)
fmt.Println(err == nil, locked) // true true
if locked {
	_ = c.Unlock("job:sync")
}

LockHandle.Get

Get acquires the lock once, runs fn if acquired, then releases automatically.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
lock := c.NewLockHandle("job:sync", 10*time.Second)
locked, err := lock.Get(func() error {
	// do protected work
	return nil
})
fmt.Println(err == nil, locked) // true true

NewLockHandle

NewLockHandle creates a reusable lock handle for a key/ttl pair.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
lock := c.NewLockHandle("job:sync", 10*time.Second)
locked, err := lock.Acquire()
fmt.Println(err == nil, locked) // true true
if locked {
	_ = lock.Release()
}

Release

Release unlocks the key if this handle previously acquired and still owns it.

It is safe to call multiple times; repeated calls become no-ops after the first successful release.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
lock := c.NewLockHandle("job:sync", 10*time.Second)
locked, _ := lock.Acquire()
if locked {
	_ = lock.Release()
}

TryLock

TryLock acquires a short-lived lock key when this Cache instance has no active lifecycle for it.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
locked, _ := c.TryLock("job:sync", 10*time.Second)
fmt.Println(locked) // true
if locked {
	_ = c.Unlock("job:sync")
}

Unlock

Unlock closes this Cache instance's lifecycle and releases the key only while it still owns the backend lock.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
locked, _ := c.TryLock("job:sync", 10*time.Second)
if locked {
	_ = c.Unlock("job:sync")
}

Memoization

NewMemoStore

NewMemoStore decorates a backing store with a short-lived local read snapshot. Create one per request or unit of work. It holds up to 256 hits or misses, each for at most one second from the start of its backing read. Those reads can outlive the value's backing TTL or miss a write made through another handle. Use the backing store directly when you need backend TTL or immediate visibility. Writes through the decorator invalidate the memoized keys. The caller retains ownership of the backing store. NewMemoStore panics when the store is nil.

ctx := context.Background()
base := cache.NewMemoryStore(ctx)
memo := cache.NewMemoStore(base)
c := cache.NewCache(memo)
fmt.Println(c.Driver()) // memory

Observability

OnCacheOp

OnCacheOp implements Observer.

obs := cache.ObserverFunc(func(ctx context.Context, event cache.CacheOpEvent) {
	fmt.Println(event.Operation, event.Key, event.Hit, event.Err == nil, event.Driver)
	_ = ctx
	_ = event.Duration
})
obs.OnCacheOp(context.Background(), cache.CacheOpEvent{Operation: "get", Key: "user:42", Hit: true, Duration: time.Millisecond, Driver: cachecore.DriverMemory})

WithObserver

WithObserver attaches an observer to receive operation events. WithObserver mutates c for backward compatibility and must be called during construction, before c is used concurrently. The observer must be safe for concurrent callbacks.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
c = c.WithObserver(cache.ObserverFunc(func(ctx context.Context, event cache.CacheOpEvent) {
	// See docs/production-guide.md for a real metrics recipe.
	fmt.Println(event.Operation, event.Driver, event.Hit, event.Err == nil)
	_ = ctx
	_ = event.Key
	_ = event.Duration
}))
_, _, _ = c.GetBytes("profile:42")

Other

LockHandle.WithContext

WithContext returns a derived handle that shares lock ownership state with l.

Rate Limiting

RateLimit

RateLimit increments a fixed-window counter and returns allowance metadata.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
res, err := c.RateLimit("rl:api:ip:1.2.3.4", 100, time.Minute)
fmt.Println(err == nil, res.Allowed, res.Count, res.Remaining, !res.ResetAt.IsZero())
// Output: true true 1 99 true

Read Through

Cache.Remember

Remember is the ergonomic, typed remember helper using JSON encoding by default.

type Profile struct { Name string `json:"name"` }
ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
profile, err := c.Remember("profile:42", time.Minute, func() (Profile, error) {
	return Profile{Name: "Ada"}, nil
})
fmt.Println(err == nil, profile.Name) // true Ada

Cache.RememberStale

RememberStale returns a typed value with stale fallback semantics using JSON encoding by default.

type Profile struct { Name string `json:"name"` }
ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
profile, usedStale, err := c.RememberStale("profile:42", time.Minute, 10*time.Minute, func() (Profile, error) {
	return Profile{Name: "Ada"}, nil
})
fmt.Println(err == nil, usedStale, profile.Name) // true false Ada

Remember

Remember is the ergonomic, typed remember helper using JSON encoding by default. It remains available for compatibility; new code can use Cache.Remember.

RememberBytes

RememberBytes returns a cached value or computes and stores it on a miss. Concurrent misses can each run the callback.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
data, err := c.RememberBytes("dashboard:summary", time.Minute, func() ([]byte, error) {
	return []byte("payload"), nil
})
fmt.Println(err == nil, string(data)) // true payload

RememberStale

RememberStale returns a typed value with stale fallback semantics using JSON encoding by default. It remains available for compatibility; new code can use Cache.RememberStale.

RememberStaleBytes

RememberStaleBytes returns a fresh value when available, otherwise computes and caches it. If computing fails and a stale value exists, it returns the stale value. The returned bool is true when a stale fallback was used.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
body, usedStale, err := c.RememberStaleBytes("profile:42", time.Minute, 10*time.Minute, func() ([]byte, error) {
	return []byte(`{"name":"Ada"}`), nil
})
fmt.Println(err == nil, usedStale, len(body) > 0)

Reads

BatchGetBytes

BatchGetBytes returns all found values for the provided keys. Missing keys are omitted from the returned map. Reads run individually.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
_ = c.SetBytes("a", []byte("1"), time.Minute)
_ = c.SetBytes("b", []byte("2"), time.Minute)
values, err := c.BatchGetBytes("a", "b", "missing")
fmt.Println(err == nil, string(values["a"]), string(values["b"])) // true 1 2

Cache.Get

Get returns a typed value for key using the default codec (JSON) when present.

type Profile struct { Name string `json:"name"` }
ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
_ = c.Set("profile:42", Profile{Name: "Ada"}, time.Minute)
_ = c.Set("settings:mode", "dark", time.Minute)
profile, ok, err := c.Get[Profile]("profile:42")
mode, ok2, err2 := c.Get[string]("settings:mode")
fmt.Println(err == nil, ok, profile.Name, err2 == nil, ok2, mode) // true true Ada true true dark

Cache.GetJSON

GetJSON decodes a JSON value into T when key exists.

type Profile struct { Name string `json:"name"` }
ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
_ = c.SetJSON("profile:42", Profile{Name: "Ada"}, time.Minute)
profile, ok, err := c.GetJSON[Profile]("profile:42")
fmt.Println(err == nil, ok, profile.Name) // true true Ada

Get

Get returns a typed value for key using the default codec (JSON) when present. It remains available for compatibility; new code can use Cache.Get.

GetBytes

GetBytes returns raw bytes for key when present.

ctx := context.Background()
s := cache.NewMemoryStore(ctx)
c := cache.NewCache(s)
_ = c.SetBytes("user:42", []byte("Ada"), 0)
value, ok, _ := c.GetBytes("user:42")
fmt.Println(ok, string(value)) // true Ada

GetJSON

GetJSON decodes a JSON value into T when key exists. It remains available for compatibility; new code can use Cache.GetJSON.

GetString

GetString returns a UTF-8 string value for key when present.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
_ = c.SetString("user:42:name", "Ada", 0)
name, ok, _ := c.GetString("user:42:name")
fmt.Println(ok, name) // true Ada

ListPage

ListPage lists cache entries from an inspector-capable store.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
_ = c.SetString("profile:1", "Ada", time.Minute)
_ = c.SetString("profile:2", "Grace", time.Minute)
page, _ := cache.ListPage(ctx, c, cachecore.ListPageOptions{
	Query: "profile:",
	Limit: 10,
})
fmt.Println(len(page.Entries), page.Entries[0].Key) // 2 profile:1

Refresh Ahead

Cache.RefreshAhead

RefreshAhead returns a typed value and refreshes asynchronously when near expiry.

type Summary struct { Text string `json:"text"` }
ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
s, err := c.RefreshAhead("dashboard:summary", time.Minute, 10*time.Second, func() (Summary, error) {
	return Summary{Text: "ok"}, nil
})
fmt.Println(err == nil, s.Text) // true ok

Cache.RefreshAheadValueWithCodec

RefreshAheadValueWithCodec allows custom encoding/decoding for typed refresh-ahead operations.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
codec := cache.ValueCodec[string]{
	Encode: func(value string) ([]byte, error) { return []byte(value), nil },
	Decode: func(body []byte) (string, error) { return string(body), nil },
}
value, err := c.RefreshAheadValueWithCodec("status", time.Minute, 10*time.Second, func() (string, error) {
	return "ready", nil
}, codec)
fmt.Println(err == nil, value)
// true ready

RefreshAhead

RefreshAhead returns a typed value and refreshes asynchronously when near expiry. It remains available for compatibility; new code can use Cache.RefreshAhead.

RefreshAheadBytes

RefreshAheadBytes returns cached value immediately and refreshes asynchronously when near expiry. On miss, it computes and stores synchronously.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
body, err := c.RefreshAheadBytes("dashboard:summary", time.Minute, 10*time.Second, func() ([]byte, error) {
	return []byte("payload"), nil
})
fmt.Println(err == nil, len(body) > 0) // true true

RefreshAheadValueWithCodec

RefreshAheadValueWithCodec allows custom encoding/decoding for typed refresh-ahead operations. It remains available for compatibility; new code can use Cache.RefreshAheadValueWithCodec.

Testing Helpers

AssertCalled

AssertCalled verifies key was touched by op the expected number of times.

f := cachefake.New()
c := f.Cache()
_ = c.SetString("settings:mode", "dark", 0)
t := &testing.T{}
f.AssertCalled(t, cachefake.OpSet, "settings:mode", 1)

AssertNotCalled

AssertNotCalled ensures key was never touched by op.

f := cachefake.New()
t := &testing.T{}
f.AssertNotCalled(t, cachefake.OpDelete, "settings:mode")

AssertTotal

AssertTotal ensures the total call count for an op matches times.

f := cachefake.New()
c := f.Cache()
_ = c.Delete("a")
_ = c.Delete("b")
t := &testing.T{}
f.AssertTotal(t, cachefake.OpDelete, 2)

Cache

Cache returns the cache facade to inject into code under test.

f := cachefake.New()
c := f.Cache()
_, _, _ = c.GetBytes("settings:mode")

Count

Count returns calls for op+key.

f := cachefake.New()
c := f.Cache()
_ = c.SetString("settings:mode", "dark", 0)
n := f.Count(cachefake.OpSet, "settings:mode")
_ = n

New

New creates a Fake using an in-memory store.

f := cachefake.New()
c := f.Cache()
_ = c.SetString("settings:mode", "dark", 0)

Reset

Reset clears recorded counts.

f := cachefake.New()
_ = f.Cache().SetString("settings:mode", "dark", 0)
f.Reset()

Total

Total returns total calls for an op across keys.

f := cachefake.New()
c := f.Cache()
_ = c.Delete("a")
_ = c.Delete("b")
n := f.Total(cachefake.OpDelete)
_ = n

Writes

Add

Add writes value only when key is not already present.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
created, _ := c.Add("boot:seeded", []byte("1"), time.Hour)
fmt.Println(created) // true

BatchSetBytes

BatchSetBytes writes each key individually using a shared TTL. A write failure can leave an arbitrary subset of keys updated.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
err := c.BatchSetBytes(map[string][]byte{
	"a": []byte("1"),
	"b": []byte("2"),
}, time.Minute)
fmt.Println(err == nil) // true

Cache.Set

Set encodes value with the default codec (JSON) and writes it to key.

type Settings struct { Enabled bool `json:"enabled"` }
ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
err := c.Set("settings:alerts", Settings{Enabled: true}, time.Minute)
err2 := c.Set("settings:mode", "dark", time.Minute)
fmt.Println(err == nil, err2 == nil) // true true

Cache.SetJSON

SetJSON encodes value as JSON and writes it to key.

type Settings struct { Enabled bool `json:"enabled"` }
ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
err := c.SetJSON("settings:alerts", Settings{Enabled: true}, time.Minute)
fmt.Println(err == nil) // true

Decrement

Decrement decrements a numeric value and returns the result.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
val, _ := c.Decrement("rate:login:42", 1, time.Minute)
fmt.Println(val) // -1

Increment

Increment increments a numeric value and returns the result.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
val, _ := c.Increment("rate:login:42", 1, time.Minute)
fmt.Println(val) // 1

Set

Set encodes value with the default codec (JSON) and writes it to key. It remains available for compatibility; new code can use Cache.Set.

SetBytes

SetBytes writes raw bytes to key.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
fmt.Println(c.SetBytes("token", []byte("abc"), time.Minute) == nil) // true

SetJSON

SetJSON encodes value as JSON and writes it to key. It remains available for compatibility; new code can use Cache.SetJSON.

SetString

SetString writes a string value to key.

ctx := context.Background()
c := cache.NewCache(cache.NewMemoryStore(ctx))
fmt.Println(c.SetString("user:42:name", "Ada", time.Minute) == nil) // true

Development

make test                          # Test the root module
make vet                           # Vet the root module
make test-integration              # Test all drivers with Docker
make test-integration sqlitecache  # Test SQLite without Docker
make generate                      # Regenerate the README and runnable examples
make docs-watch                    # Refresh docs and test badges as source changes

Use make help to see the available targets. To refresh test badges once, run CACHE_LOCAL_SIBLINGS=1 go -C docs run ./readme/testcounts.

About

Go caching library with local, distributed, and SQL-backed drivers, plus typed helpers, locks, counters, and rate limits.

Topics

Resources

Security policy

Stars

6 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages