By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A cache is easy to add and hard to make correct. Before writing one, answer three questions: what is the key, how long is the value valid, and what happens when it changes? A TTL cache is the simplest defensible option; an LRU adds memory bounds; a write-through cache keeps storage and cache consistent by construction. Anything more complicated needs a real eviction and invalidation story.
Inject a clock. Caching and rate limiting are dominated by time, and a now func() time.Time field makes them deterministic to test and readable in production. It is also the difference between a test that sleeps thirty seconds and a test that runs in microseconds.
A token bucket allows bursts up to a ceiling and refills at a steady rate: simple, fair and the default choice for an API. Apply it in middleware, keyed by API key or client IP, and return 429 with Retry-After when the bucket is empty. A global limiter without a per-tenant key punishes one noisy tenant and hides which one; a per-tenant limiter without a global fallback lets the sum of tenants exceed capacity.
package main
import (
"fmt"
"math"
"time"
)
type cacheEntry[T any] struct {
value T
expires time.Time
}
type ttlCache[T any] struct {
items map[string]cacheEntry[T]
ttl time.Duration
now func() time.Time
}
func newTTLCache[T any](ttl time.Duration, now func() time.Time) *ttlCache[T] {
return &ttlCache[T]{items: make(map[string]cacheEntry[T]), ttl: ttl, now: now}
}
func (c *ttlCache[T]) Get(key string) (T, bool) {
var zero T
entry, ok := c.items[key]
if !ok || c.now().After(entry.expires) {
return zero, false
}
return entry.value, true
}
func (c *ttlCache[T]) Set(key string, value T) {
c.items[key] = cacheEntry[T]{value: value, expires: c.now().Add(c.ttl)}
}
type tokenBucket struct {
tokens float64
burst float64
refill float64
last time.Time
now func() time.Time
}
func newTokenBucket(burst, refill float64, now func() time.Time) *tokenBucket {
return &tokenBucket{tokens: burst, burst: burst, refill: refill, last: now(), now: now}
}
func (b *tokenBucket) Allow() bool {
current := b.now()
b.tokens = math.Min(b.burst, b.tokens+current.Sub(b.last).Seconds()*b.refill)
b.last = current
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
func main() {
clock := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
now := func() time.Time { return clock }
cache := newTTLCache[int](30*time.Second, now)
cache.Set("stats:api", 42)
value, ok := cache.Get("stats:api")
fmt.Println("cache hit:", ok, "value:", value)
clock = clock.Add(31 * time.Second)
_, ok = cache.Get("stats:api")
fmt.Println("cache hit after ttl:", ok)
clock = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
limiter := newTokenBucket(2, 1, now)
fmt.Println("allow 1:", limiter.Allow())
fmt.Println("allow 2:", limiter.Allow())
fmt.Println("allow 3:", limiter.Allow())
clock = clock.Add(time.Second)
fmt.Println("allow after refill:", limiter.Allow())
}| Strategy | Good at | Cost or risk |
|---|---|---|
| TTL cache | Cheap, simple, bounded staleness | Stale reads until expiry |
| LRU cache | Bounded memory, hot data | Eviction can be surprising |
| Write-through | Fresh reads | Writes pay cache latency |
| Token bucket | Smooth rate with bursts | Per-key state to store |
| Fixed window | Simple counters | Bursts at window boundaries |
| Distributed limiter | Many instances | Shared store becomes a dependency |
Key takeaways
Decide the key, the TTL and the invalidation rule before adding a cache.
Inject a clock so caching and rate-limiting logic is testable without sleeping.
Token buckets allow controlled bursts and refill steadily; return 429 with Retry-After.
Limit per tenant and globally, so one client cannot consume all capacity.
Cache keys must include every dimension that changes the cached value.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.