golang-samber-hot

oleh samber

Caching dalam memori di Golang menggunakan samber/hot — algoritma eviction (LRU, LFU, TinyLFU, W-TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, pemuat cache, sharding, stale-while-revalidate, caching kunci yang hilang, dan metrik Prometheus. Terapkan saat menggunakan atau mengadopsi samber/hot, saat basis kode mengimpor github.com/samber/hot, atau saat proyek berulang kali memuat sumber daya dengan kardinalitas rendah hingga sedang pada frekuensi tinggi dan perlu mengurangi latensi atau tekanan backend.

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

Lebih banyak skill dari samber

chrome-extension
samber
Panduan lengkap untuk membangun ekstensi Chrome dengan Manifest V3. Gunakan keterampilan ini setiap kali pengguna menyebutkan ekstensi Chrome, ekstensi peramban, manifest.json, skrip konten, service worker (dalam konteks ekstensi), popup, panel samping, chrome.runtime, chrome.tabs, chrome.storage, chrome.scripting, skrip latar belakang, MV3, Manifest V3, atau API ekstensi Chrome lainnya. Juga aktifkan ketika pengguna ingin menyuntikkan skrip ke halaman web, berkomunikasi antara halaman dan latar belakang, melewati CSP dari...
developmentbrowser-automation
conventional-git
samber
Standar penamaan cabang, penamaan worktree, dan pesan commit untuk proyek GitHub dan GitLab berdasarkan Conventional Commits v1.0.0. Gunakan saat membuat cabang, menamai worktree, menulis commit, menghasilkan pesan commit, meninjau konvensi cabang, atau menyiapkan otomatisasi changelog. Terapkan ketika proyek Anda membutuhkan riwayat git yang konsisten, rilis berbasis SemVer, pembuatan changelog yang dapat diurai, atau penutupan masalah otomatis. Aktifkan saat pengguna bertanya cara menamai worktree, membuat git worktree, atau...
developmentcode-reviewdevops
copywriting-cta
samber
Rancang CTA akhir artikel (ajakan bertindak yang ditempatkan di bagian bawah posting blog, buletin, esai, artikel, atau konten panjang apa pun). Gunakan keterampilan ini setiap kali pengguna meminta untuk menulis, merancang, meninjau, atau meningkatkan CTA di bagian bawah artikel, posting blog, atau esai; menyebutkan "CTA akhir posting", "bagian bawah artikel", "ajakan bertindak", "kotak pendaftaran", "CTA buletin", "blok berlangganan", "apa yang harus saya taruh di bagian bawah", "bagaimana cara membuat pembaca berlangganan / membagikan / memesan panggilan / membeli /...
marketingcreativecommunication
copywriting-hooks
samber
Hasilkan kalimat pembuka dan judul artikel untuk konten panjang dalam bahasa Inggris atau Prancis — posting blog, Substack/Medium/dev.to, konten panjang LinkedIn, buletin berbayar, esai opini, laporan feature, ulasan teknis mendalam. Aktifkan saat pengguna meminta hook, pembuka, lede, intro, kalimat/paragraf pertama, opener, accroche, attaque, phrase d'accroche, atau première phrase — termasuk membuat intro datar lebih menarik atau menulis ulang pembuka draf. Juga aktifkan saat pengguna meminta judul posting, titre d'article,...
marketingcreativecommunication
copywriting-prose-creator
samber
Mengkodekan cara seseorang atau merek menulis — mekanika prosa (leksikon, sintaksis, ritme, struktur, gerakan khas) yang independen dari nada emosional. Keluaran: PROSE.md. Tiga mode: MEMBANGUN panduan baru dari SOUL.md + TONE.md + wawancara penemuan; MENYESUAIKAN panduan yang ada ke saluran baru; AUDIT korpus untuk pola prosa sebelum pengkodean. Gunakan saat: menulis aturan untuk pabrik konten, mengkodekan suara ghostwriting untuk konsistensi multi-penulis, mendefinisikan kata terlarang dan target panjang kalimat,...
creativecommunicationdocument
copywriting-tone-of-voice-creator
samber
Bangun panduan nada bicara merek (TONE.md) melalui penemuan, definisi suara, dan modulasi saluran. Menghasilkan atribut suara dengan daftar boleh/tidak boleh, posisi NN/g, matriks modulasi nada, leksikon, mekanika, dan aturan saluran — digunakan oleh keterampilan konten hilir yang menulis salinan sesuai merek. Mencakup merek B2B SaaS, B2C/D2C, NGO, sektor publik, konsultasi, industri, berbasis produk, personal, dan sukarelawan; meneliti konteks yang belum terungkap (politik, ceruk yang diatur, organisasi keagamaan, game) pada...
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
Keterampilan riset mendalam — pencarian web paralel yang luas, validasi multi-sumber, pelacakan kepercayaan, laporan Markdown dengan kutipan. Mendukung 11 jenis riset: pasar (TAM/SAM, segmen, harga, tren), domain (struktur industri, ekosistem, lanskap regulasi), teknis (arsitektur, alat, tolok ukur), kompetitif (analisis pesaing, posisi, menang/kalah), produk (analisis fitur, ulasan, sinyal peta jalan), akademis (survei literatur, jaringan kutipan, penulis kunci), orang/org (due...
researchweb-scrapingdata-analysis