Gin and your data · 7 MIN READ
Cache public GETs in Gin: key by route template, bypass identity, coalesce misses, invalidate on write
Build a Gin middleware that caches public GET responses under a route-template key, never stores per-user responses, coalesces concurrent misses with singleflight and stays correct across writes, TTLs and conditional requests.
A popular public endpoint renders the same page of articles thousands of times a minute, and each render costs a query and a JSON encode. Caching the finished response inside the service removes that work, but only if the cache never answers differently from the handler: not for another user, not for another query string and not after a write.
gin · A MAP OF THE IDEA
- Bypass identity, unknowns
- Key route + canonical query
- Coalesce the miss
- Store only public 200s
Useful when
- A popular public page costs one handler run per TTL per process.
- Concurrent misses collapse into one fill, and 304s are answered from the entry.
Watch out
- Invalidation is per process; other replicas serve old entries until their TTL ends.
- A follower keeps waiting for the leader even after its own client has gone.
Implementation & operation cost: Memory for stored bodies, a capture writer, per-route allow-lists that must track what handlers read, and an invalidation call in every write path.
The cache must never change the answer
One invariant drives every decision: the cache may answer only when the stored response is exactly what the handler would produce for this request. The key must therefore capture every input the handler reads, a request that carries identity must bypass the cache, and only a response that declares itself public may be stored. The conditional-requests lesson set Cache-Control and ETags for browsers and CDNs, which saves bandwidth. A server-side cache saves the handler's own work, the query and the render, and it lives inside your process, where you control the key, the lifetime and invalidation. The stampede and cache-aside lessons explain why concurrent misses are dangerous; this lesson builds the Gin middleware that handles them.
Key by what the handler reads
c.FullPath() returns the route template, such as /articles/:id, so the set of keys and the unit of invalidation follow routes rather than raw paths, and an unmatched request has an empty template and is never cached. Add the values from c.Params, then the query parsed with url.ParseQuery and re-encoded with Values.Encode, which sorts parameter names, so ?sort=new&page=1 and ?page=1&sort=new share an entry. Encode keeps the order of repeated values, because that order can be meaningful. Each route lists the parameters its handler reads. A request with any other parameter bypasses the cache instead of having the parameter dropped: dropping utm_source would be harmless, but dropping a parameter the handler does read would serve the wrong page. If you know some tracking parameters are ignored, strip them through a named list. Requests with Authorization or Cookie bypass, and a stored response must not carry Set-Cookie or Vary, because the key does not include the request headers it would vary on.
The middleware, a fake clock and a gated handler
The program wraps one list route in the cache. A fake clock decides expiry. The handler counts its calls, reads the data version before doing slow work, and can be held at a gate so that misses overlap deterministically. The sequence covers a hit through a reordered query, three bypasses, a 304 served from the entry, a write, expiry, a write that lands during a fill, and two bursts of five concurrent misses, with and without coalescing.
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"net/url"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/sync/singleflight"
)
// Clock is injected so that tests, not the wall clock, decide when entries expire.
type Clock struct {
mu sync.Mutex
now time.Time
}
func (c *Clock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *Clock) Advance(d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.now = c.now.Add(d)
}
// entry is everything needed to replay a response. It is shared by
// concurrent readers, so it is never modified after it is stored.
type entry struct {
status int
header http.Header
body []byte
stored time.Time
}
type ResponseCache struct {
now func() time.Time
ttl time.Duration
allowed map[string][]string // route template -> query parameters it reads
coalesce bool
group singleflight.Group
mu sync.Mutex
entries map[string]entry
gen map[string]uint64 // bumped per route template on every invalidation
}
func (rc *ResponseCache) get(key string) (entry, bool) {
rc.mu.Lock()
defer rc.mu.Unlock()
e, ok := rc.entries[key]
if ok && rc.now().Sub(e.stored) >= rc.ttl {
delete(rc.entries, key)
return entry{}, false
}
return e, ok
}
func (rc *ResponseCache) generation(route string) uint64 {
rc.mu.Lock()
defer rc.mu.Unlock()
return rc.gen[route]
}
// put stores e unless the route was invalidated after the fill started.
func (rc *ResponseCache) put(route, key string, gen uint64, e entry) {
rc.mu.Lock()
defer rc.mu.Unlock()
if rc.gen[route] == gen {
rc.entries[key] = e
}
}
func (rc *ResponseCache) Invalidate(routes ...string) {
rc.mu.Lock()
defer rc.mu.Unlock()
for _, route := range routes {
rc.gen[route]++
}
for key := range rc.entries {
route, _, _ := strings.Cut(key, " ")
if slices.Contains(routes, route) {
delete(rc.entries, key)
}
}
}
// key returns false when the request must bypass the cache.
func (rc *ResponseCache) key(c *gin.Context) (route, key string, ok bool) {
route = c.FullPath()
params, listed := rc.allowed[route]
if c.Request.Method != http.MethodGet || !listed {
return "", "", false
}
if c.GetHeader("Authorization") != "" || c.GetHeader("Cookie") != "" {
return "", "", false // the response may depend on who is asking
}
q, err := url.ParseQuery(c.Request.URL.RawQuery)
if err != nil {
return "", "", false
}
for name := range q {
if !slices.Contains(params, name) {
return "", "", false // an input the key would not capture
}
}
key = route
for _, p := range c.Params {
key += " " + p.Key + "=" + url.QueryEscape(p.Value)
}
return route, key + " ?" + q.Encode(), true // Encode sorts by name
}
// capture buffers the handler's response instead of sending it.
type capture struct {
gin.ResponseWriter
header http.Header
status int
body bytes.Buffer
}
func (w *capture) Header() http.Header { return w.header }
func (w *capture) WriteHeader(code int) { w.status = code }
func (w *capture) WriteHeaderNow() {}
func (w *capture) Write(b []byte) (int, error) { return w.body.Write(b) }
func (w *capture) WriteString(s string) (int, error) { return w.body.WriteString(s) }
func (w *capture) Status() int { return w.status }
func (w *capture) Size() int { return w.body.Len() }
func (w *capture) Written() bool { return w.body.Len() > 0 }
func (w *capture) Flush() {}
// record runs the rest of the chain for a full, unconditional response.
func (rc *ResponseCache) record(c *gin.Context) entry {
w := &capture{ResponseWriter: c.Writer, header: http.Header{}, status: http.StatusOK}
writer, req := c.Writer, c.Request
defer func() { c.Writer, c.Request = writer, req }() // also when a handler panics
c.Writer, c.Request = w, req.Clone(req.Context())
c.Request.Header.Del("If-None-Match") // never store a 304 meant for one client
c.Request.Header.Del("If-Modified-Since")
c.Next()
return entry{status: w.status, header: w.header, body: bytes.Clone(w.body.Bytes()), stored: rc.now()}
}
func storable(e entry) bool {
var cc []string
for d := range strings.SplitSeq(strings.ToLower(e.header.Get("Cache-Control")), ",") {
cc = append(cc, strings.TrimSpace(d))
}
return e.status == http.StatusOK && e.header.Get("Set-Cookie") == "" && e.header.Get("Vary") == "" &&
slices.Contains(cc, "public") && !slices.Contains(cc, "private") && !slices.Contains(cc, "no-store")
}
func matches(ifNoneMatch, etag string) bool {
for candidate := range strings.SplitSeq(ifNoneMatch, ",") {
if t := strings.TrimSpace(candidate); t == "*" || strings.TrimPrefix(t, "W/") == etag {
return true
}
}
return false
}
func (rc *ResponseCache) replay(c *gin.Context, e entry, state string) {
h := c.Writer.Header()
h.Set("X-Cache", state)
h.Set("Age", strconv.Itoa(int(rc.now().Sub(e.stored)/time.Second)))
if etag := e.header.Get("ETag"); etag != "" && matches(c.GetHeader("If-None-Match"), etag) {
h.Set("ETag", etag)
h.Set("Cache-Control", e.header.Get("Cache-Control"))
c.AbortWithStatus(http.StatusNotModified)
return
}
maps.Copy(h, e.header.Clone()) // copies: outer middleware may append to these slices
c.Status(e.status)
_, _ = c.Writer.Write(e.body)
c.Abort()
}
func (rc *ResponseCache) Middleware(c *gin.Context) {
route, key, ok := rc.key(c)
if !ok {
c.Header("X-Cache", "BYPASS")
c.Next()
return
}
if e, ok := rc.get(key); ok {
rc.replay(c, e, "HIT")
return
}
gen := rc.generation(route)
fill := func() (any, error) {
if e, ok := rc.get(key); ok {
return e, nil // a flight that ended a moment ago already stored it
}
e := rc.record(c)
if storable(e) {
rc.put(route, key, gen, e)
}
return e, nil
}
var v any
if rc.coalesce {
v, _, _ = rc.group.Do(key+" #"+strconv.FormatUint(gen, 10), fill)
} else {
v, _ = fill()
}
rc.replay(c, v.(entry), "MISS")
}
// articles is the origin handler with counters the demo can read.
type articles struct {
version atomic.Int64
calls atomic.Int64
gate chan struct{} // when set, the handler waits so misses overlap
entered chan struct{}
}
func (a *articles) list(c *gin.Context) {
a.calls.Add(1)
version := a.version.Load() // read the data first, as a query would
if a.gate != nil {
a.entered <- struct{}{}
<-a.gate
}
body := fmt.Sprintf(`{"page":%q,"sort":%q,"version":%d}`, c.DefaultQuery("page", "1"),
c.DefaultQuery("sort", "new"), version)
sum := sha256.Sum256([]byte(body))
c.Header("ETag", `"`+hex.EncodeToString(sum[:8])+`"`)
c.Header("Cache-Control", "public, max-age=60")
c.Data(http.StatusOK, "application/json", []byte(body))
}
func main() {
gin.SetMode(gin.TestMode)
clock := &Clock{now: time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)}
rc := &ResponseCache{now: clock.Now, ttl: time.Minute, coalesce: true,
allowed: map[string][]string{"/articles": {"page", "sort"}},
entries: map[string]entry{}, gen: map[string]uint64{}}
a := &articles{}
a.version.Store(1)
r := gin.New()
r.Use(rc.Middleware)
r.GET("/articles", a.list)
r.POST("/articles", func(c *gin.Context) {
a.version.Add(1) // the write commits first,
rc.Invalidate("/articles")
c.Status(http.StatusCreated) // then the cache forgets
})
do := func(method, target string, header ...string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, target, nil)
for i := 0; i+1 < len(header); i += 2 {
req.Header.Set(header[i], header[i+1])
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
show := func(label, method, target string, header ...string) *httptest.ResponseRecorder {
w := do(method, target, header...)
age := w.Header().Get("Age")
if age == "" {
age = "-"
}
fmt.Printf("%-13s %d %-6s age=%-2s handler calls=%d\n", label, w.Code, w.Header().Get("X-Cache"), age, a.calls.Load())
return w
}
first := show("first", "GET", "/articles?page=1&sort=new")
clock.Advance(10 * time.Second)
show("reordered", "GET", "/articles?sort=new&page=1")
show("bearer", "GET", "/articles?page=1&sort=new", "Authorization", "Bearer t-1")
show("cookie", "GET", "/articles?page=1&sort=new", "Cookie", "session=s-1")
show("utm param", "GET", "/articles?page=1&sort=new&utm_source=mail")
show("If-None-Match", "GET", "/articles?page=1&sort=new", "If-None-Match", first.Header().Get("ETag"))
fmt.Println("POST /articles", do("POST", "/articles").Code)
after := show("after write", "GET", "/articles?page=1&sort=new")
fmt.Println(" new body:", after.Body.String())
clock.Advance(time.Minute)
show("after TTL", "GET", "/articles?page=1&sort=new")
a.gate, a.entered = make(chan struct{}), make(chan struct{}, 1)
slow := make(chan string)
go func() { slow <- do("GET", "/articles?page=4").Body.String() }()
<-a.entered // this fill has read version 2 and is still running
do("POST", "/articles")
close(a.gate)
inflight := <-slow
a.gate = nil
next := do("GET", "/articles?page=4")
fmt.Println("write during a fill: in-flight", inflight)
fmt.Println(" next GET", next.Header().Get("X-Cache"), next.Body.String())
burst := func(target string, wait int) (calls int64, identical bool) {
a.gate, a.entered = make(chan struct{}), make(chan struct{}, 5)
before := a.calls.Load()
bodies := make([]string, 5)
var wg sync.WaitGroup
for i := range bodies {
wg.Go(func() { bodies[i] = do("GET", target).Body.String() })
}
for range wait {
<-a.entered // these handler calls are now in flight together
}
close(a.gate)
wg.Wait()
a.gate = nil
identical = true
for _, b := range bodies {
identical = identical && b == bodies[0]
}
return a.calls.Load() - before, identical
}
calls, same := burst("/articles?page=2", 1)
fmt.Printf("5 concurrent misses, singleflight: handler calls=%d identical bodies=%t\n", calls, same)
rc.coalesce = false
calls, same = burst("/articles?page=3", 5)
fmt.Printf("5 concurrent misses, no coalescing: handler calls=%d identical bodies=%t\n", calls, same)
}The first request misses and stores the response; ten seconds later the reordered query hits and Age reports 10. The bearer, cookie and utm requests bypass and each runs the handler. If-None-Match is answered 304 from the stored entry without a handler call. The POST bumps the version and invalidates /articles, so the next GET misses, and after the clock passes the 60 second TTL it misses again. In the write-during-a-fill step, the fill reads version 2 and waits; the POST invalidates the route meanwhile, so put discards the result and the next GET sees version 3 instead of a stale page for a minute. In the singleflight burst the gated leader is the only handler run: the other requests wait for it or hit the entry it stored. capture keeps its own header map, so headers that outer middleware set, such as a request ID, are never stored and replayed.
Coalescing misses inside Gin with singleflight
group.Do runs the fill function on the calling goroutine, so the leader runs its own c.Next and no other goroutine ever touches its *gin.Context, as the context-fallback lesson requires. Followers block until the leader finishes and replay the same immutable entry onto their own writers, then Abort so their chains do not run. The fill re-checks the cache first, because a request that missed just before the previous flight ended would otherwise start a second fill. The flight key includes the route's generation, so a request that arrives after an invalidation never joins a flight that started before it. The limits are real. Do has no context, so a follower keeps waiting after its own client has gone; DoChan could select on cancellation, but it runs the function on a new goroutine, where calling c.Next would break the one-owner rule. If the leader's client disconnects and the handler fails, every follower receives that failed response, which at least is not stored. singleflight re-panics in the leader and in every follower; record restores the real writer in a defer so an outer Recovery can still answer 500, and registering Recovery inside the cache turns a panic into an ordinary 500 that is never stored. Coalescing is per process, so ten replicas still make ten fills.
Invalidate after the commit, and guard fills in flight
A write handler commits and then invalidates the route templates whose responses it changed. Invalidating before the commit opens a window in which a read refills the entry with the old data. Even after the commit, a fill that read the old data before the write can finish afterwards and store it, which is the race the cache-aside lesson warns about. The per-route generation closes it: the fill captures the generation before running the handler, and put stores only if it is unchanged. Per-route invalidation is coarse but easy to verify; tagging entries by resource ID is finer and costs bookkeeping in every handler. This cache lives in one process, so other replicas keep their entries until the TTL ends unless you broadcast invalidations or move to a shared cache, which makes the TTL your honest bound on staleness. The model also lacks two things a real service adds: a cap on entry count and body size with eviction, and metrics for hit ratio and bypass reasons.
Stay consistent with ETags, Age and Cache-Control
The handler from the conditional-requests lesson derives its ETag from the response bytes, so a stored body and its validator always travel together. Before filling, the cache removes If-None-Match and If-Modified-Since from its copy of the request, so a leader that sent a validator cannot produce a bodiless 304 that would be stored or replayed to followers. On replay the cache compares If-None-Match with the stored ETag and answers 304 itself, carrying ETag and Cache-Control, without running the handler. The Age header tells downstream caches how old the copy already is, so public, max-age=60 still means sixty seconds in total rather than sixty more on top of the time it spent in your cache. Responses marked private or no-store are never stored. Test the X-Cache sequence for each rule above, use the fake clock instead of sleeping, hold the handler at a gate to make concurrent misses reproducible, race a write against a fill, and run the suite under go test -race.
TAKE THIS WITH YOU
Cache only public GETs whose every input is in the key: route template, path params and allow-listed query. Bypass identity, coalesce misses with singleflight on the request goroutine, and guard invalidation with a generation so in-flight fills cannot store stale data.
Check your understanding
A response-cache middleware keys entries by c.FullPath(), the path params and the allow-listed query. What should it do with a GET that carries an Authorization header?
Go to the source
Progress stays in this browser. No account needed.