For most Go services, an in-memory cache with expiry is a plain map behind a sync.RWMutex, an expiry time on each entry, and one background goroutine that sweeps out dead entries. That takes under 80 lines with generics and no dependencies. Two more pieces make it safe under load: singleflight, so a burst of misses on one key turns into one database call instead of a hundred, and a Close method, so the cleanup goroutine doesn't outlive the cache. sync.Map is usually the wrong starting point, and the reason why is in its own documentation.
Everything below ran on Go 1.27.4, the current release (10 November 2026, per the Go release history), with golang.org/x/sync v0.25.0. The cache itself only needs generics (Go 1.18). The test at the end needs testing/synctest (Go 1.25) and uses one helper added in 1.27.
A TTL cache with a map and a mutex
Each entry stores its value and the time it stops being valid. Get treats an expired entry as a miss straight away, so callers never see stale data, even if the cleanup goroutine hasn't run yet:
package cache
import (
"sync"
"time"
)
type entry[V any] struct {
value V
expiresAt time.Time
}
type Cache[K comparable, V any] struct {
mu sync.RWMutex
items map[K]entry[V]
ttl time.Duration
stop chan struct{}
}
func New[K comparable, V any](ttl, cleanupEvery time.Duration) *Cache[K, V] {
c := &Cache[K, V]{
items: make(map[K]entry[V]),
ttl: ttl,
stop: make(chan struct{}),
}
go c.janitor(cleanupEvery)
return c
}
func (c *Cache[K, V]) Set(key K, value V) {
c.mu.Lock()
c.items[key] = entry[V]{value: value, expiresAt: time.Now().Add(c.ttl)}
c.mu.Unlock()
}
func (c *Cache[K, V]) Get(key K) (V, bool) {
c.mu.RLock()
e, ok := c.items[key]
c.mu.RUnlock()
if !ok || time.Now().After(e.expiresAt) {
var zero V
return zero, false
}
return e.value, true
}
There's a reason Get doesn't delete the expired entry it finds. It only holds the read lock, and upgrading to the write lock on a read path would make every reader that hits an expired key contend with every writer. Leaving the entry in place costs a little memory until the next sweep. That trade is almost always worth it for a read-heavy cache.
The sweep is the part people forget. Without it, a key that's written once and never read again stays in the map forever. Expiry only hides the value, it doesn't free it. The janitor walks the map on a ticker and exits when the cache is closed:
func (c *Cache[K, V]) janitor(every time.Duration) {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-t.C:
c.deleteExpired()
case <-c.stop:
return
}
}
}
func (c *Cache[K, V]) deleteExpired() {
now := time.Now()
c.mu.Lock()
for k, e := range c.items {
if now.After(e.expiresAt) {
delete(c.items, k)
}
}
c.mu.Unlock()
}
// Close stops the janitor goroutine.
func (c *Cache[K, V]) Close() { close(c.stop) }
Deleting from a map while ranging over it is well defined: the Go spec only says an entry removed before it's reached won't be produced, so the single pass is safe. The sweep holds the write lock for the whole walk, which matters once a cache holds millions of entries. Choose a cleanup interval that's a few times the TTL, not shorter, because Get already hides expired values and the sweep only exists to reclaim memory.
A TTL limits how stale a value can get. It doesn't limit how big the cache can grow. If keys come from user input (URLs, search terms, session IDs), the map can grow as fast as traffic does within a single TTL window. In that case you need a maximum size with an eviction policy such as LRU, not just expiry.
When sync.Map is the right tool
Reaching for sync.Map because it's "the concurrent map" is a common mistake. The sync.Map documentation says it's optimized for two cases: "(1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys." It also says directly that "Most code should use a plain Go map instead, with separate locking or coordination, for better type safety."
A TTL cache fits neither case. Entries get overwritten whenever they expire and reload, and to expire them you need a timestamp next to each value, which sync.Map doesn't give you. Its API is any in and any out, so every read needs a type assertion. Where it does fit is a grow-only cache of things that are expensive to build and never change, such as compiled regular expressions:
var patterns sync.Map // string -> *regexp.Regexp
func compiled(expr string) *regexp.Regexp {
if re, ok := patterns.Load(expr); ok {
return re.(*regexp.Regexp)
}
re := regexp.MustCompile(expr)
actual, loaded := patterns.LoadOrStore(expr, re)
if loaded {
fmt.Println("lost the race, using the stored value")
}
return actual.(*regexp.Regexp)
}
LoadOrStore is what makes this correct. If two goroutines compile the same pattern at the same time, both store attempts are resolved atomically, and both callers get the same *regexp.Regexp back. The extra compile is wasted work, but no caller ends up with a different value from the others.
Stop the stampede with singleflight
The usual way to use a cache is "get, and on a miss, load and set." It has a failure mode that only shows up under load. When a popular key expires, every request that arrives before the reload finishes misses too, and each one goes to the database. This site's article on cache penetration, breakdown and avalanche calls this cache breakdown. golang.org/x/sync/singleflight fixes it. Its Do method makes sure "only one execution is in-flight for a given key at a time", and a duplicate caller "waits for the original to complete and receives the same results."
var group singleflight.Group
func getOnce(c *cache.Cache[string, string], id string) (string, error) {
if v, ok := c.Get(id); ok {
return v, nil
}
v, err, _ := group.Do(id, func() (any, error) {
if v, ok := c.Get(id); ok { // filled while we waited
return v, nil
}
v, err := loadUser(id)
if err != nil {
return "", err
}
c.Set(id, v)
return v, nil
})
if err != nil {
return "", err
}
return v.(string), nil
}
To measure it, we started 100 goroutines that all asked for the same uncached key, with a loadUser that takes 50 ms and counts how often it's called. We ran it with the race detector on:
naive 100 concurrent misses -> 100 database calls
singleflight 100 concurrent misses -> 1 database calls
Three things to know before you copy this. The key is always a string, so a cache with integer or struct keys needs a string form of the key for the group. Errors are shared too: if the one load fails, every waiting caller gets that error, and nothing is cached, so the next request tries again. The third return value, shared, reports whether the result went to more than one caller. It's useful as a metric, because a high rate means your TTLs line up with traffic spikes.
Testing expiry without sleeping
Testing a TTL cache usually means real time.Sleep calls and slow, flaky tests. testing/synctest, generally available since Go 1.25, runs the test in a "bubble" where the time package uses a fake clock. That clock "only advances when every goroutine in the bubble is durably blocked." The janitor's select on the ticker and the stop channel counts as durably blocked, so the whole test, including eleven minutes of simulated time, runs instantly:
func TestExpiry(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := New[string, int](time.Minute, 10*time.Minute)
defer c.Close()
c.Set("a", 1)
time.Sleep(59 * time.Second)
if _, ok := c.Get("a"); !ok {
t.Fatal("expired too early")
}
time.Sleep(2 * time.Second)
if _, ok := c.Get("a"); ok {
t.Fatal("still there after TTL")
}
if c.Len() != 1 {
t.Fatalf("janitor ran early, len=%d", c.Len())
}
synctest.Sleep(10 * time.Minute) // Go 1.27: time.Sleep + synctest.Wait
if c.Len() != 0 {
t.Fatalf("janitor did not clean up, len=%d", c.Len())
}
})
}
=== RUN TestExpiry
--- PASS: TestExpiry (0.00s)
Len is a three-line helper that returns len(c.items) under the read lock. The test checks both halves of expiry: Get hides the value at 61 seconds, while the entry stays in the map until the janitor's ten-minute tick. synctest.Sleep is new in Go 1.27. On 1.25 and 1.26, write time.Sleep followed by synctest.Wait().
The bubble also catches the leak this cache is most likely to have. synctest.Test waits for every goroutine it started to exit, so if you remove the defer c.Close(), the janitor is still parked in its select when the test function returns:
--- FAIL: TestForgotClose (0.00s)
panic: deadlock: main bubble goroutine has exited but blocked goroutines remain [recovered, repanicked]
...
goroutine 26 [select (durable), synctest bubble 2]:
example.com/gocache/cache.(*Cache[...]).janitor(0x100ca21a0, 0x739035bdc488)
Outside a test, that same mistake goes unnoticed. A cache created per request or per tenant, and never closed, leaves behind one ticker goroutine plus the whole map it points to. If your caches have a shorter lifetime than the process, give them a Close and call it. If they live as long as the process, a package-level cache created once in main is simpler and needs no cleanup.
No comment for this article.