cachex

package module
v2.0.0-...-605f64f Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 19 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

cachex

A multi-layer read-through cache for Go: concurrent misses of a key are fetched once, writes reach every layer in one order, and every layer keeps its own freshness.

Go Reference License

English | 中文

A Cache reads its layers top down (memory, then Redis, then a database table, say) and asks the source only when no layer has a usable entry. Upgrading from v1? See MIGRATION.md.

Install

go get github.com/theplant/cachex/v2

Quick start

One in-memory layer over a source:

mem, err := ottercachex.New[*Product](ottercachex.Config[*Product]{MaximumSize: 100_000})
if err != nil {
    log.Fatal(err)
}

source := cachex.SourceFunc[*Product](func(ctx context.Context, id string) (*Product, error) {
    p, err := loadProduct(ctx, id) // your database query
    if errors.Is(err, gorm.ErrRecordNotFound) {
        return nil, cachex.ErrNotFound // "does not exist" is ErrNotFound
    }
    return p, err
})

products := cachex.New(source, []cachex.Layer[*Product]{
    cachex.NewLayer[*Product](mem, cachex.TTL(time.Minute, 10*time.Minute)),
})
defer products.Close()

p, err := products.Get(ctx, "42")
switch {
case errors.Is(err, cachex.ErrNotFound):
    // no such product
case err != nil:
    // a layer or the source failed
}

TTL(fresh, stale): for a minute the entry is returned as is; for ten more minutes it is still returned at once while a background refresh fetches it again; after that it is not served.

Two layers

Memory in front of Redis, both in front of the database. Each layer has its own TTLs; an entry copied from Redis into memory is kept for the memory layer's TTL, but never fresher or longer than the entry in Redis:

mem, _ := ottercachex.New[*Product](ottercachex.Config[*Product]{MaximumSize: 100_000})
shared := rediscachex.New[*Product](rediscachex.Config[*Product]{Client: rdb, KeyPrefix: "product:v1:"})

products := cachex.New(source, []cachex.Layer[*Product]{
    cachex.NewLayer[*Product](mem,
        cachex.TTL(30*time.Second, time.Minute),
        cachex.NotFoundTTL(5*time.Second, 0)), // remember "does not exist" for 5s
    cachex.NewLayer[*Product](shared,
        cachex.TTL(5*time.Minute, time.Hour),
        cachex.NotFoundTTL(30*time.Second, 0)),
}, cachex.WithFetchTimeout(3*time.Second))

Values that expire on their own, such as tokens, get a per-value cap with WithMaxAge; it works on types you cannot add methods to:

tokenMem, _ := ottercachex.New[*oauth2.Token](ottercachex.Config[*oauth2.Token]{MaximumSize: 10_000})
tokens := cachex.New(tokenSource, []cachex.Layer[*oauth2.Token]{ // tokenSource is a cachex.Source[*oauth2.Token]
    cachex.NewLayer[*oauth2.Token](tokenMem, cachex.TTL(time.Hour, 0)),
}, cachex.WithMaxAge(func(t *oauth2.Token) time.Duration {
    return time.Until(t.Expiry) - time.Minute // never serve a token about to expire
}))

Writes

Change the source first, then write through the same Cache:

if err := db.WithContext(ctx).Save(p).Error; err != nil { // 1. the source
    return err
}
return products.Set(ctx, p.ID, p) // 2. every layer, bottom up

Set writes every layer, bottom up; Del drops the key from every layer, so the next read asks the source. Neither writes the source. A read that started before the write cannot put the old value back after it. SetMany and DelMany do the same for many keys.

Batch reads

GetMany reads many keys with one call per layer. If the source also implements BatchSource, the misses are fetched in one call too:

// GetMany makes productSource a cachex.BatchSource: a key it does not return
// does not exist.
func (s productSource) GetMany(ctx context.Context, ids []string) (map[string]*Product, error) {
    var rows []*Product
    if err := s.db.WithContext(ctx).Where("id IN ?", ids).Find(&rows).Error; err != nil {
        return nil, err // every key failed
    }
    out := make(map[string]*Product, len(rows))
    for _, p := range rows {
        out[p.ID] = p
    }
    return out, nil
}

found, err := products.GetMany(ctx, []string{"1", "2", "3"})
var be *cachex.BatchError
if errors.As(err, &be) {
    // be.Errors lists the keys that failed; found holds every other key
}

Several instances

When several processes share a Redis layer, one of them may read a value from the source, another may then change the source and call Set, and the first may write its old value into Redis after that write. Every instance then copies the old value into its memory layer until the Redis entry rots. Turn leases on to prevent it:

shared := rediscachex.New[*Product](rediscachex.Config[*Product]{Client: rdb, KeyPrefix: "product:v1:", Leases: true})

gormcachex has the same Leases option, for a table several instances share (after Migrate). A fetch leases each key it misses in Redis, a write of the key ends the lease, and the fetch writes Redis only if it still holds its lease. A miss whose lease another instance holds is still answered, without writing Redis; a background refresh then leaves the key to that instance. Turn leases on for every instance sharing the layer at once: a write from an instance without them does not end the leases of one with them, which may then write its older value over it. Leases do not reach other instances' memory layers. For that, turn on the invalidation broadcast: after a write, each instance drops the written keys from its memory layers.

products := cachex.New(source, layers, cachex.WithBroadcast(
    rediscachex.NewBroadcast(rediscachex.BroadcastConfig{Client: rdb, KeyPrefix: "product:v1:"})))

It uses Redis Pub/Sub (Redis Cluster too); without Redis but with PostgreSQL, gobuscachex.NewBroadcast does the same over go-bus, with messages polled from a queue per instance. Over Redis, messages published while an instance is disconnected are lost; over go-bus they wait in its queue, unless its subscription expired. Either way, each time an instance subscribes again it clears its memory layers: the cost of a message lost that way is a cold memory layer, not an old value. Only layers whose backend lives in the process are touched (ottercachex, bigcachex, or your own backend implementing cachex.LocalBackend); a Cache with a broadcast needs one. A publish that fails is tried again twice (a pooled connection the database dropped, say); if it still fails, it is logged as an error, not returned, and the other instances serve the old value from their memory layers until it stops being fresh there (they then refresh it, or miss and read the shared layer): the memory layers' fresh TTL bounds how long, so keep it short enough for that. With leases and the broadcast on, the Redis layer's TTLs can be long and a write shows on every instance as soon as the message arrives.

Options

Option Default What
TTL(fresh, stale) (layer) required How long an entry is fresh, then how long it is still served while refreshed
NotFoundTTL(fresh, stale) (layer) 0, 0: not recorded The same for "does not exist"
Jitter(ratio) (layer) 0.1 Shortens each entry's fresh period by up to this share, so entries written together do not turn stale or rotten together
WithMaxAge(func(T) time.Duration) none Caps how long a value is kept, in every layer; called for fetched values and for those Set/SetMany write
WithFetchTimeout(d) 60s Bounds, each on its own: a fetch's double check, each lower layer read with its backfill, each source call with its backfill, taking and releasing leases (a lease lasts two of it), the invalidation after a failed write, a broadcast's publish, a received invalidation, and the clear after subscribing again
WithGetManyConcurrency(n) 16 How many source requests one GetMany has in flight
WithGetManyChunkSize(n) 0: one chunk Fetches a GetMany's misses in chunks of at most n keys, each claimed when it starts; a Get of a key whose chunk has not started does not wait
WithBroadcast(b) off Sends the keys of each write to the other instances, which drop them from their local layers; see "Several instances"
WithLogger(l) slog.Default() Logs failures that do not fail a call (a backfill, an invalidation, a background refresh) and panics in fetches
WithNow(f) time.Now The clock entries are computed and judged by (backends still expire entries by the wall clock); cachextest.Clock is a manual one for tests

Backends

Package Stores Notes
ottercachex values in memory MaximumSize (entries) or MaximumWeight with Weigher is required; each entry expires at its own time
bigcachex encoded entries in memory For millions of entries, when the garbage collector shows in profiles; every read decodes
rediscachex encoded entries in Redis or Redis Cluster Native expiry per entry; batch calls are pipelines of ChunkSize keys; Leases for a Redis several instances share; NewBroadcast for the invalidation broadcast
gormcachex encoded entries in a table Call Migrate; on MySQL, 8.0.17+ only; see Pitfalls for keys, isolation and expired rows; Leases for a table several instances share
goquecachex nothing: gormcachex's cleanup as a go-que job PostgreSQL for the queue (the table may be elsewhere); StartCleanup on every instance runs DeleteExpired on one of them at a time
gobuscachex nothing: the invalidation broadcast over go-bus PostgreSQL only; for deployments with PostgreSQL and no Redis; each instance subscribes a queue of its own, kept alive by heartbeats
cachextest values in memory, unbounded For tests only, with Clock, NewLeasingMap (a shared map with leases, for Caches standing for instances), NewBus (an in-memory broadcast that can lose messages), and TestBackend, TestByteBackend, TestLeaser and TestBroadcast, contract tests for your own backends and transports

rediscachex.New and bigcachex.New return a cachex.Backend[T]; gormcachex.New returns a *gormcachex.Backend[T], which is one and adds Migrate.

Your own store implements Backend[T], or SingleBackend[T] wrapped with cachex.Batched. A store of bytes implements cachex.ByteBackend and is wrapped with cachex.Encoded, which encodes entries with a Codec, treats data that does not decode as a miss, and deletes an entry already rotten instead of writing it. A store used as the first layer may also implement cachex.SliceGetter[T] (GetInto, which reads many keys into slices): GetMany then reads that layer without building a map, which spares an allocation per key when the cached value is a large value type. ottercachex, bigcachex, rediscachex, cachextest.Map and Batched stores have it. A wrapper of such a store that overrides GetMany must override GetInto too, or the first layer is read without its GetMany.

Pitfalls

Each item: the mistake, what happens, what to do.

Source

  • Returning nil, nil for a missing key. The zero value is cached as a real value. Return cachex.ErrNotFound (wrapping it is fine).
  • Returning ErrNotFound from BatchSource.GetMany. Every key of the call reads as missing but nothing is cached, so each read asks again. Leave missing keys out of the map; for some keys failing, return a *cachex.BatchError as is, not wrapped.
  • Relying on the caller's cancellation inside the source. A fetch is shared by every caller waiting for the key, so its ctx does not end when one caller leaves; it is bounded by WithFetchTimeout instead, and keeps the caller's values. Do not use caller state from it, such as a database transaction (cachex.IsShared(ctx) tells you it is a fetch).
  • Calling the same Cache from inside the source for a key the same fetch is fetching. The same key, or another key of the same GetMany chunk, could be waiting for this very call: the call fails at once with an error saying so. Other keys are read as usual. A cycle through other fetches (a's source reads b, b's reads a) is not recognized and fails at the fetch timeout. Read what the source needs from the data store, or from another Cache.
  • A source without GetMany behind large GetMany calls. Keys are fetched one by one (WithGetManyConcurrency at a time), and by default a concurrent Get of a queued key waits for its turn. Implement BatchSource, or set WithGetManyChunkSize to about WithGetManyConcurrency.

Reads

  • Treating err != nil from GetMany as "nothing found". The map holds every key that succeeded; only the keys in the *BatchError failed. A key absent from both does not exist.
  • Testing presence with m[k] == nil. A cached nil is a value. Use v, ok := m[k].
  • Expecting a stale value never to be returned. With a stale TTL above zero, a value past its fresh TTL is returned at once and refreshed in the background. Use a zero stale TTL where that is not acceptable.
  • Values that expire on their own (tokens, signed URLs) cached for the layer TTL. Use WithMaxAge so an entry never outlives the value.
  • Expecting a broken layer to be skipped. If a layer cannot be read, the read fails rather than sending every request to the source.
  • Checking a backend right after Get returns. The answer is returned before it is written into the layers. Call Close first in tests.
  • A key with a } but no hash tag (such as a}b). Such keys are not supported: Get, GetMany, Set and SetMany fail with ErrUnsupportedKey for them; Del and DelMany do nothing (nothing was stored). Give it a hash tag ({user:1}:profile) or drop the }.

Writes

  • Writing the cache before the source, or only the cache. Set and Del never write the source. Change the source first, then call Set or Del on the same Cache; the other order lets a read in between cache the old value again.
  • Expecting a write in one process to reach another's memory layer. It does not; there only the TTLs bound how long old data lives. Turn on the invalidation broadcast, or set the memory layer's TTLs to what you can accept; turn leases on for a shared Redis (see Several instances), or its TTLs bound old data too.
  • Expecting Del to record that the key no longer exists. It only drops the entries; the next read asks the source.
  • Ignoring an error from Set or Del. The layers below the failed one may hold the new value; the key is dropped from the failed layer and those above (best effort). The source is as you left it.

Values and backends

  • Modifying a value you got from an in-memory backend (ottercachex, cachextest.Map). It is the stored value itself, shared with every reader. Treat values as read-only, or copy them.

  • Changing a value type incompatibly and keeping KeyPrefix. JSON decodes leniently: a renamed field reads back as a zero value. Change KeyPrefix with the type.

  • ottercachex without a bound. New fails: set MaximumSize, or MaximumWeight with a Weigher.

  • bigcachex with a LifeWindow shorter than the layer's TTLs. Entries disappear early. Use it only for millions of entries where GC shows in profiles; every read decodes.

  • gormcachex without Migrate, or a MySQL table not in utf8mb4_0900_bin. Migrate creates the table, and rejects an existing MySQL table whose key column uses any other collation. Keys, KeyPrefix included, are at most 255 characters of valid UTF-8 without NUL; any other key always misses and fails to be written. Expired rows are not deleted for you: call DeleteExpired from time to time (goquecachex.StartCleanup runs it on one instance, on PostgreSQL). Only each database's default isolation level is supported.

  • Calling Set/Del inside the transaction that changes the source. gormcachex never joins it: every statement commits on its own, so a rollback does not undo the cache. Call them after the commit.

  • A cachextest.Clock far behind the wall clock, with a backend that expires entries. Backends expire entries by the wall clock whatever WithNow says, so they drop entries computed by such a clock at once and every read misses. Start the clock at time.Now(), or use cachextest.Map.

  • gobuscachex without PostgreSQL. go-bus runs on PostgreSQL only: with MySQL, it would take a PostgreSQL of its own just for the broadcast. Use it when the database is PostgreSQL and there is no Redis; otherwise use rediscachex.NewBroadcast.

Lifecycle

  • Closing the backends while the Cache still works. Call Close first: it stops listening to the broadcast, if any, and waits for the fetches in progress and their backfills, background refreshes, and the invalidations of writes that gave up waiting (and their publishes).
  • Exiting right after a read (a command-line tool, a cron job). A read returns before its answer is written into the layers, so the process can end before Redis or the table is filled, and the next run fetches again. Call Close before exiting.

Documentation

License

MIT

Documentation

Overview

Package cachex is a multi-layer read-through cache: a Cache reads its layers top down (memory, then Redis, then a database table, say) and asks the source only when none of them has a usable entry. Concurrent misses of a key are fetched once; writes through the Cache reach every layer in one order. See docs/design.md.

Index

Constants

View Source
const (
	DefaultFetchTimeout       = 60 * time.Second
	DefaultGetManyConcurrency = 16
)

Defaults of the Cache options.

View Source
const DefaultJitter = 0.1

DefaultJitter is the jitter of a layer that does not set one (see Jitter).

Variables

View Source
var ErrNotFound = errors.New("cachex: not found")

ErrNotFound reports that a key does not exist. Sources return it from Get for a missing key; Cache.Get returns it for a key the source does not have, whether it was just asked or a cached not-found answered. Test with errors.Is.

View Source
var ErrUnsupportedKey = errors.New("cachex: unsupported key: it holds a \"}\" but no hash tag")

ErrUnsupportedKey reports a key that holds a "}" but no hash tag: a "{" followed, later, by a "}" with something between them, as Redis Cluster reads it. Such a key cannot share its Redis Cluster slot with the key of its lease, so the Cache rejects it whatever its layers, and a key that works now keeps working when a layer moves to Redis: Get, GetMany, Set and SetMany fail it, Del and DelMany do nothing (it was never stored). Test with errors.Is.

Functions

func IsShared

func IsShared(ctx context.Context) bool

IsShared reports whether ctx belongs to a fetch shared by every request of a key rather than to one caller: it carries the caller's values but not its cancellation, and a backend must not use caller state from it, such as a database transaction.

func NewBatchError

func NewBatchError(errs map[string]error) error

NewBatchError returns a *BatchError listing errs, or nil if errs is empty: what a backend's Many method returns after trying every key.

Types

type Backend

type Backend[T any] interface {
	Get(ctx context.Context, key string) (Entry[T], bool, error)
	GetMany(ctx context.Context, keys []string) (map[string]Entry[T], error)
	Set(ctx context.Context, key string, entry Entry[T]) error
	SetMany(ctx context.Context, entries map[string]Entry[T]) error
	Del(ctx context.Context, key string) error
	DelMany(ctx context.Context, keys []string) error
}

Backend stores the entries of one layer. A missing key is not an error: Get reports it with false, GetMany leaves it out of the map. The Many methods are best effort: a failure of some keys is reported as a *BatchError listing them (returned as is, not wrapped); any other error means the whole call failed. A store with single-key operations only can implement SingleBackend and be wrapped with Batched.

func Batched

func Batched[T any](b SingleBackend[T]) Backend[T]

Batched turns a SingleBackend into a Backend whose Many methods go key by key, best effort: the keys that fail are reported in a *BatchError. It forwards b's LocalBackend and Leasing, if b has them.

func Encoded

func Encoded[T any](b ByteBackend, codec Codec[T], logger *slog.Logger) Backend[T]

Encoded turns a ByteBackend into a Backend that stores each entry as bytes: its times, whether it is a not-found, and its value as codec (nil: DefaultCodec) marshals it. Data that does not decode is a miss, not a failure: it was written by something else, or before the value's type changed, so Encoded logs a WARN to logger (nil: slog.Default()), deletes the key, and reports it absent. An entry already past its ExpiresAt is not written: its key is deleted instead. That is judged by the wall clock (time.Now), as backends expire entries by it, whatever clock the Cache uses. It forwards ByteLeasing (as Leasing) and ByteLocalBackend (as LocalBackend).

type BatchError

type BatchError struct {
	Errors map[string]error
}

BatchError lists the keys a batch operation failed for. Keys that do not exist are never in it.

func (*BatchError) Error

func (e *BatchError) Error() string

type BatchSource

type BatchSource[T any] interface {
	GetMany(ctx context.Context, keys []string) (map[string]T, error)
}

BatchSource is a Source that can answer many keys in one call; GetMany uses it when the source implements it. A key the source does not have is absent from the map (not an error). A *BatchError returned as is fails only the keys it lists; any other error fails every key. An error that wraps ErrNotFound (for a key, or for the call) reads its keys as not found but caches nothing, so each read asks again: leave missing keys out instead.

type Broadcast

type Broadcast interface {
	// Publish sends msg to every instance listening; it may reach this one
	// too.
	Publish(ctx context.Context, msg []byte) error
	// Listen calls deliver with each message published, one at a time, until
	// ctx ends, and returns then. It calls ready each time it subscribes,
	// before delivering what is published from then on: what was published
	// while it was not subscribed is lost.
	Listen(ctx context.Context, ready func(), deliver func(msg []byte)) error
}

Broadcast carries invalidations between the instances of a Cache: the keys each write changed, so that the other instances drop them from their local layers (see WithBroadcast). Messages are opaque to it.

type ByteBackend

type ByteBackend interface {
	Get(ctx context.Context, key string) ([]byte, bool, error)
	GetMany(ctx context.Context, keys []string) (map[string][]byte, error)
	// Set stores data until expiresAt, which Encoded passes only in the
	// future; the backend may drop the key from then on.
	Set(ctx context.Context, key string, data []byte, expiresAt time.Time) error
	SetMany(ctx context.Context, entries map[string]ByteEntry) error
	Del(ctx context.Context, key string) error
	DelMany(ctx context.Context, keys []string) error
}

ByteBackend stores bytes by key, for a backend that stores entries encoded: wrap it with Encoded to get a Backend. Like Backend, a missing key is not an error (Get reports it with false, GetMany leaves it out of the map), and the Many methods are best effort: a failure of some keys is a *BatchError listing them, returned as is; any other error means the whole call failed. The single-key methods return plain errors.

type ByteEntry

type ByteEntry struct {
	Data      []byte
	ExpiresAt time.Time
}

ByteEntry is an encoded entry for ByteBackend.SetMany, and when it expires.

type ByteLeaser

type ByteLeaser interface {
	Lease(ctx context.Context, keys []string, ttl time.Duration) (map[string]string, error)
	PutLeased(ctx context.Context, tokens map[string]string, entries map[string]ByteEntry) error
	Release(ctx context.Context, tokens map[string]string) error
}

ByteLeaser is Leaser for a ByteBackend; Encoded turns it into a Leaser. Like ByteBackend.Set, PutLeased gets only entries that expire in the future.

type ByteLeasing

type ByteLeasing interface {
	Leaser() ByteLeaser
}

ByteLeasing is a ByteBackend that can lease its keys; see Leasing.

type ByteLocalBackend

type ByteLocalBackend interface {
	Clear(ctx context.Context) error
}

ByteLocalBackend is LocalBackend for a ByteBackend; Encoded forwards it.

type Cache

type Cache[T any] struct {
	// contains filtered or unexported fields
}

Cache reads through its layers to its source. Build it with New.

func New

func New[T any](source Source[T], layers []Layer[T], opts ...Option) *Cache[T]

New returns a Cache reading layers top down (layers[0] first) and then source. With no layers it only merges concurrent fetches of a key.

func (*Cache[T]) Close

func (c *Cache[T]) Close() error

Close stops listening to the broadcast, if any, and waits for the fetches and background refreshes in progress (and their backfills) and for the invalidations of writes that gave up waiting (and their publishes), so that the backends can be closed after it, and starts no more background refreshes. It does not close the backends. The Cache still serves reads and writes, but no longer hears of other instances' writes: its local layers may serve what they overwrote until it rots.

func (*Cache[T]) Del

func (c *Cache[T]) Del(ctx context.Context, key string) error

Del drops key from every layer, bottom up, so the next read asks the source. Like Set, call it after changing the source; it records nothing about whether the key exists. Failures and waiting are as for Set.

func (*Cache[T]) DelMany

func (c *Cache[T]) DelMany(ctx context.Context, keys []string) error

DelMany is Del for many keys, with one call per layer; failures are reported as for SetMany.

func (*Cache[T]) Get

func (c *Cache[T]) Get(ctx context.Context, key string) (T, error)

Get returns key's value from the first layer with a usable entry, or else from the source; concurrent misses of a key share one fetch, whose result is backfilled into the layers above where it was found. A stale entry is returned at once and refreshed in the background. Get returns ErrNotFound for a key the source does not have.

func (*Cache[T]) GetMany

func (c *Cache[T]) GetMany(ctx context.Context, keys []string) (map[string]T, error)

GetMany returns the values of keys that exist, with the semantics of calling Get for each: the first layer is read in one call, the layers below and a BatchSource in one call per chunk (see WithGetManyChunkSize; by default one chunk), any other source key by key (see WithGetManyConcurrency), and keys being fetched by other calls are waited for, not fetched again. A key the source does not have is absent from the map. If some keys failed, the map holds every other key and the error is a *BatchError listing the failed ones.

func (*Cache[T]) Set

func (c *Cache[T]) Set(ctx context.Context, key string, value T) error

Set writes value for key into every layer, bottom up, as if the source had just answered it. It does not write the source: change the source first, then call Set (or Del), so that a read in between cannot cache the old value after the write.

Until Set returns, a concurrent read may still see the old value; once it returns, no read gets a value fetched before it, and a fetch that started before it does not backfill over it. Writes of one key through one Cache apply one at a time, in the same order on every layer. If a layer fails, the key is dropped from that layer and every layer above it (what the layers below hold was written), and the error is returned.

Set waits while another write of a key in the same stripe is in progress; if ctx ends first it returns ctx's error, writes nothing, and drops the key from every layer once the stripe is free, since the caller may have changed the source already (with a broadcast, it publishes the key again then).

func (*Cache[T]) SetMany

func (c *Cache[T]) SetMany(ctx context.Context, values map[string]T) error

SetMany is Set for many keys, with one call per layer. A key that fails in a layer is dropped from that layer and those above and listed in the returned *BatchError; the other keys are written. An error that is not a *BatchError means nothing was written (ctx ended while waiting).

type Codec

type Codec[T any] interface {
	Marshal(value T) ([]byte, error)
	Unmarshal(data []byte) (T, error)
}

Codec turns values into bytes and back, for backends that store bytes.

func DefaultCodec

func DefaultCodec[T any]() Codec[T]

DefaultCodec stores []byte and string values as they are, values whose T implements encoding.BinaryMarshaler (and *T BinaryUnmarshaler) as they marshal themselves, and anything else as JSON.

func JSONCodec

func JSONCodec[T any]() Codec[T]

JSONCodec encodes values as JSON.

type Entry

type Entry[T any] struct {
	Value    T
	NotFound bool // the source does not have the key; Value is the zero value

	// CachedAt is when the source answered; an entry copied from a lower layer
	// keeps it.
	CachedAt time.Time
	// FreshUntil is when the entry turns stale: still served (and refreshed in
	// the background) until ExpiresAt, if the layer has a stale TTL.
	FreshUntil time.Time
	// ExpiresAt is when the entry is rotten: never served again. A backend may
	// drop it from then on.
	ExpiresAt time.Time
}

Entry is what a layer stores for one key: a value, or a record that the source does not have the key, and when it stops being fresh and usable. The Cache computes every field and never serves an entry past ExpiresAt; a backend stores it as given and may drop it from then on (rediscachex and ottercachex expire it natively).

type Layer

type Layer[T any] struct {
	// contains filtered or unexported fields
}

Layer is one level of a Cache: a backend and how long its entries stay fresh and usable. Build it with NewLayer.

func NewLayer

func NewLayer[T any](backend Backend[T], opts ...LayerOption) Layer[T]

NewLayer returns a layer storing its entries in backend.

type LayerOption

type LayerOption func(*layerConfig)

LayerOption configures a Layer.

func Jitter

func Jitter(ratio float64) LayerOption

Jitter shortens each entry's fresh period by a random part of up to ratio (in [0, 1), default DefaultJitter), so entries written together do not all turn stale or rotten at the same moment. It never lengthens one.

func NotFoundTTL

func NotFoundTTL(fresh, stale time.Duration) LayerOption

NotFoundTTL is TTL for the answer that a key does not exist. With a zero fresh (the default) the layer does not record such answers.

func TTL

func TTL(fresh, stale time.Duration) LayerOption

TTL sets how long a value stays fresh and, after that, how long it is still served stale while being refreshed in the background (zero: not at all). Both count from when an entry is written into the layer (an answer of the source, a copy from a layer below, a Set); a copy is never fresher or longer lived than the entry it came from. Required, with a positive fresh; fresh plus stale is at most 100 years.

type Leaser

type Leaser[T any] interface {
	// Lease takes a lease, for ttl, on each of keys that nobody leases, and
	// returns a token for each lease it took. A key leased by someone else is
	// left out; a key that failed, or that the backend cannot lease (one it
	// cannot store, say), is left out and reported in the error.
	Lease(ctx context.Context, keys []string, ttl time.Duration) (map[string]string, error)
	// PutLeased writes, for each key of tokens whose lease still holds its
	// token, the key's entry in entries, or deletes the key if it has none, and
	// ends its lease. A key whose lease has ended or holds another token is
	// left alone, without an error.
	PutLeased(ctx context.Context, tokens map[string]string, entries map[string]Entry[T]) error
	// Release ends, for each key of tokens, its lease if it still holds the
	// token, and writes nothing.
	Release(ctx context.Context, tokens map[string]string) error
}

Leaser keeps an old answer out of a layer that several instances share. A fetch leases the keys it misses in the layer, before it reads further down; a write of a key (Set, SetMany, Del, DelMany on the backend) ends its lease; and the fetch backfills the layer only with the keys whose lease it still holds. So an answer read before another instance's write is never written over it. A Cache never waits for a lease another instance holds: it fetches the key anyway, without backfilling that layer.

Like Backend's Many methods, its methods are best effort: a *BatchError returned as is fails only the keys it lists; any other error fails every key.

type Leasing

type Leasing[T any] interface {
	Leaser() Leaser[T]
}

Leasing is a Backend that can lease its keys. Its Leaser returns nil when leases are off; when they are on, every write of a key ends its lease. Wrappers of a backend forward it.

type LocalBackend

type LocalBackend interface {
	Clear(ctx context.Context) error
}

LocalBackend is a Backend whose entries live in this process only, such as one in memory: a write on another instance never reaches it through a shared layer. Its layers are the ones a broadcast invalidates (see WithBroadcast), and Clear drops all of their entries when a broadcast may have been missed. A backend shared by instances must not implement it.

type Option

type Option func(*options)

Option configures a Cache.

func WithBroadcast

func WithBroadcast(b Broadcast) Option

WithBroadcast makes the Cache share its writes with the other instances over b: after a write, it publishes the keys it wrote, and an instance that receives them drops them from its local layers (those whose backend is a LocalBackend), through the write-order guard as a write of its own would. The shared layers were written by the writer. Each time b subscribes, the Cache clears its local layers, as a message may have been lost. A Cache with a broadcast needs a local layer. A publish that fails is tried again twice; if it still fails it is logged as an error, not returned (the layers were written), and the other instances serve what their local layers hold of those keys until it stops being fresh there.

func WithFetchTimeout

func WithFetchTimeout(timeout time.Duration) Option

WithFetchTimeout bounds, each on its own: a fetch's double check, each lower layer read together with the backfill of what it found, each source call together with the backfill of its answers, taking and releasing leases (a lease lasts two of it), the invalidation after a failed write, a broadcast's publish of each message, a received invalidation, and the clear after subscribing again. Default DefaultFetchTimeout.

func WithGetManyChunkSize

func WithGetManyChunkSize(size int) Option

WithGetManyChunkSize splits the keys one GetMany fetches (and a background refresh of many keys) into chunks of at most size keys. A chunk is claimed when it starts, read from each layer below the first in one call, and sent to the source in one call (a BatchSource) or as a Get per key; its answers are returned and backfilled as soon as they arrive. The keys of a chunk not started yet are not claimed: a Get of one of them fetches it at once instead of waiting for the GetMany, and if the GetMany's ctx ends they are not fetched at all. Smaller chunks cost more calls to the lower layers. Zero (the default) makes all the keys one chunk.

func WithGetManyConcurrency

func WithGetManyConcurrency(n int) Option

WithGetManyConcurrency sets how many source requests one GetMany has in flight at once: Get calls if the source is not a BatchSource, chunk calls otherwise. A chunk (see WithGetManyChunkSize) starts only when the source has room for its requests. Default DefaultGetManyConcurrency.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger for failures that do not fail a call (a failed backfill, invalidation or background refresh) and for panics in fetches. Default slog.Default().

func WithMaxAge

func WithMaxAge[T any](maxAge func(T) time.Duration) Option

WithMaxAge caps how long a value from the source is kept, in every layer: maxAge is called once when the value is fetched, and the entry is never served after that much time (zero or less: the value is not cached). Use it for values that expire on their own, such as tokens. Set and SetMany call it too, for the values they write. Its argument type must be the Cache's T, or New panics.

func WithNow

func WithNow(now func() time.Time) Option

WithNow sets the clock the Cache computes and judges entries by. Default time.Now. A backend that expires entries natively does so by the wall clock, whatever this clock says (see Encoded): with a clock far behind the wall clock, it drops every entry at once.

type SingleBackend

type SingleBackend[T any] interface {
	Get(ctx context.Context, key string) (Entry[T], bool, error)
	Set(ctx context.Context, key string, entry Entry[T]) error
	Del(ctx context.Context, key string) error
}

SingleBackend is a Backend without the Many methods; see Batched.

type SliceGetter

type SliceGetter[T any] interface {
	GetInto(ctx context.Context, keys []string, entries []Entry[T], found []bool) error
}

SliceGetter is an optional Backend method for the first layer: GetInto reads keys into entries and found (both as long as keys), entries[i] and found[i] being what Get returns for keys[i], with errors as GetMany's. A GetMany of the Cache uses it instead of the backend's GetMany: that map allocates once per entry when Entry[T] is over 128 bytes (a value type of over 48 bytes, say), as Go maps hold larger values out of line. A wrapper that embeds a backend having GetInto and overrides GetMany must override GetInto too (or embed the Backend interface), or reads bypass its GetMany.

type Source

type Source[T any] interface {
	Get(ctx context.Context, key string) (T, error)
}

Source is where the data lives, asked when no layer has a usable entry. Get returns ErrNotFound (possibly wrapped) for a key it does not have.

type SourceFunc

type SourceFunc[T any] func(ctx context.Context, key string) (T, error)

SourceFunc adapts a function to a Source.

func (SourceFunc[T]) Get

func (f SourceFunc[T]) Get(ctx context.Context, key string) (T, error)

Get calls f.

Directories

Path Synopsis
Package bigcachex is an in-memory cachex backend that stores entries as bytes in a BigCache, out of reach of the garbage collector: worth it when the memory layer holds millions of values and GC shows in profiles, at the cost of decoding on every read.
Package bigcachex is an in-memory cachex backend that stores entries as bytes in a BigCache, out of reach of the garbage collector: worth it when the memory layer holds millions of values and GC shows in profiles, at the cost of decoding on every read.
Package cachextest has helpers for testing code that uses cachex: an in-memory Backend (with leases, NewLeasingMap), an in-memory broadcast (NewBus), a manual clock, and the contract tests for Backend, ByteBackend, Leaser and Broadcast implementations (TestBackend, TestByteBackend, TestLeaser, TestBroadcast).
Package cachextest has helpers for testing code that uses cachex: an in-memory Backend (with leases, NewLeasingMap), an in-memory broadcast (NewBus), a manual clock, and the contract tests for Backend, ByteBackend, Leaser and Broadcast implementations (TestBackend, TestByteBackend, TestLeaser, TestBroadcast).
Package gobuscachex is the cachex invalidation broadcast over go-bus (github.com/qor5/go-bus), a publish-subscribe bus on PostgreSQL, which it needs: it is for deployments on PostgreSQL that have no Redis (with MySQL, use rediscachex.NewBroadcast).
Package gobuscachex is the cachex invalidation broadcast over go-bus (github.com/qor5/go-bus), a publish-subscribe bus on PostgreSQL, which it needs: it is for deployments on PostgreSQL that have no Redis (with MySQL, use rediscachex.NewBroadcast).
Package goquecachex runs a cache's cleanup (gormcachex's DeleteExpired) as a recurring job on go-que (github.com/qor5/go-que), on one instance at a time however many run it.
Package goquecachex runs a cache's cleanup (gormcachex's DeleteExpired) as a recurring job on go-que (github.com/qor5/go-que), on one instance at a time however many run it.
Package gormcachex is a cachex backend on a database table through GORM: one row per key, the entry encoded in the value column.
Package gormcachex is a cachex backend on a database table through GORM: one row per key, the entry encoded in the value column.
internal
flight
Package flight is a singleflight whose Claim answers at once whether the caller now leads the fetch of a key.
Package flight is a singleflight whose Claim answers at once whether the caller now leads the fetch of a key.
stripe
Package stripe orders the writes and backfills of keys without a lock per key: keys hash into a fixed number of stripes, each with a read-write lock and two counters.
Package stripe orders the writes and backfills of keys without a lock per key: keys hash into a fixed number of stripes, each with a read-write lock and two counters.
Package ottercachex is an in-memory cachex backend built on otter: bounded by entry count or weight, and each entry expires at its own ExpiresAt.
Package ottercachex is an in-memory cachex backend built on otter: bounded by entry count or weight, and each entry expires at its own ExpiresAt.
Package rediscachex is a cachex backend on Redis (or Redis Cluster): each entry is one string key, expiring natively at the entry's ExpiresAt.
Package rediscachex is a cachex backend on Redis (or Redis Cluster): each entry is one string key, expiring natively at the entry's ExpiresAt.

Jump to

Keyboard shortcuts

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