Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ jobs:
- name: govulncheck
run: make vuln

# Integration tests. db, cache, kafka and rabbitmq start their dependencies
# Integration tests. db, kafka and rabbitmq start their dependencies
# with testcontainers (Docker is available on ubuntu-latest); oauth2 and i18n
# use in-process fakes.
integration:
Expand All @@ -55,7 +55,7 @@ jobs:
strategy:
fail-fast: false
matrix:
module: [db, cache, kafka, rabbitmq, oauth2, i18n]
module: [db, kafka, rabbitmq, oauth2, i18n]
defaults:
run:
working-directory: ${{ matrix.module }}
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Multi-module Go monorepo. Each subdirectory is its own Go module.
| Module | Module path (go.mod) | Has Makefile | Docker needed for tests |
|--------|---------------------|--------------|------------------------|
| db/ | `db` | yes | yes (testcontainers) |
| cache/ | `cache` | yes | no* — unit tests use miniredis |
| cache/ | `cache` | yes | no — unit tests use miniredis |
| kafka/ | `kafka` | yes | yes (testcontainers) |
| rabbitmq/ | `rabbitmq` | yes | yes (testcontainers) |
| oauth2/ | `oauth2` | yes | no* — mock OIDC server |
Expand Down
8 changes: 2 additions & 6 deletions cache/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@

include ../Makefile.common

# Everything, including the integration tests (needs Docker: testcontainers).
test:
go test -tags integration -v -count=1 -timeout 300s ./...

# Unit tests only: no Docker, the integration tests are excluded by build tag.
test-unit:
# All tests are unit tests on miniredis: no Docker needed.
test test-unit:
go test -count=1 -timeout 120s ./...
74 changes: 20 additions & 54 deletions cache/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[![Go Reference](https://pkg.go.dev/badge/github.com/Chandra179/fiddle/cache.svg)](https://pkg.go.dev/github.com/Chandra179/fiddle/cache)

A small key-value `Cache` interface with a cache-aside helper. Redis is the bundled implementation. Minimal surface, battle-tested patterns.
A small key-value `Cache` interface with a cache-aside helper. Redis is the bundled implementation. Minimal surface.

## Install

Expand All @@ -20,6 +20,7 @@ package main
import (
"context"
"fmt"
"log"
"time"

"github.com/Chandra179/fiddle/cache"
Expand All @@ -35,7 +36,7 @@ func main() {
})
defer c.Close()

// Read-through: returns the cached value, or runs Load and stores the result.
// Returns the cached value, or runs Load and stores the result.
user, err := cacheaside.GetOrSet(ctx, cacheaside.GetOrSetRequest{
Cache: c,
Key: "user:42",
Expand All @@ -45,77 +46,42 @@ func main() {
},
Options: cacheaside.GetOrSetOptions{
LoadTimeout: 2 * time.Second,
OnError: func(err error) { fmt.Println("cache error:", err) },
OnError: func(err error) { log.Println("cache error:", err) },
},
})
if err != nil {
panic(err)
log.Fatal(err)
}
fmt.Println(user)

// Direct use of the Cache interface.
if err := c.Set(ctx, "greeting", "hello", time.Minute); err != nil {
panic(err)
}
v, err := c.Get(ctx, "greeting")
if cache.IsCacheMiss(err) {
fmt.Println("not cached")
} else if err != nil {
panic(err)
} else {
fmt.Println(v)
}
}
```

## Current API
## API

```go
type Cache interface {
Set(ctx context.Context, key string, value string, ttl time.Duration) error
SetNX(ctx context.Context, key string, value string, ttl time.Duration) (bool, error)
Get(ctx context.Context, key string) (string, error)
Del(ctx context.Context, key string) error
DelIfValue(ctx context.Context, key, value string) (bool, error)
Ping(ctx context.Context) error
Close() error
}
```

- `Cache` is backend-neutral. `cacheaside` works with any implementation; `redis_cache.go` provides one backed by Redis.
- `NewRedisCacheFromConfig(RedisConfig)` builds a `Cache` with auth, TLS, DB, pool, and timeout settings. It does not connect; a failure shows on the first operation. `NewRedisCache(addr)` is the no-auth shortcut.
- `Get` returns `ErrCacheMiss` for a missing key. Check it with `cache.IsCacheMiss(err)`.
- `SetNX` and `DelIfValue` are low-level primitives. `cacheaside.GetOrSet` does not use them.
The `Cache` interface (see [pkg.go.dev](https://pkg.go.dev/github.com/Chandra179/fiddle/cache) for signatures):

## Cache-aside (`cache/cacheaside`)
- `Set`, `Get`, `Del`: basic key-value access. `Get` returns `ErrCacheMiss` for a missing key; test it with `cache.IsCacheMiss(err)`.
- `SetNX`, `DelIfValue`: lock primitives. `SetNX` requires a positive TTL and returns `ErrInvalidTTL` otherwise. `cacheaside.GetOrSet` does not use them.
- `Ping`, `Close`.

`cacheaside.GetOrSet` is the read path of the cache-aside pattern. A call checks the cache, runs `Load` on a miss, and stores the result. Writes and invalidation stay with the caller. See [diagrams/cache_aside.md](diagrams/cache_aside.md) for the read path, failure behavior, and use cases.
`NewRedisCacheFromConfig(RedisConfig)` builds a Redis-backed `Cache` with auth, TLS, DB, pool and timeout settings. It does not connect; a failure shows on the first operation. `NewRedisCache(addr)` is the no-auth shortcut.

| Behavior | Details |
|---|---|
| Stampede control | Concurrent misses for one key share one `Load` per process. Not coordinated across instances. |
| TTL jitter | Stored TTL varies by ±10%, so keys do not expire together. |
| `LoadTimeout` | Bounds one `Load` (default 5s). Callers waiting on the same key share this budget. |
| Degradation | A failed read counts as a miss. A failed write still returns the value. Both are reported to `OnError`. |
| `CacheNil` | Optionally stores empty results so known-missing keys are not reloaded. |
## Cache-aside (`cache/cacheaside`)

Each `GetOrSet` call takes a `cacheaside.GetOrSetRequest`. Keys must be unique per source: concurrent loads share one singleflight group across every `Cache` in the process.
`cacheaside.GetOrSet` is the read path of the cache-aside pattern: check the cache, run `Load` on a miss, store the result. Concurrent misses for a key share one `Load` per process, stored TTLs vary by ±10%, and cache failures degrade to the loader instead of failing the call. Writes and invalidation stay with the caller. See [diagrams/cache_aside.md](diagrams/cache_aside.md) for the read path, failure behavior, options and use cases.

## Package layout
Caveats:

| Path | Contents |
|---|---|
| `client.go` | `Cache` interface, `ErrCacheMiss`, `IsCacheMiss` |
| `redis_cache.go` | Redis implementation and constructors |
| `cacheaside/` | `GetOrSet` and its request and option types |
| `example/` | Integration tests (Docker required, build tag `integration`) |
| `diagrams/` | Design notes |
- `Load` must return failures as errors and must not panic. A panic in `Load` cannot be recovered by the caller and ends the process.
- Stampede control covers one process and one `Cache` instance; instances that miss together each run `Load`.
- A `Load` result equal to the internal nil sentinel (`"\x00nil\x00"`) reads back as an empty string.
- A `Del` that lands while a `Load` is in flight can be overwritten by that load's stale result, which then stays cached for a full TTL.
- A zero or negative `TTL` stores the value without expiry.

## Testing

```bash
make test-unit # unit tests, miniredis, no Docker
make test # all tests, integration needs Docker
make test # unit tests on miniredis, no Docker needed
```

## License
Expand Down
66 changes: 49 additions & 17 deletions cache/cacheaside/cacheaside.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ package cacheaside

import (
"context"
"fmt"
"math/rand/v2"
"reflect"
"time"

"github.com/Chandra179/fiddle/cache"
Expand All @@ -15,22 +17,36 @@ import (

const (
defaultLoadTimeout = 5 * time.Second
nilSentinel = "\x00nil\x00"
// cacheOpTimeout bounds each cache read or write made inside a load, so a
// slow cache cannot use up the time LoadTimeout gives the loader.
cacheOpTimeout = time.Second
nilSentinel = "\x00nil\x00"
// jitterFraction spreads expiry by up to ±10% so keys stored together do
// not expire together.
jitterFraction = 0.1
)

// loads coalesces concurrent loads for the same key within this process. It is
// shared by every Cache in the process, so the same key on two Caches (for
// example two Redis databases) shares one load.
// keyed by Cache instance and key, so the same key on two Caches (for example
// two Redis databases) loads separately.
var loads singleflight.Group

// flightKey scopes key to the Cache it is stored in. Scoping needs a pointer
// Cache, which every constructor here returns; any other Cache shares loads by
// key alone.
func flightKey(c cache.Cache, key string) string {
if v := reflect.ValueOf(c); v.Kind() == reflect.Pointer {
return fmt.Sprintf("%x\x00%s", v.Pointer(), key)
}
return key
}

// GetOrSetOptions tunes one GetOrSet call. Zero values select the defaults.
type GetOrSetOptions struct {
// LoadTimeout bounds one run of Load. Concurrent callers for the key wait for
// that run, so it also bounds their wait. Set it above the loader's p99
// latency. Defaults to 5s.
// latency. Defaults to 5s. The cache read before and the write after Load
// have their own 1s limit each, so a caller can wait slightly longer.
LoadTimeout time.Duration
// CacheNil stores an empty result as a sentinel, so a known-missing key is
// not reloaded on every call.
Expand All @@ -45,11 +61,14 @@ type GetOrSetOptions struct {
type GetOrSetRequest struct {
// Cache is the store to read from and write to.
Cache cache.Cache
// Key is the cache key. Load runs once per key within the process.
// Key is the cache key. Load runs once per Cache and key within the process.
Key string
// TTL is the stored lifetime, varied by ±10%. Zero means no expiry.
// TTL is the stored lifetime, varied by ±10%. Zero or negative means no expiry.
TTL time.Duration
// Load computes the value on a miss.
// Load computes the value on a miss. It must report failures by returning an
// error, never by panicking: a panic in Load cannot be recovered by the
// caller and ends the process. A result equal to the internal nil sentinel
// ("\x00nil\x00") reads back as an empty string.
Load func(context.Context) (string, error)
// Options tunes the call. Zero values select the defaults.
Options GetOrSetOptions
Expand All @@ -74,11 +93,11 @@ func GetOrSet(ctx context.Context, req GetOrSetRequest) (string, error) {
}
req.Options = withDefaults(req.Options)

if val, ok := lookup(ctx, req.Cache, req.Key, req.Options); ok {
if val, ok := boundedLookup(ctx, req); ok {
return val, nil
}

ch := loads.DoChan(req.Key, func() (any, error) {
ch := loads.DoChan(flightKey(req.Cache, req.Key), func() (any, error) {
return load(ctx, req)
})
// The caller stops waiting when its ctx ends. The load keeps running for
Expand All @@ -103,7 +122,7 @@ func load(ctx context.Context, req GetOrSetRequest) (string, error) {
defer cancel()

// Another process may have stored the key since our first read.
if val, ok := lookup(ctx, req.Cache, req.Key, req.Options); ok {
if val, ok := boundedLookup(ctx, req); ok {
return val, nil
}

Expand All @@ -120,18 +139,31 @@ func load(ctx context.Context, req GetOrSetRequest) (string, error) {
}
storeVal = nilSentinel
}
if err := req.Cache.Set(ctx, req.Key, storeVal, jitter(req.TTL)); err != nil {
// Set gets its own budget: Load may have used all of ctx.
writeCtx, cancelWrite := context.WithTimeout(context.WithoutCancel(ctx), cacheOpTimeout)
defer cancelWrite()
if err := req.Cache.Set(writeCtx, req.Key, storeVal, jitter(req.TTL)); err != nil {
// The value is still good. The next call will load it again.
req.Options.report(err)
}
return result, nil
}

// boundedLookup is lookup limited to cacheOpTimeout, so a hung cache costs one
// short wait instead of the caller's whole deadline.
func boundedLookup(ctx context.Context, req GetOrSetRequest) (string, bool) {
readCtx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
defer cancel()
return lookup(ctx, readCtx, req.Cache, req.Key, req.Options)
}

// lookup returns the cached value and whether it was found. A read error other
// than a miss is reported and treated as a miss. Once ctx has ended, the error
// is a result of the caller leaving, so it is not reported.
func lookup(ctx context.Context, c cache.Cache, key string, o GetOrSetOptions) (string, bool) {
val, err := c.Get(ctx, key)
// is a result of the caller leaving, so it is not reported. The read itself
// runs under readCtx, which may be a shorter-lived child of ctx: its timeout is
// a cache failure and is reported.
func lookup(ctx, readCtx context.Context, c cache.Cache, key string, o GetOrSetOptions) (string, bool) {
val, err := c.Get(readCtx, key)
if err == nil {
return fromStore(val), true
}
Expand All @@ -147,11 +179,11 @@ func (o GetOrSetOptions) report(err error) {
}
}

// jitter returns ttl changed by up to ±jitterFraction. A non-positive ttl (no
// expiry) is returned unchanged.
// jitter returns ttl changed by up to ±jitterFraction. A non-positive ttl means
// no expiry and returns 0.
func jitter(ttl time.Duration) time.Duration {
if ttl <= 0 {
return ttl
return 0
}
spread := float64(ttl) * jitterFraction
d := ttl + time.Duration((rand.Float64()*2-1)*spread)
Expand Down
Loading
Loading