Xpersona
G

golang-samber-hot

CLAWHUB · Unverified

In-memory caching in Golang using samber/hot — eviction algorithms (LRU, LFU, TinyLFU, W-TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, cache loaders, sharding, stale-while-revalidate, missing key caching, and Prometheus metrics. Apply when using or adopting samber/hot, when the codebase imports github.com/samber/hot, or when the project repeatedly loads the same medium-to-low cardinality resources at high frequency and needs to reduce latency or backend pressure. Skill: golang-samber-hot Owner: samber Summary: In-memory caching in Golang using samber/hot — eviction algorithms (LRU, LFU, TinyLFU, W-TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, cache loaders, sharding, stale-while-revalidate, missing key caching, and Prometheus metrics. Apply when using or adopting samber/hot, when the codebase imports github.com/samber/hot, or when the project repeatedly loads the same me

62
Rank
84
Safety
1.0k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1K downloads reported by the source. Last updated 10/11/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-samber-hot
  1. Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-samber-hot/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

143,915 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: 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, sharding, stale-while-revalidate, missing key caching, and Prometheus metrics. Apply when using or adopting samber/hot, when the codebase imports github.com/samber/hot, or when the project repeatedly loads the same medium-to-low cardinality resources at high frequency and needs to reduce latency or backend pressure."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
  author: samber
  version: "1.1.0"
  openclaw:
    emoji: "🔥"
    homepage: https://github.com/samber/cc-skills-golang
    requires:
      bins:
        - go
    install: []
    skill-library-version: "0.13.0"
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs AskUserQuestion Bash(godig:*) Bash(gopls:*) LSP mcp__gopls__*
paths:
  - "**/*.go"
---

**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:**

- [pkg.go.dev/github.com/samber/hot](https://pkg.go.dev/github.com/samber/hot)
- [github.com/samber/hot](https://github.com/samber/hot)

This skill is not exhaustive. Please 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`) — prefer it 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.

```bash
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)

_meta.json

{
  "ownerId": "kn72rhnkwjfeex9wr1n7y24qa983cjn3",
  "slug": "golang-samber-hot",
  "version": "1.1.0",
  "publishedAt": 1787413585298
}

references/algorithm-guide.md

# Algorithm Selection Guide

## Decision Tree

```
Start here
  |
  v
Do you know your access pattern?
  |-- No --> Use W-TinyLFU (adapts automatically)
  |-- Yes
       |
       v
     Is recency the primary signal? (sessions, recent queries, time-windowed data)
       |-- Yes --> LRU
       |-- No
            |
            v
          Is frequency the primary signal? (popular products, DNS, static config)
            |-- Yes --> Does the popularity ranking shift over time?
            |           |-- Yes --> TinyLFU (frequency with decay)
            |           |-- No --> LFU
            |-- No
                 |
                 v
               Is throughput critical and cache is large? (>100k items, high write rate)
                 |-- Yes --> S3FIFO
                 |-- No
                      |
                      v
                    Do you want self-tuning with no config? (unknown or shifting patterns)
                      |-- Yes --> ARC (higher memory) or W-TinyLFU (lower memory)
                      |-- No
                           |
                           v
                         Is scan resistance needed with simplicity?
                           |-- Yes --> SIEVE
                           |-- No --> W-TinyLFU (safe default)
```

## Algorithm Deep Dives

### LRU (Least Recently Used)

**Constant:** `hot.LRU`

Evicts the item that hasn't been accessed for the longest time. Simple doubly-linked list + hash map implementation.

- **Strengths:** Simple mental model, predictable behavior, low overhead per operation
- **Weaknesses:** Scan pollution — a single sequential scan evicts all hot items. No frequency awareness.
- **Ideal workload:** Time-windowed data (user sessions, recent search results, short-lived tokens)
- **Degrades when:** A batch job or sequential scan touches many cold keys, evicting frequently-used items

### LFU (Least Frequently Used)

**Constant:** `hot.LFU`

Evicts the item with the fewest accesses. Tracks access counts per key.

- **Strengths:** Keeps genuinely popular items regardless of access timing
- **Weaknesses:** Stale popular items never evict — an item accessed 10,000 times yesterday blocks new hot items today. No frequency decay.
- **Ideal workload:** Stable popularity rankings (DNS records, country code lookups, static configuration)
- **Degrades when:** Popularity shifts over time or new items need to ramp up quickly

### TinyLFU

**Constant:** `hot.TinyLFU`

Combines frequency estimation with a compact Count-Min Sketch instead of per-key counters. Includes frequency decay — old access counts fade over time.

- **Strengths:** Low memory overhead for frequency tracking, handles popularity shifts via decay, good admission filtering
- **Weaknesses:** Admission filter adds overhead on writes. Sketch approximation can cause rare false positives.
- **Ideal workload:** Read-heavy with moderate frequency bias (API response caching, content delivery metadata)
- **Degrades when:** Write-heavy wor

references/api-reference.md

# API Reference

## Constructor

```go
hot.NewHotCache[K comparable, V any](algorithm hot.EvictionAlgorithm, capacity int) *HotCacheBuilder[K, V]
```

**Algorithm constants:**

| Constant       | Algorithm                              |
| -------------- | -------------------------------------- |
| `hot.LRU`      | Least Recently Used                    |
| `hot.LFU`      | Least Frequently Used                  |
| `hot.TinyLFU`  | TinyLFU with frequency decay           |
| `hot.WTinyLFU` | Weighted TinyLFU (recommended default) |
| `hot.S3FIFO`   | Segmented Small-Size FIFO              |
| `hot.ARC`      | Adaptive Replacement Cache             |
| `hot.TwoQueue` | Two-Queue                              |
| `hot.SIEVE`    | SIEVE eviction                         |
| `hot.FIFO`     | First In, First Out                    |

## Builder Methods

Call these on the builder returned by `NewHotCache()`, then finalize with `.Build()`.

| Method | Description |
| --- | --- |
| `WithTTL(ttl time.Duration)` | Default expiration for all entries |
| `WithJitter(lambda float64, upperBound time.Duration)` | Randomize TTL by +/-lambda (capped at upperBound) to prevent thundering herd |
| `WithJanitor()` | Start background goroutine to evict expired entries. Mutually exclusive with `WithoutLocking()` |
| `WithLoaders(loaders ...Loader[K, V])` | Chain of loader functions for cache misses. Execute sequentially; later loaders receive only unmapped keys |
| `WithRevalidation(stale time.Duration, loaders ...Loader[K, V])` | Enable stale-while-revalidate. After TTL, entries become stale and trigger async refresh. Hard-expired after `stale` duration |
| `WithRevalidationErrorPolicy(policy)` | `hot.KeepOnError` (keep stale value) or `hot.DropOnError` (drop on refresh failure) |
| `WithMissingCache(algorithm, capacity)` | Dedicated cache for missing keys (independent eviction) |
| `WithMissingSharedCache()` | Store missing keys in the main cache |
| `WithSharding(shards uint64, hasher Hasher[K])` | Split into N shards to reduce lock contention. Use powers of 2 |
| `WithCopyOnRead(fn func(V) V)` | Clone values on retrieval to prevent external mutation |
| `WithCopyOnWrite(fn func(V) V)` | Clone values on storage to capture snapshots |
| `WithPrometheusMetrics(cacheName string)` | Enable Prometheus metrics collection |
| `WithEvictionCallback(fn func(K, V))` | Synchronous callback on eviction |
| `WithoutLocking()` | Disable mutexes. Single-goroutine access only. Mutually exclusive with `WithJanitor()` |
| `WithWarmUp(fn func() (map[K]V, []K, error))` | Pre-populate cache on build. Returns values + missing keys + error |
| `WithWarmUpWithTimeout(timeout, fn)` | Same as WarmUp with timeout protection |
| `Build()` | Finalize and return `*HotCache[K, V]` |

## Read Operations

| Method | Signature | Behavior |
| --- | --- | --- |
| `Get` | `(key K) (V, bool, error)` | Value, found, loader error. Triggers loaders on miss |
| `GetWithLoaders` | `(key K, loaders ...Loader[K, 

references/production-patterns.md

# Production Patterns

## Stale-While-Revalidate

Return stale data immediately while refreshing in the background. Two time thresholds:

1. **TTL** — after this, entries become "stale" and trigger async background refresh via loaders
2. **Stale duration** — after TTL + stale, entries are hard-expired and removed

```go
refreshLoader := func(keys []string) (map[string]*Config, error) {
    return fetchConfigsFromDB(keys)
}

cache := hot.NewHotCache[string, *Config](hot.WTinyLFU, 1_000).
    WithTTL(5 * time.Minute).                              // stale after 5min
    WithRevalidation(1 * time.Minute, refreshLoader).       // hard-expire after 6min total
    WithRevalidationErrorPolicy(hot.KeepOnError).           // keep stale value if refresh fails
    WithJitter(0.1, 30*time.Second).                        // spread expirations
    WithJanitor().
    Build()
defer cache.StopJanitor()
```

**Timeline for an entry set at T=0 with this config:**

- T=0 to T=5min: fresh — returned directly
- T=5min to T=6min: stale — returned immediately, background refresh triggered
- T>6min: expired — removed, next `Get()` blocks on loader

**Error policies:**

- `hot.KeepOnError` — if background refresh fails, keep the stale value until hard expiry
- `hot.DropOnError` — if refresh fails, drop the entry immediately

Use `KeepOnError` when stale data is better than no data (config caches, product catalogs). Use `DropOnError` when correctness matters more than availability.

## Sharding

Split the cache into N independent segments to reduce lock contention under high concurrency:

```go
cache := hot.NewHotCache[string, *User](hot.WTinyLFU, 100_000).
    WithTTL(5 * time.Minute).
    WithSharding(16, func(key string) uint64 {
        h := fnv.New64a()
        h.Write([]byte(key))
        return h.Sum64()
    }).
    WithJanitor().
    Build()
defer cache.StopJanitor()
```

**Sizing guidance:**

- Use powers of 2 (4, 8, 16, 32) for optimal hash distribution
- Rule of thumb: shard count ~= number of CPU cores for high-contention workloads
- Each shard gets `capacity / shards` items
- Over-sharding (>64 shards) adds overhead without benefit

## Missing Key Caching (Negative Caching)

Prevents repeated loader calls for keys that don't exist in the source:

### Dedicated missing cache (recommended)

Independent eviction algorithm and capacity — gives fine-grained control:

```go
cache := hot.NewHotCache[string, *User](hot.WTinyLFU, 100_000).
    WithTTL(1 * time.Hour).
    WithMissingCache(hot.LFU, 10_000).  // separate LFU cache for missing keys
    WithLoaders(userLoader).
    WithJanitor().
    Build()
defer cache.StopJanitor()
```

### Shared missing cache

Missing entries stored in the main cache — simpler but uses main cache capacity:

```go
cache := hot.NewHotCache[string, *User](hot.WTinyLFU, 100_000).
    WithTTL(1 * time.Hour).
    WithMissingSharedCache().
    WithLoaders(userLoader).
    WithJanitor().
    Build()
defer cache.StopJanitor()
```

### Manual mis

Sponsored

Ads related to golang-samber-hot and adjacent AI workflows.