Prev Next

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)
        })
    }
}
What HTTP status code should be returned when an If-None-Match request matches the current ETag?
What does 'Cache-Control: stale-while-revalidate=10' tell a CDN?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.

Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

Why does Go treat errors as values instead of using exceptions, and what are the advantages? How do you wrap errors in Go 1.13+ and use errors.Is and errors.As for inspection? What are the best practices for defining custom error types in Go? What is context.Context in Go, what does it carry, and how do you create one? How does context propagate through an HTTP request lifecycle in Go? What are the best practices and anti-patterns for using context.WithValue? How do you build a production-ready HTTP server using Go's standard net/http package? What is the standard Go HTTP middleware signature and how do you chain multiple middleware? How has http.ServeMux evolved in Go 1.22 and what routing patterns does it support? How do you encode and decode JSON in Go and what are the common pitfalls? What are the rules for writing HTTP responses correctly in Go handlers? How do you implement dependency injection in Go without a framework? How do you implement structured logging in Go using the slog package? What are the idiomatic Go patterns for managing application configuration? How do you interact with a SQL database in Go using the standard database/sql package? How do you implement graceful shutdown of an HTTP server in Go? How do you test HTTP handlers in Go without starting a real server? What are table-driven tests in Go and why are they the preferred testing pattern? How do you write testable Go code using interfaces and mocks without a framework? How do you implement rate limiting in a Go HTTP server? How do you implement CORS correctly in a Go HTTP server? How and when should you use panic and recover in production Go code? How do you manage environment-specific settings and feature flags in Go? How do you implement health check and readiness endpoints for a Go service? How do you add observability (metrics and distributed tracing) to a Go service? How do build tags work in Go and when do you use them? What are the best practices for using Go's HTTP client in production? What patterns make HTTP error handling consistent and DRY in Go? What are the common API versioning strategies in Go HTTP services? How do Go programs handle OS signals and interact with the operating system? How do you profile a Go service in production using pprof? How does Go's module system work and what are the key commands? How do you validate HTTP request inputs in Go without a framework? How do you implement streaming HTTP responses in Go? How do you write and interpret Go benchmarks? How do you embed static files into a Go binary using go:embed? How do you implement timeouts for non-HTTP operations like database queries and external calls? What are the conventions for returning structured error responses from a Go REST API? How do you implement pagination for list endpoints in a Go REST API? How do you implement JWT authentication middleware in Go? How do you implement HTTP response caching in a Go service? How does gRPC work in Go and when would you choose it over REST/JSON? What linters and static analysis tools are essential for production Go code quality? What is the recommended project structure for a production Go service? How do you implement load shedding and request queue limits in a Go HTTP server? How do you correctly propagate errors from concurrent goroutines in a Go service? How do you document a Go REST API and maintain an OpenAPI specification? What is the production readiness checklist for a Go HTTP service?
Show more question and Answers...

GoLang System Architecture and Testing Interview Questions

Comments & Discussions