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
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
go
func UploadChunk(c *gin.Context) { uploadID := c.Param("uploadID") if !validUploadID.MatchString(uploadID) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload id"})
Resumable chunked uploads in Gin
file-upload
content-range
streaming
Advanced
9 steps
go
func (h *ArticleHandler) Create(c *gin.Context) { var req struct { Title string `json:"title" binding:"required"` Body string `json:"body" binding:"required"`
Handling a POST request in Gin
request binding
validation
http status codes
Intermediate
7 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.