Prev Next

Golang / GoLang Production Patterns and Web Standards Interview Questions

How do you correctly propagate errors from concurrent goroutines in a Go service?

When multiple goroutines run in parallel, errors must be collected and propagated without data races or goroutine leaks. The idiomatic tools are errgroup for structured concurrency and buffered channels for ad-hoc patterns.

import "golang.org/x/sync/errgroup"

// Pattern 1: errgroup — run N tasks, fail fast on first error
func fetchUserProfile(ctx context.Context, userID int) (*Profile, error) {
    g, ctx := errgroup.WithContext(ctx)
    // gctx cancelled when any goroutine fails or g.Wait() returns

    var user *User
    g.Go(func() error {
        var err error
        user, err = userRepo.FindByID(ctx, userID)
        return fmt.Errorf("fetching user: %w", err)
    })

    var orders []Order
    g.Go(func() error {
        var err error
        orders, err = orderRepo.ListByUser(ctx, userID)
        return fmt.Errorf("fetching orders: %w", err)
    })

    if err := g.Wait(); err != nil {
        return nil, err // first error from any goroutine
    }
    return buildProfile(user, orders), nil
}

// Pattern 2: collect ALL errors (don't fail fast)
func validateItems(ctx context.Context, items []Item) error {
    errs := make([]error, len(items))
    var wg sync.WaitGroup
    wg.Add(len(items))

    for i, item := range items {
        go func(idx int, it Item) {
            defer wg.Done()
            errs[idx] = validateItem(ctx, it) // each goroutine writes its own slot
        }(i, item)
    }
    wg.Wait()

    // Filter nil errors and join
    var nonNil []error
    for _, e := range errs { if e != nil { nonNil = append(nonNil, e) } }
    return errors.Join(nonNil...)
}

// errgroup with concurrency limit (Go 1.20+)
g.SetLimit(10)  // max 10 goroutines running at once
for _, item := range items {
    item := item
    g.Go(func() error { return process(ctx, item) })
}
What does errgroup.WithContext(ctx) return in addition to the group?
In the validateItems pattern, why is it safe to write 'errs[idx] = err' from multiple goroutines without a mutex?

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