golang-samber-hot▌
samber/cc-skills-golang · updated Apr 8, 2026
MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.
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.
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.
| 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:
- 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).
- 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.
- 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
- Forgetting
WithJanitor()— without it, expired entries stay in memory until the algorithm evicts them. Always chain.WithJanitor()in the builder anddefer cache.StopJanitor(). - Calling
SetMissing()without missing cache config — panics at runtime. EnableWithMissingCache(algorithm, capacity)orWithMissingSharedCache()in the builder first. WithoutLocking()+WithJanitor()— mutually exclusive, panics.WithoutLocking()is only safe for single-goroutine access without background cleanup.- 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.
- Ignoring loader errors —
Get()returns(zero, false, err)on loader failure. Always checkerr, not justfound.
Best Practices
- Always set TTL — unbounded caches serve stale data indefinitely because there is no signal to refresh
- Use
WithJitter(lambda, upperBound)to spread expirations — without jitter, items created together expire together, causing thundering herd on the loader - Monitor with
WithPrometheusMetrics(cacheName)— hit rate below 80% usually means the cache is undersized or the algorithm is wrong for the workload - 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-performanceskill for general caching strategy and when to use in-memory cache vs Redis vs CDN - → See
samber/cc-skills-golang@golang-observabilityskill for Prometheus metrics integration and monitoring - → See
samber/cc-skills-golang@golang-databaseskill for database query patterns that pair with cache loaders - → See
samber/cc-skills@promql-cliskill for querying Prometheus cache metrics via CLI
How to use golang-samber-hot on Cursor
AI-first code editor with Composer
Prerequisites
Before installing skills in Cursor, ensure your development environment meets these requirements:
- ›Cursor installed and configured on your development machine
- ›Node.js version 16.0+ with npm package manager (verify with
node --version) - ›Active project directory or workspace where you want to add golang-samber-hot
Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
The skills CLI fetches golang-samber-hot from GitHub repository samber/cc-skills-golang and configures it for Cursor.
Select Cursor when prompted
The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:
Verify installation
Confirm successful installation by checking the skill directory location:
Reload or restart Cursor to activate golang-samber-hot. Access the skill through slash commands (e.g., /golang-samber-hot) or your agent's skill management interface.
Security & Verification Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.
List & Monetize Your Skill
Submit your Claude Code skill and start earning
Use Cases▌
Task Automation & Efficiency
Automate repetitive workflows and reduce manual effort
Example
Generate reports, summarize documents, draft communications
Save 3-5 hours per week on routine tasks
Knowledge Enhancement
Learn new skills, understand complex topics, get expert guidance
Example
Explain concepts, provide examples, suggest learning resources
Accelerate learning and skill development by 2x
Quality Improvement
Enhance output quality through reviews, suggestions, and refinements
Example
Review drafts, suggest improvements, catch errors
Improve work quality by 30-40% with less effort
Implementation Guide▌
Prerequisites
- ›Claude Desktop or compatible AI client with skill support
- ›Clear understanding of task or problem to solve
- ›Willingness to iterate and refine outputs
Time Estimate
15-45 minutes depending on use case complexity
Installation Steps
- 1.Install skill using provided installation command
- 2.Test with simple use case relevant to your work
- 3.Evaluate output quality and relevance
- 4.Iterate on prompts to improve results
- 5.Integrate into regular workflow if valuable
Common Pitfalls
- ⚠Expecting perfect results without iteration
- ⚠Not providing enough context in prompts
- ⚠Using skill for tasks outside its intended scope
- ⚠Accepting outputs without review and validation
Best Practices▌
✓ Do
- +Start with clear, specific prompts
- +Provide relevant context and constraints
- +Review and refine all outputs before using
- +Iterate to improve output quality
- +Document successful prompt patterns
✗ Don't
- −Don't use without understanding skill limitations
- −Don't skip validation of outputs
- −Don't share sensitive information in prompts
- −Don't expect skill to replace human judgment
💡 Pro Tips
- ★Be specific about desired format and style
- ★Ask for multiple options to choose from
- ★Request explanations to understand reasoning
- ★Combine AI efficiency with human expertise
When to Use This▌
✓ Use When
Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.
✗ Avoid When
Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.
Learning Path▌
- 1Familiarize yourself with skill capabilities and limitations
- 2Start with low-risk, non-critical tasks
- 3Progress to more complex and valuable use cases
- 4Build expertise through regular use and experimentation
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
Ratings
4.6★★★★★32 reviews- ★★★★★Alexander Martin· Dec 24, 2024
Useful defaults in golang-samber-hot — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Li Sharma· Dec 16, 2024
golang-samber-hot is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
- ★★★★★Chen Sethi· Nov 7, 2024
Keeps context tight: golang-samber-hot is the kind of skill you can hand to a new teammate without a long onboarding doc.
- ★★★★★Rahul Santra· Nov 3, 2024
Useful defaults in golang-samber-hot — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Zaid White· Oct 26, 2024
We added golang-samber-hot from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.
- ★★★★★Pratham Ware· Oct 22, 2024
Registry listing for golang-samber-hot matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★Sakshi Patil· Sep 25, 2024
Solid pick for teams standardizing on skills: golang-samber-hot is focused, and the summary matches what you get after install.
- ★★★★★Alexander Verma· Sep 13, 2024
golang-samber-hot has been reliable in day-to-day use. Documentation quality is above average for community skills.
- ★★★★★Chaitanya Patil· Aug 16, 2024
I recommend golang-samber-hot for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.
- ★★★★★Amelia Gill· Aug 4, 2024
golang-samber-hot fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
showing 1-10 of 32