Singleton Cache in Go: Step-by-Step Guide
In this article
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
- 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:
- Add expiration logic. Store an expiration time for each entry. Use
time.Now().Add(ttl).UnixNano()for TTL-based expiry. - Implement the singleton pattern. Declare a package-level variable and a
sync.Onceinstance. TheOnceensures the initialization function runs exactly once, even with concurrent calls: - Create the constructor. The constructor initializes the map and sets a default TTL. It's called only from the
Onceblock: - Implement the
Setmethod. Acquire a write lock, store the value with expiration, and release the lock: - Implement the
Getmethod. Use a read lock to check existence and expiration. If expired, delete the entry and return zero value: - Add a cleanup method (optional). Periodically remove expired items to prevent memory leaks. Run it in a goroutine:
- Use the singleton in your application. Call
GetCache()from any goroutine to get the same instance:
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
}
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
}
func NewCache[K comparable, V any](ttl time.Duration) *Cache[K, V] {
return &Cache[K, V]{
items: make(map[K]item[V]),
ttl: ttl,
}
}
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(),
}
}
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
}
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()
}
}()
}
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
RLockfor 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 -raceto 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 inGet, ensure you useRLockfor reads andLockfor 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.