Go Cache TTL Not Expiring
In this tutorial, you'll learn about Go Cache TTL Not Expiring. We cover key concepts, practical examples, and best practices.
Cache TTL -- Set expiration time when caching items to prevent stale data from being served indefinitely.
The Problem
In-memory caches without TTL grow unboundedly and serve stale data. Always set TTL (time-to-live) when adding cache entries.
Wrong
cache["key"] = value
// No expiration!
Output:
// Item stays forever. Memory grows. Data goes stale.
Right
type CacheItem struct {
Value interface{}
ExpiresAt time.Time
}
func (c *Cache) Set(key string, val interface{}, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = CacheItem{Value: val, ExpiresAt: time.Now().Add(ttl)}
}
func (c *Cache) Get(key string) interface{} {
c.mu.RLock()
defer c.mu.RUnlock()
item, ok := c.items[key]
if !ok || time.Now().After(item.ExpiresAt) {
delete(c.items, key)
return nil
}
return item.Value
}
Output:
// Items expire after TTL. Cache bounded.
Prevention
- Always set TTL on cached items
- Use a cleanup goroutine for expired items
- Use sync.RWMutex for concurrent access
- Consider using freecache/bigcache for production
- TTL depends on data staleness tolerance
Common Mistakes with cache ttl
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro