golang-samber-hot
Skill11 starsChanged 5 months agoMITView on GitHub
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.
- Installs packages
We split this skill into the rules it gives an agent
7 rules. 3 are common, 0 are distinctive, and 4 are very specific to this project.
3
Common
Most of the 6 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 54
Decision shortcut: Start with hot.WTinyLFU. Switch only when profiling shows the miss rate is too high for your SLO.
- Common: line 96
Before setting the cache capacity, estimate how many items fit in the memory budget:
- Very specific: line 107
If the item size is unknown, ask the developer to measure it with a unit test that allocates N items and checks runtime.ReadMemStats.
- Common: line 119
Always set TTL — unbounded caches serve stale data indefinitely because there is no signal to refresh
- Very specific: line 120
Use WithJitter(lambda, upperBound) to spread expirations — without jitter, items created together expire together, causing thundering herd …
- Very specific: line 122
Use WithCopyOnRead(fn) / WithCopyOnWrite(fn) for mutable values — without copies, callers mutate cached objects and corrupt shared state
- Common: line 128
If you encounter a bug or unexpected behavior in samber/hot, open an issue at <https://github.com/samber/hot/issues>.
“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
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. Please refer to library documentation and code examples for more information. Context7 can help as a discoverability platform.
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 loader - Monitor with
WithPrometheusMetrics(cacheName)— hit rate below 80% usually means the cache is undersized or the algorithm is wrong for the workload - 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-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
Other versions9 projects use a version of this.
Word for word · 3
- poizoncoded/skills★ 2100% same
- VerifiedOrganic/onboard★ 1100% same
- guynhsichngeodiec/cc-skills-golang★ 0100% same
Edited · 5
- samber/cc-skills-golang★ 3.6k91% same
- klawisha012/agentsync★ 1893% same
- tstapler/dotfiles★ 892% same
- rockcookies/skills★ 191% same
- rzisso/golang-skills★ 091% same
Wrote their own version · 1
- reagin/agent-skills★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use golang-pkg-go-dev, golang-gopls and 1 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
rockcookiesSkillgolang-pkg-go-dev
Golang package and module documentation and exploration via `godig`, a pkg.go.dev API client (CLI + MCP server) — package docs, API references, symbols, code examples, available versions, importers (who imports a package), licenses, and known vulnerabilities. Read-only, no auth. Use for looking up any Go/Golang library's documentation, API signatures, usage examples, which versions exist, whether a dependency has CVEs, or who imports a package — prefer this over Context7 for any Go package or module. Triggers on: how to use a Go library, Go API docs, import usage, code examples, pkg.go.dev. Not for upgrading dependencies (→ See `golang-dependency-management` skill) or choosing a library (→ See `golang-popular-libraries` skill). Not for local symbols, or for navigating an already-used dependency's resolved source, call sites, or generic instantiations — → See `golang-gopls` skill for those.
Also in 4 projects that use this
jkeddariSkillgolang-gopls
Golang semantic code intelligence with the official gopls language server: definitions, references, symbols, call and implementation hierarchies, diagnostics, formatting, code actions, safe rename, extract, inline, and package API discovery. Use when navigating or refactoring a local Go workspace or when semantic analysis is safer than text search.
Also in 4 projects that use this
jkeddariSkillgolang-refactoring
Golang refactoring workflow for safe structural change: blast-radius discovery, coverage-adaptive safety nets, semantic rename and extract operations, package moves, import-cycle removal, staged commits, and behavior-preserving verification. Use when restructuring existing Go code without intentionally changing its public behavior.
Also in 4 projects that use this
In this repository46 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .agents/skills/humanizer/AGENTS.mdAGENTS.md
- cli-to-go-migrationSkill
- golang-benchmarkSkill
- golang-cliSkill
- golang-code-styleSkill
- golang-concurrencySkill
- golang-contextSkill
- golang-continuous-integrationSkill
- golang-databaseSkill
- golang-data-structuresSkill
- golang-dependency-injectionSkill
- golang-dependency-managementSkill
- golang-design-patternsSkill
- golang-documentationSkill
- golang-error-handlingSkill
- golang-google-wireSkill
- golang-graphqlSkill
- golang-grpcSkill
- golang-how-toSkill
- golang-lintSkill
- golang-modernizeSkill
- golang-namingSkill
- golang-observabilitySkill
- golang-performanceSkill
- golang-popular-librariesSkill
- golang-project-layoutSkill
- golang-safetySkill
- golang-samber-doSkill
- golang-samber-loSkill
- golang-samber-moSkill
- golang-samber-oopsSkill
- golang-samber-roSkill
- golang-samber-slogSkill
- golang-securitySkill
- golang-spf13-cobraSkill
- golang-spf13-viperSkill
- golang-stay-updatedSkill
- golang-stretchr-testifySkill
- golang-structs-interfacesSkill
- golang-swaggerSkill
- golang-testingSkill
- golang-troubleshootingSkill
- golang-uber-digSkill
- golang-uber-fxSkill
- humanizerSkill
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
Reviews can't be read right now.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

