← Back to Skills Marketplace
samber

Golang Samber Hot

by Samuel Berthe · GitHub ↗ · v1.0.1 · MIT-0
cross-platform ✓ Security Clean
152
Downloads
0
Stars
0
Active Installs
2
Versions
Install in OpenClaw
/install golang-samber-hot
Description
In-memory caching in Golang using samber/hot — eviction algorithms (LRU, LFU, TinyLFU, W-TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, cache loaders, sh...
README (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 informations. 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.

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 (\x3C1000 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:

  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
Usage Guidance
This skill is a documentation-style, instruction-only guide for the samber/hot Go library and appears internally consistent. Before using it or letting an agent execute its steps: 1) verify you actually want the agent to run `go get`/go commands (they will fetch code from the network); 2) prefer pinning a module version (e.g., use a specific tag or module version) rather than `go get -u` to avoid pulling unexpected updates; 3) review the upstream repository (https://github.com/samber/hot) yourself for trustworthiness and license compatibility (MIT is stated); 4) if you enable autonomous agent invocation, remember the agent could perform network operations (fetching repos, running go build/tests) — restrict that capability if you are not comfortable. Overall the skill is coherent for its purpose.
Capability Analysis
Type: OpenClaw Skill Name: golang-samber-hot Version: 1.0.1 The skill bundle provides comprehensive documentation and instructions for using the 'samber/hot' Go caching library. It includes detailed algorithm comparisons, API references, and production patterns in SKILL.md and the references directory. No malicious code, data exfiltration, or harmful prompt injections were found; the instructions and evaluation cases (evals.json) are strictly focused on correct, safe, and efficient library usage.
Capability Assessment
Purpose & Capability
Name and description match the SKILL.md content. The only required binary is 'go', which is appropriate for a Go-focused usage guide and the SKILL.md's 'go get' examples. No unrelated environment variables, binaries, or config paths are requested.
Instruction Scope
SKILL.md contains usage guidance, code snippets, and operational patterns (algorithms, janitor, loaders, sharding, metrics). It does not instruct reading arbitrary files, harvesting env vars, or sending data to unexpected endpoints. It does call out `go get`/GitHub links (expected for fetching the library).
Install Mechanism
This is instruction-only with no install spec. The only install-like instruction is `go get -u github.com/samber/hot`, which is a standard way to fetch a Go module. No downloads from untrusted personal servers, no archives extracted, and nothing written to nonstandard locations by the skill itself.
Credentials
The skill requests no environment variables or credentials. Prometheus examples assume a typical monitoring setup but do not require secrets. The requested permissions and environment access are proportional to the stated purpose.
Persistence & Privilege
Skill flags show no forced always-on presence and it is not user-invocable by default. Being an instruction-only skill, it does not claim to modify other skills or system-wide settings. Allowed-tool permissions (e.g., WebFetch, Bash) are broad but consistent with a coding agent expected to fetch docs and run Go commands.
How to Use
  1. Make sure OpenClaw is installed (local or Docker)
  2. Run the install command in chat: /install golang-samber-hot
  3. After installation, invoke the skill by name or use /golang-samber-hot
  4. Provide required inputs per the skill's parameter spec and get structured output
Version History
v1.0.1
- Version bump to 1.0.1 in metadata. - Added evals/evals.json (new file for skill evaluation configuration). - No changes to skill content or instructions—documentation unchanged.
v0.1.0
Initial release of the golang-samber-hot skill. - Introduces guidance for in-memory caching in Go using samber/hot. - Covers algorithm selection (LRU, LFU, TinyLFU, ARC, etc.), loader patterns, and TTL handling. - Provides capacity sizing recommendations and highlights common mistakes. - Outlines cache usage best practices and advanced features like sharding, stale-while-revalidate, and Prometheus metrics. - Includes links to supplementary resources and related skills for performance, observability, and database patterns.
Metadata
Slug golang-samber-hot
Version 1.0.1
License MIT-0
All-time Installs 0
Active Installs 0
Total Versions 2
Frequently Asked Questions

What is 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, sh... It is an AI Agent Skill for Claude Code / OpenClaw, with 152 downloads so far.

How do I install Golang Samber Hot?

Run "/install golang-samber-hot" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.

Is Golang Samber Hot free?

Yes, Golang Samber Hot is completely free, licensed under MIT-0. You can download, install and use it at no cost.

Which platforms does Golang Samber Hot support?

Golang Samber Hot is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).

Who created Golang Samber Hot?

It is built and maintained by Samuel Berthe (@samber); the current version is v1.0.1.

💬 Comments