Skills Agentes

Golang Samber Hot

Caché en memoria en Golang con samber/hot: algoritmos de expulsión (LRU, LFU, TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, loaders, sharding y métricas Prometheus.

Solicitaread 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__*
Estrellas
3k

en todo el repo

Actividad
56

0–100, la ruta de este skill

Actualizado
el mes pasado

último commit aquí

Commits
3

últimos 90 días

Contexto
2k tok

119 tok en reposo

Paquete
5 archivos

45 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add samber/cc-skills-golang --skill golang-samber-hot --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Configura caché en memoria con samber/hot: elige algoritmo de expulsión, TTL, loaders con singleflight, sharding y métricas Prometheus
  • Calcula la capacidad de la caché a partir del presupuesto de memoria y el tamaño estimado por entrada
  • Detecta errores comunes de configuración (WithJanitor, SetMissing, WithoutLocking) antes de que causen pánicos en runtime

Úsalo cuando

  • Se adopta o usa samber/hot en el proyecto
  • El código importa github.com/samber/hot
  • El proyecto carga repetidamente los mismos recursos de cardinalidad media-baja con alta frecuencia y necesita reducir latencia o presión en el backend

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • Añade una caché LRU con TTL usando samber/hot
    • ¿Qué algoritmo de expulsión debería usar para mi caché de usuarios?
    • Configura un loader con singleflight para samber/hot
    • Calcula la capacidad de mi caché en memoria para 256 MB

    SKILL.md

    En inglés

    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. 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.

    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 (<1000 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

    Reproducido de samber/cc-skills-golang bajo licencia MIT. Leer esta página en markdown.

    Archivos

    5 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Antes de instalar

    Requiere Go 1.22+ y el binario go instalado; se instala con go get -u github.com/samber/hot.

    Detalles

    Creador
    samber
    Licencia
    MIT
    Recursos incluidos
    referencias
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de samber/cc-skills-golang

    Este repo incluye 46 skills. Si instalas uno, normalmente ya tienes los demás.

    Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters.

    Costo de contexto al activarse
    1.8k tok
    Tamaño del paquete
    5 archivos
    Última actualización
    hace 3 días
    herramientas desarrollo

    Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI.

    Costo de contexto al activarse
    3.3k tok
    Tamaño del paquete
    10 archivos
    Última actualización
    hace 28 días
    testing qa

    Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez.

    Costo de contexto al activarse
    3.8k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 20 días
    herramientas desarrollo

    Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron.

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    9 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo

    Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración.

    Costo de contexto al activarse
    4.4k tok
    Tamaño del paquete
    6 archivos
    Última actualización
    el mes pasado
    testing qa

    Inyección de dependencias en Golang con samber/do: contenedores de servicios, gestión de ciclo de vida, scopes, health checks, apagado ordenado y organización en módulos.

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 22 días
    herramientas desarrollo

    Skills relacionados

    Desarrollo de aplicaciones CLI en Go: estructura de comandos, flags, configuración por capas, versión embebida, exit codes, señales, completions y testing con cobra, viper o urfave/cli.

    Costo de contexto al activarse
    2.6k tok
    Tamaño del paquete
    14 archivos
    Última actualización
    hace 3 meses
    herramientas desarrollo

    Convenciones de estilo en Golang: longitud y corte de líneas, declaración de variables, claridad del control de flujo y cuándo los comentarios ayudan u estorban.

    Costo de contexto al activarse
    2.5k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo

    Patrones de concurrencia en Go: úsalo al escribir o revisar código concurrente con goroutines, channels, select, locks, sync primitives, errgroup, singleflight, worker pools o pipelines fan-out/fan-in.

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    5 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo