Caching
suggest changeCaching stores expensive computation results or database queries in fast, temporary storage to minimize latency and protect backend infrastructure from overload. In Go, caching is typically implemented using in-memory thread-safe maps with TTL, deduplicated loading via singleflight, HTTP ETag / conditional requests, or distributed stores like Redis.
1. Thread-Safe In-Memory Cache with TTL and Generics
Using Go generics and sync.RWMutex, you can build an in-memory cache that automatically expires stale items:
package main
import (
"context"
"fmt"
"sync"
"time"
)
type cacheItem[V any] struct {
value V
expiresAt time.Time
}
func (item cacheItem[V]) isExpired() bool {
return !item.expiresAt.IsZero() && time.Now().After(item.expiresAt)
}
type MemoryCache[K comparable, V any] struct {
mu sync.RWMutex
items map[K]cacheItem[V]
}
func NewMemoryCache[K comparable, V any](ctx context.Context, cleanupInterval time.Duration) *MemoryCache[K, V] {
c := &MemoryCache[K, V]{
items: make(map[K]cacheItem[V]),
}
// Background goroutine to periodically clean up expired items
go c.startEvictionLoop(ctx, cleanupInterval)
return c
}
func (c *MemoryCache[K, V]) Set(key K, value V, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
var expires time.Time
if ttl > 0 {
expires = time.Now().Add(ttl)
}
c.items[key] = cacheItem[V]{
value: value,
expiresAt: expires,
}
}
func (c *MemoryCache[K, V]) Get(key K) (V, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
item, exists := c.items[key]
var zero V
if !exists || item.isExpired() {
return zero, false
}
return item.value, true
}
func (c *MemoryCache[K, V]) startEvictionLoop(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
c.mu.Lock()
now := time.Now()
for k, v := range c.items {
if !v.expiresAt.IsZero() && now.After(v.expiresAt) {
delete(c.items, k)
}
}
c.mu.Unlock()
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cache := NewMemoryCache[string, string](ctx, 500*time.Millisecond)
cache.Set("user:101", "Alice", 200*time.Millisecond)
val, found := cache.Get("user:101")
fmt.Printf("Initial Get: %s (found: %v)\n", val, found) // Alice, true
time.Sleep(300 * time.Millisecond)
val, found = cache.Get("user:101")
fmt.Printf("After TTL Get: %s (found: %v)\n", val, found) // "", false
}
2. Preventing Thundering Herds with singleflight
When a popular cached item expires, hundreds of concurrent web requests may experience a cache miss at the same millisecond and all query the database simultaneously. This is called a cache stampede or thundering herd.
The standard subrepository package golang.org/x/sync/singleflight deduplicates concurrent requests for the same key:
package main
import (
"fmt"
"sync"
"time"
"golang.org/x/sync/singleflight"
)
var group singleflight.Group
func queryDatabase(userID int) (string, error) {
// Simulate slow database read
fmt.Println("--> EXECUTING EXPENSIVE DATABASE QUERY <--")
time.Sleep(200 * time.Millisecond)
return fmt.Sprintf("User#%d Data", userID), nil
}
func getUserData(userID int) (string, error) {
key := fmt.Sprintf("user:%d", userID)
// singleflight.Group.Do ensures only ONE goroutine executes the query
v, err, shared := group.Do(key, func() (any, error) {
return queryDatabase(userID)
})
if err != nil {
return "", err
}
if shared {
fmt.Printf("Request for user %d shared database result with another caller!\n", userID)
}
return v.(string), nil
}
func main() {
var wg sync.WaitGroup
// Launch 5 concurrent requests for the exact same user ID
for i := 0; i < 5; i++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
data, _ := getUserData(42)
fmt.Printf("Worker %d received: %s\n", workerID, data)
}(i)
}
wg.Wait()
}
Notice the expensive query is executed only once, while all other concurrent goroutines receive the exact same result simultaneously.
3. HTTP Conditional Caching with ETags
In HTTP APIs, returning 304 Not Modified eliminates bandwidth consumption and payload rendering when resources have not changed:
package main
import (
"crypto/sha256"
"fmt"
"net/http"
)
func handleGetResource(w http.ResponseWriter, r *http.Request) {
payload := `{"id": 42, "name": "Widget", "version": 3}`
// Generate entity tag (ETag) from payload hash
hash := sha256.Sum256([]byte(payload))
etag := fmt.Sprintf(`"%x"`, hash[:8])
// Check if client provided matching If-None-Match header
if match := r.Header.Get("If-None-Match"); match == etag {
w.WriteHeader(http.StatusNotModified) // 304: Client uses browser cache
return
}
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "public, max-age=3600")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(payload))
}
4. Distributed Caching with Redis (Cache-Aside Pattern)
In multi-node architectures, use a distributed cache such as Redis:
package main
import (
"context"
"time"
"github.com/redis/go-redis/v9"
)
type Service struct {
rdb *redis.Client
}
func (s *Service) GetUserProfile(ctx context.Context, userID string) (string, error) {
cacheKey := "profile:" + userID
// 1. Check Redis cache
val, err := s.rdb.Get(ctx, cacheKey).Result()
if err == nil {
return val, nil // Cache HIT
}
if err != redis.Nil {
// Redis connection error (optional fallback to DB)
}
// 2. Cache MISS: query primary database
profileData := "Fetched from PostgreSQL"
// 3. Populate cache with TTL (15 minutes)
_ = s.rdb.Set(ctx, cacheKey, profileData, 15*time.Minute).Err()
return profileData, nil
}
Best Practices
- Always Set a TTL: Every cached item should have a sensible Time-To-Live to prevent memory exhaustion and permanent stale data.
- Use
singleflightfor Expensive Resources: Protect databases from spikes by collapsing concurrent queries for the same key. - Handle Cache Failure Gracefully: Caching should be an acceleration layer, not a single point of failure. If Redis or local memory fails, the application should fall back to querying primary storage.