Golang Samber Hot
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Tool integration
- Software development
- MIT
- No issues found
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/samber/golang-samber-hot/downloadUnzip 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-devskill (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-goplsskill (gopls).Context7 remains a fallback for docs not indexed on pkg.go.dev.
go get -u github.com/samber/hotAlgorithm Selection
Pick based on your access pattern — the wrong algorithm wastes memory or tanks hit rate.
| Algorithm | Constant | Best for | Avoid when |
|---|---|---|---|
| W-TinyLFU | hot.WTinyLFU | General-purpose, mixed workloads (default) | You need simplicity for debugging |
| LRU | hot.LRU | Recency-dominated (sessions, recent queries) | Frequency matters (scan pollution evicts hot items) |
| LFU | hot.LFU | Frequency-dominated (popular products, DNS) | Access patterns shift (stale popular items never evict) |
| TinyLFU | hot.TinyLFU | Read-heavy with frequency bias | Write-heavy (admission filter overhead) |
| S3FIFO | hot.S3FIFO | High throughput, scan-resistant | Small caches (<1000 items) |
| ARC | hot.ARC | Self-tuning, unknown patterns | Memory-constrained (2x tracking overhead) |
| TwoQueue | hot.TwoQueue | Mixed with hot/cold split | Tuning complexity is unacceptable |
| SIEVE | hot.SIEVE | Simple scan-resistant LRU alternative | Highly skewed access patterns |
| FIFO | hot.FIFO | Simple, predictable eviction order | Hit 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 missCapacity Sizing
Before setting the cache capacity, estimate how many items fit in the memory budget:
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).
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.
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 itemsIf 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
Forgetting
WithJanitor()— without it, expired entries stay in memory until the algorithm evicts them. Always chain.WithJanitor()in the builder anddefer cache.StopJanitor().Calling
SetMissing()without missing cache config — panics at runtime. EnableWithMissingCache(algorithm, capacity)orWithMissingSharedCache()in the builder first.WithoutLocking()+WithJanitor()— mutually exclusive, panics.WithoutLocking()is only safe for single-goroutine access without background cleanup.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.
Ignoring loader errors —
Get()returns(zero, false, err)on loader failure. Always checkerr, not justfound.
Best Practices
Always set TTL — unbounded caches serve stale data indefinitely because there is no signal to refresh
Use
WithJitter(lambda, upperBound)to spread expirations — without jitter, items created together expire together, causing thundering herd on the loaderMonitor with
WithPrometheusMetrics(cacheName)— hit rate below 80% usually means the cache is undersized or the algorithm is wrong for the workloadUse
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-performanceskill for general caching strategy and when to use in-memory cache vs Redis vs CDN→ See
samber/cc-skills-golang@golang-observabilityskill for Prometheus metrics integration and monitoring→ See
samber/cc-skills-golang@golang-databaseskill for database query patterns that pair with cache loaders→ See
samber/cc-skills@promql-cliskill for querying Prometheus cache metrics via CLI
Files
- ATTRIBUTION.mdAdded by AutoGineer908 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md7.8 KiB
- evals/evals.json16.3 KiB
- references/algorithm-guide.md9.2 KiB
- references/api-reference.md6.6 KiB
- references/production-patterns.md7.4 KiB
references/api-reference.md
API Reference
Table of Contents
Constructor
Builder Methods
Read Operations
Write Operations
Maintenance Operations
Loader Type
Hasher Type (for Sharding)
Prometheus Integration
Constructor
hot.NewHotCache[K comparable, V any](algorithm hot.EvictionAlgorithm, capacity int) *HotCacheBuilder[K, V]Algorithm constants:
| Constant | Algorithm |
|---|---|
hot.LRU | Least Recently Used |
hot.LFU | Least Frequently Used |
hot.TinyLFU | TinyLFU with frequency decay |
hot.WTinyLFU | Weighted TinyLFU (recommended default) |
hot.S3FIFO | Segmented Small-Size FIFO |
hot.ARC | Adaptive Replacement Cache |
hot.TwoQueue | Two-Queue |
hot.SIEVE | SIEVE eviction |
hot.FIFO | First In, First Out |
Builder Methods
Call these on the builder returned by NewHotCache(), then finalize with .Build().
| Method | Description |
|---|---|
WithTTL(ttl time.Duration) | Default expiration for all entries |
WithJitter(lambda float64, upperBound time.Duration) | Randomize TTL by +/-lambda (capped at upperBound) to prevent thundering herd |
WithJanitor() | Start background goroutine to evict expired entries. Mutually exclusive with WithoutLocking() |
WithLoaders(loaders ...Loader[K, V]) | Chain of loader functions for cache misses. Execute sequentially; later loaders receive only unmapped keys |
WithRevalidation(stale time.Duration, loaders ...Loader[K, V]) | Enable stale-while-revalidate. After TTL, entries become stale and trigger async refresh. Hard-expired after stale duration |
WithRevalidationErrorPolicy(policy) | hot.KeepOnError (keep stale value) or hot.DropOnError (drop on refresh failure) |
WithMissingCache(algorithm, capacity) | Dedicated cache for missing keys (independent eviction) |
WithMissingSharedCache() | Store missing keys in the main cache |
WithSharding(shards uint64, hasher Hasher[K]) | Split into N shards to reduce lock contention. Use powers of 2 |
WithCopyOnRead(fn func(V) V) | Clone values on retrieval to prevent external mutation |
WithCopyOnWrite(fn func(V) V) | Clone values on storage to capture snapshots |
WithPrometheusMetrics(cacheName string) | Enable Prometheus metrics collection |
WithEvictionCallback(fn func(K, V)) | Synchronous callback on eviction |
WithoutLocking() | Disable mutexes. Single-goroutine access only. Mutually exclusive with WithJanitor() |
WithWarmUp(fn func() (map[K]V, []K, error)) | Pre-populate cache on build. Returns values + missing keys + error |
WithWarmUpWithTimeout(timeout, fn) | Same as WarmUp with timeout protection |
Build() | Finalize and return *HotCache[K, V] |
Read Operations
| Method | Signature | Behavior |
|---|---|---|
Get | (key K) (V, bool, error) | Value, found, loader error. Triggers loaders on miss |
GetWithLoaders | (key K, loaders ...Loader[K, V]) (V, bool, error) | Per-call loader override |
GetMany | (keys []K) (map[K]V, []K, error) | Batch get. Returns found map + missing keys + error |
GetManyWithLoaders | (keys []K, loaders ...Loader[K, V]) (map[K]V, []K, error) | Batch with loader override |
MustGet | (key K) (V, bool) | Panics on loader error |
MustGetWithLoaders | (key K, loaders ...Loader[K, V]) (V, bool) | Panics on loader error |
MustGetMany | (keys []K) (map[K]V, []K) | Panics on error |
MustGetManyWithLoaders | (keys []K, loaders ...Loader[K, V]) (map[K]V, []K) | Panics on error |
Peek | (key K) (V, bool) | Read without side effects: no loaders, ignores expiration |
PeekMany | (keys []K) (map[K]V, []K) | Batch peek |
Has | (key K) bool | Key existence check without triggering loaders |
HasMany | (keys []K) map[K]bool | Batch existence check |
Keys | () []K | All keys with values (excludes missing entries) |
Values | () []V | All values |
All | () map[K]V | Key-value snapshot |
Range | (fn func(K, V) bool) | Iterate. Return false to stop |
Len | () int | Total item count |
Capacity | () (int, int) | Main capacity, missing cache capacity |
Algorithm | () (string, string) | Main algorithm name, missing algorithm name |
Write Operations
| Method | Signature | Description |
|---|---|---|
Set | (key K, value V) | Set with default TTL |
SetWithTTL | (key K, value V, ttl time.Duration) | Set with custom TTL |
SetMany | (items map[K]V) | Batch set with default TTL |
SetManyWithTTL | (items map[K]V, ttl time.Duration) | Batch set with custom TTL |
SetMissing | (key K) | Mark key as non-existent. Requires WithMissingCache() or WithMissingSharedCache() |
SetMissingWithTTL | (key K, ttl time.Duration) | Mark missing with custom TTL |
SetMissingMany | (keys []K) | Batch mark as missing |
SetMissingManyWithTTL | (keys []K, ttl time.Duration) | Batch mark missing with custom TTL |
Maintenance Operations
| Method | Signature | Description |
|---|---|---|
Delete | (key K) bool | Remove single key. Returns true if existed |
DeleteMany | (keys []K) map[K]bool | Batch delete. Returns existence map |
Purge | () | Clear all entries |
WarmUp | (fn func() (map[K]V, []K, error)) error | Pre-populate cache at runtime |
Janitor | () | Start background expiration cleanup |
StopJanitor | () | Stop background cleanup goroutine |
Loader Type
type Loader[K comparable, V any] func(keys []K) (found map[K]V, err error)Chain semantics:
Loaders execute sequentially in provided order
Each loader receives only unmapped keys from previous loaders
Later loader values overwrite earlier values for the same key
Any loader error stops the chain and returns
(nil, err)Built-in singleflight deduplication: concurrent
Get()calls for the same key share one loader invocation
Hasher Type (for Sharding)
type Hasher[K any] func(key K) uint64Prometheus Integration
*HotCache implements prometheus.Collector. Register it to expose metrics:
cache := hot.NewHotCache[string, *User](hot.WTinyLFU, 10_000).
WithPrometheusMetrics("user_cache").
Build()
prometheus.MustRegister(cache)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