golang-samber-hot

作者: samber

使用samber/hot在Golang中实现内存缓存——包含淘汰算法(LRU、LFU、TinyLFU、W-TinyLFU、S3FIFO、ARC、TwoQueue、SIEVE、FIFO)、TTL、缓存加载器、分片、过期重验证、缺失键缓存以及Prometheus指标。适用于使用或采用samber/hot时、代码库导入github.com/samber/hot时,或项目高频重复加载相同中低基数资源且需降低延迟或后端压力时。

npx skills add https://github.com/samber/cc-skills-golang --skill golang-samber-hot

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

来自 samber 的更多技能

chrome-extension
samber
使用 Manifest V3 构建 Chrome 扩展的全面指南。当用户提到 Chrome 扩展、浏览器扩展、manifest.json、内容脚本、服务工作者(扩展上下文)、弹出窗口、侧边栏、chrome.runtime、chrome.tabs、chrome.storage、chrome.scripting、后台脚本、MV3、Manifest V3 或任何 Chrome 扩展 API 时,使用此技能。当用户想要向网页注入脚本、在页面与后台之间通信、绕过 CSP 时,也触发此技能。
developmentbrowser-automation
conventional-git
samber
Conventional Commits v1.0.0 分支命名、工作树命名及提交信息标准,适用于 GitHub 和 GitLab 项目。在创建分支、命名工作树、编写提交、生成提交信息、审查分支规范或设置变更日志自动化时使用。当项目需要一致的 Git 历史记录、基于语义化版本控制的发布、可解析的变更日志生成或自动关闭问题时应用。当用户询问如何命名工作树、创建 Git 工作树或...时触发。
developmentcode-reviewdevops
copywriting-cta
samber
设计文章末尾的CTA(置于博客文章、新闻通讯、随笔、文章或任何长文底部的行动号召)。当用户要求撰写、设计、审查或改进文章、博客或随笔底部的CTA;提及“文末CTA”、“文章底部”、“行动号召”、“注册框”、“新闻通讯CTA”、“订阅模块”、“底部该放什么”、“如何让读者订阅/分享/预约通话/购买/...”时,使用此技能。
marketingcreativecommunication
copywriting-hooks
samber
为长篇文章(英文或法文)生成开篇钩子和文章标题——包括博客文章、Substack/Medium/dev.to、领英长文、付费新闻通讯、观点文章、深度报道、技术解析。当用户要求提供钩子、开篇、导语、引言、首句/首段、开场白、accroche、attaque、phrase d'accroche或première phrase时触发——包括让平淡的引言更有冲击力或重写草稿开篇。当用户要求提供文章标题、titre d'article时也触发。
marketingcreativecommunication
copywriting-prose-creator
samber
将某人或品牌的写作方式编码为散文机制(词汇、句法、节奏、结构、标志性手法),独立于情感基调。输出:PROSE.md。三种模式:从SOUL.md + TONE.md + 探索性访谈中构建全新指南;将现有指南适配到新渠道;在编码前审计语料库以提取散文模式。适用场景:为内容工厂制定写作规则,为多写手一致性编码代笔风格,定义禁用词和句子长度目标……
creativecommunicationdocument
copywriting-tone-of-voice-creator
samber
通过发现、声音定义和渠道调制,构建品牌语调指南(TONE.md)。输出包含行为准则的语音属性、NN/g定位、语调调制矩阵、词汇库、机制和渠道规则——供下游内容技能用于撰写符合品牌调性的文案。涵盖B2B SaaS、B2C/D2C、非政府组织、公共部门、咨询、工业、产品驱动、个人及志愿者品牌;研究未覆盖的语境(政治、受监管领域、宗教组织、游戏等)……
marketingcreativecommunication
crxjs
samber
CRXJS Chrome扩展开发 — 为弹出窗口、选项页
developmentbrowser-automation
deep-research
samber
深度研究技能——广泛并行网络搜索、多源验证、置信度追踪、带引用的Markdown报告。支持11种研究类型:市场(TAM/SAM、细分市场、定价、趋势)、领域(行业结构、生态系统、监管环境)、技术(架构、工具、基准测试)、竞争(竞争对手拆解、定位、赢/输分析)、产品(功能分析、评论、路线图信号)、学术(文献综述、引用网络、关键作者)、人物/组织(尽职...
researchweb-scrapingdata-analysis