Skip to content

Go Cache TTL Not Expiring

DodaTech Updated 2026-06-24 1 min read

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

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

**What TTL should I use?**

Depends on data. User sessions: 24h. API responses: 5-60s.

How to handle cache stampede?

Use singleflight or distributed locks for cache refresh.

Should I use TTL or LRU?

Both. TTL for freshness, LRU for memory management.


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