My account

Interview questions

1Two shipping options from one cartMedium–Go language basics

Question: The checkout page shows the cart with two shipping options, so the user can compare the totals. The cart lines come from the database. A colleague wrote this helper:

type Line struct {
	Name  string
	Price int
}

// withShipping returns the cart with each shipping option.
func withShipping(cart []Line) (express, normal []Line) {
	express = append(cart, Line{"Express shipping", 15})
	normal = append(cart, Line{"Normal shipping", 5})
	return express, normal
}

The unit test passes. It uses a cart written as a slice literal with two lines. You see this in code review. What do you think? Is there a problem?

Short answer: Yes. Both append calls can write into the same backing array. If the cart slice has spare capacity (cap is bigger than len), the first append writes “Express” into the free slot, and the second append writes “Normal” into the same slot. Then express and normal show the same last line. The test passes only because a slice literal has no spare capacity. The fix: copy the cart into a new slice for each option, for example with slices.Clone, or use a full slice expression cart[:len(cart):len(cart)].

Hint (if the candidate says there is no problem): In production, a cart with 3 items shows “Normal shipping” in both options. The cart is built in a loop with append while reading rows from the database.

Why does this happen? (step by step)

  1. A slice is a small header: a pointer to an array, a length and a capacity.
  2. The cart is built with append in a loop. After 3 items, Go has grown the array to capacity 4, so there is one free slot.
  3. The first append sees free space. It writes “Express” into slot 3 of the shared array and returns a new header with length 4.
  4. The second append also starts from the cart header (length 3). It sees the same free slot and writes “Normal” into slot 3.
  5. Both express and normal point to the same array. Slot 3 now holds “Normal” for both.
  6. With a slice literal of 2 items, capacity is 2. Each append must make a new array, so the bug does not show in the test.

The fix:

func withShipping(cart []Line) (express, normal []Line) {
	express = append(slices.Clone(cart),
		Line{"Express shipping", 15})
	normal = append(slices.Clone(cart),
		Line{"Normal shipping", 5})
	return express, normal
}
  1. The slices.Clone function makes a new array for each result, so the two results never share memory.
  2. Another way: a full slice expression, cart[:len(cart):len(cart)], sets the capacity equal to the length. Then append must copy. It is shorter, but harder to read.
  3. Add a test with a cart that has spare capacity, for example made with make and a capacity of 10.

Follow-up question: A function gets a big slice of orders and returns only the paid ones, using orders[:0] as the start and appending to it. Is that safe?

Follow-up answer:

  • This “filter in place” trick reuses the same backing array. It is fast and does not allocate.
  • But it overwrites the caller’s slice. If the caller still uses the original orders after the call, it sees changed data.
  • It is fine only when the function owns the slice, or the documentation clearly says the input is changed. Otherwise make a new slice, for example with make and capacity len(orders), or use slices.DeleteFunc on a copy.

Red flag: Says “append always makes a copy”, or “slices are passed by reference” without being able to explain the header and the shared array.

Report a problem or send a better text

Edit on GitHub

2Order not found, or server error?Easy–Errors in Go

Question: The order service has a repository and an HTTP handler. Here is the important part:

func (r *Repo) Order(ctx context.Context, id int64) (Order, error) {
	var o Order
	err := r.db.QueryRowContext(ctx,
		"SELECT id, total FROM orders WHERE id = $1", id,
	).Scan(&o.ID, &o.Total)
	if err != nil {
		return o, fmt.Errorf("load order %d: %w", id, err)
	}
	return o, nil
}

func (h *Handler) GetOrder(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
	o, err := h.repo.Order(r.Context(), id)
	if err == sql.ErrNoRows {
		http.Error(w, "order not found", http.StatusNotFound)
		return
	}
	if err != nil {
		http.Error(w, "server error", http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(o)
}

You see this in code review. What do you think? Is there a problem?

Short answer: Yes. The repository wraps the error with %w, so the handler gets a new error value that only contains sql.ErrNoRows. The check with == compares the outer value, so it is never true. A missing order returns 500 instead of 404. Use errors.Is, which walks the whole chain of wrapped errors. The ignored error from ParseInt is a second problem: a bad id quietly becomes 0.

Hint (if the candidate says there is no problem): Monitoring shows many 500 errors on this endpoint, and the logs say “load order 42: sql: no rows in result set”. The mobile app shows “server error” for deleted orders.

Why does this happen? (step by step)

  1. The Scan method returns sql.ErrNoRows when the query finds no row.
  2. The fmt.Errorf function with %w builds a new error. Its text is “load order 42: sql: no rows…”, and it keeps the original error inside.
  3. The == operator compares two interface values. The new error is a different value, so the result is false.
  4. The handler falls into the “err != nil” branch and returns 500.
  5. The errors.Is function calls Unwrap again and again and compares each error in the chain. It finds sql.ErrNoRows and returns true.

The fix:

id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
	http.Error(w, "bad order id", http.StatusBadRequest)
	return
}
o, err := h.repo.Order(r.Context(), id)
switch {
case errors.Is(err, sql.ErrNoRows):
	http.Error(w, "order not found", http.StatusNotFound)
	return
case err != nil:
	log.Printf("get order: %v", err)
	http.Error(w, "server error", http.StatusInternalServerError)
	return
}
  1. Use errors.Is for sentinel errors and errors.As for error types. Never compare the text of an error.
  2. Better design: the repository returns its own error, for example ErrOrderNotFound. Then the handler does not depend on the database/sql package.
  3. Check every error. Here the ParseInt error must become a 400 response.

Follow-up question: When should you wrap with %w, and when with %v?

Follow-up answer:

  • With %w, the inner error becomes part of your API. Callers can check it with errors.Is or errors.As.
  • With %v, only the text is kept. Callers cannot depend on the inner error.
  • Use %w when callers really need to react to the cause. Use %v (or your own error) at a boundary when you do not want to leak details, for example the database driver’s errors to the HTTP layer.

Red flag: Compares err.Error with a string, or uses strings.Contains on the error message.

Report a problem or send a better text

Edit on GitHub

3Importing a year of supplier price filesMedium–Go language basicsErrors in Go

Question: Every day each supplier uploads a CSV file with new prices. A nightly job imports all files of the last year. There are about 40 suppliers, so the job reads around 14,000 files. The code:

func importAll(paths []string, db *Store) error {
	for _, p := range paths {
		f, err := os.Open(p)
		if err != nil {
			return err
		}
		defer f.Close()

		prices, err := parseCSV(f)
		if err != nil {
			return err
		}
		if err := db.SavePrices(prices); err != nil {
			return err
		}
	}
	return nil
}

You see this in code review. What do you think? Is there a problem?

Short answer: Yes. A deferred call runs when the function returns, not at the end of each loop turn. So all 14,000 files stay open until importAll ends. The process hits the limit of open files (often 1024 by default on Linux) and Open fails with “too many open files”. Move the body of the loop into its own function, so defer runs after each file. Also, the returned errors do not say which file failed.

Hint (if the candidate says there is no problem): The job works on a test folder with 50 files. In production it fails after about a thousand files with “open …: too many open files”.

Why does this happen? (step by step)

  1. The defer statement pushes f.Close onto a list for the current function call.
  2. The list runs only when importAll returns.
  3. Each loop turn opens one more file and adds one more Close to the list. Nothing is closed yet.
  4. Every open file uses one file descriptor. The operating system gives each process a limit.
  5. When the limit is reached, os.Open returns an error, and the whole import stops.

The fix:

func importAll(paths []string, db *Store) error {
	for _, p := range paths {
		if err := importFile(p, db); err != nil {
			return fmt.Errorf("import %s: %w", p, err)
		}
	}
	return nil
}

func importFile(path string, db *Store) error {
	f, err := os.Open(path)
	if err != nil {
		return err
	}
	defer f.Close() // runs when importFile returns

	prices, err := parseCSV(f)
	if err != nil {
		return err
	}
	return db.SavePrices(prices)
}
  1. Now defer belongs to importFile. Each file is closed before the next one is opened.
  2. The error is wrapped with the file name, so the log shows which file is broken.
  3. A closure inside the loop works too, but a named function is easier to read and test.
  4. Ignoring the error of Close is fine here, because the file is only read. When you write a file, check the error of Close (or call Sync), because a failed write can show up only there.

Follow-up question: One broken file from one supplier stops the whole import. Product managers want the other files to be imported anyway. How do you change it?

Follow-up answer:

  • Keep going after an error: collect the errors in a slice and continue the loop.
  • At the end, return errors.Join of the collected errors, or a summary with the failed file names. Log each failure with the file name.
  • Make the import of one file atomic (one transaction per file), so a half-imported file never stays in the database.
  • If files can be imported again, make it idempotent, for example by remembering the imported file names.

Red flag: Suggests raising the open file limit (ulimit) as the fix, without seeing that the files are never closed during the loop.

Report a problem or send a better text

Edit on GitHub

4Every order is rejected as invalidMedium to hard–Errors in GoGo language basics

Question: The order service checks a new order before it saves it. A colleague added a custom error type, so the client can see all wrong fields at once:

type ValidationError struct {
	Fields []string
}

func (e *ValidationError) Error() string {
	return "invalid fields: " + strings.Join(e.Fields, ", ")
}

func validate(o Order) error {
	var fields []string
	if o.Email == "" {
		fields = append(fields, "email")
	}
	if len(o.Items) == 0 {
		fields = append(fields, "items")
	}
	var verr *ValidationError
	if len(fields) > 0 {
		verr = &ValidationError{Fields: fields}
	}
	return verr
}

// In the handler:
if err := validate(order); err != nil {
	http.Error(w, err.Error(), http.StatusBadRequest)
	return
}

You see this in code review. What do you think? Is there a problem?

Short answer: Yes. This is the typed nil trap. validate returns verr, a *ValidationError pointer that is nil. But the return type is the error interface. An interface value holds two things: a type and a value. Here the type is *ValidationError and the value is nil, so the interface itself is not nil. Every order, even a valid one, goes into the error branch. Then err.Error runs on a nil pointer and the handler panics. The fix: return a plain nil when there is no error.

Hint (if the candidate says there is no problem): After the deploy, every order fails. The logs show “runtime error: invalid memory address or nil pointer dereference” inside the Error method.

Why does this happen? (step by step)

  1. An interface value is a pair: (type, value). It is nil only when both parts are empty.
  2. For a valid order, verr stays a nil *ValidationError.
  3. On “return verr”, Go converts the pointer to the error interface. The pair becomes (*ValidationError, nil).
  4. The check “err != nil” asks: is the pair empty? No, the type part is set. So the result is true.
  5. The handler calls err.Error. Go calls the method on the nil pointer. The method reads e.Fields, which needs a real struct, so the program panics.

The fix:

func validate(o Order) error {
	var fields []string
	if o.Email == "" {
		fields = append(fields, "email")
	}
	if len(o.Items) == 0 {
		fields = append(fields, "items")
	}
	if len(fields) == 0 {
		return nil // a real nil interface
	}
	return &ValidationError{Fields: fields}
}
  1. Return the literal nil for “no error”. Never return a typed pointer variable through an error interface.
  2. Functions should use error as the return type, not a concrete pointer type like *ValidationError. Callers can still get the details with errors.As.
  3. A unit test for a valid order would have caught this bug before the deploy.

Follow-up question: The handler wants to send the list of wrong fields as JSON with status 422. How does it get the fields from err?

Follow-up answer:

var verr *ValidationError
if errors.As(err, &verr) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusUnprocessableEntity)
	json.NewEncoder(w).Encode(verr.Fields)
	return
}
  • The errors.As function walks the chain of wrapped errors and finds the first one with this type.
  • It works even if a lower layer wrapped the error with fmt.Errorf and %w.
  • A type assertion (err.(*ValidationError)) would fail on a wrapped error.

Red flag: Cannot explain why a nil pointer is not equal to nil when it is stored in an interface, or “fixes” it by checking reflect.ValueOf(err).IsNil.

Report a problem or send a better text

Edit on GitHub

5Some receipts are never sentMedium–Goroutines and channels

Question: A nightly job sends a receipt email for every order of the day. It runs as a small program in a Kubernetes CronJob and exits when it is done. There are about 300 orders on a normal day. The code (Go 1.24):

func notifyAll(orders []Order, mail Mailer) {
	var wg sync.WaitGroup
	for _, o := range orders {
		go func() {
			wg.Add(1)
			defer wg.Done()
			mail.SendReceipt(o)
		}()
	}
	wg.Wait()
	log.Printf("sent %d receipts", len(orders))
}

func main() {
	orders := loadTodayOrders()
	notifyAll(orders, newMailer())
}

You see this in code review. What do you think? Is there a problem?

Short answer: Yes. wg.Add(1) runs inside the new goroutine. The loop only starts goroutines; it does not wait for them to run. So wg.Wait can run while the counter is still 0 (or small), return at once, and main exits. Goroutines that did not call Add yet are killed, and their receipts are never sent. Call wg.Add before the go statement, or use the WaitGroup.Go method (Go 1.25 and later). Also, errors from SendReceipt are lost.

Hint (if the candidate says there is no problem): Customers complain that they did not get a receipt. The log always says “sent 300 receipts”, but the mail provider shows fewer emails. It happens more on a busy machine.

Why does this happen? (step by step)

  1. The go statement creates a goroutine and returns at once. The new goroutine runs later, when the scheduler picks it.
  2. The loop can finish before many goroutines have started. Their Add has not run yet.
  3. wg.Wait checks the counter. If it is 0, it returns immediately.
  4. main returns, and the program exits. Go does not wait for other goroutines when main ends.
  5. The log line is also wrong: it prints the number of orders, not the number of sent emails.
  6. Note: since Go 1.22 each loop turn has its own variable o, so capturing o in the closure is safe now. In older Go versions it was a second bug.

The fix:

func notifyAll(orders []Order, mail Mailer) error {
	var (
		wg   sync.WaitGroup
		mu   sync.Mutex
		errs []error
	)
	for _, o := range orders {
		wg.Add(1) // before the goroutine starts
		go func() {
			defer wg.Done()
			if err := mail.SendReceipt(o); err != nil {
				mu.Lock()
				errs = append(errs, err)
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	return errors.Join(errs...)
}
  1. Add runs in the loop, before the goroutine exists. When the loop ends, the counter is exactly the number of goroutines.
  2. With Go 1.25, the wg.Go method does Add and Done for you, so this mistake cannot happen.
  3. Errors are collected with a mutex and returned. main can exit with a non-zero code so the CronJob shows a failure.
  4. Since Go 1.25, go vet has a waitgroup check that reports a wg.Add call inside the new goroutine. Run go vet in CI.

Follow-up question: On Black Friday there are 50,000 orders, and the mail provider allows only 20 connections at the same time. What do you change?

Follow-up answer:

  • Do not start one goroutine per order without a limit. Limit how many run at once.
  • Simple way: the errgroup package (golang.org/x/sync/errgroup) with SetLimit(20). The Go method then blocks when 20 goroutines are already running. Use errgroup.WithContext if one failure should cancel the rest.
  • Another way: a channel of size 20 as a semaphore, or a fixed pool of 20 worker goroutines that read orders from a channel.
  • Make sending idempotent (remember which receipts were sent), so a rerun of the job does not send a receipt twice.

Red flag: Adds time.Sleep before wg.Wait “so all goroutines can start”, or says the race detector will always catch this.

Report a problem or send a better text

Edit on GitHub

6A small cache for product pricesMedium–Goroutines and channelsHTTP services in Go

Question: The product service reads prices from a slow pricing service. To make the product page faster, a colleague added a small cache. The service gets about 2,000 requests per second at peak. The code:

type PriceHandler struct {
	pricing PricingClient
	cache   map[string]int // product id -> price in cents
}

func (h *PriceHandler) ServeHTTP(w http.ResponseWriter,
	r *http.Request) {
	id := r.PathValue("id")
	price, ok := h.cache[id]
	if !ok {
		var err error
		price, err = h.pricing.Price(r.Context(), id)
		if err != nil {
			http.Error(w, "pricing failed", http.StatusBadGateway)
			return
		}
		h.cache[id] = price
	}
	fmt.Fprintf(w, `{"id":%q,"price":%d}`, id, price)
}

It works well in local tests. You see this in code review. What do you think? Is there a problem?

Short answer: Yes. The net/http server runs every request in its own goroutine, so many goroutines read and write the same map at the same time. A Go map is not safe for concurrent use. The runtime often detects this and stops the whole process with “fatal error: concurrent map writes”. This is not a panic, so recover cannot catch it. Protect the map with a sync.RWMutex (or use sync.Map). Also, the cache never expires, so prices can be wrong forever, and the map grows without a limit.

Hint (if the candidate says there is no problem): Under load, the pods restart a few times per hour. The last log lines show “fatal error: concurrent map read and map write”. Running the load test with the race flag prints “WARNING: DATA RACE”.

Why does this happen? (step by step)

  1. The HTTP server starts a new goroutine for each connection. All of them call ServeHTTP on the same handler value.
  2. So all goroutines share the same cache map.
  3. A map write can move entries inside the map (for example when it grows). A read at the same moment can see broken internal state.
  4. The Go runtime has a cheap check for this. When it sees a concurrent write, it stops the program with a fatal error. A fatal error cannot be recovered, so the pod crashes and every in-flight request fails.
  5. Local tests send one request at a time, so the race never happens there.

The fix:

type PriceHandler struct {
	pricing PricingClient
	mu      sync.RWMutex
	cache   map[string]int
}

func (h *PriceHandler) cached(id string) (int, bool) {
	h.mu.RLock()
	defer h.mu.RUnlock()
	p, ok := h.cache[id]
	return p, ok
}

func (h *PriceHandler) store(id string, price int) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.cache[id] = price
}
  1. Many readers can hold RLock at the same time. A writer waits for Lock and blocks everybody else for a very short time.
  2. Do not hold the lock while calling the slow pricing service. Lock only around the map access.
  3. The sync.Map type is another choice. It is good when keys are written once and read many times, like this cache. For most code, a map with a mutex is simpler and clearer.
  4. Run tests and a load test with the race flag (go test -race) in CI.
  5. Add a time to live (for example 1 minute) and a size limit, or use a tested cache library.

Follow-up question: A new campaign product gets 5,000 requests in the first second. The cache is empty for it, so all of them call the pricing service at once and it falls over. How do you prevent this?

Follow-up answer:

  • This is a cache stampede. Many requests miss the cache at the same moment.
  • Use the singleflight package (golang.org/x/sync/singleflight). Requests for the same key share one call to the pricing service, and all of them get the same result.
  • Optional: refresh hot keys a little before they expire, and add a small random jitter to expiry times.
  • Also set a timeout on the call to the pricing service, so slow calls do not pile up.

Red flag: Says “maps are safe because each request writes a different key”, or wraps the handler in recover to stop the crash.

Report a problem or send a better text

Edit on GitHub

7Selling more items than we haveMedium to hard–Goroutines and channelsGo language basics

Question: The stock service reserves items when a user starts checkout. One shared Stock value is used by all HTTP handlers. A colleague added a mutex to make it safe:

var ErrOutOfStock = errors.New("out of stock")

type Stock struct {
	mu    sync.Mutex
	items map[string]int // sku -> count
}

func (s Stock) Reserve(sku string, n int) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.items[sku] < n {
		return ErrOutOfStock
	}
	s.items[sku] -= n
	return nil
}

Unit tests pass. You see this in code review. What do you think? Is there a problem?

Short answer: Yes. Reserve has a value receiver (s Stock, not s *Stock). Every call gets a copy of the struct, and that copy includes its own mutex. So each call locks a different mutex, and the lock protects nothing. The map is not copied (a map value points to the same data), so all calls still change the same shared map at the same time. Result: overselling, and sometimes “fatal error: concurrent map writes”. Use a pointer receiver. The go vet tool reports this: “Reserve passes lock by value”.

Hint (if the candidate says there is no problem): During a flash sale with 10 items in stock, 13 orders were accepted. Once the service crashed with a “concurrent map writes” fatal error.

Why does this happen? (step by step)

  1. A method with a value receiver works on a copy of the value, like a normal function parameter.
  2. A sync.Mutex is a small struct with state. Copying it makes a second, independent mutex.
  3. Two goroutines call Reserve at the same moment. Each one locks its own copy, so neither waits.
  4. A map value is a small pointer to the real map data. The copy of the struct still points to the same map.
  5. Both goroutines read “1 left”, both pass the check, and both subtract. The count goes below zero, and the concurrent writes can crash the process.
  6. Unit tests call Reserve from one goroutine, so they never see the problem.

The fix:

func (s *Stock) Reserve(sku string, n int) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.items[sku] < n {
		return ErrOutOfStock
	}
	s.items[sku] -= n
	return nil
}
  1. With a pointer receiver, all calls use the same struct and the same mutex.
  2. Rule: if a type has a mutex (or any field that must not be copied), use pointer receivers for all its methods, and pass it as a pointer.
  3. Run go vet in CI. Its copylocks check finds a mutex copied by a value receiver, by assignment, or in a range loop.
  4. Add a test that calls Reserve from many goroutines and run it with the race flag.

Follow-up question: The shop now runs 6 replicas of the stock service. Is the mutex still enough?

Follow-up answer:

  • No. A mutex only protects memory inside one process. Six processes have six separate maps and six mutexes.
  • The real stock must live in one shared place, usually the database.
  • Make the check and the change one atomic step there, for example one conditional update: “set count = count minus n where sku matches and count is at least n”, and check that one row changed.
  • Other options: a row lock in a transaction (SELECT … FOR UPDATE), or optimistic locking with a version column. A distributed lock is rarely needed for this.

Red flag: Says “the mutex makes it safe” without noticing the value receiver, or thinks the map is copied too.

Report a problem or send a better text

Edit on GitHub

8A timeout for the shipping priceMedium to hard–Goroutines and channelsThe context package

Question: The checkout page asks an external carrier API for the shipping price. The carrier is sometimes very slow, so a colleague added a 2-second timeout. The checkout service handles about 300 requests per second. The code:

var ErrTimeout = errors.New("shipping quote timeout")

func (s *Service) ShippingQuote(o Order) (Quote, error) {
	ch := make(chan Quote)
	go func() {
		ch <- s.carrier.Quote(o) // slow HTTP call
	}()
	select {
	case q := <-ch:
		return q, nil
	case <-time.After(2 * time.Second):
		return Quote{}, ErrTimeout
	}
}

You see this in code review. What do you think? Is there a problem?

Short answer: Yes. This is a goroutine leak. The channel is unbuffered, so a send waits until someone receives. After a timeout, ShippingQuote has returned and nobody will ever receive from ch. The goroutine blocks on the send forever, with its order and its memory. When the carrier is slow, hundreds of goroutines pile up every second, and memory keeps growing. Also, the slow HTTP call itself is never cancelled. The fix: pass a context with a timeout down to the carrier call, and if you keep a goroutine, give the channel a buffer of 1.

Hint (if the candidate says there is no problem): On days when the carrier is slow, the memory of the checkout pods grows for hours until Kubernetes kills them (OOMKilled). The goroutine count in the metrics goes from 2,000 to 400,000.

Why does this happen? (step by step)

  1. An unbuffered send and a receive must meet. The sender waits until a receiver is ready.
  2. The carrier answers after 5 seconds. At 2 seconds the timeout case wins, and ShippingQuote returns ErrTimeout.
  3. At 5 seconds the goroutine tries to send. There is no receiver anymore, so it waits forever.
  4. Go never kills or collects a blocked goroutine. Its stack and everything it points to stay in memory.
  5. With 300 requests per second and many timeouts, the number of stuck goroutines grows without end.
  6. The HTTP call to the carrier also keeps running after the timeout, so we still use connections for answers nobody wants.

The fix:

func (s *Service) ShippingQuote(ctx context.Context,
	o Order) (Quote, error) {
	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
	defer cancel()

	q, err := s.carrier.Quote(ctx, o) // uses the ctx
	if errors.Is(err, context.DeadlineExceeded) {
		return Quote{}, ErrTimeout
	}
	return q, err
}
  1. The context goes into the carrier client, and from there into the HTTP request (http.NewRequestWithContext). When the deadline passes, the request is cancelled and Quote returns at once.
  2. No extra goroutine and no channel are needed. Simple code is easier to make correct.
  3. The context also comes from the HTTP handler (the request’s context), so if the user closes the page, the call stops too.
  4. If you must keep a goroutine (for example the library has no context support), make the channel buffered with size 1. Then the late send succeeds and the goroutine can end.
  5. The goroutine profile of pprof (and a goroutine count metric) shows leaks like this in production.

Follow-up question: How would you write a test that proves this function does not leak goroutines?

Follow-up answer:

  • Use a fake carrier that blocks until its context is cancelled.
  • Call ShippingQuote with a short timeout, then check that the fake saw the cancellation and that the call returned ErrTimeout.
  • The goleak library (go.uber.org/goleak) can check at the end of a test that no extra goroutines are still running.
  • With Go 1.25, the testing/synctest package runs the test in a bubble with a fake clock, so a 2-second timeout runs instantly and is deterministic.

Red flag: Says “the garbage collector will clean up the goroutine”, or only makes the timeout longer.

Report a problem or send a better text

Edit on GitHub

9The slow sales reportMedium–The context packageHTTP services in Go

Question: The admin panel has a sales report. It runs a heavy SQL query that takes 20 to 40 seconds on a big date range. About 30 staff members use it in the morning. The handler:

func (h *Admin) SalesReport(w http.ResponseWriter,
	r *http.Request) {
	from := r.URL.Query().Get("from")
	to := r.URL.Query().Get("to")

	ctx := context.Background()
	rows, err := h.db.QueryContext(ctx, salesSQL, from, to)
	if err != nil {
		http.Error(w, "report failed", http.StatusInternalServerError)
		return
	}
	defer rows.Close()
	writeCSV(w, rows)
}

You see this in code review. What do you think? Is there a problem?

Short answer: Yes. The handler uses context.Background instead of the request’s context (r.Context). When the user closes the tab, presses refresh, or the proxy times out, the server cancels the request context, but this query does not listen to it. The query keeps running in the database for 40 seconds for nobody. Impatient users press refresh, so every click adds one more heavy query, and the database slows down for the whole shop. Pass r.Context into the query, and add a timeout.

Hint (if the candidate says there is no problem): Every morning between 9 and 10 the database CPU is at 100% and checkout gets slow. The database shows 60 copies of the sales query running, but only about 10 people have the report open.

Why does this happen? (step by step)

  1. The net/http server makes a context for each request. It is cancelled when the client connection closes or the handler returns.
  2. context.Background is an empty root context. It is never cancelled and has no deadline.
  3. The database driver watches the context given to QueryContext. With Background, it never gets a signal to stop.
  4. A user waits 15 seconds, then presses refresh. The first request’s connection closes, but its query keeps running. A second query starts.
  5. Each running query also holds one connection from the database/sql pool. When the pool is full, other handlers wait for a connection too.

The fix:

func (h *Admin) SalesReport(w http.ResponseWriter,
	r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(),
		60*time.Second)
	defer cancel()

	from := r.URL.Query().Get("from")
	to := r.URL.Query().Get("to")
	rows, err := h.db.QueryContext(ctx, salesSQL, from, to)
	if err != nil {
		http.Error(w, "report failed", http.StatusInternalServerError)
		return
	}
	defer rows.Close()
	writeCSV(w, rows)
}
  1. Now the query stops when the user leaves or after 60 seconds, whichever comes first. The driver asks the database to cancel the query (how exactly depends on the driver).
  2. Rule: every function that does I/O takes a ctx as its first parameter and passes it on. A handler starts from r.Context, never from context.Background.
  3. Also validate from and to (dates, maximum range) before running a heavy query.
  4. Linters like contextcheck can find functions that drop the incoming context.

Follow-up question: Even with cancellation, the report is too slow, and staff want it every morning. How would you change the design?

Follow-up answer:

  • Do not compute a heavy report on every click. Precompute it: a nightly job writes daily sales totals into a summary table, and the report reads the small table.
  • Or make it asynchronous: the request starts a background job and returns a job id (202 Accepted). The user downloads the file when it is ready.
  • Run heavy reports on a read replica, not on the primary database that serves checkout.
  • Add an index that matches the date filter, and check the query plan.

Red flag: Suggests only a bigger database or a longer timeout, or says context is “only for passing values”.

Report a problem or send a better text

Edit on GitHub

10Calling the payment providerMedium–HTTP services in GoThe context package

Question: The checkout service charges the customer’s card through an external payment provider. It handles about 50 payments per second. The client code:

type ChargeResult struct {
	ID     string `json:"id"`
	Status string `json:"status"`
}

func (p *Payments) Charge(ctx context.Context,
	c Charge) (ChargeResult, error) {
	var out ChargeResult
	body, _ := json.Marshal(c)
	resp, err := http.Post(p.baseURL+"/charges",
		"application/json", bytes.NewReader(body))
	if err != nil {
		return out, err
	}
	if resp.StatusCode != http.StatusOK {
		return out, fmt.Errorf("charge: %s", resp.Status)
	}
	defer resp.Body.Close()
	err = json.NewDecoder(resp.Body).Decode(&out)
	return out, err
}

You see this in code review. What do you think? Is there a problem?

Short answer: Yes, several:

  1. http.Post uses http.DefaultClient, which has no timeout. If the provider hangs, the request can hang for a very long time, holding the user’s checkout and a goroutine.
  2. The ctx parameter is ignored, so a cancelled checkout does not stop the call.
  3. On a non-200 response the function returns before closing resp.Body. The connection is never returned to the pool. Over time this leaks connections and file descriptors.
  4. The error from json.Marshal is ignored.

The fix: build the request with http.NewRequestWithContext, use one shared http.Client with a Timeout, and close the body right after the error check, on every path.

Hint (if the candidate says there is no problem): When the provider had an incident and returned many 503 errors, the checkout pods ran out of file descriptors (“too many open files”). Another day the provider was very slow, and some checkout requests hung for minutes.

Why does this happen? (step by step)

  1. The zero http.Client (and DefaultClient) has Timeout set to 0, which means no limit for the whole request.
  2. A response body is a stream from a network connection. The client can reuse the connection only after the body is read and closed.
  3. On a 503, the early return skips the defer line, because defer was not registered yet. The body stays open.
  4. Every unclosed body keeps one TCP connection busy. During an incident with many errors, they pile up fast.
  5. Without the ctx, the call does not know that the user left or that the handler’s deadline passed.

The fix:

// One client for the whole service, made at startup.
var payClient = &http.Client{Timeout: 10 * time.Second}

func (p *Payments) Charge(ctx context.Context,
	c Charge) (ChargeResult, error) {
	var out ChargeResult
	body, err := json.Marshal(c)
	if err != nil {
		return out, err
	}
	req, err := http.NewRequestWithContext(ctx, "POST",
		p.baseURL+"/charges", bytes.NewReader(body))
	if err != nil {
		return out, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Idempotency-Key", c.OrderID)

	resp, err := payClient.Do(req)
	if err != nil {
		return out, err
	}
	defer resp.Body.Close() // on every path
	if resp.StatusCode != http.StatusOK {
		return out, fmt.Errorf("charge: %s", resp.Status)
	}
	err = json.NewDecoder(resp.Body).Decode(&out)
	return out, err
}
  1. Close the body right after the error check of Do, before any other return.
  2. One shared client reuses connections. Making a new client (or a new Transport) per request wastes connections.
  3. The client Timeout is a hard upper limit. The ctx adds the caller’s own deadline and cancellation.
  4. The Idempotency-Key header (if the provider supports one) makes a retry safe: the provider will not charge the card twice for the same order.

Follow-up question: The call timed out after 10 seconds. Did the customer pay or not? What should the service do?

Follow-up answer:

  • We do not know. The provider may have charged the card and the answer was lost. A timeout is an unknown result, not a failure.
  • Do not simply show “payment failed” and let the user pay again.
  • Retry with the same idempotency key, or ask the provider for the status of this order’s charge.
  • Store the payment as “pending” first, and finish it from the provider’s webhook or from a background job that checks the status.

Red flag: Retries the charge with a new request and no idempotency key, or says “Go closes the body automatically”.

Report a problem or send a better text

Edit on GitHub

11Errors on every deployMedium–HTTP services in GoKubernetes

Question: The order service runs in Kubernetes with 4 pods. The team deploys about 10 times a day with a rolling update. Some requests (for example “place order”) take 1 to 3 seconds. The main function:

func main() {
	db := mustOpenDB(os.Getenv("DATABASE_URL"))
	defer db.Close()

	mux := http.NewServeMux()
	mux.HandleFunc("POST /orders", placeOrder(db))
	mux.HandleFunc("GET /orders/{id}", getOrder(db))

	log.Fatal(http.ListenAndServe(":8080", mux))
}

You see this in code review. What do you think? Is there a problem?

Short answer: Yes. The service has no graceful shutdown. In a rolling update, Kubernetes sends SIGTERM to the old pod. Go’s default action for SIGTERM is to exit at once, so every request in progress is cut in the middle: users get errors (often 502 from the load balancer), and an order can be half done. The fix: catch SIGTERM with signal.NotifyContext, then call Shutdown on the http.Server. It stops accepting new connections and waits for running requests to finish. Also, ListenAndServe uses a server with no timeouts, and log.Fatal skips the deferred db.Close.

Hint (if the candidate says there is no problem): During each deploy, the error dashboard shows a short spike of 502 errors. Support sometimes finds orders that were paid but have no items saved.

Why does this happen? (step by step)

  1. Kubernetes starts a new pod, then stops an old one by sending SIGTERM to the process.
  2. The program does not handle SIGTERM, so the Go runtime ends the process right away. No deferred function runs.
  3. Requests that were running on this pod lose their connection. The load balancer returns 502 to those users.
  4. If “place order” was between two database writes without a transaction, the data stays half written.
  5. With 10 deploys a day and 4 pods, this happens about 40 times a day.

The fix:

func main() {
	db := mustOpenDB(os.Getenv("DATABASE_URL"))
	defer db.Close()

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           routes(db),
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      30 * time.Second,
		IdleTimeout:       60 * time.Second,
	}

	ctx, stop := signal.NotifyContext(context.Background(),
		syscall.SIGTERM, os.Interrupt)
	defer stop()

	go func() {
		err := srv.ListenAndServe()
		if err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("listen: %v", err)
		}
	}()

	<-ctx.Done() // wait for SIGTERM or Ctrl+C
	log.Println("shutting down")

	shutCtx, cancel := context.WithTimeout(
		context.Background(), 20*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutCtx); err != nil {
		log.Printf("shutdown: %v", err)
	}
}
  1. The signal.NotifyContext function gives a context that is cancelled when SIGTERM arrives.
  2. The Shutdown method closes the listeners, then waits until all active requests finish, or until shutCtx expires.
  3. ListenAndServe returns http.ErrServerClosed after Shutdown. That is the normal case, not an error.
  4. The 20-second limit stays below the Kubernetes grace period (30 seconds by default), so the process can exit cleanly before it is killed.
  5. After main returns, the deferred db.Close runs too.

Follow-up question: You added graceful shutdown, but a few 502 errors still appear during deploys. Why, and what do you do?

Follow-up answer:

  • Kubernetes sends SIGTERM and removes the pod from the Service endpoints at the same time. These happen in parallel, so for a short moment the load balancer and kube-proxy still send new requests to a pod that has stopped listening.
  • A common fix: keep serving for a few seconds after SIGTERM before calling Shutdown. Many teams use a preStop hook with a short sleep, or sleep in Go after the signal.
  • Optionally make the readiness endpoint return 503 right after SIGTERM, so traffic moves away sooner.
  • Make “place order” safe against cut requests anyway: one database transaction, and an idempotency key so a retry from the client does not create a second order.

Red flag: Says “Kubernetes already waits for requests to finish”, or handles SIGTERM by calling os.Exit.

Report a problem or send a better text

Edit on GitHub

12Exporting the orders of the day as CSVMedium to hard–Go performance and memory

Question: The finance team downloads all orders of the day as a CSV file. On a normal day there are 2,000 orders. On sale days there are up to 50,000. The code:

func ordersCSV(orders []Order) string {
	out := "id,customer,total\n"
	for _, o := range orders {
		out += fmt.Sprintf("%d,%s,%d\n",
			o.ID, o.Customer, o.Total)
	}
	return out
}

func (h *Admin) ExportOrders(w http.ResponseWriter,
	r *http.Request) {
	orders, err := h.repo.TodayOrders(r.Context())
	if err != nil {
		http.Error(w, "export failed", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/csv")
	io.WriteString(w, ordersCSV(orders))
}

You see this in code review. What do you think? Is there a problem?

Short answer: Yes. A Go string can not change, so each “out +=” makes a new string and copies everything written so far. The total work grows with the square of the number of orders. With 50,000 orders the loop copies many gigabytes, and the garbage collector works hard. The whole file is also built in memory before anything is sent. Second problem: a customer name with a comma (“Sara, Tehran”) breaks the CSV columns. The fix: write the rows directly to the response with the encoding/csv writer. It buffers the output and quotes the fields for you.

Hint (if the candidate says there is no problem): On normal days the export is instant. On a sale day it takes more than a minute, the pod’s CPU is at 100%, and other admin pages get slow. In a quick benchmark with 20,000 orders, the function allocated about 5 GB for one call.

Why does this happen? (step by step)

  1. Strings in Go are immutable. “a += b” makes a new string with the length of a plus b, and copies both into it.
  2. After 1,000 rows the string has about 1,000 rows of text. Adding row 1,001 copies all of them again.
  3. So the copies are 1 + 2 + 3 + … + n rows, which is about n squared divided by 2. Twice the orders means about four times the work.
  4. Each old string becomes garbage. The garbage collector must find and free gigabytes of short-lived memory, which uses CPU from all goroutines on the pod.
  5. fmt.Sprintf also allocates a new string for every row.
  6. Finally the whole file is in memory at once, so memory use is high even after the loop.

The fix:

func writeOrdersCSV(w io.Writer, orders []Order) error {
	cw := csv.NewWriter(w) // buffered, and quotes commas
	cw.Write([]string{"id", "customer", "total"})
	row := make([]string, 3) // reused for every order
	for _, o := range orders {
		row[0] = strconv.FormatInt(o.ID, 10)
		row[1] = o.Customer
		row[2] = strconv.FormatInt(o.Total, 10)
		if err := cw.Write(row); err != nil {
			return err
		}
	}
	cw.Flush()
	return cw.Error()
}
  1. Rows go straight to the http.ResponseWriter through a buffer. There is no big string, and the user starts getting the file at once.
  2. The work now grows in a straight line with the number of orders. In the same quick benchmark, 20,000 orders took about 2 milliseconds instead of about 2 seconds.
  3. The csv writer puts quotes around a field with a comma, so the columns stay correct.
  4. If you really need a string, use strings.Builder (and its Grow method if you know the size). It appends without copying everything again.
  5. For very large exports, stream rows from the database with rows.Next instead of loading all orders into a slice first.

Follow-up question: Before you change code for speed, how do you prove where the time goes, and that your change helped?

Follow-up answer:

  • Write a benchmark for the function with realistic data (for example 20,000 orders). Since Go 1.24 the loop can be written with b.Loop.
  • Run it with the benchmem flag to see bytes and allocations per call. Run old and new code several times and compare them with benchstat.
  • In production, use pprof: the CPU profile shows where time goes, and the heap profile (alloc_space) shows which lines allocate the most.
  • Do not expose the pprof endpoints on the public port. Serve them on an internal port or behind authentication.

Red flag: Wants to make it faster with goroutines, or suggests tuning GOGC first, before removing the quadratic copying.

Report a problem or send a better text

Edit on GitHub

13Design a service for payment webhooksDesignWeight ×2–Goroutines and channelsThe context packageIdempotency

Question: Design a Go service that receives payment webhooks from our payment provider. Each webhook says “payment succeeded” or “payment failed” for an order. After a success we must mark the order as paid, confirm the stock reservation and send a receipt email. Numbers and rules:

  • Normal traffic is about 20 webhooks per second. On sale days it peaks at about 200 per second.
  • The provider waits up to 10 seconds for a 2xx answer. Without it, it sends the same webhook again, for up to 3 days.
  • The provider can send the same event more than once, and events can arrive out of order (“failed” after “succeeded” for a retried payment).
  • The service runs in Kubernetes with 3 pods and deploys several times a day.

Explain your design step by step: the HTTP endpoint, how work is queued, the worker goroutines, retries, shutdown and monitoring.

Short answer: Split receiving from processing. The HTTP handler only checks the signature, saves the event in an inbox table with the provider’s event id as a unique key, and answers 200 at once. Duplicates hit the unique key and are simply acknowledged. A small, fixed pool of worker goroutines in each pod claims events from the table (SELECT … FOR UPDATE SKIP LOCKED), processes each one inside a transaction with a timeout, and retries failures with backoff, moving an event to “dead” after too many attempts. Processing is idempotent, and the order is a state machine, so a duplicate or late event cannot break it. On SIGTERM the pod stops claiming, finishes the events it holds, and exits. Metrics show the queue size and the age of the oldest event.

Requirements and numbers:

  1. A 10-second limit means the handler must never wait for the email server or other slow work. Answer in milliseconds.
  2. “At least once” delivery from the provider means every step must be safe to run twice.
  3. 200 events per second, with maybe 50 ms of database work per event, is about 10 events in progress at any moment. A few workers per pod are enough. We do not need one goroutine per event.
  4. Events are stored in the database, so a crash or a deploy loses nothing.

The parts:

  1. The HTTP endpoint
  • Read the body with a size limit (http.MaxBytesReader) and check the provider’s signature with a constant time compare (hmac.Equal). Reject a bad signature with 400 or 401.
  • Insert the event into the inbox table: event id, type, order id, raw body, status “new”, attempts 0, next try time.
  • If the insert fails on the unique key, the event is a duplicate. Answer 200 anyway, so the provider stops sending it.
  • Answer 200 only after the insert commits. If the database is down, answer 503, and the provider will retry later. Nothing is lost.
  1. The worker pool
// Run starts the workers and blocks until ctx is cancelled
// and every worker has finished its current event.
func (w *Worker) Run(ctx context.Context) {
	var wg sync.WaitGroup
	for range w.workers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			w.loop(ctx)
		}()
	}
	wg.Wait()
}

func (w *Worker) loop(ctx context.Context) {
	for ctx.Err() == nil {
		ev, err := w.store.ClaimNext(ctx)
		if err != nil {
			if !errors.Is(err, ErrNoEvent) {
				log.Printf("claim: %v", err)
			}
			sleep(ctx, time.Second) // nothing to do
			continue
		}
		// Finish the current event even during shutdown.
		hctx, cancel := context.WithTimeout(
			context.WithoutCancel(ctx), 30*time.Second)
		w.handle(hctx, ev)
		cancel()
	}
}
  • The number of workers is fixed (for example 8 per pod) and comes from config. This also limits the load on the database and the email server.
  • ClaimNext picks one due event with FOR UPDATE SKIP LOCKED, so workers in different pods never take the same row.
  • The sleep helper waits on a timer and on ctx.Done, so shutdown does not wait a full second.
  1. Processing one event (idempotent)
  • Treat the order as a state machine: pending, then paid or failed. Only allowed moves are applied. If the order is already paid, a second “succeeded” does nothing. A late “failed” for an older payment attempt is ignored if the order is already paid with another attempt.
  • Change the order and mark the event “done” in one transaction.
  • Do not send the email inside the transaction. Write an “email to send” row in the same transaction (an outbox), and let a separate worker send it. Then a crash never sends an email for an order that was not saved, or loses the email.
  1. Retries and dead events
  • On an error, add 1 to attempts and set the next try time with exponential backoff and a little random jitter (for example 1 s, 2 s, 4 s … up to 10 minutes).
  • After about 10 attempts, set status to “dead” and send an alert. A person checks it. Never retry forever, and never drop it silently.
  • Separate errors that can pass (database timeout) from errors that will never pass (unknown order id, bad data). The second kind goes to “dead” at once.
  1. Shutdown
  • main uses signal.NotifyContext. On SIGTERM it calls Shutdown on the HTTP server and cancels the worker context.
  • Each worker stops claiming new events and finishes the one it holds (the WithoutCancel context above), then Run returns.
  • If a pod is killed in the middle anyway, the transaction rolls back, the row lock is released, and another worker picks the event up again. Idempotency makes this safe.
  1. Monitoring
  • Metrics: events received, processed, failed, and dead; the number of “new” events; and the age of the oldest waiting event. Alert when the age grows, because that means the workers cannot keep up.
  • Logs with the event id and order id on every line, so one payment can be followed from webhook to email.

Trade-offs:

  • Database table as a queue: simple and transactional with the order data. Good for hundreds of events per second. For much more traffic, or many consumers, a message broker (Kafka, RabbitMQ) can be better, but it adds a system to run and still needs idempotency.
  • Polling: costs a few cheap queries per second when idle. LISTEN/NOTIFY in Postgres can wake workers faster, but polling is simpler and enough here.
  • Ordering: we do not try to process events in arrival order. The state machine makes the result correct in any order, which is simpler than strict ordering.

Follow-up question: On Black Friday the age of the oldest event grows to 15 minutes. How do you find the cause, and what do you change?

Follow-up answer:

  • First find the slow part: look at the processing time per event, database metrics (lock waits, slow queries), and the CPU profile of a worker pod.
  • If the database is fine and workers are just busy, add workers per pod or add pods. The fixed pool makes this a config change.
  • If the database is the limit, adding workers makes it worse. Make each event cheaper: an index for ClaimNext, shorter transactions, and the email in the outbox, not inline.
  • Check that dead or always-failing events are not taking the workers’ time with fast retries. Backoff should push them out of the way.

Red flag: Processes everything inside the HTTP handler before answering, starts one goroutine per webhook with no limit, ignores duplicates (“the provider sends each event once”), or keeps the queue only in memory (a Go channel), so a deploy loses events.

Report a problem or send a better text

Edit on GitHub

14Slow requests on a pod with free CPUHard–Go inside: scheduler and GC

Question: The order service is built with Go 1.24 and runs in Kubernetes on nodes with 64 cores. The pod spec has:

resources:
  requests:
    cpu: "2"
  limits:
    cpu: "2"

During a sale, p99 latency goes from 40 ms to 300 ms. The CPU graph of the pod shows about 1.2 cores used on average, so the team says “CPU is fine”. pprof shows nothing special. What do you think is going on, and how do you check it?

Short answer: GOMAXPROCS is 64, because Go 1.24 counts the cores of the node and does not read the container CPU limit. So up to 64 threads run Go code at the same time (including the GC workers). The CPU limit is enforced by the Linux CFS quota: 2 CPUs means 200 ms of CPU time per 100 ms period. 64 busy threads use that quota in a few milliseconds, then the kernel throttles the whole pod until the next period. Requests that are in flight just stop for tens of milliseconds. The average CPU looks fine, but the pod spends part of each period frozen. Check the container metric for throttled periods (container_cpu_cfs_throttled_periods_total). Fix: upgrade to Go 1.25, which sets GOMAXPROCS from the cgroup CPU limit, or set GOMAXPROCS=2 (or use automaxprocs) on older versions.

Hint (if the candidate is stuck): Ask how many threads can run Go code at the same time in this pod, and what the kernel does when a pod uses its CPU quota early in a period.

Why does this happen? (step by step)

  1. The runtime starts with GOMAXPROCS = 64, so there are 64 Ps.
  2. During the sale, many requests and the GC run on many threads at once.
  3. In the first 3 to 4 ms of a 100 ms period, the threads use the 200 ms of quota.
  4. The kernel stops all threads of the pod for the rest of the period. Every request in flight waits.
  5. Averaged over a minute, the graph shows only about 1.2 cores. pprof only samples CPU time, so it cannot show waiting.
  6. go tool trace would show long gaps where no P runs anything at all.

The fix:

env:
  - name: GOMAXPROCS
    value: "2"   # only for Go 1.24 and older
  1. Best: build with Go 1.25 or newer. The default GOMAXPROCS then follows the CPU limit, and changes if the limit changes.
  2. On older versions, set GOMAXPROCS to the limit, or use go.uber.org/automaxprocs.
  3. Check that throttled periods drop to near zero, and that p99 goes back down.
  4. Some teams remove the CPU limit and keep only the request. Then there is no quota and no throttling, but the pod can take CPU from its neighbors. That is a team decision, not a Go fix.

Follow-up question: After the fix, GOMAXPROCS is 2. A report endpoint does a 2-second CPU heavy calculation. Now small requests on the same pod become slow when a report runs. Why, and what do you do?

Follow-up answer:

  • With only 2 Ps, one long calculation uses half of the pod’s Go capacity. The scheduler preempts it every 10 ms or so, but other goroutines still get less CPU.
  • If the calculation also allocates a lot, GC assist slows every goroutine on the pod.
  • Move heavy reports to their own deployment or a job queue, so request pods stay fast. Or limit how many reports run at once.

Red flag: Says “add more CPU” or “raise the limit to 64” without measuring, or thinks the CPU average proves there is no CPU problem.

Report a problem or send a better text

Edit on GitHub

15Reserving stock over gRPCMedium to hard–gRPC in GoThe context package

Question: The order service reserves items in the inventory service over gRPC. Here is the client and a part of the server:

// Order service, called for every checkout.
func (h *Checkout) reserve(r *http.Request,
	items []*inventoryv1.Item) (string, error) {
	conn, err := grpc.NewClient("inventory:9090",
		grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return "", err
	}
	defer conn.Close()

	inv := inventoryv1.NewInventoryClient(conn)
	res, err := inv.Reserve(context.Background(),
		&inventoryv1.ReserveRequest{Items: items})
	if err != nil {
		return "", err
	}
	return res.GetReservationId(), nil
}

// Inventory service.
func (s *server) Reserve(ctx context.Context,
	req *inventoryv1.ReserveRequest,
) (*inventoryv1.ReserveResponse, error) {
	id, err := s.store.Reserve(context.Background(), req.GetItems())
	if err != nil {
		return nil, fmt.Errorf("reserve: %w", err)
	}
	return &inventoryv1.ReserveResponse{ReservationId: id}, nil
}

You see this in code review. What problems do you see?

Short answer:

  1. A new connection for every checkout. Each call pays for DNS, TCP and the HTTP/2 setup, and opens a new socket. Create the client connection once at startup and share it.
  2. No deadline. context.Background() means the call can wait forever if inventory hangs. Use the incoming request’s ctx with a timeout, like 300 ms.
  3. The server drops the ctx too. It passes context.Background() to the store, so when the client gives up, the database work keeps running. Pass ctx down.
  4. Plain Go errors. The client gets codes.Unknown for everything, so it cannot tell “out of stock” from “database down”. Return status.Error with codes like FailedPrecondition, InvalidArgument or Unavailable, and check status.Code(err) on the client.
  5. No order id is sent, so the server cannot make a retry safe. Send the order id and use it as an idempotency key.

Hint (if the candidate finds only one problem): Ask what happens to a checkout when the inventory database is locked for 30 seconds, and how the order service can show “sold out” to the user.

Why do these matter? (step by step)

  1. At 200 checkouts per second, the client opens and closes 200 connections per second. Latency and CPU go up, and sockets wait in TIME_WAIT.
  2. Inventory hangs. Every checkout goroutine waits with no limit, memory grows, and the user sees a spinner much longer than they would wait.
  3. Even when the user leaves, the inventory server keeps the database busy, so it recovers more slowly.
  4. The order service cannot react to “out of stock”, so it shows a general error.

The fix:

// At startup, once.
conn, err := grpc.NewClient("dns:///inventory:9090",
	grpc.WithTransportCredentials(creds))
if err != nil {
	return err
}
h.inv = inventoryv1.NewInventoryClient(conn)

// For every checkout.
ctx, cancel := context.WithTimeout(r.Context(),
	300*time.Millisecond)
defer cancel()
res, err := h.inv.Reserve(ctx, &inventoryv1.ReserveRequest{
	OrderId: orderID, Items: items,
})
switch status.Code(err) {
case codes.OK:
	return res.GetReservationId(), nil
case codes.FailedPrecondition:
	return "", ErrSoldOut
default:
	return "", fmt.Errorf("reserve: %w", err)
}
// Inventory server.
id, err := s.store.Reserve(ctx, req.GetOrderId(), req.GetItems())
switch {
case errors.Is(err, ErrOutOfStock):
	return nil, status.Error(codes.FailedPrecondition,
		"out of stock")
case err != nil:
	return nil, status.Error(codes.Internal, "reserve failed")
}

Follow-up question: After the fix, the team scales inventory from 2 to 6 pods, but the new pods get almost no calls. The Kubernetes Service is a normal ClusterIP Service. Why?

Follow-up answer:

  • The order service now keeps one long HTTP/2 connection, and a ClusterIP Service balances connections, not requests. The connection was made to one pod, so all calls go there.
  • Fix with client-side balancing: a headless Service, the dns:/// target and the round_robin policy in the service config. Or put an HTTP/2-aware proxy (Envoy, a service mesh) in between.
  • On the server, MaxConnectionAge makes clients reconnect from time to time, so new pods get traffic.

Red flag: Wants to create a new connection per request “to spread the load”, or sets a very long timeout “to be safe”.

Report a problem or send a better text

Edit on GitHub