samber/cc-skills-golang/skills/golang-samber-hot/SKILL.md
golang-samber-hot
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.
- Source repository stars
- 3,074
- Declared platforms
- 2
- Static risk flags
- 1
- Last source update
- 2026-08-23
- Source checked
- 2026-08-26
Decision brief
What it does: where it fits
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.
Not for
- Forgetting WithJanitor() — without it, expired entries stay in memory until the algorithm evicts them. Always chain .WithJanitor() in the builder and defer cache.StopJanitor().
- Calling SetMissing() without missing cache config — panics at runtime. Enable WithMissingCache(algorithm, capacity) or WithMissingSharedCache() in the builder first.
Compatibility matrix
Platform support, with evidence labels
| Platform | Status | Evidence | What to check |
|---|---|---|---|
| Codex | Declared | Source record | Install path and trigger |
| Claude Code | Declared | Source record | Install path and trigger |
| Cursor | Not declared | No explicit evidence | Portability before use |
| Gemini CLI | Not declared | No explicit evidence | Portability before use |
Installation
Inspect first. Install second.
The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.
npx skills add https://github.com/samber/cc-skills-golang --skill "skills/golang-samber-hot"Inspect the Agent Skill "golang-samber-hot" from https://github.com/samber/cc-skills-golang/blob/a18860b303ef1d3d928f9670631e03210b8698bf/skills/golang-samber-hot/SKILL.md at commit a18860b303ef1d3d928f9670631e03210b8698bf. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.
Workflow
What the source asks the agent to do
- 01
Core Usage
Loaders fetch missing keys automatically with singleflight deduplication — concurrent Get() calls for the same missing key share one loader invocation:
Loaders fetch missing keys automatically with singleflight deduplication — concurrent Get() calls for the same missing key share one loader invocation: - 02
Algorithm Selection
Pick based on your access pattern — the wrong algorithm wastes memory or tanks hit rate.
Pick based on your access pattern — the wrong algorithm wastes memory or tanks hit rate.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. - 03
Basic Cache with TTL
Review the “Basic Cache with TTL” section in the pinned source before continuing.
Review and apply the “Basic Cache with TTL” source section. - 04
Loader Pattern (Read-Through)
Loaders fetch missing keys automatically with singleflight deduplication — concurrent Get() calls for the same missing key share one loader invocation:
Loaders fetch missing keys automatically with singleflight deduplication — concurrent Get() calls for the same missing key share one loader invocation: - 05
Capacity 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…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.
Permission review
Static risk signals and limitations
Runs scripts
The documentation asks the agent to run terminal commands or scripts.
go get -u github.com/samber/hotEvidence record
Why each signal appears
| Signal | Value | Evidence type | Meaning |
|---|---|---|---|
| Quality score | 90/100 | Computed | Documentation, specificity, maintenance, and trust rules |
| Repository stars | 3,074 | Source | Repository attention, not individual Skill quality |
| Compatibility | 2 platforms | Source | Declared in the catalog source record |
| Usage guide | automated source guide | Editorial | Generated or reviewed according to the visible evidence level |
Pinned source
Provenance and original SKILL.md
- Repository
- samber/cc-skills-golang
- Skill path
- skills/golang-samber-hot/SKILL.md
- Commit
- a18860b303ef1d3d928f9670631e03210b8698bf
- License
- MIT
- Collected
- 2026-08-26
- Default branch
- main
View the original SKILL.md
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. For Go package docs, symbols, versions, importers, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill (godig) — prefer it 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.
| 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 miss
Capacity 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 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
- 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
Frequently asked questions
What to verify before installation and use
What does the golang-samber-hot source document cover?
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.
How do I install golang-samber-hot?
The source record exposes this install command: npx skills add https://github.com/samber/cc-skills-golang --skill "skills/golang-samber-hot". Inspect the command and pinned source before running it.
Which Agent platforms does the source record declare?
The pinned source record declares support for: codex, claude code.
Which permission-related actions were detected?
Static rules flagged exec-script in the source; the page lists the matching lines and excerpts.
Alternatives
Compare before choosing
vasilyu1983/AI-Agents-public
agents-hooks
Configures Claude Code hooks and Codex hooks.json/notify callbacks. Use when adding guardrails, preflight, audit trails, worktree automation, or budget enforcement.
vasilyu1983/AI-Agents-public
qa-testing-ios
Guides iOS testing with XCTest, XCUITest, Swift Testing, simctl, and xcresult. Use when choosing destinations, controlling flakes, or parsing test artifacts for native apps.
samber/cc-skills-golang
golang-samber-mo
Monadic types for Golang using samber/mo — Option, Result, Either, Future, IO, Task, and State types for type-safe nullable values, error handling, and functional composition with pipeline sub-packages. Apply when using or adopting samber/mo, when the codebase imports `github.com/samber/mo`, or when considering functional programming patterns as a safety design for Golang.
vasilyu1983/AI-Agents-public
ai-distributed-training
Guides multi-GPU pre-training: DDP, FSDP2, ZeRO, tensor/pipeline/expert parallelism, fp8/Muon. Use when scaling a run, training MoE, or reproducing GPT-2 on rented GPUs.