redcache

package module
v0.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

redcache

Build CodeQL Govulncheck OpenSSF Scorecard Go Reference Go Version Latest Release Go Report Card codecov License

A typed cache-aside for Redis, built on the rueidis client. It combines rueidis client-side caching with distributed SET NX locking so that, across every process, only one caller populates a missing key while the rest wait on the invalidation push. A single Cache serves every key and value type: each operation infers K and V from its arguments.

Features

  • Per-operation key and value types — one JSON-backed Cache stores different Go types under keys of different Go types; K and V are inferred per call.
  • Stampede protection — in-process leader/follower coordination plus a distributed SET NX lock-and-wait, so a single caller runs your loader per key and the rest wait on the invalidation rather than piling onto the origin.
  • Client-side caching — rueidis client-side cache with Redis invalidation messages cuts round trips and unblocks waiters the moment the value lands.
  • Multi-key batching — GetMulti and the other multi-key calls send each phase as one pipeline; in cluster mode rueidis splits it per node and runs the nodes in parallel.
  • Refresh-ahead + XFetch — optional background refresh of stale-but-valid entries, with XFetch-style probabilistic early expiration to smear reload moments across the keyspace.
  • Write-through priming — Set / ForceSet / Touch (and their multi variants) populate or extend entries on every subscribed client without a read-through miss.
  • Typed keys and values — pluggable Codec and KeyCodec; per-key partial failures surface as *BatchKeyError[K].
  • Pluggable metrics — a Metrics interface for hits/misses, lock contention, lock-wait duration, and refresh events.

Requirements

  • Go 1.27+
  • Redis 7+ with RESP3 and client-side caching (tracking) enabled

RESP3 client-side caching is load-bearing, not optional: redcache wakes waiters through Redis invalidation pushes. Without RESP3 (or with tracking disabled) there are no pushes — waiters fall back to jittered polling until the lock TTL, raising tail latency and Redis read traffic under contention.

Installation

go get github.com/dcbickfo/redcache

Runnable examples

Standalone examples live under examples/. They compile with the module and can be run directly against a local Redis:

go run ./examples/string-cache
go run ./examples/typed-cache
go run ./examples/metrics

Set REDIS_ADDR to point them at a non-default Redis address.

Migrating from v0.3.x

v0.4 requires Go 1.27 and moves both type parameters from cache construction to the operations (Go 1.27 generic methods). Cache is no longer generic:

// v0.3.x
users  := redcache.NewString[User](conn, redcache.JSONCodec[User]{})
orders := redcache.New[OrderID, Order](conn, orderIDCodec, redcache.JSONCodec[Order]{})

// v0.4 — one cache, K and V inferred per call
cache := redcache.New(conn, redcache.JSONCodec{})
user, err  := cache.Get(ctx, ttl, "u-1", loadUser)      // K=string, V=User
order, err := cache.Get(ctx, ttl, OrderID(7), loadOrder) // K=OrderID, V=Order
profile, ok, err := cache.Peek[string, Profile](ctx, ttl, profileKey)

New(conn, valCodec) uses StringKeyCodec, which accepts string, any type with underlying type string, and encoding.TextMarshaler. For other key types use NewKeyed(conn, keyCodec, valCodec); KeyCodecFunc[K] still adapts a typed function. Codec[V] and KeyCodec[K] become Codec and KeyCodec (their methods take any); JSONCodec[V]{} becomes JSONCodec{}.

There is no interface form anymore — generic methods cannot satisfy Go interfaces — so code that depended on the Cache[K, V] interface now takes *redcache.Cache. For tests, redcache.OpenMemory() returns a Conn backed by an in-process map; redcachetest is removed:

// v0.3.x
func NewUserService(c redcache.Cache[string, User]) *UserService
svc := NewUserService(redcachetest.New[string, User]())

// v0.4
func NewUserService(c *redcache.Cache) *UserService
svc := NewUserService(redcache.New(redcache.OpenMemory(), redcache.JSONCodec{}))

JSONCodec keeps encoding/json (v1) semantics, so stored payloads are unchanged. JSONV2Codec is new and opts in to encoding/json/v2 defaults.

Quickstart

Open builds a Conn that owns a rueidis client. New constructs a Cache with one value codec (string-ish keys by default). Get infers its key type from the key and its value type from the loader, which runs only on a miss and only on one caller per key.

package main

import (
    "context"
    "log"
    "time"

    "github.com/redis/rueidis"

    "github.com/dcbickfo/redcache"
)

type User struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

func main() {
    conn, err := redcache.Open(
        rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
        redcache.WithLockTTL(5*time.Second),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    cache := redcache.New(conn, redcache.JSONCodec{})

    ctx := context.Background()

    // Get-with-loader: fn runs only on a cache miss, and only on one caller
    // per key across all processes. The loader receives the key being missed.
    u, err := cache.Get(ctx, time.Minute, "u-123",
        func(ctx context.Context, key string) (User, error) {
            // load from the database / upstream service
            return User{ID: "u-123", Name: "alice"}, nil
        },
    )
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("user: %+v", u)
}

Absence semantics are the caller's to own — there is no ErrNotFound sentinel. Use a *T, sql.Null[T], or a domain sentinel inside V to cache "not found" and avoid cache penetration.

GetMulti follows the same pattern in batch: it returns the cached values and calls the loader once with just the missing keys. The loader must return a value for every key it is given; an omitted key fails the call with ErrMissingValue.

users, err := cache.GetMulti(ctx, time.Minute, []string{"u-1", "u-2", "u-3"},
    func(ctx context.Context, missing []string) (map[string]User, error) {
        out := make(map[string]User, len(missing))
        // load the missing keys in one round trip
        for _, id := range missing {
            out[id] = User{ID: id}
        }
        return out, nil
    },
)

Peek is a read-only, client-side-cached lookup — no loader, no lock. It returns (value, true, nil) on a cached hit and (zero, false, nil) on a miss (or when the key currently holds a lock value), for warm-cache checks without populating:

u, ok, err := cache.Peek[string, User](ctx, time.Minute, "u-123")
// ok == false means not currently cached; Peek never runs your loader.

Write-through with Set

Set takes a per-call write lock on the key, runs your callback, and writes the callback's value under that lock; SetMulti does the same for a batch. Use it to update the source of truth and the cache together:

err := cache.Set(ctx, time.Minute, "u-123",
    func(ctx context.Context, key string) (User, error) {
        return db.UpdateUser(ctx, key) // write to the database, return the new value
    },
)

Restore-on-error precondition. If the callback returns an error, Set puts the prior cached value back with the remaining TTL captured when Set took the key (not reduced by the callback's run time); a key with no prior value is deleted. If another writer replaced the lock in the meantime, that writer's value is kept, and if Redis is unreachable the lock stays until LockTTL expires. Restoring is only correct when a failed callback did not change the source of truth. If the callback can commit and then return an error (a timeout waiting for the acknowledgement of a write that did land), the restored value is stale. Make such callbacks return success once the write is committed, or follow a failed Set with Del so the next Get reloads. A callback that panics is rolled back the same way before the panic continues, so a caller that recovers (an HTTP server, for example) does not leave the key locked.

ErrLockLost. The write lock is held for LockTTL and is not extended while your callback runs. Set returns ErrLockLost (test with errors.Is; SetMulti wraps it in a *BatchKeyError per key) when the lock was removed or expired before the value was written: a concurrent ForceSet or Del took the key, or the callback outlasted LockTTL. The callback's value was not written and the key holds whatever the other writer left, so the source of truth and the cache may disagree. Do not blindly retry a callback with side effects; reconcile with Del (the next Get reloads from the source) and size LockTTL above your slowest write callback.

Typed keys

Keys whose underlying type is string (e.g. type UserID string) and types implementing encoding.TextMarshaler work with New as-is. For anything else, construct the cache with NewKeyed, a KeyCodec, and a value Codec; KeyCodecFunc[K] adapts a plain function into a KeyCodec that accepts only K.

type UserID int64

userIDCodec := redcache.KeyCodecFunc[UserID](func(id UserID) (string, error) {
    return fmt.Sprintf("user:%d", id), nil
})

conn, err := redcache.Open(
    rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
)
if err != nil {
    log.Fatal(err)
}
defer conn.Close()

cache := redcache.NewKeyed(conn, userIDCodec, redcache.JSONCodec{})

u, err := cache.Get(ctx, time.Minute, UserID(123),
    func(ctx context.Context, id UserID) (User, error) {
        return loadUser(ctx, id)
    },
)

The key codec must be deterministic, concurrent-safe, produce a non-empty key, and encode distinct logical keys to distinct Redis keys. Multi-key operations reject typed-key collisions before touching Redis.

Raw bytes

NewBytes constructs a zero-copy Cache for opaque []byte payloads. The decoded slice aliases the cache's borrowed read buffer; do not mutate or retain it past the callback. Copy it out if you need an owned value.

conn, err := redcache.Open(
    rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
)
if err != nil {
    log.Fatal(err)
}
defer conn.Close()

cache := redcache.NewBytes(conn)

b, err := cache.Get(ctx, time.Minute, "blob:42",
    func(ctx context.Context, key string) ([]byte, error) {
        return loadBlob(ctx, key)
    },
)
// b aliases borrowed memory — copy it before retaining or mutating.

Codecs

A Codec maps operation values to and from the stored envelope payload; a KeyCodec maps keys to Redis key strings. Both must be concurrent-safe. Decode receives a pointer to the operation's value type, like json.Unmarshal. A codec that does not support that type returns an error.

Codec For Allocation behavior
JSONCodec any JSON-supported value Encode/Decode via encoding/json (v1 semantics); decoded values are caller-owned.
JSONV2Codec any JSON-supported value encoding/json/v2: nil slices/maps encode as []/{}, case-sensitive field matching, duplicate names rejected. Changes the stored form of nil containers relative to JSONCodec.
StringCodec V = string Identity for immutable strings; safe to retain.
UnsafeBytesCodec V = []byte Zero-copy. The decoded slice aliases borrowed library memory; do not mutate or retain it past the call.
StringKeyCodec string, ~string, encoding.TextMarshaler Default key codec. String-underlying keys take the zero-copy multi-key fast path.
KeyCodecFunc[K] exactly K Adapts func(K) (string, error) into a KeyCodec; other key types are rejected.

JSONCodec returns owned decoded values, and StringCodec returns immutable strings that are safe to retain. UnsafeBytesCodec skips the copy, so its decoded []byte borrows the cache's internal buffer and must not be mutated or retained. A slice returned by any codec's Encode is also owned by the library after the call.

Decode failures on read are returned wrapped with redcache.ErrDecode (errors.Is-checkable). The library does not auto-evict on a decode failure; the caller decides whether to log, Del, or retry.

Options

Construction takes functional options. They are applied in order; later wins.

Option Default Description
WithLockTTL(d) 10s Bounds how long a lock survives without its holder (the holder extends it every LockTTL/3 while its loader runs, so loaders may take longer than LockTTL) and how long callers wait for one. Values below 100ms are rejected.
WithLogger(l) slog.Default() Logger for errors and debug output. Must be concurrent-safe.
WithMetrics(m) NoopMetrics{} Observability sink. Runs on the hot path; must be concurrent-safe.
WithLockPrefix(p) __redcache:lock: Prefix tagged onto in-Redis lock values so reads recognise a lock as a miss.
WithRefreshLockPrefix(p) __redcache:refresh: Prefix for refresh-ahead dedup keys.
WithRefreshAfterFraction(f) 0 (disabled) Enables refresh-ahead. Reads with low remaining TTL may trigger a background refresh. Must be in [0, 1).
WithRefreshBeta(b) 0 (XFetch off) Enables XFetch probabilistic sampling within the refresh window, weighted by recorded compute time. 1.0 matches canonical XFetch.
WithRefreshTimeout(d) data ttl Bounds how long a refresh-ahead callback may run. Decoupled from LockTTL.
WithRefreshWorkers(n) 4 Refresh worker pool size.
WithRefreshQueueSize(n) 64 Pending-refresh queue capacity; over-full drops silently and the stale value keeps serving.
WithClientBuilder(b) rueidis.NewClient Overrides how the internal client is built, including for tests.

Refresh-ahead and XFetch

Set WithRefreshAfterFraction to enable background refreshes. When a Get/GetMulti returns a value whose remaining TTL has crossed the configured threshold, the stale value is returned immediately and a background worker repopulates the entry. Distributed and local dedup ensure only one refresh runs per key.

conn, err := redcache.Open(
    rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
    redcache.WithLockTTL(5*time.Second),
    redcache.WithRefreshAfterFraction(0.8), // refresh once 80% of TTL has elapsed
    redcache.WithRefreshTimeout(20*time.Second),
    redcache.WithRefreshWorkers(4),
    redcache.WithRefreshQueueSize(64),
)
if err != nil {
    log.Fatal(err)
}
defer conn.Close()

cache := redcache.New(conn, redcache.JSONCodec{})
XFetch probabilistic refresh

Set WithRefreshBeta(b) with b > 0 to add the XFetch sampling layer on top of the floor. Below the floor, each read fires a refresh with probability proportional to how close the value is to expiry, weighted by how long the previous value took to compute. Slow-to-compute values get more headroom and refresh earlier; cheap values defer until closer to expiry. This smooths refresh load instead of bunching it at the floor crossing. 1.0 matches the canonical XFetch beta (Vattani et al.); for multi-key writes the recorded compute time is divided evenly across the returned values. That is an approximation: if one key in a batch dominates loader time and per-key XFetch precision matters, split that workload into separate Get calls or smaller GetMulti groups.

Decoupled refresh budget

By default WithRefreshTimeout is the data ttl passed to Get/GetMulti, not LockTTL. This matters: the refresh callback's compute budget is independent of how long the lock is held. A refresh function that legitimately takes 20s is no longer silently cancelled by a 10s LockTTL. The refresh lock itself still uses LockTTL, and the back-write that records a slow-but-successful result is decoupled from the timeout so a successful-but-slow refresh keeps its write.

Value envelope and rollback

Values are stored with a small envelope (__redcache:v1:<delta_ns>:<payload>) capturing the compute time XFetch needs. Reads transparently unwrap it, and legacy un-enveloped values are served with delta=0, falling back to plain floor-based refresh.

Rollback warning: if a deployment writes values under the enveloped format and then rolls back to a pre-envelope release, those older clients will return the raw envelope string as the user value. Flush affected keys (or run a full cache invalidation) before rolling back.

Comparison to rueidisaside

rueidis already ships rueidisaside and rueidislock, and the core lock-and-wait stampede technique is shared between them and redcache: one caller wins a distributed lock, populates the key, and everyone else waits on the client-side-cache invalidation. If that single-key, single-value-type contract is all you need, rueidisaside is an excellent, well-maintained choice and you should reach for it first.

redcache adds, on top of that shared foundation:

  • GetMulti with cluster-aware batching — multi-key reads and writes pipelined, split per cluster node by rueidis.
  • Refresh-ahead + XFetch — probabilistic early refresh of stale-but-valid entries, decoupling reload latency from request latency.
  • Typed keys, not just values — a KeyCodec maps a domain key type to the Redis key, and multi-key write failures come back as a typed, per-key *BatchKeyError[K].
  • Write-through priming — Set / ForceSet / Touch (and multi variants) populate or extend entries without a read-through miss. This is the hardest piece for rueidisaside to absorb rather than just a missing feature: rueidisaside claims only missing keys, with a single per-client placeholder and no value backup, whereas Set overwrites an already-live value under a per-call lock token and restores the prior value if the write fails. In-place locking, per-call lock identity, and a backup/restore path are structural to redcache's model, not a flag on the read-miss-only one.
  • Per-operation value types — a JSON-backed cache can read and write unrelated Go types without constructing a cache per type.

This is an honest superset for those specific needs, not a claim that rueidisaside is deficient — it deliberately keeps a smaller surface.

Sharing one client across caches

Open one Conn, then construct one cache per codec pair the service needs. Every cache shares the Conn's client and invalidation stream, and a single JSON-backed cache serves any key and value types on each operation.

conn, err := redcache.Open(
    rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
)
if err != nil {
    log.Fatal(err)
}
defer conn.Close()

values := redcache.New(conn, redcache.JSONCodec{})
raw := redcache.NewBytes(conn)

session, err := values.Get(ctx, ttl, sessionKey, loadSession)  // K=string,  V=Session
order, err   := values.Get(ctx, ttl, OrderID("o-9"), loadOrder) // K=OrderID, V=Order
payload, err := raw.Get(ctx, ttl, "blob", loadBlob)             // V=[]byte

New, NewKeyed, and NewBytes do no I/O and panic on a nil codec. Close the Conn to tear down the shared client and every cache built over it.

Metrics

Implement Metrics, or embed NoopMetrics and override only the methods you care about, to wire counters into Prometheus, OpenTelemetry, or any other backend. Methods run on the hot path and must be concurrent-safe.

High-volume events (CacheHits, CacheMisses, LockContended, RefreshTriggered, RefreshSkipped, RefreshDropped) are aggregated per operation and emitted once with a count rather than once per key. LockWaitDuration fires once per resolved wait, and LoaderDuration once per foreground origin-loader call (Get/GetMulti miss, Set/SetMulti — background refresh excluded). LoaderErrors(n) fires when a foreground loader returns an error, with n the number of keys it was responsible for. Diagnostic events (LockLost, RefreshError, RefreshPanicked, InvalidationError) carry the affected key where applicable.

RedisError(op) uses read, lock, set, del, and touch for command failures, and read_fallback for an attempted uncached retry after a clustered cached read aborted. It emits one event per uncached retry attempt, whether for one key or a batch. A polling Get or GetMulti can make more than one attempt. The count includes retries that fail, return Redis nil, or are canceled before sending. Missing PTTL permission can trigger an abort. A sustained rate alone cannot identify a server-side EXEC abort because rueidis also reports ErrDoCacheAborted when a connection closes.

Metrics implementations and dashboards that enumerate operation labels need to accept read_fallback. Unfiltered redis.errors alerts include successful retries. Exclude op="read_fallback" from alerts that count only command failures.

type myMetrics struct {
    redcache.NoopMetrics
    hits, misses atomic.Int64
}

func (m *myMetrics) CacheHits(n int64)   { m.hits.Add(n) }
func (m *myMetrics) CacheMisses(n int64) { m.misses.Add(n) }

conn, err := redcache.Open(
    rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
    redcache.WithMetrics(&myMetrics{}),
)
if err != nil {
    log.Fatal(err)
}
defer conn.Close()

cache := redcache.New(conn, redcache.JSONCodec{})
OpenTelemetry

For OpenTelemetry, use the redcacheotel subpackage — a drop-in Metrics adapter you import as github.com/dcbickfo/redcache/redcacheotel:

import "github.com/dcbickfo/redcache/redcacheotel"

m, err := redcacheotel.NewMetrics(meterProvider) // metric.MeterProvider (e.g. your own *sdkmetric.MeterProvider)
if err != nil {
    log.Fatal(err)
}
conn, err := redcache.Open(opt, redcache.WithMetrics(m))
if err != nil {
    log.Fatal(err)
}
defer conn.Close()

cache := redcache.New(conn, redcache.JSONCodec{})

It records counters (hits, misses, lock contention, refresh and error events) and histograms (lock.wait.duration, loader.duration, in seconds). High-cardinality keys are deliberately not attached as labels; RedisError's bounded op is.

Importing redcache's core does not pull OpenTelemetry into your binary (verified: zero otel symbols linked) — OTel is only compiled in if you import redcacheotel. It does appear in the module graph, since it lives in the main module.

Testing

Cache is concrete because generic methods cannot satisfy a Go interface, so code under test takes *redcache.Cache. To unit-test without Redis, build the cache over redcache.OpenMemory() — a Conn backed by an in-process map:

func TestUserService(t *testing.T) {
    cache := redcache.New(redcache.OpenMemory(), redcache.JSONCodec{})
    svc := NewUserService(cache)
    // exercise svc; the real codecs run, a miss calls your loader,
    // a present unexpired entry is a hit, and TTLs expire.
}

For deterministic expiry pass redcache.WithMemoryClock(func() time.Time) and move the returned time forward instead of sleeping. The memory Conn does not model distributed single-flight, invalidation pushes, refresh-ahead, or metrics; for those, construct the real cache with WithClientBuilder and rueidis/mock, or run against Redis. Miniredis cannot emulate RESP3 client-side invalidation.

Stampede mitigation without refresh-ahead

If you can't or don't want to enable refresh-ahead, the lock layer already prevents per-key thundering herd: only one caller per key runs the origin function while peers wait on the cached invalidation. The remaining stampede risk is cross-key simultaneous expiry — many keys SET in the same window (deploys, batch imports, cold-start backfill) all expire together.

This library deliberately does not jitter the ttl you pass to Get/GetMulti/Set/ForceSet: the contract is that you get the TTL you asked for. Jitter expiries at the call site instead, so callers retain control over the policy:

ttl := baseTTL + time.Duration(rand.Int64N(int64(baseTTL/10))) // ±10%
val, err := cache.Get(ctx, ttl, key, fetch)

For workloads that already use WithRefreshAfterFraction + WithRefreshBeta, XFetch handles this naturally — the probabilistic refresh window smears reload moments across the keyspace without changing observable TTLs.

Local Development

# Install the pinned Go and golangci-lint versions via asdf
make setup

# Start Redis
docker compose up -d

# Run tests (requires Redis on localhost:6379)
make test-race

# Check coverage against the current baseline
make cover-check

# Lint
make lint

# Benchmarks
make bench

Documentation

Overview

Package redcache is a typed cache-aside for Redis, built on the rueidis client. It combines rueidis client-side caching with distributed SET NX locking so that, across every process, only one caller populates a missing key while the rest wait on the invalidation push for the populated value — a stampede-resistant cache behind a single Cache whose operations infer their key and value types per call.

How it works

A read registers an in-process lock entry, then issues a client-side-cached GET. That GET serves a dual purpose: it returns any cached value and subscribes the connection to Redis invalidation for the key. On a miss, one caller wins a distributed lock (SET NX with a UUIDv7 value), runs the loader, and atomically replaces the lock with the real value via a Lua CAS. Every other caller — in this process or another — waits for the resulting invalidation, with jittered polling as a fallback until the lock TTL, and then reads the populated value. In-process leader/follower coordination collapses a thundering herd on one key to a single Redis SET NX.

Constructing a cache

Open one Conn (it owns the rueidis client and invalidation stream), then construct caches over it that all share that client:

A Cache owns one KeyCodec and one Codec. Its generic methods infer K from the key and V from the loader or value on every call, so one JSON-backed Cache can store different Go types under keys of different Go types. Cache.Peek requires an explicit value type because it has no loader or value argument from which Go can infer one. Lifecycle (Close) and raw-client access (Client) live on the Conn.

There is no interface form (generic methods cannot satisfy Go interfaces); code under test takes a *Cache and builds it over OpenMemory, an in-process Conn, instead of Redis.

Minimal example

conn, err := redcache.Open(
	rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
)
if err != nil {
	return err
}
defer conn.Close()

cache := redcache.New(conn, redcache.StringCodec{})

v, err := cache.Get(ctx, time.Minute, "k", func(ctx context.Context, key string) (string, error) {
	return loadFromUpstream(ctx, key) // runs only on a miss, once per key
})

Beyond read-through

Every Cache also supports write-through priming — Set, ForceSet, and Touch (with Multi variants) — for populating or extending entries without a read-through miss. Opt into background refresh of stale-but-valid entries with WithRefreshAfterFraction (and WithRefreshBeta for XFetch-style probabilistic early expiration). Wire counters through WithMetrics.

Values, codecs, and absence

Values are stored through a Codec; keys through a KeyCodec. JSONCodec is the typical choice; StringCodec and UnsafeBytesCodec are identity codecs. The string path is safe to retain because strings are immutable; the bytes path is zero-copy and returns borrowed memory. Decode failures on read are wrapped with ErrDecode. Absence semantics are the caller's to own — there is no ErrNotFound sentinel; cache a *T, sql.Null[T], or a domain sentinel inside V to represent "not found" and avoid cache penetration.

Index

Examples

Constants

View Source
const (
	// DefaultLockPrefix tags in-Redis lock values so reads recognise a lock as
	// a miss.
	DefaultLockPrefix = "__redcache:lock:"
	// DefaultRefreshPrefix prefixes refresh-ahead dedup lock keys.
	DefaultRefreshPrefix = "__redcache:refresh:"
)

Variables

View Source
var ErrDecode = errors.New("decode failed")

ErrDecode is returned (wrapped) from typed reads when a stored value cannot be decoded. The library does not auto-evict — the caller decides whether to log, Del, or retry.

View Source
var ErrInvalidTTL = errors.New("redcache: ttl must be at least 1ms; use Del to remove")

ErrInvalidTTL is returned by TTL-bearing methods when ttl is under one millisecond, the resolution of Redis PX (which rejects PX 0); use Del to remove an entry.

View Source
var ErrLockLost = errors.New("lock was lost or expired before value could be set")

ErrLockLost is returned when the distributed lock was stolen or expired before the value could be written.

View Source
var ErrMissingValue = errors.New("redcache: loader returned no value for key")

ErrMissingValue is returned (wrapped, naming the keys) when a GetMulti or SetMulti loader returns no value for a key it was given. Loaders must return every key; encode a known-absent entity as a value (e.g. a tombstone).

Functions

This section is empty.

Types

type BatchKeyError added in v0.3.0

type BatchKeyError[K comparable] struct {
	Failed    map[K]error
	Succeeded []K
}

BatchKeyError is the typed, key-preserving error returned via errors.As from the multi-key write methods (SetMulti, ForceSetMulti) on partial failure. K is the operation's key type (the element type of its keys, or the key type of its values map), not a property of the Cache: match it with that same K. Unwrap exposes every per-key error to errors.Is and errors.As. All accessors are nil-safe.

func (*BatchKeyError[K]) Error added in v0.3.0

func (e *BatchKeyError[K]) Error() string

Error formats the batch outcome with failed keys sorted by their %v rendering for stable output.

func (*BatchKeyError[K]) ErrorFor added in v0.3.0

func (e *BatchKeyError[K]) ErrorFor(k K) error

ErrorFor returns the error for k, or nil.

func (*BatchKeyError[K]) HasError added in v0.3.0

func (e *BatchKeyError[K]) HasError(k K) bool

HasError reports whether k failed.

func (*BatchKeyError[K]) HasFailures added in v0.3.0

func (e *BatchKeyError[K]) HasFailures() bool

HasFailures reports whether any key failed.

func (*BatchKeyError[K]) Unwrap added in v0.4.0

func (e *BatchKeyError[K]) Unwrap() []error

Unwrap returns the per-key errors, so errors.Is(err, context.Canceled) or errors.Is(err, ErrLockLost) matches when any key failed that way.

type Cache added in v0.3.0

type Cache struct {
	// contains filtered or unexported fields
}

Cache is a cache-aside handle. It owns one KeyCodec and one value Codec; every operation infers its key and value types independently, so a single Cache can store different Go types under keys of different Go types. Codec compatibility with each operation's K and V is checked by the codecs at call time. Lifecycle and raw-client access remain on the owning Conn.

func New added in v0.3.0

func New(c *Conn, valCodec Codec) *Cache

New constructs a Cache over c with StringKeyCodec and the given value codec. It does no I/O. Passing a nil codec panics because it is a programmer error.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/rueidis"

	"github.com/dcbickfo/redcache"
)

func main() {
	conn, err := redcache.Open(
		rueidis.ClientOption{
			InitAddress: []string{"127.0.0.1:6379"},
		},
		redcache.WithLockTTL(5*time.Second),
	)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	client := redcache.New(conn, redcache.StringCodec{})

	val, err := client.Get(context.Background(), time.Minute, "example:get", func(ctx context.Context, key string) (string, error) {
		// Called only on cache miss — fetch from your data source.
		return "hello", nil
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(val)
	// This example dials Redis, so it omits an Output: directive (which would
	// make `go test` run it). It is compiled to keep the snippet honest.
}
Example (GetMulti)
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/rueidis"

	"github.com/dcbickfo/redcache"
)

func main() {
	conn, err := redcache.Open(
		rueidis.ClientOption{
			InitAddress: []string{"127.0.0.1:6379"},
		},
		redcache.WithLockTTL(5*time.Second),
	)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	client := redcache.New(conn, redcache.StringCodec{})

	keys := []string{"example:multi:a", "example:multi:b"}
	vals, err := client.GetMulti(context.Background(), time.Minute, keys, func(ctx context.Context, keys []string) (map[string]string, error) {
		// Called only for keys not in cache — fetch from your data source.
		result := make(map[string]string, len(keys))
		for _, k := range keys {
			result[k] = "value-for-" + k
		}
		return result, nil
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(len(vals))
	// Redis-dependent; omits Output: so `go test` does not run it.
}
Example (SharedConn)

A Conn owns one Redis client and invalidation stream. A JSON-backed Cache infers a different key and value type for each generic operation.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/rueidis"

	"github.com/dcbickfo/redcache"
)

func main() {
	conn, err := redcache.Open(
		rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
		redcache.WithLockTTL(5*time.Second),
	)
	if err != nil {
		panic(err)
	}
	defer conn.Close() // closing the Conn closes the shared client (and all views)

	values := redcache.New(conn, redcache.JSONCodec{})
	_, err = values.Get(context.Background(), time.Minute, "user:u-123",
		func(ctx context.Context, key string) (string, error) {
			return "alice", nil
		},
	)
	if err != nil {
		panic(err)
	}

	type AccountID string // ~string keys need no KeyCodec
	n, err := values.Get(context.Background(), time.Minute, AccountID("login-count:u-123"),
		func(ctx context.Context, id AccountID) (int, error) {
			return 7, nil
		},
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(n)
}

func NewBytes added in v0.3.0

func NewBytes(c *Conn) *Cache

NewBytes is New with UnsafeBytesCodec preset. Decoded byte slices alias borrowed cache memory and must not be mutated or retained after the call.

func NewKeyed added in v0.4.0

func NewKeyed(c *Conn, keyCodec KeyCodec, valCodec Codec) *Cache

NewKeyed is New with an explicit KeyCodec, for key types StringKeyCodec does not handle.

Example

NewKeyed keys the cache by a non-string domain type via a KeyCodec. KeyCodecFunc adapts a plain function into a KeyCodec.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/rueidis"

	"github.com/dcbickfo/redcache"
)

func main() {
	type UserID int64
	type User struct {
		ID   UserID
		Name string
	}

	userIDCodec := redcache.KeyCodecFunc[UserID](func(id UserID) (string, error) {
		return fmt.Sprintf("user:%d", id), nil
	})

	conn, err := redcache.Open(
		rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
		redcache.WithLockTTL(5*time.Second),
	)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	cache := redcache.NewKeyed(conn, userIDCodec, redcache.JSONCodec{})

	u, err := cache.Get(context.Background(), time.Minute, UserID(123),
		func(ctx context.Context, id UserID) (User, error) {
			// Load from your data source; runs only on a miss.
			return User{ID: id, Name: "alice"}, nil
		},
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(u.Name)
}

func (*Cache) Del added in v0.3.0

func (c *Cache) Del[K comparable](ctx context.Context, k K) error

Del removes k and triggers invalidation on subscribed clients.

func (*Cache) DelMulti added in v0.3.0

func (c *Cache) DelMulti[K comparable](ctx context.Context, keys []K) error

DelMulti removes keys and triggers invalidation on subscribed clients.

func (*Cache) ForceSet added in v0.3.0

func (c *Cache) ForceSet[K comparable, V any](ctx context.Context, ttl time.Duration, k K, v V) error

ForceSet writes v unconditionally, bypassing locks. V is inferred from v. In-progress Get callers on the same key retry and observe the new value; in-progress Set callers receive ErrLockLost and abandon their pending write.

Example

ForceSet writes a value unconditionally, bypassing the lock. Any in-progress Get or Set on the same key sees ErrLockLost and retries. Redis-dependent, so it omits an Output: directive.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/rueidis"

	"github.com/dcbickfo/redcache"
)

func main() {
	conn, err := redcache.Open(
		rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
		redcache.WithLockTTL(5*time.Second),
	)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	cache := redcache.New(conn, redcache.StringCodec{})

	if err := cache.ForceSet(context.Background(), time.Minute, "config:greeting", "hola"); err != nil {
		panic(err)
	}
	fmt.Println("forced")
}

func (*Cache) ForceSetMulti added in v0.3.0

func (c *Cache) ForceSetMulti[K comparable, V any](ctx context.Context, ttl time.Duration, values map[K]V) error

ForceSetMulti writes values unconditionally. K and V are inferred from values; pass them explicitly when values is an untyped nil map. Encode failures are collected per key and successful entries are still written; partial failures surface as *BatchKeyError[K].

Example

Multi-key writes report per-key partial failures as *BatchKeyError[K], reachable via errors.As. Note the generic type argument on the target pointer: it must match the cache's key type (string here).

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/redis/rueidis"

	"github.com/dcbickfo/redcache"
)

// failOnEmpty is a value codec that refuses to encode the empty string, used to
// force a deterministic per-key failure in the ForceSetMulti example.
type failOnEmpty struct{}

func (failOnEmpty) Encode(v any) ([]byte, error) {
	s, ok := v.(string)
	if !ok {
		return nil, fmt.Errorf("failOnEmpty cannot encode %T", v)
	}
	if s == "" {
		return nil, errors.New("empty value not allowed")
	}
	return []byte(s), nil
}

func (failOnEmpty) Decode(b []byte, dst any) error {
	p, ok := dst.(*string)
	if !ok {
		return fmt.Errorf("failOnEmpty cannot decode into %T", dst)
	}
	*p = string(b)
	return nil
}

func main() {
	conn, err := redcache.Open(
		rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
	)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	cache := redcache.New(conn, failOnEmpty{})

	err = cache.ForceSetMulti(context.Background(), time.Minute, map[string]string{
		"a": "alpha",
		"b": "", // fails to encode
	})

	if be, ok := errors.AsType[*redcache.BatchKeyError[string]](err); ok {
		fmt.Println("b failed:", be.HasError("b"))
		fmt.Println("a succeeded:", !be.HasError("a"))
		for k, kerr := range be.Failed {
			_ = k
			_ = kerr // handle each failed key
		}
	}
}

func (*Cache) Get added in v0.3.0

func (c *Cache) Get[K comparable, V any](
	ctx context.Context,
	ttl time.Duration,
	k K,
	fn func(context.Context, K) (V, error),
) (V, error)

Get returns the cached value for k, calling fn on a miss. Only one caller across all processes runs fn for a given key; the rest wait on invalidation. V is inferred from fn. Decode errors are wrapped with ErrDecode.

func (*Cache) GetMulti added in v0.3.0

func (c *Cache) GetMulti[K comparable, V any](
	ctx context.Context,
	ttl time.Duration,
	keys []K,
	fn func(context.Context, []K) (map[K]V, error),
) (map[K]V, error)

GetMulti returns cached values for keys, calling fn for misses. V is inferred from fn. fn must return a value for every key it is given; an omitted key fails the call with ErrMissingValue. Each phase is one pipeline, which the cluster client splits per node; a decode error aborts the batch and is wrapped with ErrDecode.

func (*Cache) Peek added in v0.3.0

func (c *Cache) Peek[K comparable, V any](ctx context.Context, ttl time.Duration, k K) (V, bool, error)

Peek is a read-only, client-side-cached lookup with no loader and no lock. The caller must supply both K and V (as Peek[K, V]) because Peek has no value argument from which Go can infer V. It returns (value, true, nil) on a hit, (zero, false, nil) on a miss or lock value, and (zero, false, err) on a Redis or decode error. ttl is the client-side-cache subscription TTL, like Get.

func (*Cache) Set added in v0.3.0

func (c *Cache) Set[K comparable, V any](
	ctx context.Context,
	ttl time.Duration,
	k K,
	fn func(context.Context, K) (V, error),
) error

Set populates k via fn under a write lock, writing the value to every subscribed client. V is inferred from fn. On callback error the prior value is restored.

Example

Set primes a key under a write lock without a prior read. If the callback returns an error, the cache restores the value that was there before, so a failed refresh never leaves the key empty. Redis-dependent, so it omits an Output: directive and is compiled but not run by `go test`.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/rueidis"

	"github.com/dcbickfo/redcache"
)

func main() {
	conn, err := redcache.Open(
		rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
		redcache.WithLockTTL(5*time.Second),
	)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	cache := redcache.New(conn, redcache.StringCodec{})

	err = cache.Set(context.Background(), time.Minute, "config:greeting",
		func(ctx context.Context, key string) (string, error) {
			// Compute the value to cache; runs under a write lock.
			return "hello", nil
		},
	)
	if err != nil {
		panic(err)
	}
	fmt.Println("primed")
}

func (*Cache) SetMulti added in v0.3.0

func (c *Cache) SetMulti[K comparable, V any](
	ctx context.Context,
	ttl time.Duration,
	keys []K,
	fn func(context.Context, []K) (map[K]V, error),
) error

SetMulti populates keys via fn under write locks. V is inferred from fn. Partial failures surface as *BatchKeyError[K] via errors.As; a key fn omits is restored to its prior value and fails with ErrMissingValue.

func (*Cache) Touch added in v0.3.0

func (c *Cache) Touch[K comparable](ctx context.Context, ttl time.Duration, k K) error

Touch updates the TTL of a cached value. It is a no-op for a missing key or lock value. Clients caching the key are invalidated and re-fetch it with the new TTL on their next read.

func (*Cache) TouchMulti added in v0.3.0

func (c *Cache) TouchMulti[K comparable](ctx context.Context, ttl time.Duration, keys []K) error

TouchMulti updates the TTL of cached values, with the same behavior as Touch.

type Codec added in v0.3.0

type Codec interface {
	Encode(any) ([]byte, error)
	Decode([]byte, any) error
}

Codec encodes and decodes values into the envelope payload. A Cache owns one Codec and may use it with different value types across operations. Decode writes into the supplied destination; the cache never asserts a decoded interface value back to the operation's type. Implementations must be concurrent-safe and return an error for unsupported value or destination types.

Ownership of return values:

  • Encode's returned slice is handed to the library and must not be mutated by the caller afterward. The library may alias it without copying, so the codec must not retain or later modify it either.
  • Decode receives a pointer to the operation's value type. Its input slice is borrowed from library-internal memory and is only valid for the duration of the call; it must not be retained.

Identity codecs (UnsafeBytesCodec) alias this borrowed memory directly and so trade safety for zero copies — the decoded []byte must not outlive the call or be mutated. JSONCodec returns owned decoded values. StringCodec returns immutable strings that are safe to retain.

type Conn added in v0.3.0

type Conn struct {
	// contains filtered or unexported fields
}

Conn owns one rueidis client, its invalidation stream, and a lock namespace. Every Cache derived from it shares the single client and invalidation subscription. Lifecycle stays on the Conn: open it once and close it when done with all derived caches.

func Open added in v0.3.0

func Open(clientOption rueidis.ClientOption, opts ...Option) (*Conn, error)

Open builds a Conn with its own rueidis.Client (wired for invalidation). Construct caches over it with New, NewKeyed, or NewBytes.

func OpenMemory added in v0.4.0

func OpenMemory(opts ...MemoryOption) *Conn

OpenMemory returns a Conn backed by an in-process map instead of Redis, for unit tests and local development. Caches built over it (New, NewKeyed, NewBytes) behave identically at the typed layer — codecs run, TTLs expire, a present entry is a hit, a miss calls the loader, and loader results for keys nobody asked for are dropped — but there is no single-flight (concurrent misses each call the loader), no distributed locking, invalidation, refresh-ahead, or metrics, and Client() returns nil. It never fails and needs no Close.

func (*Conn) Client added in v0.3.0

func (c *Conn) Client() rueidis.Client

Client returns the underlying rueidis.Client, shared by every cache. It is nil for a Conn from OpenMemory.

func (*Conn) Close added in v0.3.0

func (c *Conn) Close()

Close closes the underlying engine and client. Idempotent. It also closes every cache constructed over this Conn because they share the client.

type JSONCodec added in v0.3.0

type JSONCodec struct{}

JSONCodec encodes values via encoding/json (v1 semantics: nil slices and maps encode as null, case-insensitive field matching, duplicate object names tolerated). Its wire format is unchanged from earlier releases, so caches written by older binaries stay readable.

func (JSONCodec) Decode added in v0.3.0

func (JSONCodec) Decode(b []byte, dst any) error

Decode unmarshals b into dst, which must be a non-nil pointer.

func (JSONCodec) Encode added in v0.3.0

func (JSONCodec) Encode(v any) ([]byte, error)

Encode marshals v to JSON.

type JSONV2Codec added in v0.4.0

type JSONV2Codec struct{}

JSONV2Codec encodes values via encoding/json/v2 with its stricter defaults: nil slices and maps encode as [] and {}, field names match case-sensitively, and duplicate object names and invalid UTF-8 are rejected on decode. Use it for new caches; switching an existing cache from JSONCodec changes the stored representation of nil containers.

func (JSONV2Codec) Decode added in v0.4.0

func (JSONV2Codec) Decode(b []byte, dst any) error

Decode unmarshals b into dst, which must be a non-nil pointer.

func (JSONV2Codec) Encode added in v0.4.0

func (JSONV2Codec) Encode(v any) ([]byte, error)

Encode marshals v to JSON.

type KeyCodec added in v0.3.0

type KeyCodec interface {
	EncodeKey(any) (string, error)
}

KeyCodec encodes a key into the Redis key string. A Cache owns one KeyCodec and may use it with different key types across operations; implementations must be concurrent-safe and return an error for unsupported key types. StringKeyCodec is the default; KeyCodecFunc adapts a typed function.

type KeyCodecFunc added in v0.3.0

type KeyCodecFunc[K any] func(K) (string, error)

KeyCodecFunc adapts a typed function into a KeyCodec. Keys of any type other than K are rejected with an error.

func (KeyCodecFunc[K]) EncodeKey added in v0.3.0

func (f KeyCodecFunc[K]) EncodeKey(k any) (string, error)

EncodeKey calls f when k is a K.

type Logger added in v0.1.6

type Logger interface {
	Error(msg string, args ...any)
	Debug(msg string, args ...any)
}

Logger is the slog-shaped subset the cache calls into. *slog.Logger satisfies it.

type MemoryOption added in v0.4.0

type MemoryOption func(*memEngine)

MemoryOption configures OpenMemory.

func WithMemoryClock added in v0.4.0

func WithMemoryClock(now func() time.Time) MemoryOption

WithMemoryClock sets the time source used for TTL expiry, so tests can advance time without sleeping. The default is time.Now.

type Metrics added in v0.1.7

type Metrics interface {
	CacheHits(n int64)
	CacheMisses(n int64)
	LockContended(n int64)
	// LockWaitDuration fires once per resolved wait, regardless of outcome
	// (invalidation, ctx cancel, or lockTTL). Typically histogrammed.
	LockWaitDuration(d time.Duration)
	// LoaderDuration measures foreground origin-loader latency (Get/GetMulti
	// miss, Set/SetMulti). Background refresh is excluded. Typically histogrammed.
	LoaderDuration(d time.Duration)
	// LoaderErrors fires when a foreground loader returns an error; n is the
	// number of keys the loader was responsible for (1 for single, len(missing)
	// for multi).
	LoaderErrors(n int64)
	// RedisError records command failures with op "read", "lock", "set",
	// "del", or "touch". "read_fallback" counts an attempted uncached retry
	// after a clustered cached read aborted. It emits one event per uncached
	// retry attempt, whether for one key or a batch. A polling Get or
	// GetMulti can make more than one attempt. The count includes retries
	// that fail, return Redis nil, or are canceled before sending. Missing
	// PTTL permission can trigger an abort. A sustained rate alone cannot
	// identify a server-side EXEC abort because rueidis also reports
	// ErrDoCacheAborted when a connection closes.
	// Lock-lost, Redis nil, and script-drift parse failures are excluded
	// from the command-failure labels.
	RedisError(op string)
	RefreshTriggered(n int64)
	// RefreshSkipped covers both local and distributed dedup.
	RefreshSkipped(n int64)
	// RefreshDropped fires when the refresh queue is full.
	RefreshDropped(n int64)
	// LockLost fires when a CAS detected a stolen lock (e.g. via ForceSet).
	LockLost(key string)
	RefreshError(key string)
	// RefreshPanicked fires once per key when a refresh callback panicked.
	RefreshPanicked(key string)
	// InvalidationError fires when an invalidation message couldn't be parsed.
	InvalidationError()
}

Metrics receives observability events. Methods run on the hot path and must be concurrent-safe. High-volume events (hits/misses/contention/refresh counts) are batched per operation and emitted once with n. Diagnostics (LockLost, RefreshError, RefreshPanicked) carry the affected key. Embed NoopMetrics to opt in to a subset.

type NoopMetrics added in v0.1.7

type NoopMetrics struct{}

NoopMetrics is the zero-value Metrics implementation. Embed and override.

Example

Pass a Metrics implementation via WithMetrics to count cache events. The cache calls these on the hot path, batched per operation. This example invokes them directly (no Redis needed) to show the counting shape.

package main

import (
	"fmt"
	"sync/atomic"

	"github.com/dcbickfo/redcache"
)

// countingMetrics shows the embed-and-override pattern: embed NoopMetrics and
// implement only the events you care about.
type countingMetrics struct {
	redcache.NoopMetrics
	hits, misses atomic.Int64
}

func (m *countingMetrics) CacheHits(n int64)   { m.hits.Add(n) }
func (m *countingMetrics) CacheMisses(n int64) { m.misses.Add(n) }

func main() {
	m := &countingMetrics{}
	// In real use: open a Conn and construct redcache.New(conn, codec) with redcache.WithMetrics(m) passed to Open.
	m.CacheHits(3)
	m.CacheMisses(1)
	fmt.Println(m.hits.Load(), m.misses.Load())
}
Output:
3 1

func (NoopMetrics) CacheHits added in v0.2.0

func (NoopMetrics) CacheHits(int64)

func (NoopMetrics) CacheMisses added in v0.2.0

func (NoopMetrics) CacheMisses(int64)

func (NoopMetrics) InvalidationError added in v0.1.7

func (NoopMetrics) InvalidationError()

func (NoopMetrics) LoaderDuration added in v0.3.0

func (NoopMetrics) LoaderDuration(time.Duration)

func (NoopMetrics) LoaderErrors added in v0.3.0

func (NoopMetrics) LoaderErrors(int64)

func (NoopMetrics) LockContended added in v0.1.7

func (NoopMetrics) LockContended(int64)

func (NoopMetrics) LockLost added in v0.1.7

func (NoopMetrics) LockLost(string)

func (NoopMetrics) LockWaitDuration added in v0.2.0

func (NoopMetrics) LockWaitDuration(time.Duration)

func (NoopMetrics) RedisError added in v0.3.0

func (NoopMetrics) RedisError(string)

func (NoopMetrics) RefreshDropped added in v0.1.7

func (NoopMetrics) RefreshDropped(int64)

func (NoopMetrics) RefreshError added in v0.1.7

func (NoopMetrics) RefreshError(string)

func (NoopMetrics) RefreshPanicked added in v0.1.7

func (NoopMetrics) RefreshPanicked(string)

func (NoopMetrics) RefreshSkipped added in v0.1.7

func (NoopMetrics) RefreshSkipped(int64)

func (NoopMetrics) RefreshTriggered added in v0.1.7

func (NoopMetrics) RefreshTriggered(int64)

type Option added in v0.3.0

type Option func(*config)

Option configures a Conn. Options are applied in order; later wins.

func WithClientBuilder added in v0.3.0

func WithClientBuilder(b func(option rueidis.ClientOption) (rueidis.Client, error)) Option

WithClientBuilder overrides rueidis.NewClient when building the internal client. Useful as a test seam.

func WithLockPrefix added in v0.3.0

func WithLockPrefix(p string) Option

WithLockPrefix sets the in-Redis prefix tagged onto lock values so reads can recognise a lock as a miss. Defaults to DefaultLockPrefix.

func WithLockTTL added in v0.3.0

func WithLockTTL(d time.Duration) Option

WithLockTTL bounds both how long a Redis lock survives and how long callers wait for one. Defaults to 10s; values below 100ms are rejected.

func WithLogger added in v0.3.0

func WithLogger(l Logger) Option

WithLogger sets the logger. Defaults to slog.Default().

func WithMetrics added in v0.3.0

func WithMetrics(m Metrics) Option

WithMetrics sets the metrics sink. Defaults to NoopMetrics. Methods run on the hot path; impls must be concurrent-safe.

func WithRefreshAfterFraction added in v0.3.0

func WithRefreshAfterFraction(f float64) Option

WithRefreshAfterFraction enables refresh-ahead. Reads with remaining TTL below (1 - fraction) * ttl may trigger a background refresh while still returning the cached value. Must be in [0, 1); 0 disables.

func WithRefreshBeta added in v0.3.0

func WithRefreshBeta(b float64) Option

WithRefreshBeta enables XFetch-style probabilistic sampling within the refresh window, weighting by recorded compute time so slow values get more headroom. 0 (default) = always refresh below the floor; 1.0 matches canonical XFetch (Vattani et al). Multi-key writes record fn duration divided evenly across returned values.

func WithRefreshLockPrefix added in v0.3.0

func WithRefreshLockPrefix(p string) Option

WithRefreshLockPrefix sets the prefix for refresh-ahead dedup keys. Defaults to DefaultRefreshPrefix. Refresh lock keys embed the data key for uniqueness; refresh-ahead correctness does not require Redis cluster-slot co-location.

func WithRefreshQueueSize added in v0.3.0

func WithRefreshQueueSize(n int) Option

WithRefreshQueueSize bounds pending refresh jobs; over-full drops are counted via RefreshDropped. Defaults to 64.

func WithRefreshTimeout added in v0.3.0

func WithRefreshTimeout(d time.Duration) Option

WithRefreshTimeout bounds how long a refresh-ahead callback may run. Defaults to the data ttl passed to Get/GetMulti (not LockTTL). The refresh lock itself still uses LockTTL; the back-write that records a slow-but-successful result is decoupled from this timeout so it is not lost.

func WithRefreshWorkers added in v0.3.0

func WithRefreshWorkers(n int) Option

WithRefreshWorkers sets the refresh worker pool size. Defaults to 4.

type StringCodec added in v0.3.0

type StringCodec struct{}

StringCodec is the identity codec for string.

func (StringCodec) Decode added in v0.3.0

func (StringCodec) Decode(b []byte, dst any) error

Decode assigns b as a string.

func (StringCodec) Encode added in v0.3.0

func (StringCodec) Encode(v any) ([]byte, error)

Encode returns v as bytes.

type StringKeyCodec added in v0.3.0

type StringKeyCodec struct{}

StringKeyCodec is the default KeyCodec. A string, or any type whose underlying type is string, is used as-is (this is what enables the zero-allocation multi-key fast path); an encoding.TextMarshaler is encoded with MarshalText; any other type is an error.

func (StringKeyCodec) EncodeKey added in v0.3.0

func (StringKeyCodec) EncodeKey(k any) (string, error)

EncodeKey returns k's string value, or its MarshalText output.

type UnsafeBytesCodec added in v0.3.0

type UnsafeBytesCodec struct{}

UnsafeBytesCodec is the zero-copy identity codec for []byte. It aliases library-internal memory in both directions: Encode hands its input straight to the library (which may alias it), and Decode returns a []byte backed by the cache's borrowed read buffer. The decoded slice must not be mutated or retained past the call. Use a copying codec if you need an owned value.

func (UnsafeBytesCodec) Decode added in v0.3.0

func (UnsafeBytesCodec) Decode(b []byte, dst any) error

Decode assigns b unchanged (no copy); the result aliases borrowed memory.

func (UnsafeBytesCodec) Encode added in v0.3.0

func (UnsafeBytesCodec) Encode(v any) ([]byte, error)

Encode returns v unchanged (no copy).

Directories

Path Synopsis
examples
metrics command
Package main demonstrates wiring a custom Metrics implementation.
Package main demonstrates wiring a custom Metrics implementation.
string-cache command
Package main demonstrates a migration-friendly string-key/string-value cache.
Package main demonstrates a migration-friendly string-key/string-value cache.
typed-cache command
Package main demonstrates typed keys and JSON-encoded values.
Package main demonstrates typed keys and JSON-encoded values.
internal
lockpool
Package lockpool provides fast lock value generation using an atomic counter and a per-instance UUID prefix.
Package lockpool provides fast lock value generation using an atomic counter and a per-instance UUID prefix.
poolx
Package poolx provides typed sync.Pool wrappers for reusing slice headers across multi-key call paths.
Package poolx provides typed sync.Pool wrappers for reusing slice headers across multi-key call paths.
syncx
Package syncx provides concurrency helpers: a sharded string-keyed map and a multi-channel wait.
Package syncx provides concurrency helpers: a sharded string-keyed map and a multi-channel wait.
Package redcacheotel provides a drop-in OpenTelemetry adapter for the redcache.Metrics interface.
Package redcacheotel provides a drop-in OpenTelemetry adapter for the redcache.Metrics interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址