Docs/Data & infrastructure/Caching

Caching

Cache byte values in Fletch with cache.Cache across in-memory LRU, SQLite, Postgres, and Redis, with dev dashboard tracing and conformance tests.

github.com/fletchhq/fletch/cache

fletch/cachepkg.go.devfletch/cache/redispkg.go.devfletch/cache/postgrespkg.go.dev

Updated 2026-12-06 fletch docs show cache 6 min read

On this page

github.com/fletchhq/fletch/cache provides Fletch's byte-level cache.Cache contract along with bounded in-process memory and SQLite stores in the standard library. Shared multi-replica backends live in standalone cache/postgres and cache/redis modules so you can swap stores with one option.

Introduction

Most applications start on a single instance where a bounded in-process cache is fast and requires zero infrastructure. As soon as you deploy multiple replicas, you want a shared store—either Postgres if you already run it, or Redis/Valkey for lower latency—without rewriting every call site.

Fletch gives every app a 64 MiB in-memory cache by default (app.Cache()). Every backend implements the same four-method cache.Cache interface and never performs I/O in its constructor, so wiring a cache at startup never blocks boot or breaks tests.

Configuration

Pass a cache backend to fletch.New with fletch.WithCache. Wrap custom backends with fletch.ObserveCache if you want cache hits, misses, and writes to appear in the dev dashboard's request timeline.

app := fletch.New(
	fletch.WithCache(fletch.ObserveCache(
		cache.Memory(cache.WithMaxBytes(128<<20)),
	)),
)
app := fletch.New(
	fletch.WithCache(fletch.ObserveCache(
		cache.SQLite(db, cache.WithTable("app_cache")),
	)),
)
// Run postgres.SchemaSQL() in a migration or at startup first.
pgCache := pgcache.New(pool, pgcache.Prefix("app:"))

app := fletch.New(
	fletch.WithCache(fletch.ObserveCache(pgCache)),
)
rc := rediscache.New(
	rediscache.URL(os.Getenv("REDIS_URL")),
	rediscache.Prefix("app:"),
)
defer rc.Close()

app := fletch.New(
	fletch.WithCache(fletch.ObserveCache(rc)),
)

If you omit fletch.WithCache, Fletch configures cache.Memory() (64 MiB) and wraps it with fletch.ObserveCache automatically.

Core concepts

The cache.Cache contract

Every backend implements four methods:

type Cache interface {
	Get(ctx context.Context, key string) ([]byte, bool, error)
	Set(ctx context.Context, key string, val []byte, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
	Describe() Description
}
  • Get returns (val, true, nil) on a hit and (nil, false, nil) when the key is missing or expired.
  • Set stores a copy of val. A ttl of 0 or less means the entry never expires.
  • Delete removes key. Deleting a missing key returns nil.
  • Describe reports the provider name and redacted settings (secrets replaced with cache.Redacted) for fletch ax inspect.

Choosing a backend

Backend Module Shared across replicas Persistence Extra dependency
cache.Memory fletch/cache No (per process) No Stdlib only
cache.SQLite fletch/cache Single node (disk-backed) Yes App's *sql.DB
postgres.New fletch/cache/postgres Yes Lost on crash (UNLOGGED) pgx/v5
redis.New fletch/cache/redis Yes Configurable in Redis go-redis/v9

In-memory LRU (cache.Memory)

cache.Memory bounds total key and value bytes (cache.DefaultMaxBytes is 64 MiB) using CLOCK second-chance LRU eviction. When maxBytes is at least 1 MiB, keys are spread across 64 shards with per-shard read/write locks so concurrent hits do not wait on each other. Smaller bounds use a single shard so eviction order stays exact. Entries larger than maxBytes are skipped on Set.

SQLite (cache.SQLite)

cache.SQLite(db, opts...) stores entries in a table of an app-owned *sql.DB (default fletch_cache). It creates the table lazily on first use with CREATE TABLE IF NOT EXISTS and deletes expired rows on read. Table names must match ^[A-Za-z_][A-Za-z0-9_]*$.

Postgres (github.com/fletchhq/fletch/cache/postgres)

cache/postgres gives multi-replica apps a shared cache without running Redis. It accepts any postgres.DB (*pgxpool.Pool, pgx.Conn, or pgx.Tx). Create its table once using postgres.SchemaSQL(), which builds an UNLOGGED table and a partial index on expires_at. Skipping the write-ahead log makes cache writes much cheaper; as a trade-off, cache rows are cleared after a Postgres crash and are not copied to read replicas.

Expired rows are filtered out on Get, and you should call pgCache.Sweep(ctx) every few minutes (for example from a scheduled Quiver job) to delete dead rows across all prefixes:

removed, err := pgCache.Sweep(ctx)

Redis / Valkey (github.com/fletchhq/fletch/cache/redis)

cache/redis wraps go-redis/v9 and connects lazily on first use. Pass redis.URL(...) for redis:// or rediss:// connection strings; any explicit option passed after URL (Addr, Username, Password, DB, TLSConfig) takes precedence. Call rc.Close() during shutdown to release the connection pool. Passwords are automatically replaced with cache.Redacted in Describe().

Common tasks

Cache-aside reads with JSON

Read through app.Cache() in a service or handler, falling back to the database on a miss:

func (s *Service) GetProfile(ctx context.Context, userID string) (Profile, error) {
	key := "profile:" + userID
	if raw, ok, err := s.cache.Get(ctx, key); err == nil && ok {
		var p Profile
		if err := json.Unmarshal(raw, &p); err == nil {
			return p, nil
		}
	}

	p, err := s.loadProfileFromDB(ctx, userID)
	if err != nil {
		return Profile{}, err
	}

	if raw, err := json.Marshal(p); err == nil {
		_ = s.cache.Set(ctx, key, raw, 5*time.Minute)
	}
	return p, nil
}

When a profile updates, call s.cache.Delete(ctx, "profile:"+userID) to invalidate the cached copy.

Allocation-free reads with cache.AppendGet

On hot paths that read many cached values in a loop, reuse a caller-owned byte buffer with cache.AppendGet. Backends that implement cache.Appender (such as cache.Memory) copy directly into dst without allocating a slice per hit; other backends fall back to Get.

buf := make([]byte, 0, 4096)
for _, id := range ids {
	buf = buf[:0]
	var ok bool
	var err error
	buf, ok, err = cache.AppendGet(ctx, c, buf, "item:"+id)
	if err != nil {
		return err
	}
	if ok {
		handleBytes(buf)
	}
}

Observing cache operations in the dev dashboard

Wrap any custom cache passed to fletch.WithCache with fletch.ObserveCache(c). When the dev dashboard is running, cache Get, Set, and Delete calls appear as spans correlated by request_id in the Request Detail drawer and at GET /api/spans?kind=cache. Outside dev mode, the wrapper adds zero overhead.

c := fletch.ObserveCache(rediscache.New(
	rediscache.Addr("127.0.0.1:6379"),
	rediscache.Prefix("shop:"),
))
app := fletch.New(fletch.WithCache(c))

Testing a custom backend with cachetest.Run

If you write your own cache.Cache implementation, verify its contract with github.com/fletchhq/fletch/cache/cachetest. cachetest.Run supplies a fresh virtual clock to every subtest and checks Set/Get, empty and binary values, defensive byte copies, overwrites, deletes, TTL expiry, TTL resets on overwrite, canceled contexts, concurrent access, and secret redaction in Describe().

package mycache_test

import (
	"testing"
	"time"

	"github.com/fletchhq/fletch/cache"
	"github.com/fletchhq/fletch/cache/cachetest"
)

func TestMyCacheConformance(t *testing.T) {
	cachetest.Run(t, func(t *testing.T, now func() time.Time) cache.Cache {
		return NewMyCache(WithClock(now))
	})
}

Reference

Core package (github.com/fletchhq/fletch/cache)

Symbol Role
Cache Interface (Get, Set, Delete, Describe).
Appender Optional interface (AppendGet(ctx, dst, key)) for zero-allocation reads.
AppendGet(ctx, c, dst, key) Appends a cached value to dst via Appender when supported, or Get otherwise.
Memory(opts ...MemoryOption) Cache Bounded in-process sharded CLOCK-LRU cache.
WithMaxBytes(n int64) Bounds total key + value bytes for Memory. Default DefaultMaxBytes (64 << 20).
WithClock(now func() time.Time) Overrides the expiry clock for Memory tests.
SQLite(db *sql.DB, opts ...SQLiteOption) Cache Table-backed cache over an app-owned *sql.DB.
WithTable(name string) Sets the SQLite cache table name. Default "fletch_cache".
WithSQLiteClock(now func() time.Time) Overrides the expiry clock for SQLite tests.
Description, Redacted AX inspection metadata and secret redaction sentinel ("[redacted]").

App integration, Redis, Postgres, and test suite

Symbol Package Role
WithCache(c cache.Cache) Option fletch Configures the app's cache (read via app.Cache()).
ObserveCache(c cache.Cache) cache.Cache fletch Wraps a cache to emit dev dashboard request-timeline spans.
New(opts ...Option) *Cache cache/redis Creates a Redis/Valkey cache (URL, Addr, Username, Password, DB, Prefix, TLSConfig, Close).
New(db DB, opts ...Option) *Cache cache/postgres Creates a Postgres UNLOGGED table cache (SchemaSQL, Prefix, Clock, Sweep).
Run(t, newCache) cache/cachetest Conformance test suite for any cache.Cache implementation.