User Agents

Web browsers and everyday web tech, explained

Singleton Cache in Go: Step-by-Step Guide

· 5 min read · Cookies and Cache

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to create a thread-safe singleton cache in Go using the sync.Once pattern. A singleton cache ensures only one instance of the cache exists across your entire application, preventing redundant memory usage and ensuring consistent data access. You'll learn to implement a generic cache with expiration, which is practical for real-world use.

What You'll Need

  • Go 1.18 or later (for generics support)
  • Basic familiarity with Go syntax and concurrency
  • A text editor or IDE

Step-by-Step

  1. Define the cache structure. Create a struct that holds the cache data and a mutex to protect concurrent access. For a generic cache, use type parameters:
  2. type Cache[K comparable, V any] struct {
        mu    sync.RWMutex
        items map[K]item[V]
    }
    
    type item[V any] struct {
        value      V
        expiration int64 // Unix timestamp in nanoseconds
    }
  3. Add expiration logic. Store an expiration time for each entry. Use time.Now().Add(ttl).UnixNano() for TTL-based expiry.
  4. Implement the singleton pattern. Declare a package-level variable and a sync.Once instance. The Once ensures the initialization function runs exactly once, even with concurrent calls:
  5. var (
        cacheInstance *Cache[string, string]
        cacheOnce     sync.Once
    )
    
    func GetCache() *Cache[string, string] {
        cacheOnce.Do(func() {
            cacheInstance = NewCache[string, string](5 * time.Minute)
        })
        return cacheInstance
    }
  6. Create the constructor. The constructor initializes the map and sets a default TTL. It's called only from the Once block:
  7. func NewCache[K comparable, V any](ttl time.Duration) *Cache[K, V] {
        return &Cache[K, V]{
            items: make(map[K]item[V]),
            ttl:   ttl,
        }
    }
  8. Implement the Set method. Acquire a write lock, store the value with expiration, and release the lock:
  9. func (c *Cache[K, V]) Set(key K, value V) {
        c.mu.Lock()
        defer c.mu.Unlock()
        c.items[key] = item[V]{
            value:      value,
            expiration: time.Now().Add(c.ttl).UnixNano(),
        }
    }
  10. Implement the Get method. Use a read lock to check existence and expiration. If expired, delete the entry and return zero value:
  11. func (c *Cache[K, V]) Get(key K) (V, bool) {
        c.mu.RLock()
        it, ok := c.items[key]
        c.mu.RUnlock()
        if !ok {
            var zero V
            return zero, false
        }
        if time.Now().UnixNano() > it.expiration {
            c.mu.Lock()
            delete(c.items, key)
            c.mu.Unlock()
            var zero V
            return zero, false
        }
        return it.value, true
    }
  12. Add a cleanup method (optional). Periodically remove expired items to prevent memory leaks. Run it in a goroutine:
  13. func (c *Cache[K, V]) Cleanup(interval time.Duration) {
        ticker := time.NewTicker(interval)
        go func() {
            for range ticker.C {
                c.mu.Lock()
                now := time.Now().UnixNano()
                for k, it := range c.items {
                    if now > it.expiration {
                        delete(c.items, k)
                    }
                }
                c.mu.Unlock()
            }
        }()
    }
  14. Use the singleton in your application. Call GetCache() from any goroutine to get the same instance:
  15. func main() {
        cache := GetCache()
        cache.Set("key", "value")
        val, ok := cache.Get("key")
        fmt.Println(val, ok) // value true
    }

Common Mistakes

  • Forgetting to use sync.Once: If you initialize the singleton in an init function or directly, you risk multiple instances in concurrent environments.
  • Not protecting the map with a mutex: Concurrent reads/writes to a map cause panics. Always use locks.
  • Checking expiration without deleting: If you return false but don't delete, the entry stays in memory and may cause stale reads if you later check again.
  • Using a non-comparable key type: The cache requires K comparable; using slices or maps as keys will cause compile errors.
  • Starting cleanup without stopping it: The goroutine runs forever; ensure you have a way to stop it if needed (e.g., context cancellation).

Tips

  • Use generics for flexibility: The generic cache works with any key/value types, making it reusable.
  • Consider a max size: Add a maximum number of items and evict oldest entries (LRU) to bound memory usage.
  • Use RLock for reads: Multiple readers can access concurrently, improving performance.
  • Set a reasonable TTL: Too short causes frequent misses; too long uses stale data.
  • Test with the race detector: Run go test -race to catch data races.

Troubleshooting

  • Panic: assignment to entry in nil map: This happens if you didn't initialize the map in the constructor. Ensure you call make() before using.
  • Data race detected: Run with -race. Check that all map accesses are under the appropriate lock. If you see a race in Get, ensure you use RLock for reads and Lock for writes.
  • Cache returns stale data: Verify your expiration check uses UnixNano() and that you compare correctly. If TTL is zero, entries expire immediately.
  • Singleton not actually singleton: If you have multiple packages importing the same variable, ensure you're not redefining it. Use a single package-level variable and GetCache() function.
  • Memory grows unbounded: If you don't set a TTL or cleanup, entries never expire. Add a TTL and run cleanup periodically.

Frequently Asked Questions

Why use a singleton cache instead of a regular one?

A singleton ensures one shared cache across the app, avoiding duplicate data and inconsistent state. It's useful for global configuration, database query results, or API responses.

Is the cache safe for concurrent use?

Yes, because it uses sync.RWMutex and sync.Once, making it safe for concurrent reads and writes.

How do I change the TTL after creation?

You can add a method to update the TTL field, but be careful: existing entries keep their original expiration. For simplicity, create a new cache instance if TTL changes.

Can I use a struct as a key?

Yes, if the struct is comparable (all fields are comparable). For example, a struct with string and int fields works.

What happens if I call GetCache() from multiple goroutines?

Only one instance is created because sync.Once guarantees the initialization runs exactly once, even with concurrent calls.

How do I stop the cleanup goroutine?

Use a context with cancel. Pass the context to Cleanup and select on ctx.Done() to exit the loop.