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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing an absolute expiry per entry makes staleness a cheap comparison at read time rather than a background job.
- 2A sync.RWMutex lets many readers proceed in parallel while writes stay exclusive, matching a read-heavy cache.
- 3Lazy expiry on Get keeps reads correct even when a separate Purge sweep hasn't run yet.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-thread-safe-ttl-cache-in-go-explained-go-dc8a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.