System Design

G18

Protobuf and Connect

A schema first, then typed Go on both sides. Here is the whole path with connect-go v2: the buf toolchain, validation, handlers, streams, interceptors, and which schema changes break which readers.

Not startedSaved in this browser only.
  1. 1The .proto file is the contract. Generated code is committed, and buf breaking guards it in CI.
  2. 2A field number is forever. Reserve it on delete, and never reuse it.
  3. 3Only a *connect.Error you wrote reaches the client. A forwarded remote error becomes internal.
  4. 4One handler serves Connect, gRPC and gRPC-Web, and a unary Connect call is plain HTTP.
G18
    A

    The trap

    connect-go v2, a real run
    a handler that forwards an errorgo
    // api calls another Connect service and returns its error unchanged.
    type api struct {
      *connectlab.Service
      billing interface {
        GetOrder(context.Context, *v1.GetOrderRequest) (
          *v1.GetOrderResponse, error)
      }
    }
    
    func (a api) GetOrder(ctx context.Context, req *v1.GetOrderRequest) (
      *v1.GetOrderResponse, error) {
      return a.billing.GetOrder(ctx, req)1
    }
    1. 1The client marks each error it receives as remote. This returns one as the verdict of this server.
    handlerrecorded outputstatus
    Returns the error as it iscode: internal error: internal404 lost
    Maps it, keeps it as a causecode: not_found error: not_found: no such orderApproved
    the fixgo
    res, err := a.billing.GetOrder(ctx, req)
      if connect.CodeOf(err)1 == connect.CodeNotFound {
        return nil, connect.NewError(connect.CodeNotFound, "no such order").
          WithCause(err)2
      }
      if err != nil {
        return nil, connect.NewError(connect.CodeUnavailable, "try again").
          WithCause(err)
      }
    1. 1Read the downstream code, then decide what this API says.
    2. 2The cause stays in the server for logs. It is never sent.
    • v2 scrubs a remote error to internal with no message, so one service cannot speak for another by accident.
    • Check this path when you migrate a v1 service: the code a client sees can change.

    A handler states its own verdict. If it returns a downstream error as it is, the client gets internal and no message.

    B

    The model: one call

    connect-go v2
    client processserver processyour codeclient.GetOrdergeneratedconnect.Clientinterceptorsclient sideinterceptorsrecover, authgenerateddecode, validateyour codeService.GetOrdertransportconnecthttpin tests:connectinprocessHeaders reach the interceptors first. The message is decoded only when generated code calls Receive.
    generated from the service in panel Cgo
    type OrderServiceHandler interface1 {
      // Unary.
      CreateOrder(context.Context, *v1.CreateOrderRequest) (*v1.CreateOrderResponse, error)
      // Unary with no side effects, so a Connect client may use HTTP GET.
      GetOrder(context.Context, *v1.GetOrderRequest) (*v1.GetOrderResponse, error)
      // Server stream.
      WatchOrders(context.Context, *v1.WatchOrdersRequest, OrderServiceWatchOrdersServerStream2) error
      // Client stream.
      ImportOrders(context.Context, OrderServiceImportOrdersServerStream) (*v1.ImportOrdersResponse, error)
      // Bidirectional stream.
      Reconcile(context.Context, OrderServiceReconcileServerStream) error
    }
    1. 1You implement this. Embedding UnimplementedOrderServiceHandler keeps your struct compiling when the schema grows.
    2. 2A named type per stream. It offers Send only, so an illegal Receive cannot compile.

    Interceptors wrap the whole call, so auth runs on the headers before any message is decoded.

    C

    The contract

    the files
    orders.protoproto
    service OrderService {
      // Unary.
      rpc CreateOrder(CreateOrderRequest) returns (CreateOrderResponse);
      // Unary with no side effects, so a Connect client may use HTTP GET.
      rpc GetOrder(GetOrderRequest) returns (GetOrderResponse) {
        option idempotency_level = NO_SIDE_EFFECTS;1
      }
      // Server stream.
      rpc WatchOrders(WatchOrdersRequest) returns (stream WatchOrdersResponse)2;
      // Client stream.
      rpc ImportOrders(stream ImportOrdersRequest) returns (ImportOrdersResponse);
      // Bidirectional stream.
      rpc Reconcile(stream ReconcileRequest) returns (stream ReconcileResponse);
    }
    1. 1A Connect client may now use HTTP GET, so a CDN can cache the call.
    2. 2The word stream on either side picks the stream shape.

    I version the package name. A breaking change means orders.v2, side by side, not an edit to orders.v1.

    D

    The toolchain

    buf, committed output
    buf.yamlyaml
    version: v2
    modules:
      - path: proto
    deps:
      - buf.build/bufbuild/protovalidate1
    lint:
      use:
        - STANDARD
    breaking:
      use:
        - FILE2
    1. 1A dependency from the schema registry, pinned in buf.lock.
    2. 2The strictest level. It also protects generated Go source.
    buf.gen.yamlyaml
    version: v2
    managed:
      enabled: true1
      override:
        - file_option: go_package_prefix
          value: github.com/rudrite/system-design/lab/golang/connectlab/gen
      disable:
        - file_option: go_package
          module: buf.build/bufbuild/protovalidate
    plugins:
      - local: protoc-gen-go
        out: gen
        opt: paths=source_relative
      - local: protoc-gen-connect-go2
        out: gen
        opt: paths=source_relative
    1. 1Managed mode sets go_package, so the .proto stays free of Go paths.
    2. 2Install it from the v2 module. The simple flag is gone: v2 output has one style.
    commandchecks
    buf lintNames, package versions, unique request types.
    buf breakingThis schema against the last one (panel M).
    buf generateWrites the .pb.go and .connect.go files.

    buf lint, buf breaking and buf generate run in CI. The generated files are committed, so a build needs no generator.

    E

    protovalidate: rules in the schema

    tested: each rule, each stream message
    orders.protoproto
    enum OrderState {
      ORDER_STATE_UNSPECIFIED = 0;
      ORDER_STATE_OPEN = 1;
      ORDER_STATE_PAID = 2;
    }
    
    message Order {
      // Field 5 was the free-text note. Never use the number or the name again.
      reserved 5;1
      reserved "note";
    
      string id = 1;
      string email = 2;
      int64 total_cents = 3;
      OrderState state = 4;
      optional string coupon2 = 6;
    }
    
    message CreateOrderRequest {
      option (buf.validate.message).cel = {
        id: "order.coupon_needs_total"
        message: "a coupon needs a total of at least 1000 cents"
        expression: "!has(this.coupon) || this.total_cents >= 1000"3
      };
    
      string email = 1 [(buf.validate.field).string.email = true4];
      int64 total_cents = 2 [(buf.validate.field).int64.gt = 0];
      optional string coupon = 3 [(buf.validate.field).string.max_len = 16];
      string request_id = 4 [(buf.validate.field).string.uuid = true];
    }
    1. 1The compiler now refuses a new field with this number.
    2. 2optional gives presence: unset and empty differ.
    3. 3A CEL rule across fields. It runs at run time, with no generated code.
    4. 4A standard rule. The rule ID string.email returns to the client.
    requestcoderule ID in the detail
    Email "ada"invalid_argumentstring.email
    Total 0invalid_argumentint64.gt
    Request ID "1"invalid_argumentstring.uuid
    23-character couponinvalid_argumentstring.max_len
    Coupon on a 10-cent orderinvalid_argumentorder.coupon_needs_total
    • The interceptor wraps the stream, so it checks each message of a client stream as it arrives.
    • A bad second message fails the stream there, after the handler has read the first.
    • Validate on the server. A client with an old schema must not reject a value the server now allows.
    • Validation cost here: 1.3 µs and 0 allocations per message.

    Rules live in the schema, so each language enforces the same ones. Handlers can assume a valid message.

    F

    Handlers

    tested
    unary handlersgo
    // CreateOrder stores one order. A repeated request_id returns the first
    // result, so a client may retry after a timeout.
    func (s *Service) CreateOrder(ctx context.Context,
      req *v1.CreateOrderRequest) (*v1.CreateOrderResponse, error) {
      s.mu.Lock()
      defer s.mu.Unlock()
      if s.Fail != nil {
        return nil, connect.NewError(connect.CodeUnavailable, "try again").2
          WithCause(s.Fail)
      }
      if old, ok := s.byKey[req.GetRequestId()]3; ok {
        return &v1.CreateOrderResponse{Order: old}, nil
      }
      o := &v1.Order{
        Id:         fmt.Sprintf("ord_%d", len(s.orders)+1),
        Email:      req.GetEmail()1,
        TotalCents: req.GetTotalCents(),
        State:      v1.OrderState_ORDER_STATE_OPEN,
        Coupon:     req.Coupon,
      }
      s.orders = append(s.orders, o)
      s.byKey[req.GetRequestId()] = o
      return &v1.CreateOrderResponse{Order: o}, nil
    }
    
    // GetOrder returns one order, or not_found with text the client may show.
    func (s *Service) GetOrder(ctx context.Context, req *v1.GetOrderRequest) (
      *v1.GetOrderResponse, error) {
      s.mu.Lock()
      defer s.mu.Unlock()
      i := slices.IndexFunc(s.orders, func(o *v1.Order) bool {
        return o.GetId() == req.GetId()
      })
      if i < 0 {
        return nil, connect.Errorf(connect.CodeNotFound,4
          "order %q does not exist", req.GetId())
      }
      return &v1.GetOrderResponse{Order: s.orders[i]}, nil
    }
    1. 1Getters are safe on a nil message. Prefer them to field reads.
    2. 2The text the client sees. You write it, so it holds no internals.
    3. 3An idempotency key: a retry after a timeout returns the first order.
    4. 4The status becomes HTTP 404 on Connect, and grpc-status 5 on gRPC.

    A handler is a method on a struct. v2 passes the message itself, and metadata lives on CallInfo in the context.

    G

    Streams

    tested on Connect and gRPC
    the three stream shapesgo
    // WatchOrders sends each order until limit, then returns. A nil return ends
    // the stream cleanly. The loop checks ctx, so a client that leaves stops it.
    func (s *Service) WatchOrders(ctx context.Context, req *v1.WatchOrdersRequest,
      stream ordersv1connect.OrderServiceWatchOrdersServerStream) error {
      s.mu.Lock()
      orders := slices.Clone(s.orders)
      s.mu.Unlock()
      for i, o := range orders {
        if req.GetLimit() > 0 && i == int(req.GetLimit()) {
          break
        }
        if err := ctx.Err()1; err != nil {
          return err
        }
        res := &v1.WatchOrdersResponse{Order: o}
        if err := stream.Send(res)4; err != nil {
          return err
        }
      }
      return nil
    }
    
    // ImportOrders reads until io.EOF, then sends its one response.
    func (s *Service) ImportOrders(ctx context.Context,
      stream ordersv1connect.OrderServiceImportOrdersServerStream) (
      *v1.ImportOrdersResponse, error) {
      res := &v1.ImportOrdersResponse{}
      for {
        req, err := stream.Receive()
        if errors.Is(err, io.EOF)2 {
          return res, nil3
        }
        if err != nil {
          return nil, err
        }
        res.Imported++
        res.TotalCents += req.GetTotalCents()
      }
    }
    
    // Reconcile answers each message on the same stream.
    func (s *Service) Reconcile(ctx context.Context,
      stream ordersv1connect.OrderServiceReconcileServerStream) error {
      var balance int64
      for {
        req, err := stream.Receive()
        if errors.Is(err, io.EOF) {
          return nil
        }
        if err != nil {
          return err
        }
        balance += req.GetCents()
        res := &v1.ReconcileResponse{BalanceCents: balance}
        if err := stream.Send(res); err != nil {
          return err
        }
      }
    }
    1. 1The client can leave at any time. Without this check the loop keeps working.
    2. 2The clean end of a client stream. In v2 it is distinct from a network EOF.
    3. 3A client stream gets one response, after the handler has read everything.
    4. 4A handler ends a stream by returning. A ServerStream has no Close.
    shapetransport needs
    Unary, server stream, client streamHTTP/1.1 or HTTP/2
    BidirectionalHTTP/2. On HTTP/1.1 the handler answers 505.

    Each stream shape has its own generated type, so the type shows which calls are legal. Receive ends with io.EOF.

    H

    Interceptors

    tested
    interceptorsgo
    // Recover turns a panic into an internal error with no detail.
    func Recover(next connect.ServerFunc) connect.ServerFunc1 {
      return func(ctx context.Context, spec connect.Spec,
        stream connect.ServerStream) (err error) {
        defer func() {
          if r := recover(); r != nil {
            err = connect.NewError(connect.CodeInternal, "internal error")
          }
        }()
        return next(ctx, spec, stream)
      }
    }
    
    // Auth rejects a call from its headers, before any message is decoded.
    func Auth(verify func(token string) bool) connect.ServerInterceptor {
      return func(next connect.ServerFunc) connect.ServerFunc {
        return func(ctx context.Context, spec connect.Spec,
          stream connect.ServerStream) error {
          info, _ := connect.CallInfoForServerContext(ctx)2
          if !verify(info.RequestHeader().Get("Authorization")) {
            return connect.NewError(connect.CodeUnauthenticated,
              "missing or invalid token")
          }
          return next(ctx, spec, stream)
        }
      }
    }
    
    // Count wraps the stream, so it sees each message of every stream shape.
    func Count(received *int) connect.ServerInterceptor {
      return func(next connect.ServerFunc) connect.ServerFunc {
        return func(ctx context.Context, spec connect.Spec,
          stream connect.ServerStream) error {
          return next(ctx, spec, countingStream{stream, received}3)
        }
      }
    }
    
    type countingStream struct {
      connect.ServerStream
      received *int
    }
    
    func (c countingStream) Receive(msg any) error {
      err := c.ServerStream.Receive(msg)
      if err == nil {
        *c.received++
      }
      return err
    }
    1. 1v2 has no recover option: this is an ordinary interceptor.
    2. 2Headers, protocol, peer and sizes. It replaces the v1 Request wrapper.
    3. 3Wrap the stream to see each message. One interceptor covers all 4 shapes.

    An interceptor wraps a function with the whole stream in view. A rejection on headers costs no decode.

    I

    Server and client

    tested
    NewServer, NewHTTPgo
    // NewServer builds the RPC server. The first interceptor is the outermost.
    func NewServer(svc ordersv1connect.OrderServiceHandler,
      verify func(string) bool) *connect.Server {
      server := connect.NewServer(
        Recover,1
        Auth(verify),2
        validate.NewServerInterceptor(),
      )
      ordersv1connect.RegisterOrderServiceHandler(server, svc)
      return server
    }
    
    // NewHTTP mounts the server beside plain routes, with size limits and
    // HTTP/2 without TLS for gRPC clients inside the network.
    func NewHTTP(addr string, server *connect.Server) *http.Server {
      mux := http.NewServeMux()
      connecthttp.Mount(mux, server,
        connecthttp.WithReadMaxBytes(1<<20)3,
        connecthttp.WithCompressMinBytes(1024),
      )
      mux.HandleFunc("GET /healthz", func(w http.ResponseWriter,
        _ *http.Request) {
        w.WriteHeader(http.StatusOK)
      })
      protocols := new(http.Protocols)
      protocols.SetHTTP1(true)
      protocols.SetUnencryptedHTTP2(true)4
      return &http.Server{
        Addr:              addr,
        Handler:           mux,
        Protocols:         protocols,
        ReadHeaderTimeout: 5 * time.Second,
      }
    }
    1. 1First in the list is the outermost, so it catches panics from all the others.
    2. 2Before validate: an anonymous caller learns nothing about your rules.
    3. 3A larger message gets resource_exhausted. The default is 4 MiB, so set your real maximum.
    4. 4Go 1.24: gRPC clients with prior knowledge, with no extra library.
    NewClientgo
    // NewClient returns a typed client. Each option picks a protocol, and the
    // handler serves them all on the same routes.
    func NewClient(httpClient connecthttp.HTTPClient, baseURL, token string,
      opts ...connecthttp.Option) ordersv1connect.OrderServiceClient {
      return ordersv1connect.NewOrderServiceClient(connect.NewClient(
        connecthttp.NewTransport(httpClient, baseURL, opts...)1,
        bearer(token),
      ))
    }
    
    func bearer(token string) connect.ClientInterceptor {
      return func(next connect.ClientFunc) connect.ClientFunc {
        return func(ctx context.Context, spec connect.Spec) (
          connect.ClientStream, error) {
          info, ok := connect.CallInfoForClientContext(ctx)
          if ok {
            info.RequestHeader().Set("Authorization", "Bearer "+token)
          }
          return next(ctx, spec)
        }
      }
    }
    1. 1Pass connecthttp.WithGRPC() to speak gRPC. The generated client does not change.

    Connect routes share a ServeMux with health checks. Options set the protocol, the size limit and compression.

    J

    See it: a request through the stack

    recorded with a probe around each layer
    recoverauthvalidatehandler

    step 1 of 8

    The call enters recover.

    the client gets

    HTTP 200, code ok

    • With no token, the call never reaches validate, so the server decodes nothing.
    • An invalid message stops inside validate. The handler body does not run.
    • A panic passes through auth and validate with no return value. Recover turns it into internal.

    Order matters: recover outermost, then auth, then validate. Each layer sees the error on the way out.

    K

    Tests without a listener

    tested, with one difference
    Localgo
    // Local connects a client to a handler in the same process. Tests skip the
    // listener and the wire, and each message is a deep copy.
    func Local(svc ordersv1connect.OrderServiceHandler,
      interceptors ...connect.ServerInterceptor,
    ) ordersv1connect.OrderServiceClient {
      server := connect.NewServer(interceptors...)
      ordersv1connect.RegisterOrderServiceHandler(server, svc)
      return ordersv1connect.NewOrderServiceClient(
        connect.NewClient(connectinprocess.New(server)1))
    }
    1. 1New in v2. It dispatches to the server with no bytes on a wire.
    checkover HTTPin process
    Time per call106 µs0.9 µs
    Interceptors and handlers runYesYes
    Codec and size limits runYesNo
    errors.Is finds a server causeNo: the wire drops itYes: same error value

    connectinprocess runs handlers and interceptors with no network. A test for leaked error text still needs HTTP.

    L

    Error codes on the wire

    recorded: 16 codes, 3 paths, real calls
    grpc-statusConnect unarycode, use it forretry
    1499canceled
    The caller gave up.
    No
    2500unknown
    A plain Go error reached the wire.
    No
    3400invalid_argument
    The request is wrong in any state.
    No
    4504deadline_exceeded
    Time ran out. The work may have run.
    If idempotent
    5404not_found
    The entity does not exist.
    No
    6409already_exists
    A create clashed.
    No
    7403permission_denied
    Known caller, not allowed.
    No
    8429resource_exhausted
    A quota or a size limit.
    With backoff
    9400failed_precondition
    Wrong state. Fix the state first.
    No
    10409aborted
    Lost a race, for example a 40001.
    From the top
    11400out_of_range
    A valid request past the end.
    No
    12501unimplemented
    The method does not exist.
    No
    13500internal
    A bug on the server.
    No
    14503unavailable
    Down for now. Safe to try again.
    With backoff
    15500data_loss
    Unrecoverable data damage.
    No
    16401unauthenticated
    No valid credentials.
    After a new token

    All 16 codes returned HTTP 200 on a Connect stream and on gRPC, so HTTP metrics count those failures as successes. Read the code in an interceptor. The raw body of a not_found: {"code":"not_found","message":"order \"ord_9\" does not exist"}

    On unary Connect the code is the HTTP status. On a stream and on gRPC the status is 200, and the code is in the body or the trailer.

    M

    Compatibility: what each change does

    recorded: real bytes read with each new schema, and buf at each level
    changebinary: new reader, old bytesJSON: new reader, old textFILEWIRE_JSONWIREverdict
    Add a fieldname="ada" tag=""name="ada" tag=""PassesPassesPassesSafe
    Rename a fieldtitle="ada"fails: proto: unknown field "name"FailsFailsPassesBinary only
    int32 to int64count=7count=7FailsFailsPassesAn old reader truncates
    Delete a fieldname="ada", 7 unknown bytes keptfails: proto: unknown field "note"FailsFailsFailsNumber can return
    Delete, then reserve number and namename="ada", 7 unknown bytes keptfails: proto: unknown field "note"FailsPassesPassesThe safe delete
    Reuse a number, same typeemail="hello"fails: proto: unknown field "note"FailsFailsPassesSilent wrong data
    Reuse a number, new typenote=0, 7 unknown bytes keptfails: proto: invalid value for int32 field note: "hello"FailsFailsFailsSilent loss
    Change a numbernote="", 7 unknown bytes keptnote="hello", 0 unknown bytes keptFailsFailsFailsSilent loss
    Scalar to repeatedname=["ada"]fails: proto: syntax error: unexpected token "ada"FailsFailsFailsBinary only
    • The old message was name "ada", count 7, note "hello". Each row read those bytes with one changed schema.
    • Unknown fields survive: a test passed a new field through an old reader and back, and the value was intact.
    • A widened field read by an old program truncates: 5,000,000,000 became 705,032,704, with no error.
    • Choose the buf level by your clients: FILE if they import generated code, WIRE_JSON if JSON crosses the wire, WIRE if only binary does.

    I add fields, and I reserve what I delete. A rename is safe for binary readers and breaks JSON readers. buf breaking catches each case.

    N

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.22ServeMux accepts methods and wildcards.A Connect mux can hold the REST routes too.
    1.24Server.Protocols and Transport.Protocols, with unencrypted HTTP/2 (prior knowledge only).gRPC inside a network needs no golang.org/x/net/http2.
    1.26new(expr). errors.AsType.An optional field fills in one expression: Coupon: new("WELCOME").
    1.27The HTTP/2 server accepts RFC 9218 priority signals.Stream scheduling changed. Server.DisableClientPriority restores round robin.
    connect v2v2.0.0 changes the generated API, the transport and interceptors. v1 keeps its fixes.Both modules can live in one program during a migration.
    O

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildThe prompt asks for an API in 45 minutes.Use net/http and JSON by default. If libraries are allowed and you rehearsed it, the proto-first kit (K2) fits the time. Otherwise, name Connect as the next step.
    talk"How would you expose this to other teams?"A .proto contract, buf breaking in CI, and generated clients in each language.
    talk"Why not plain REST?"Connect unary is HTTP and JSON, so curl works. You add a schema, generated clients and streams.
    talk"Why not plain gRPC?"Browsers cannot speak gRPC directly. Connect serves browsers and gRPC clients from one handler.
    talk"How do you change a field?"Add the new field, write both, migrate readers, then delete and reserve the old one.
    talk"How do you stop a retry from charging twice?"A request ID in the message, checked in the handler, and a unique key in the store.

    I build on plain HTTP and JSON, or on the proto kit if the room allows it. In the talk I show the schema, because the contract is what survives.

    P

    Drill

    each answer is the output of a real run

    0 of 10 known

    1. Predict the output. The handler returns a wrapped Go error.

      package main
      
      import (
        "context"
        "errors"
        "fmt"
      
        "connectrpc.com/connect/v2"
      
        "github.com/rudrite/system-design/lab/golang/connectlab"
        v1 "github.com/rudrite/system-design/lab/golang/connectlab/gen/orders/v1"
      )
      
      type api struct{ *connectlab.Service }
      
      func (api) GetOrder(context.Context, *v1.GetOrderRequest) (
        *v1.GetOrderResponse, error) {
        return nil, fmt.Errorf("query: %w", errors.New("password rejected"))
      }
      
      func main() {
        client := connectlab.Local(api{connectlab.NewService()})
        _, err := client.GetOrder(context.Background(), &v1.GetOrderRequest{})
        fmt.Println("code:", connect.CodeOf(err))
        fmt.Printf("error: %v\n", err)
      }
    2. Predict the output.

      package main
      
      import (
        "context"
        "errors"
        "fmt"
        "net/http/httptest"
      
        "connectrpc.com/connect/v2"
      
        "github.com/rudrite/system-design/lab/golang/connectlab"
        v1 "github.com/rudrite/system-design/lab/golang/connectlab/gen/orders/v1"
      )
      
      var errDisk = errors.New("disk full on db-3")
      
      type api struct{ *connectlab.Service }
      
      func (api) GetOrder(context.Context, *v1.GetOrderRequest) (
        *v1.GetOrderResponse, error) {
        err := connect.NewError(connect.CodeInternal, "store failed").
          WithCause(errDisk)
        fmt.Println("server sees the cause:", errors.Is(err, errDisk))
        return nil, err
      }
      
      func main() {
        server := connectlab.NewServer(api{connectlab.NewService()},
          connectlab.Unauthenticated)
        ts := httptest.NewServer(connectlab.NewHTTP("", server).Handler)
        defer ts.Close()
      
        client := connectlab.NewClient(ts.Client(), ts.URL, "token")
        _, err := client.GetOrder(context.Background(),
          &v1.GetOrderRequest{Id: "ord_1"})
        fmt.Println("client sees:", err)
        fmt.Println("client sees the cause:", errors.Is(err, errDisk))
      }
    3. Predict the output. This is a plain POST with JSON and no client library.

      package main
      
      import (
        "fmt"
        "io"
        "net/http"
        "net/http/httptest"
        "strings"
      
        "github.com/rudrite/system-design/lab/golang/connectlab"
      )
      
      func main() {
        svc := connectlab.NewService()
        srv := connectlab.NewHTTP("", connectlab.NewServer(svc,
          connectlab.Unauthenticated))
        ts := httptest.NewServer(srv.Handler)
        defer ts.Close()
      
        res, err := http.Post(ts.URL+"/orders.v1.OrderService/GetOrder",
          "application/json", strings.NewReader(`{"id":"ord_9"}`))
        if err != nil {
          panic(err)
        }
        defer res.Body.Close()
        body, err := io.ReadAll(res.Body)
        if err != nil {
          panic(err)
        }
        fmt.Println(res.StatusCode)
        fmt.Println(res.Header.Get("Content-Type"))
        fmt.Println(string(body))
      }
    4. Predict the output. The rule on id is min_len 1.

      package main
      
      import (
        "fmt"
        "io"
        "net/http"
        "net/http/httptest"
        "strings"
      
        "github.com/rudrite/system-design/lab/golang/connectlab"
      )
      
      func main() {
        svc := connectlab.NewService()
        srv := connectlab.NewHTTP("", connectlab.NewServer(svc,
          connectlab.Unauthenticated))
        ts := httptest.NewServer(srv.Handler)
        defer ts.Close()
      
        res, err := http.Post(ts.URL+"/orders.v1.OrderService/GetOrder",
          "application/json", strings.NewReader(`{"id":""}`))
        if err != nil {
          panic(err)
        }
        defer res.Body.Close()
        body, err := io.ReadAll(res.Body)
        if err != nil {
          panic(err)
        }
        fmt.Println(res.StatusCode)
        fmt.Println(strings.Contains(string(body), "min_len"))
      }
    5. Predict the output. The handler sends 2 messages and returns an error.

      package main
      
      import (
        "context"
        "errors"
        "fmt"
        "io"
      
        "connectrpc.com/connect/v2"
      
        "github.com/rudrite/system-design/lab/golang/connectlab"
        v1 "github.com/rudrite/system-design/lab/golang/connectlab/gen/orders/v1"
        "github.com/rudrite/system-design/lab/golang/connectlab/gen/orders/v1/ordersv1connect"
      )
      
      type api struct{ *connectlab.Service }
      
      func (api) WatchOrders(ctx context.Context, _ *v1.WatchOrdersRequest,
        stream ordersv1connect.OrderServiceWatchOrdersServerStream) error {
        for _, id := range []string{"ord_1", "ord_2"} {
          res := &v1.WatchOrdersResponse{Order: &v1.Order{Id: id}}
          if err := stream.Send(res); err != nil {
            return err
          }
        }
        return connect.NewError(connect.CodeDataLoss, "log truncated")
      }
      
      func main() {
        client := connectlab.Local(api{connectlab.NewService()})
        stream, err := client.WatchOrders(context.Background(),
          &v1.WatchOrdersRequest{})
        fmt.Println("open:", err)
        for {
          res, err := stream.Receive()
          if errors.Is(err, io.EOF) {
            fmt.Println("clean end")
            return
          }
          if err != nil {
            fmt.Println("end:", connect.CodeOf(err))
            return
          }
          fmt.Println("got:", res.GetOrder().GetId())
        }
      }
    6. Predict the output. The server has 5 methods.

      package main
      
      import (
        "context"
        "fmt"
      
        "connectrpc.com/connect/v2"
      
        "github.com/rudrite/system-design/lab/golang/connectlab"
        v1 "github.com/rudrite/system-design/lab/golang/connectlab/gen/orders/v1"
      )
      
      type api struct{ *connectlab.Service }
      
      func (api) GetOrder(context.Context, *v1.GetOrderRequest) (
        *v1.GetOrderResponse, error) {
        fmt.Println("handler")
        return &v1.GetOrderResponse{}, nil
      }
      
      func layer(name string) connect.ServerInterceptor {
        fmt.Println("build", name)
        return func(next connect.ServerFunc) connect.ServerFunc {
          fmt.Println("wrap", name)
          return func(ctx context.Context, spec connect.Spec,
            s connect.ServerStream) error {
            fmt.Println("enter", name)
            defer fmt.Println("leave", name)
            return next(ctx, spec, s)
          }
        }
      }
      
      func main() {
        client := connectlab.Local(api{connectlab.NewService()},
          layer("a"), layer("b"))
        fmt.Println("ready")
        _, err := client.GetOrder(context.Background(), &v1.GetOrderRequest{})
        fmt.Println(err)
      }
    7. Predict the output. The handler never returns on its own.

      package main
      
      import (
        "context"
        "fmt"
        "net/http/httptest"
        "time"
      
        "connectrpc.com/connect/v2"
      
        "github.com/rudrite/system-design/lab/golang/connectlab"
        v1 "github.com/rudrite/system-design/lab/golang/connectlab/gen/orders/v1"
      )
      
      type api struct {
        *connectlab.Service
        saw chan bool
      }
      
      func (a api) GetOrder(ctx context.Context, _ *v1.GetOrderRequest) (
        *v1.GetOrderResponse, error) {
        _, ok := ctx.Deadline()
        a.saw <- ok
        <-ctx.Done()
        return nil, ctx.Err()
      }
      
      func main() {
        saw := make(chan bool, 1)
        server := connectlab.NewServer(api{connectlab.NewService(), saw},
          connectlab.Unauthenticated)
        ts := httptest.NewServer(connectlab.NewHTTP("", server).Handler)
        defer ts.Close()
      
        client := connectlab.NewClient(ts.Client(), ts.URL, "token")
        ctx, cancel := context.WithTimeout(context.Background(),
          200*time.Millisecond)
        defer cancel()
        _, err := client.GetOrder(ctx, &v1.GetOrderRequest{Id: "ord_1"})
        fmt.Println("client:", connect.CodeOf(err))
        fmt.Println("handler saw a deadline:", <-saw)
      }
    8. Predict the output.

      package main
      
      import (
        "bytes"
        "encoding/json"
        "fmt"
      
        "google.golang.org/protobuf/encoding/protojson"
      
        v1 "github.com/rudrite/system-design/lab/golang/connectlab/gen/orders/v1"
      )
      
      func main() {
        o := &v1.Order{
          Id:         "ord_1",
          TotalCents: 1250,
          State:      v1.OrderState_ORDER_STATE_OPEN,
        }
        out, err := protojson.Marshal(o)
        if err != nil {
          panic(err)
        }
        // protojson adds random spaces on purpose. Compact removes them.
        var b bytes.Buffer
        if err := json.Compact(&b, out); err != nil {
          panic(err)
        }
        fmt.Println(b.String())
      }
    9. Predict the output. Coupon is optional, and TotalCents is not.

      package main
      
      import (
        "fmt"
      
        v1 "github.com/rudrite/system-design/lab/golang/connectlab/gen/orders/v1"
      )
      
      func main() {
        empty := ""
        a := &v1.Order{}
        b := &v1.Order{Coupon: &empty}
        fmt.Println(a.Coupon == nil, a.GetCoupon() == "")
        fmt.Println(b.Coupon == nil, b.GetCoupon() == "")
        fmt.Println(a.TotalCents == 0)
      }
    10. Predict the output.

      package main
      
      import (
        "fmt"
      
        v1 "github.com/rudrite/system-design/lab/golang/connectlab/gen/orders/v1"
      )
      
      func first(res *v1.GetOrderResponse) string {
        return res.GetOrder().GetEmail()
      }
      
      func main() {
        fmt.Printf("%q\n", first(&v1.GetOrderResponse{}))
        fmt.Printf("%q\n", first(nil))
        var o *v1.Order
        defer func() { fmt.Println("recovered:", recover()) }()
        fmt.Println(o.Email)
      }
    Q

    Numbers to say

    measured with testing.B
    call, loopback
    106 µs binary; 118 µs JSON; 189 µs gRPC.
    in process
    0.9 µs per call.
    encode
    0.1 µs proto; 1.1 µs JSON.
    size
    29 B proto against 87 B JSON for one order.
    validate
    1.3 µs per message.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 interleaved runs, on a busy machine. Use these as orders of magnitude.