Prev Next

Golang / GoLang Production Patterns and Web Standards Interview Questions

How do you implement timeouts for non-HTTP operations like database queries and external calls?

Context-based timeouts apply to any blocking operation — database queries, cache lookups, file operations, and external gRPC calls. The pattern is identical: create a child context with a deadline and pass it to every blocking call.

// Database query with timeout
func getUserFromDB(ctx context.Context, db *sql.DB, id int) (*User, error) {
    // Add query-level timeout (in addition to any HTTP request timeout)
    ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
    defer cancel()

    row := db.QueryRowContext(ctx,
        "SELECT id, name, email FROM users WHERE id = $1", id)

    var u User
    if err := row.Scan(&u.ID, &u.Name, &u.Email); err != nil {
        if errors.Is(err, context.DeadlineExceeded) {
            return nil, fmt.Errorf("DB query timed out after 2s: %w", err)
        }
        return nil, fmt.Errorf("getUserFromDB: %w", err)
    }
    return &u, nil
}

// Multiple operations with individual timeouts
func getUserProfile(ctx context.Context, userID int) (*Profile, error) {
    // DB: 2s timeout
    dbCtx, dbCancel := context.WithTimeout(ctx, 2*time.Second)
    defer dbCancel()
    user, err := getUserFromDB(dbCtx, db, userID)
    if err != nil { return nil, err }

    // Cache: 500ms timeout
    cacheCtx, cacheCancel := context.WithTimeout(ctx, 500*time.Millisecond)
    defer cacheCancel()
    prefs, _ := getPrefsFromCache(cacheCtx, userID) // non-fatal if cache misses

    // External API: 3s timeout
    apiCtx, apiCancel := context.WithTimeout(ctx, 3*time.Second)
    defer apiCancel()
    avatar, err := fetchAvatarFromCDN(apiCtx, user.AvatarURL)
    if err != nil {
        log.Printf("avatar fetch failed (non-fatal): %v", err)
    }

    return buildProfile(user, prefs, avatar), nil
}
What is the effective deadline when you create a 5-second timeout on a child context whose parent already has a 3-second deadline?
When errors.Is(err, context.DeadlineExceeded) returns true in a database query, what does it indicate?

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