golang-samber-hot

작성자: samber

Golang에서 samber/hot을 사용한 인메모리 캐싱 — 제거 알고리즘(LRU, LFU, TinyLFU, W-TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, 캐시 로더, 샤딩, stale-while-revalidate, 누락 키 캐싱, 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 히스토리, SemVer 기반 릴리스, 파싱 가능한 체인지로그 생성, 자동 이슈 종료가 필요할 때 적용합니다. 사용자가 워크트리 명명 방법, Git 워크트리 생성 방법 등을 물을 때 트리거됩니다.
developmentcode-reviewdevops
copywriting-cta
samber
기사 하단의 CTA(블로그 포스트, 뉴스레터, 에세이, 기사 또는 모든 장문 콘텐츠의 하단에 배치되는 행동 유도 문구)를 설계합니다. 사용자가 기사, 블로그 포스트 또는 에세이 하단의 CTA를 작성, 설계, 검토 또는 개선해 달라고 요청하거나, "포스트 하단 CTA", "기사 하단", "행동 유도 문구", "가입 박스", "뉴스레터 CTA", "구독 블록", "하단에 무엇을 넣어야 할까요", "독자들이 구독/공유/전화 예약/구매를 하게 하려면 어떻게 해야 하나요" 등을 언급할 때 이 스킬을 사용하세요.
marketingcreativecommunication
copywriting-hooks
samber
긴 형식의 글(블로그 포스트, Substack/Medium/dev.to, LinkedIn 장문, 유료 뉴스레터, 의견 에세이, 보도 특집, 기술 심층 분석)을 위한 오프닝 훅과 포스트 제목을 영어 또는 프랑스어로 생성합니다. 사용자가 훅, 오프닝, 리드, 인트로, 첫 문장/단락, 오프너, accroche, attaque, phrase d'accroche, première phrase를 요청할 때(평범한 인트로를 더 강력하게 만들거나 초안 오프닝을 다시 작성하는 경우 포함) 트리거됩니다. 또한 사용자가 포스트 제목, titre d'article 등을 요청할 때도 트리거됩니다.
marketingcreativecommunication
copywriting-prose-creator
samber
누군가 또는 브랜드의 글쓰기 방식을 체계화합니다 — 감정적 어조와 무관한 산문 메커니즘(어휘, 구문, 리듬, 구조, 시그니처 동작). 출력: PROSE.md. 세 가지 모드: SOUL.md + TONE.md + 발견 인터뷰로 새 가이드 BUILD; 기존 가이드를 새 채널에 ADAPT; 체계화 전 코퍼스의 산문 패턴 AUDIT. 사용 시점: 콘텐츠 팩토리용 글쓰기 규칙 작성, 다중 작성자 일관성을 위한 고스트라이팅 보이스 체계화, 금지어 및 문장 길이 목표 정의 시,...
creativecommunicationdocument
copywriting-tone-of-voice-creator
samber
발견, 음성 정의, 채널 변조를 통해 브랜드 톤 앤 보이스 가이드(TONE.md)를 구축합니다. 다운스트림 콘텐츠 스킬이 브랜드에 맞는 카피를 작성할 때 사용할 음성 속성, 해야 할 일/하지 말아야 할 일, NN/g 포지셔닝, 톤 변조 매트릭스, 어휘, 메커니즘, 채널 규칙을 출력합니다. B2B SaaS, B2C/D2C, NGO, 공공 부문, 컨설팅, 산업, 제품 중심, 개인, 자원봉사 브랜드를 다루며, 정치, 규제 분야, 종교 단체, 게임 등 아직 다루지 않은 맥락을 조사합니다.
marketingcreativecommunication
crxjs
samber
CRXJS Chrome extension development — true HMR for popup, options, content scripts, side panels, manifest-driven builds, dynamic content script imports (`?script`, `?script&module`), and `defineManifest` for type-safe manifests. Uses Vite as its build tool. Use when the user mentions CRXJS, crxjs, @crxjs/vite-plugin, 'extension with hot reload', 'HMR for chrome extension', or wants to set up a CRXJS-based Chrome extension project with any framework (React, Vue, Svelte, Solid, Vanilla). Also...
developmentbrowser-automation
deep-research
samber
심층 연구 스킬 — 광범위한 병렬 웹 검색, 다중 출처 검증, 신뢰도 추적, 인용 포함 마크다운 보고서. 11가지 연구 유형 지원: 시장(TAM/SAM, 세그먼트, 가격, 트렌드), 도메인(산업 구조, 생태계, 규제 환경), 기술(아키텍처, 도구, 벤치마크), 경쟁(경쟁사 분석, 포지셔닝, 승/패), 제품(기능 분석, 리뷰, 로드맵 신호), 학술(문헌 조사, 인용 네트워크, 주요 저자), 인물/조직(실사...
researchweb-scrapingdata-analysis