go 60 lines · 9 steps

A thread-safe TTL cache in Go

An in-memory map guarded by a read-write mutex, where every entry carries its own expiry time.

Explained by highlit
1package cache
2 
3import (
4 "sync"
5 "time"
6)
7 
8type entry struct {
9 value string
10 expiresAt time.Time
11}
12 
13type TTLCache struct {
14 mu sync.RWMutex
15 items map[string]entry
16 ttl time.Duration
17}
18 
19func New(ttl time.Duration) *TTLCache {
20 return &TTLCache{
21 items: make(map[string]entry),
22 ttl: ttl,
23 }
24}
25 
26func (c *TTLCache) Get(key string) (string, bool) {
27 c.mu.RLock()
28 e, ok := c.items[key]
29 c.mu.RUnlock()
30 if !ok || time.Now().After(e.expiresAt) {
31 return "", false
32 }
33 return e.value, true
34}
35 
36func (c *TTLCache) Set(key, value string) {
37 c.mu.Lock()
38 c.items[key] = entry{value: value, expiresAt: time.Now().Add(c.ttl)}
39 c.mu.Unlock()
40}
41 
42func (c *TTLCache) Delete(key string) {
43 c.mu.Lock()
44 delete(c.items, key)
45 c.mu.Unlock()
46}
47 
48func (c *TTLCache) Purge() int {
49 now := time.Now()
50 c.mu.Lock()
51 defer c.mu.Unlock()
52 removed := 0
53 for k, e := range c.items {
54 if now.After(e.expiresAt) {
55 delete(c.items, k)
56 removed++
57 }
58 }
59 return removed
60}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Storing an absolute expiry per entry makes staleness a cheap comparison at read time rather than a background job.
  2. 2A sync.RWMutex lets many readers proceed in parallel while writes stay exclusive, matching a read-heavy cache.
  3. 3Lazy expiry on Get keeps reads correct even when a separate Purge sweep hasn't run yet.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A thread-safe TTL cache in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code