cache gives your services one cache API with multiple backend options. Swap drivers without refactoring.
What cache is
An explicit cache abstraction with a minimal Store interface and ergonomic Cache helpers. Drivers are chosen when you construct the store, so swapping backends is a dependency-injection change instead of a refactor.
Installation
go get github.com/goforj/cache
The generic method API requires Go 1.27 or newer. Projects on Go 1.26 or earlier can keep the root module at v0.4.0 and update independently versioned core, test, and driver modules that support their Go version.
Optional backends are separate modules. Install only what you use:
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
The PostgreSQL and SQLite drivers require Go 1.25 or newer. PostgreSQL uses pgx v5.11.0. The pgx update also discards pooled connections left in transactions during reset and uses the operating-system user when a PostgreSQL DSN omits a database user. Use an explicit DSN user when that default is not intended.
Supported Go versions
| Modules |
Minimum Go version |
Root cache module |
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 |
Documentation, examples, and integration tooling use Go 1.27 and can select newer dependency versions than the independently published drivers. Their dependency graph does not change a driver's published minimum.
Drivers
Each driver is thoroughly tested against the shared test suite using testcontainers or emulators where appropriate.
| Driver / Backend |
Mode |
Shared |
Durable |
TTL |
Counters |
Locks |
RateLimit |
Prefix |
Batch |
Shaping |
Notes |
|
No-op |
- |
- |
- |
- |
No-op |
No-op |
✓ |
✓ |
✓ |
Great for tests: cache calls are no-ops and never persist. |
|
Local filesystem |
- |
✓ |
✓ |
✓ |
Local |
Local |
- |
✓ |
✓ |
Simple durability on a single host; set StoreConfig.FileDir (or use NewFileStore). |
|
In-process |
- |
- |
✓ |
✓ |
Local |
Local |
- |
✓ |
✓ |
Fastest; per-process only, best for single-node or short-lived data. |
|
Networked |
✓ |
- |
✓ |
✓ |
Shared |
Shared |
✓ |
✓ |
✓ |
TTL resolution is 1s; configure addresses via memcachedcache.Config.Addresses. |
|
Networked |
✓ |
- |
✓ |
✓ |
Shared |
Shared |
✓ |
✓ |
✓ |
Full feature set; counters refresh TTL (Redis counter TTL granularity currently 1s). |
|
Networked |
✓ |
- |
✓ |
✓ |
Shared |
Shared |
✓ |
✓ |
✓ |
JetStream KV-backed driver; inject an existing bucket via natscache.Config.KeyValue. |
|
Networked |
✓ |
✓ |
✓ |
✓ |
Shared |
Shared |
✓ |
✓ |
✓ |
Backed by DynamoDB (supports localstack/dynamodb-local). |
|
Local / file |
- |
✓ |
✓ |
✓ |
Local |
Local |
✓ |
✓ |
✓ |
sqlitecache (via sqlcore); great for embedded/local durable cache. |
|
Networked |
✓ |
✓ |
✓ |
✓ |
Shared |
Shared |
✓ |
✓ |
✓ |
postgrescache (via sqlcore); good shared durable backend. |
|
Networked |
✓ |
✓ |
✓ |
✓ |
Shared |
Shared |
✓ |
✓ |
✓ |
mysqlcache (via sqlcore); good shared durable backend. |
Driver constructor quick examples
Use root constructors for in-process backends, and driver-module constructors for external backends.
Driver backends live in separate modules so applications only import/link the optional backend dependencies they actually use.
package main
import (
"context"
"fmt"
"time"
"github.com/goforj/cache"
"github.com/goforj/cache/cachecore"
"github.com/goforj/cache/driver/dynamocache"
"github.com/goforj/cache/driver/memcachedcache"
"github.com/goforj/cache/driver/mysqlcache"
"github.com/goforj/cache/driver/natscache"
"github.com/goforj/cache/driver/postgrescache"
"github.com/goforj/cache/driver/rediscache"
"github.com/goforj/cache/driver/sqlitecache"
)
func main() {
ctx := context.Background()
base := cachecore.BaseConfig{DefaultTTL: 5 * time.Minute, Prefix: "app"}
cache.NewMemoryStore(ctx) // in-process memory
cache.NewFileStore(ctx, "./cache-data") // local file-backed
cache.NewNullStore(ctx) // disabled / drop-only
// Redis (driver-owned connection config; no direct redis client required)
redisStore := rediscache.New(rediscache.Config{BaseConfig: base, Addr: "127.0.0.1:6379"})
_ = redisStore
// Memcached (one or more server addresses)
memcachedStore := memcachedcache.New(memcachedcache.Config{
BaseConfig: base,
Addresses: []string{"127.0.0.1:11211"},
})
_ = memcachedStore
// NATS JetStream KV (inject a bucket from your NATS setup)
var kv natscache.KeyValue // create via your NATS JetStream setup
natsStore := natscache.New(natscache.Config{BaseConfig: base, KeyValue: kv})
_ = natsStore
// DynamoDB (auto-creates client when Client is nil)
dynamoStore, err := dynamocache.New(ctx, dynamocache.Config{
BaseConfig: base,
Region: "us-east-1",
Table: "cache_entries",
})
fmt.Println(dynamoStore, err)
// SQLite (via sqlcore)
sqliteStore, err := sqlitecache.New(sqlitecache.Config{
BaseConfig: base,
DSN: "file::memory:?cache=shared",
Table: "cache_entries",
})
fmt.Println(sqliteStore, err)
// Postgres (via sqlcore)
postgresStore, err := postgrescache.New(postgrescache.Config{
BaseConfig: base,
DSN: "postgres://user:pass@127.0.0.1:5432/app?sslmode=disable",
Table: "cache_entries",
})
fmt.Println(postgresStore, err)
// MySQL (via sqlcore)
mysqlStore, err := mysqlcache.New(mysqlcache.Config{
BaseConfig: base,
DSN: "user:pass@tcp(127.0.0.1:3306)/app?parseTime=true",
Table: "cache_entries",
})
fmt.Println(mysqlStore, err)
}
Module Layout
Quick Start
import (
"context"
"fmt"
"time"
"github.com/goforj/cache"
"github.com/goforj/cache/cachecore"
"github.com/goforj/cache/driver/rediscache"
)
func main() {
ctx := context.Background()
store := cache.NewMemoryStoreWithConfig(ctx, cache.StoreConfig{
BaseConfig: cachecore.BaseConfig{DefaultTTL: 5 * time.Minute},
})
c := cache.NewCache(store)
type Profile struct { Name string `json:"name"` }
// Typed lifecycle (generic helpers): set -> get -> delete
_ = cache.Set(c, "user:42:profile", Profile{Name: "Ada"}, time.Minute)
profile, ok, err := cache.Get[Profile](c, "user:42:profile")
fmt.Println(err == nil, ok, profile.Name) // true true Ada
_ = c.Delete("user:42:profile")
// String lifecycle: set -> get -> delete
_ = c.SetString("settings:mode", "dark", time.Minute)
mode, ok, err := c.GetString("settings:mode")
fmt.Println(err == nil, ok, mode) // true true dark
_ = c.Delete("settings:mode")
// Remember pattern.
profile, err := cache.Remember[Profile](c, "user:42:profile", time.Minute, func() (Profile, error) {
return Profile{Name: "Ada"}, nil
})
fmt.Println(profile.Name) // Ada
// Switch to Redis (dependency injection, no code changes below).
store = rediscache.New(rediscache.Config{
BaseConfig: cachecore.BaseConfig{
Prefix: "app",
DefaultTTL: 5 * time.Minute,
},
Addr: "127.0.0.1:6379",
})
c = cache.NewCache(store)
}
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
Every root and optional driver honors the shared value-shaping fields:
CompressionGzip writes a versioned CMP1 envelope.
EncryptionKey writes an AES-GCM ENC1 envelope and requires a 16, 24, or 32 byte key.
MaxValueBytes bounds both writes and reads, including decompressed output; zero disables it and negative values are invalid.
- Backend-native counters remain raw so
Increment and Decrement stay atomic.
When compression and encryption are both enabled, the preserved on-disk/wire format is
CMP1(ENC1(plaintext)): encryption happens first and gzip is the outer envelope. Readers pass
unmarked legacy values through unchanged, so upgraded applications can read existing raw entries.