Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you implement HTTP response caching in a Go service?
HTTP caching reduces load and improves response times. Go services implement caching at multiple levels: HTTP Cache-Control headers (browser/CDN caching), application-level caching (Redis/in-memory), and conditional requests (ETag/Last-Modified).
// HTTP Cache-Control headers func publicDataHandler(w http.ResponseWriter, r *http.Request) { // Cache in browser and CDN for 60s, stale for 10s w.Header().Set("Cache-Control", "public, max-age=60, stale-while-revalidate=10") w.Header().Set("Vary", "Accept-Encoding") // vary by encoding // ... serve data } func privateDataHandler(w http.ResponseWriter, r *http.Request) { // No CDN caching â only browser may cache, private to user w.Header().Set("Cache-Control", "private, max-age=30") // ... serve user-specific data } // ETag-based conditional caching func userHandler(w http.ResponseWriter, r *http.Request) { user, err := svc.GetUser(r.Context(), r.PathValue("id")) if err != nil { /* handle error */ return } // Compute ETag (hash of the content) data, _ := json.Marshal(user) etag := fmt.Sprintf(`"%x"`, md5.Sum(data)) w.Header().Set("ETag", etag) w.Header().Set("Cache-Control", "private, must-revalidate") // Check if client has current version if r.Header.Get("If-None-Match") == etag { w.WriteHeader(http.StatusNotModified) // 304: send no body return } w.Header().Set("Content-Type", "application/json") w.Write(data) } // In-memory LRU cache middleware func cacheMiddleware(cache *lru.Cache, ttl time.Duration) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { next.ServeHTTP(w, r); return } key := r.URL.RequestURI() if val, ok := cache.Get(key); ok { w.Header().Set("X-Cache", "HIT") w.Write(val.([]byte)); return } crw := &capturingResponseWriter{ResponseWriter: w} next.ServeHTTP(crw, r) cache.Add(key, crw.body) }) } }
More Related questions...