PluginBench
Skill
Pass
Audit score 90

golang-samber-hot

samber/cc-skills-golang

Type-safe in-memory caching for Go with 9 eviction algorithms, TTL, loaders, and Prometheus metrics.

What is golang-samber-hot?

samber/hot is a generic caching library for Go 1.22+ offering multiple eviction strategies (LRU, LFU, TinyLFU, W-TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), automatic expiration, loader chains with singleflight deduplication, and built-in observability. Use it when your Go service repeatedly loads medium-to-low cardinality resources at high frequency and needs to reduce latency or backend pressure.

  • Choose from 9 eviction algorithms tuned to different access patterns (recency, frequency, scan-resistance, self-tuning)
  • Automatic TTL expiration with background janitor and jitter to prevent thundering herd
  • Read-through loaders with singleflight deduplication for concurrent miss coalescing and batch queries
  • Sharding, stale-while-revalidate, and missing-key caching for advanced patterns
  • Prometheus metrics integration for monitoring hit rate, evictions, and loader performance
  • Type-safe generics and builder pattern for ergonomic configuration

How to install golang-samber-hot

npx skills add https://github.com/samber/cc-skills-golang --skill golang-samber-hot
Prerequisites
  • Go 1.22 or later
  • github.com/samber/hot imported in the project (install via `go get -u github.com/samber/hot`)
Claude Code
Cursor
Windsurf
Cline

How to use golang-samber-hot

  1. 1.Estimate single-item size (struct + key + ~100 bytes overhead) and memory budget to compute capacity
  2. 2.Choose an eviction algorithm: start with W-TinyLFU unless profiling shows a better fit
  3. 3.Create a cache with `hot.NewHotCache[K, V](algorithm, capacity)` and chain builder methods
  4. 4.Enable TTL with `.WithTTL(duration)` and `.WithJanitor()` to auto-expire entries; always defer `cache.StopJanitor()`
  5. 5.Optionally add loaders with `.WithLoaders(fn)` for read-through caching and singleflight deduplication
  6. 6.Call `cache.Get(key)`, `cache.Set(key, value)`, or `cache.SetWithTTL(key, value, ttl)` in your code
  7. 7.Monitor hit rate and eviction metrics via Prometheus (`.WithPrometheusMetrics(name)`) to validate sizing

Use cases

Good for
  • Cache user profiles or product data fetched from a database, with W-TinyLFU for mixed workloads
  • Session storage with LRU eviction and per-entry TTL to auto-expire inactive sessions
  • DNS or API response caching with LFU to keep frequently queried entries hot
  • High-throughput request deduplication using S3FIFO to resist scan pollution
  • Monitoring cache hit rate via Prometheus to validate sizing and algorithm choice
Who it's for
  • Go backend engineers building services with repeated data access patterns
  • Systems engineers optimizing latency and reducing database or API backend load
  • Teams adopting samber/hot or refactoring existing map-based caches
  • Developers needing algorithm flexibility based on measured access patterns

golang-samber-hot FAQ

Which algorithm should I use?

Start with W-TinyLFU (default) for general-purpose mixed workloads. Switch only after profiling: use LRU for recency-dominated (sessions), LFU for frequency-dominated (popular items), S3FIFO for high throughput with scan resistance, or ARC for unknown patterns. See the Algorithm Selection table in the skill for detailed trade-offs.

How do I size the cache capacity?

Estimate the size of a single entry (struct + key + ~100 bytes overhead), then divide your memory budget by that size. Example: 500-byte user + 50-byte key + 100-byte overhead = 650 bytes; 256 MB budget ÷ 650 ≈ 393k items. Measure actual item size with a unit test if unsure; guessing leads to OOM or wasted memory.

What happens if I forget WithJanitor()?

Expired entries remain in memory until the eviction algorithm removes them, wasting space and serving stale data. Always chain `.WithJanitor()` and `defer cache.StopJanitor()` to clean up expired entries in the background.

How do loaders work and when should I use them?

Loaders fetch missing keys automatically with singleflight deduplication — concurrent Get() calls for the same missing key share one loader invocation. Use loaders for read-through caching (e.g., batch database queries) to reduce latency and backend pressure. Always check the error return value.

How do I prevent thundering herd on expiration?

Use `.WithJitter(lambda, upperBound)` to spread expiration times. Without jitter, items created together expire together, causing all concurrent requests to hit the loader at once. Jitter distributes expirations over time.

Full instructions (SKILL.md)

Source of truth, from samber/cc-skills-golang.


name: golang-samber-hot description: "In-memory caching in Golang using samber/hot — eviction algorithms (LRU, LFU, TinyLFU, W-TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, cache loaders, sharding, stale-while-revalidate, missing key caching, and Prometheus metrics. Apply when using or adopting samber/hot, when the codebase imports github.com/samber/hot, or when the project repeatedly loads the same medium-to-low cardinality resources at high frequency and needs to reduce latency or backend pressure." user-invocable: true license: MIT compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang. metadata: author: samber version: "1.1.2" openclaw: emoji: "🔥" homepage: https://github.com/samber/cc-skills-golang requires: bins: - go install: [] skill-library-version: "0.13.0" allowed-tools: Read Edit Write Glob Grep Bash(go:) Bash(golangci-lint:) Bash(git:) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs AskUserQuestion Bash(godig:) Bash(gopls:) LSP mcp__gopls__ paths:

  • "**/*.go"

Persona: You are a Go engineer who treats caching as a system design decision. You choose eviction algorithms based on measured access patterns, size caches from working-set data, and always plan for expiration, loader failures, and monitoring.

Using samber/hot for In-Memory Caching in Go

Generic, type-safe in-memory caching library for Go 1.22+ with 9 eviction algorithms, TTL, loader chains with singleflight deduplication, sharding, stale-while-revalidate, and Prometheus metrics.

Official Resources:

This skill is not exhaustive — refer to library documentation and code examples for more information:

  • For Go package docs, symbols, versions, importers, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill (godig), preferred over Context7 for Go package facts.
  • To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See samber/cc-skills-golang@golang-gopls skill (gopls).
  • Context7 remains a fallback for docs not indexed on pkg.go.dev.
go get -u github.com/samber/hot

Algorithm Selection

Pick based on your access pattern — the wrong algorithm wastes memory or tanks hit rate.

AlgorithmConstantBest forAvoid when
W-TinyLFUhot.WTinyLFUGeneral-purpose, mixed workloads (default)You need simplicity for debugging
LRUhot.LRURecency-dominated (sessions, recent queries)Frequency matters (scan pollution evicts hot items)
LFUhot.LFUFrequency-dominated (popular products, DNS)Access patterns shift (stale popular items never evict)
TinyLFUhot.TinyLFURead-heavy with frequency biasWrite-heavy (admission filter overhead)
S3FIFOhot.S3FIFOHigh throughput, scan-resistantSmall caches (<1000 items)
ARChot.ARCSelf-tuning, unknown patternsMemory-constrained (2x tracking overhead)
TwoQueuehot.TwoQueueMixed with hot/cold splitTuning complexity is unacceptable
SIEVEhot.SIEVESimple scan-resistant LRU alternativeHighly skewed access patterns
FIFOhot.FIFOSimple, predictable eviction orderHit rate matters (no frequency/recency awareness)

Decision shortcut: Start with hot.WTinyLFU. Switch only when profiling shows the miss rate is too high for your SLO.

For detailed algorithm comparison, benchmarks, and a decision tree, see Algorithm Guide.

Core Usage

Basic Cache with TTL

import "github.com/samber/hot"

cache := hot.NewHotCache[string, *User](hot.WTinyLFU, 10_000).
    WithTTL(5 * time.Minute).
    WithJanitor().
    Build()
defer cache.StopJanitor()

cache.Set("user:123", user)
cache.SetWithTTL("session:abc", session, 30*time.Minute)

value, found, err := cache.Get("user:123")

Loader Pattern (Read-Through)

Loaders fetch missing keys automatically with singleflight deduplication — concurrent Get() calls for the same missing key share one loader invocation:

cache := hot.NewHotCache[int, *User](hot.WTinyLFU, 10_000).
    WithTTL(5 * time.Minute).
    WithLoaders(func(ids []int) (map[int]*User, error) {
        return db.GetUsersByIDs(ctx, ids) // batch query
    }).
    WithJanitor().
    Build()
defer cache.StopJanitor()

user, found, err := cache.Get(123) // triggers loader on miss

Capacity Sizing

Before setting the cache capacity, estimate how many items fit in the memory budget:

  1. Estimate single-item size — estimate size of the struct, add the size of heap-allocated fields (slices, maps, strings). Include the key size. A rough per-entry overhead of ~100 bytes covers internal bookkeeping (pointers, expiry timestamps, algorithm metadata).
  2. Ask the developer how much memory is dedicated to this cache in production (e.g., 256 MB, 1 GB). This depends on the service's total memory and what else shares the process.
  3. Compute capacity — capacity = memoryBudget / estimatedItemSize. Round down to leave headroom.
Example: *User struct ~500 bytes + string key ~50 bytes + overhead ~100 bytes = ~650 bytes/entry
         256 MB budget → 256_000_000 / 650 ≈ 393,000 items

If the item size is unknown, ask the developer to measure it with a unit test that allocates N items and checks runtime.ReadMemStats. Guessing capacity without measuring leads to OOM or wasted memory.

Common Mistakes

  1. Forgetting WithJanitor() — without it, expired entries stay in memory until the algorithm evicts them. Always chain .WithJanitor() in the builder and defer cache.StopJanitor().
  2. Calling SetMissing() without missing cache config — panics at runtime. Enable WithMissingCache(algorithm, capacity) or WithMissingSharedCache() in the builder first.
  3. WithoutLocking() + WithJanitor() — mutually exclusive, panics. WithoutLocking() is only safe for single-goroutine access without background cleanup.
  4. Oversized cache — a cache holding everything is a map with overhead. Size to your working set (typically 10-20% of total data). Monitor hit rate to validate.
  5. Ignoring loader errors — Get() returns (zero, false, err) on loader failure. Always check err, not just found.

Best Practices

  1. Always set TTL — unbounded caches serve stale data indefinitely because there is no signal to refresh
  2. Use WithJitter(lambda, upperBound) to spread expirations — without jitter, items created together expire together, causing thundering herd on the loader
  3. Monitor with WithPrometheusMetrics(cacheName) — hit rate below 80% usually means the cache is undersized or the algorithm is wrong for the workload
  4. Use WithCopyOnRead(fn) / WithCopyOnWrite(fn) for mutable values — without copies, callers mutate cached objects and corrupt shared state

For advanced patterns (revalidation, sharding, missing cache, monitoring setup), see Production Patterns.

For the complete API surface, see API Reference.

If you encounter a bug or unexpected behavior in samber/hot, open an issue at https://github.com/samber/hot/issues.

Cross-References

  • → See samber/cc-skills-golang@golang-performance skill for general caching strategy and when to use in-memory cache vs Redis vs CDN
  • → See samber/cc-skills-golang@golang-observability skill for Prometheus metrics integration and monitoring
  • → See samber/cc-skills-golang@golang-database skill for database query patterns that pair with cache loaders
  • → See samber/cc-skills@promql-cli skill for querying Prometheus cache metrics via CLI