Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

Practice: gRPC and Protobuf Exercises

Practice gRPC and protobuf skills with hands-on Go exercises on status codes, retries, interceptors and schema compatibility, plus design questions and full solutions.

Reading about gRPC is not the same as using it. This lesson gives you four small coding exercises, each with a starter you can edit and run in place, a self-check that prints PASS or FAIL, and a full solution to compare with afterwards. Then come design questions to discuss with yourself or a teammate.

The exercises use plain Go on the site's runner, modelling the ideas of the lessons in this chapter group: status codes, retries, interceptors and schema compatibility. Try each one before opening the solution.

Exercise 1: map errors to status codes

Complete codeFor so each domain error returns the best gRPC code. Refresh your memory with status codes.

Go Exercise 1: choose the status code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Solution (replace the body of codeFor):

Go
package main

import (
	"errors"
	"fmt"
)

var (
	ErrEmptyName    = errors.New("name is empty")
	ErrNoSuchOrder  = errors.New("order not found")
	ErrNotYourOrder = errors.New("order belongs to someone else")
	ErrNoToken      = errors.New("no token supplied")
	ErrAlreadyPaid  = errors.New("order already paid")
	ErrStaleVersion = errors.New("version changed since you read it")
	ErrOutOfStock   = errors.New("warehouse is out of stock, try later")
)

func codeFor(err error) string {
	switch {
	case errors.Is(err, ErrEmptyName):
		return "INVALID_ARGUMENT"
	case errors.Is(err, ErrNoSuchOrder):
		return "NOT_FOUND"
	case errors.Is(err, ErrNotYourOrder):
		return "PERMISSION_DENIED"
	case errors.Is(err, ErrNoToken):
		return "UNAUTHENTICATED"
	case errors.Is(err, ErrAlreadyPaid):
		return "FAILED_PRECONDITION"
	case errors.Is(err, ErrStaleVersion):
		return "ABORTED"
	case errors.Is(err, ErrOutOfStock):
		return "UNAVAILABLE"
	}
	return "UNKNOWN"
}

func main() {
	fmt.Println(codeFor(ErrStaleVersion), codeFor(fmt.Errorf("wrapped: %w", ErrNoSuchOrder)))
}

Think about why ErrOutOfStock could also be RESOURCE_EXHAUSTED or FAILED_PRECONDITION: the "right" answer depends on whether the client should retry. Write down your reasoning.

Exercise 2: a retry helper

Write withRetry(maxAttempts, fn) that calls fn and retries only when it returns UNAVAILABLE, using the waits from the supplied sleep function (do not really sleep). It must return the last error if all attempts fail, and must not retry other errors. See retries and hedging.

Go Exercise 2: retry only UNAVAILABLE

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Solution:

Go
package main

import (
	"errors"
	"fmt"
)

var Unavailable = errors.New("UNAVAILABLE")

func withRetry(maxAttempts int, sleep func(attempt int), fn func() error) error {
	var err error
	for attempt := 1; attempt <= maxAttempts; attempt++ {
		if err = fn(); err == nil {
			return nil
		}
		if !errors.Is(err, Unavailable) {
			return err // not worth retrying
		}
		if attempt < maxAttempts {
			sleep(attempt)
		}
	}
	return err
}

func main() {
	calls := 0
	err := withRetry(3, func(int) {}, func() error {
		calls++
		return Unavailable
	})
	fmt.Println(err, calls)
}

Extension: add jitter, honour a context deadline, and refuse to retry when a throttle token bucket is empty.

Exercise 3: a rate-limiting interceptor

Write a rateLimit(max) middleware that allows max calls per "window" and rejects the rest with RESOURCE_EXHAUSTED. The test calls reset() to start a new window. Review interceptors if the chain shape is unfamiliar.

Go Exercise 3: write a rate limiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Solution:

Go
package main

import (
	"errors"
	"fmt"
)

type Handler func(user string) (string, error)
type Interceptor func(Handler) Handler

var ErrExhausted = errors.New("RESOURCE_EXHAUSTED")

func rateLimit(max int) (Interceptor, func()) {
	counts := map[string]int{}
	ic := func(next Handler) Handler {
		return func(user string) (string, error) {
			if counts[user] >= max {
				return "", ErrExhausted
			}
			counts[user]++
			return next(user)
		}
	}
	return ic, func() { counts = map[string]int{} }
}

func main() {
	ic, _ := rateLimit(1)
	h := ic(func(u string) (string, error) { return "hi " + u, nil })
	fmt.Println(h("ada"))
	fmt.Println(h("ada"))
}

A production limiter must be safe for concurrent use (add a mutex), reset by time (token bucket) and read the user from authenticated metadata.

Exercise 4: is this schema change safe?

Complete safe so it returns true only for backward-compatible changes. Use the rules from schema evolution.

Go Exercise 4: judge the change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Solution:

Go
package main

import "fmt"

type Field struct {
	Num  int
	Name string
	Type string
}

func safe(old, cur []Field) bool {
	byNum := map[int]Field{}
	for _, f := range cur {
		byNum[f.Num] = f
	}
	for _, o := range old {
		n, ok := byNum[o.Num]
		if !ok || n.Type != o.Type {
			return false
		}
	}
	return true
}

func main() {
	fmt.Println(safe([]Field{{1, "a", "int32"}}, []Field{{1, "b", "int32"}, {2, "c", "string"}}))
}

Real tools also consider JSON names, oneof membership, packed encoding and enum values. This is a good place to read the rule list in Buf's breaking categories.

Design questions

Answer these in a few sentences each; there is no single right answer, but there are wrong ones.

  1. A mobile app calls CreatePayment and loses the network before the reply arrives. Design the request so that retrying is safe. What does the server store?
  2. Your ListOrders RPC returns everything today. A customer now has 2 million orders. How do you change the API without breaking old clients?
  3. Two services call each other: A calls B calls A. What goes wrong with deadlines, and how do you detect the cycle?
  4. A service needs to send 2 GB files. Compare one unary RPC, a client stream of chunks and a pre-signed object-storage URL.
  5. You must rename the field age to birth_year and change its meaning. Describe the safe rollout across three releases.
  6. A single user floods your API. List three places you could limit them and the status each returns.
  7. Why might you choose Connect or REST over native gRPC for a public API?

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A retry helper should retry which error?

    Only transient failures such as UNAVAILABLE can succeed when the same request is repeated.
  2. 2. In the schema-safety exercise, why is reusing field number 2 for a string 'nickname' unsafe?

    The wire carries only the number and wire type, so the meaning of old data under that number changes.
  3. 3. Which status should a rate limiter return when a user is over budget?

    RESOURCE_EXHAUSTED signals quota or rate limits; ideally with a RetryInfo detail.
  4. 4. What makes a CreatePayment call safe to retry?

    With the key, a repeated request returns the stored result instead of charging twice.

Summary

  • You practiced mapping errors to status codes, retrying only transient failures, writing an interceptor and judging schema compatibility.
  • The same four skills cover most daily gRPC work: precise errors, safe retries, cross-cutting middleware, compatible schemas.
  • Design questions about idempotency, pagination, cycles, large payloads and rollouts are what interviews and design reviews ask.
  • Go back to the lessons above whenever an exercise surprised you, then build the key-value store or chat service end to end.

Next: back to the gRPC and Protocol Buffers track page