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. Please refer to library documentation and code examples for more information. Context7 can help as a discoverability platform.

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 capacitycapacity = 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 errorsGet() 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のその他のスキル

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
慣用的なGo言語のデザインパターン — 関数型オプション、コンストラクタ、エラーフローとカスケード、リソース管理とライフサイクル、グレースフルシャットダウン、耐障害性、アーキテクチャ、依存性注入、データ処理、ストリーミングなど。アーキテクチャパターンを明示的に選択する際、関数型オプションを実装する際、コンストラクタAPIを設計する際、グレースフルシャットダウンを設定する際、耐障害性パターンを適用する際、または特定の問題に適合する慣用的なGoパターンを尋ねる際に適用します。
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Golangのパフォーマンス最適化パターンと方法論 - XのボトルネックがあればYを適用。アロケーション削減、CPU効率、メモリレイアウト、GCチューニング、プーリング、キャッシング、ホットパス最適化をカバー。プロファイリングやベンチマークでボトルネックが特定され、それを修正するための適切な最適化パターンが必要な場合に使用。また、パフォーマンスコードレビューを行い、改善点や迅速なパフォーマンス向上を特定するのに役立つベンチマークを提案する場合にも使用。測定方法論には使用しない(→...)
developmentcode-review
golang-security
samber
Golangのセキュリティベストプラクティスと脆弱性防止。インジェクション(SQL、コマンド、XSS)、暗号化、ファイルシステムの安全性、ネットワークセキュリティ、クッキー、シークレット管理、メモリ安全性、ログ記録をカバー。Goコードのセキュリティに関する作成、レビュー、監査時、または暗号、I/O、シークレット管理、ユーザー入力処理、認証を含むリスクのあるコードに取り組む際に適用。セキュリティツールの設定を含む。
securitycode-reviewdevelopment
golang-database
samber
Goデータベースアクセスの包括的ガイド — パラメータ化クエリ、構造体スキャン、NULL許容カラム、トランザクション、分離レベル、SELECT FOR UPDATE、コネクションプール、バッチ処理、コンテキスト伝搬、マイグレーションツール。PostgreSQL、MariaDB、MySQL、SQLiteと連携するGolangコードの作成、レビュー、デバッグ時、データベーステスト時、またはdatabase/sql、sqlx、pgxに関する質問時に使用します。データベーススキーマやマイグレーションSQLは生成しません。
developmentdatabase
golang-lint
samber
GolangプロジェクトにおけるLintのベストプラクティスとgolangci-lintの設定 — リンターの実行、.golangci.ymlの設定、nolintディレクティブによる警告の抑制、Lint出力の解釈、リンターの選択。golangci-lintの設定時、Lint警告やnolint抑制について質問がある時、コード品質ツールのセットアップ時、またはリンターを選択する時に使用します。また、ユーザーがgolangci-lint、go vet、staticcheck、reviveに言及した場合にも使用します。
developmentcode-reviewtesting