Generated banner for Golang Samber Hot
Generated logo for Golang Samber Hot

Golang Samber Hot

Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe

  • Skill
  • Tool integration
  • Software development
  • MIT
  • No issues found

From the author

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.
— the description by samber

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The samber/hot library provides a generic, type-safe in-memory caching solution for Go 1.22+. It supports nine different eviction algorithms including W-TinyLFU, LRU, and S3FIFO, allowing developers to select a strategy based on specific access patterns. The library includes features such as TTL management, background janitors for cleanup, loader chains with singleflight deduplication, sharding to reduce lock contention, and Prometheus metrics integration.

What it does

  • Implements nine eviction algorithms including W-TinyLFU, LRU, LFU, and S3FIFO.
  • Supports TTL-based expiration with optional background janitor cleanup.
  • Provides loader chains with singleflight deduplication to handle cache misses.
  • Enables sharding to reduce lock contention in concurrent environments.
  • Offers stale-while-revalidate patterns and missing key caching.
  • Integrates with Prometheus for monitoring cache hit rates and performance metrics.

When to use it

  • When you need to reduce latency or backend pressure by caching frequently accessed resources.
  • When you need to implement in-memory caching in a Go project.
  • When you need to choose specific eviction algorithms based on known access patterns.
  • When you require automatic cache population via loader functions.

Advantages

  • Type-safe generic implementation for Go 1.22+.
  • Flexible configuration for eviction strategies and cache sizing.
  • Built-in support for observability via Prometheus metrics.
  • Prevents thundering herd issues using singleflight deduplication and TTL jitter.

Usage examples

“How do I initialize a basic cache with a 5-minute TTL?”
Use hot.NewHotCache[string, *User](hot.WTinyLFU, 10_000).WithTTL(5 * time.Minute).WithJanitor().Build() to create and start the cache.
“How can I automatically load missing keys from a database?”
Use the .WithLoaders() builder method to provide a function that fetches missing keys, which will be triggered automatically on a cache miss.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/samber/golang-samber-hot/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip golang-samber-hot.zip -d .agents/skills

Documentation by samber

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

Files

references/algorithm-guide.md

Algorithm Selection Guide

Table of Contents

  • Decision Tree

  • Algorithm Deep Dives

    • LRU (Least Recently Used)

    • LFU (Least Frequently Used)

    • TinyLFU

    • W-TinyLFU (Weighted TinyLFU)

    • S3FIFO (Segmented Small-Size FIFO)

    • ARC (Adaptive Replacement Cache)

    • TwoQueue

    • SIEVE

    • FIFO (First In, First Out)

  • Comparison Matrix

  • Measuring Hit Rate

  • Switching Algorithms

Decision Tree

Start here
  |
  v
Do you know your access pattern?
  |-- No --> Use W-TinyLFU (adapts automatically)
  |-- Yes
       |
       v
     Is recency the primary signal? (sessions, recent queries, time-windowed data)
       |-- Yes --> LRU
       |-- No
            |
            v
          Is frequency the primary signal? (popular products, DNS, static config)
            |-- Yes --> Does the popularity ranking shift over time?
            |           |-- Yes --> TinyLFU (frequency with decay)
            |           |-- No --> LFU
            |-- No
                 |
                 v
               Is throughput critical and cache is large? (>100k items, high write rate)
                 |-- Yes --> S3FIFO
                 |-- No
                      |
                      v
                    Do you want self-tuning with no config? (unknown or shifting patterns)
                      |-- Yes --> ARC (higher memory) or W-TinyLFU (lower memory)
                      |-- No
                           |
                           v
                         Is scan resistance needed with simplicity?
                           |-- Yes --> SIEVE
                           |-- No --> W-TinyLFU (safe default)

Algorithm Deep Dives

LRU (Least Recently Used)

Constant: hot.LRU

Evicts the item that hasn't been accessed for the longest time. Simple doubly-linked list + hash map implementation.

  • Strengths: Simple mental model, predictable behavior, low overhead per operation

  • Weaknesses: Scan pollution — a single sequential scan evicts all hot items. No frequency awareness.

  • Ideal workload: Time-windowed data (user sessions, recent search results, short-lived tokens)

  • Degrades when: A batch job or sequential scan touches many cold keys, evicting frequently-used items

LFU (Least Frequently Used)

Constant: hot.LFU

Evicts the item with the fewest accesses. Tracks access counts per key.

  • Strengths: Keeps genuinely popular items regardless of access timing

  • Weaknesses: Stale popular items never evict — an item accessed 10,000 times yesterday blocks new hot items today. No frequency decay.

  • Ideal workload: Stable popularity rankings (DNS records, country code lookups, static configuration)

  • Degrades when: Popularity shifts over time or new items need to ramp up quickly

TinyLFU

Constant: hot.TinyLFU

Combines frequency estimation with a compact Count-Min Sketch instead of per-key counters. Includes frequency decay — old access counts fade over time.

  • Strengths: Low memory overhead for frequency tracking, handles popularity shifts via decay, good admission filtering

  • Weaknesses: Admission filter adds overhead on writes. Sketch approximation can cause rare false positives.

  • Ideal workload: Read-heavy with moderate frequency bias (API response caching, content delivery metadata)

  • Degrades when: Write-heavy workloads where admission overhead exceeds the benefit

W-TinyLFU (Weighted TinyLFU)

Constant: hot.WTinyLFU

Adds a small "window" LRU in front of TinyLFU's admission filter. New items enter the window, and the admission filter decides whether they're promoted to the main cache. Balances recency and frequency automatically.

  • Strengths: Best general-purpose hit rate across diverse workloads. Self-adapting. Handles both recency and frequency patterns.

  • Weaknesses: Slightly more complex internals (harder to reason about eviction order during debugging)

  • Ideal workload: Mixed or unknown access patterns, general-purpose caching

  • Degrades when: Rarely — it's the safest default. May underperform specialized algorithms on extreme workloads.

S3FIFO (Segmented Small-Size FIFO)

Constant: hot.S3FIFO

Three-segment FIFO design: small, main, and ghost queues. Items promoted from small to main only if accessed again. Ghost queue tracks recently evicted keys for scan resistance.

  • Strengths: Excellent throughput (FIFO operations are cheaper than linked-list manipulations). Good scan resistance. Simple eviction path.

  • Weaknesses: Needs enough capacity for the segmented structure to work. Less effective on small caches.

  • Ideal workload: High-throughput systems with large caches (>100k items), CDN-like access patterns

  • Degrades when: Cache is very small (<1000 items) — the segments don't have enough room to differentiate access patterns

ARC (Adaptive Replacement Cache)

Constant: hot.ARC

Maintains four internal lists: two for recency (recent and recent-ghost) and two for frequency (frequent and frequent-ghost). Dynamically adjusts the split between recency and frequency based on which ghost list sees more hits.

  • Strengths: Self-tuning — learns from misses whether to favor recency or frequency. No manual parameter tuning.

  • Weaknesses: ~2x memory overhead for ghost lists. More complex implementation.

  • Ideal workload: Workloads that shift between recency and frequency patterns (mixed database query caching)

  • Degrades when: Memory is constrained — the ghost lists consume significant space

TwoQueue

Constant: hot.TwoQueue

Separates items into "hot" (frequently accessed) and "cold" (recently added) queues with independent eviction. Items graduate from cold to hot on second access.

  • Strengths: Good separation of one-hit wonders from genuinely useful items. Scan resistant.

  • Weaknesses: Requires understanding the hot/cold split ratio for optimal tuning

  • Ideal workload: Workloads with a clear hot/cold distinction (e.g., 20% of keys serve 80% of requests)

  • Degrades when: Access patterns are uniform with no clear hot/cold split

SIEVE

Constant: hot.SIEVE

Modern eviction algorithm that uses a single bit per entry (visited/not-visited) with a circular "hand" pointer. Simple scan-resistant alternative to LRU.

  • Strengths: Very low per-item overhead (1 bit). Scan-resistant. Simple implementation.

  • Weaknesses: Less sophisticated than W-TinyLFU or ARC for complex patterns

  • Ideal workload: When you want scan resistance with minimal complexity and overhead

  • Degrades when: Access patterns are highly skewed — specialized algorithms capture the skew better

FIFO (First In, First Out)

Constant: hot.FIFO

Evicts the oldest inserted item regardless of access pattern. No recency or frequency tracking.

  • Strengths: Simplest possible eviction. Predictable. Zero per-access overhead.

  • Weaknesses: No intelligence — ignores how often or recently items are accessed

  • Ideal workload: TTL-driven caches where all items have similar lifetimes and eviction order doesn't matter (log buffers, time-series windows)

  • Degrades when: Hit rate matters — any other algorithm will outperform FIFO on non-uniform access patterns

Comparison Matrix

AlgorithmScan ResistanceFrequency AwarenessMemory OverheadThroughputTuning Complexity
LRUNoneNoneLowHighNone
LFUNoneHigh (no decay)MediumMediumNone
TinyLFUMediumHigh (with decay)LowMediumNone
W-TinyLFUHighHigh (with decay)LowMediumNone
S3FIFOHighLowMediumVery HighNone
ARCHighMediumHigh (2x)MediumNone (self-tuning)
TwoQueueMediumMediumMediumMediumLow
SIEVEMediumNoneVery LowHighNone
FIFONoneNoneVery LowVery HighNone

Measuring Hit Rate

Enable Prometheus metrics and check hit ratio to validate your algorithm choice:

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

prometheus.MustRegister(cache)

Key PromQL queries:

# Hit ratio (target: >80%)
rate(hot_cache_hit_count{cache="user_cache"}[5m]) /
rate(hot_cache_get_count{cache="user_cache"}[5m])

# Eviction rate (high = cache too small)
rate(hot_cache_eviction_count{cache="user_cache"}[5m])

If hit rate is below your SLO: increase capacity first, then try a different algorithm.

Switching Algorithms

Changing the algorithm is a one-line change — the rest of the builder chain stays identical:

// Before
cache := hot.NewHotCache[string, *User](hot.LRU, 10_000).
    WithTTL(5 * time.Minute).
    WithJanitor().
    Build()

// After — only the first argument changes
cache := hot.NewHotCache[string, *User](hot.WTinyLFU, 10_000).
    WithTTL(5 * time.Minute).
    WithJanitor().
    Build()

Requirements and compatibility

Written for: Claude Code, OpenAI Codex

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Claude Code frontmatter

The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
samber
Publisher
Samuel Berthe (Community)
Distributed by
Samuel Berthe
Source
samber/cc-skills-golang · skills/golang-samber-hot · commit bb1d43d
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-samber-hot.zip