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.
- 1The .proto file is the contract. Generated code is committed, and buf breaking guards it in CI.
- 2A field number is forever. Reserve it on delete, and never reuse it.
- 3Only a *connect.Error you wrote reaches the client. A forwarded remote error becomes internal.
- 4One handler serves Connect, gRPC and gRPC-Web, and a unary Connect call is plain HTTP.
// 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
}- 1The client marks each error it receives as remote. This returns one as the verdict of this server.
| handler | recorded output | status |
|---|---|---|
| Returns the error as it is | code: internal error: internal | 404 lost |
| Maps it, keeps it as a cause | code: not_found error: not_found: no such order | Approved |
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)
}- 1Read the downstream code, then decide what this API says.
- 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.
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
}- 1You implement this. Embedding UnimplementedOrderServiceHandler keeps your struct compiling when the schema grows.
- 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.
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);
}- 1A Connect client may now use HTTP GET, so a CDN can cache the call.
- 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.
version: v2
modules:
- path: proto
deps:
- buf.build/bufbuild/protovalidate1
lint:
use:
- STANDARD
breaking:
use:
- FILE2- 1A dependency from the schema registry, pinned in buf.lock.
- 2The strictest level. It also protects generated Go source.
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- 1Managed mode sets go_package, so the .proto stays free of Go paths.
- 2Install it from the v2 module. The simple flag is gone: v2 output has one style.
| command | checks |
|---|---|
| buf lint | Names, package versions, unique request types. |
| buf breaking | This schema against the last one (panel M). |
| buf generate | Writes 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.
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];
}- 1The compiler now refuses a new field with this number.
- 2optional gives presence: unset and empty differ.
- 3A CEL rule across fields. It runs at run time, with no generated code.
- 4A standard rule. The rule ID string.email returns to the client.
| request | code | rule ID in the detail |
|---|---|---|
| Email "ada" | invalid_argument | string.email |
| Total 0 | invalid_argument | int64.gt |
| Request ID "1" | invalid_argument | string.uuid |
| 23-character coupon | invalid_argument | string.max_len |
| Coupon on a 10-cent order | invalid_argument | order.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.
// 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
}- 1Getters are safe on a nil message. Prefer them to field reads.
- 2The text the client sees. You write it, so it holds no internals.
- 3An idempotency key: a retry after a timeout returns the first order.
- 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.
// 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
}
}
}- 1The client can leave at any time. Without this check the loop keeps working.
- 2The clean end of a client stream. In v2 it is distinct from a network EOF.
- 3A client stream gets one response, after the handler has read everything.
- 4A handler ends a stream by returning. A ServerStream has no Close.
| shape | transport needs |
|---|---|
| Unary, server stream, client stream | HTTP/1.1 or HTTP/2 |
| Bidirectional | HTTP/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.
// 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
}- 1v2 has no recover option: this is an ordinary interceptor.
- 2Headers, protocol, peer and sizes. It replaces the v1 Request wrapper.
- 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.
// 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,
}
}- 1First in the list is the outermost, so it catches panics from all the others.
- 2Before validate: an anonymous caller learns nothing about your rules.
- 3A larger message gets resource_exhausted. The default is 4 MiB, so set your real maximum.
- 4Go 1.24: gRPC clients with prior knowledge, with no extra library.
// 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)
}
}
}- 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.
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.
// 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))
}- 1New in v2. It dispatches to the server with no bytes on a wire.
| check | over HTTP | in process |
|---|---|---|
| Time per call | 106 µs | 0.9 µs |
| Interceptors and handlers run | Yes | Yes |
| Codec and size limits run | Yes | No |
| errors.Is finds a server cause | No: the wire drops it | Yes: same error value |
connectinprocess runs handlers and interceptors with no network. A test for leaked error text still needs HTTP.
| grpc-status | Connect unary | code, use it for | retry |
|---|---|---|---|
| 1 | 499 | canceled The caller gave up. | No |
| 2 | 500 | unknown A plain Go error reached the wire. | No |
| 3 | 400 | invalid_argument The request is wrong in any state. | No |
| 4 | 504 | deadline_exceeded Time ran out. The work may have run. | If idempotent |
| 5 | 404 | not_found The entity does not exist. | No |
| 6 | 409 | already_exists A create clashed. | No |
| 7 | 403 | permission_denied Known caller, not allowed. | No |
| 8 | 429 | resource_exhausted A quota or a size limit. | With backoff |
| 9 | 400 | failed_precondition Wrong state. Fix the state first. | No |
| 10 | 409 | aborted Lost a race, for example a 40001. | From the top |
| 11 | 400 | out_of_range A valid request past the end. | No |
| 12 | 501 | unimplemented The method does not exist. | No |
| 13 | 500 | internal A bug on the server. | No |
| 14 | 503 | unavailable Down for now. Safe to try again. | With backoff |
| 15 | 500 | data_loss Unrecoverable data damage. | No |
| 16 | 401 | unauthenticated 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.
Compatibility: what each change does
recorded: real bytes read with each new schema, and buf at each level| change | binary: new reader, old bytes | JSON: new reader, old text | FILE | WIRE_JSON | WIRE | verdict |
|---|---|---|---|---|---|---|
| Add a field | name="ada" tag="" | name="ada" tag="" | Passes | Passes | Passes | Safe |
| Rename a field | title="ada" | fails: proto: unknown field "name" | Fails | Fails | Passes | Binary only |
| int32 to int64 | count=7 | count=7 | Fails | Fails | Passes | An old reader truncates |
| Delete a field | name="ada", 7 unknown bytes kept | fails: proto: unknown field "note" | Fails | Fails | Fails | Number can return |
| Delete, then reserve number and name | name="ada", 7 unknown bytes kept | fails: proto: unknown field "note" | Fails | Passes | Passes | The safe delete |
| Reuse a number, same type | email="hello" | fails: proto: unknown field "note" | Fails | Fails | Passes | Silent wrong data |
| Reuse a number, new type | note=0, 7 unknown bytes kept | fails: proto: invalid value for int32 field note: "hello" | Fails | Fails | Fails | Silent loss |
| Change a number | note="", 7 unknown bytes kept | note="hello", 0 unknown bytes kept | Fails | Fails | Fails | Silent loss |
| Scalar to repeated | name=["ada"] | fails: proto: syntax error: unexpected token "ada" | Fails | Fails | Fails | Binary 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.
| since | what changed | what it means here |
|---|---|---|
| 1.22 | ServeMux accepts methods and wildcards. | A Connect mux can hold the REST routes too. |
| 1.24 | Server.Protocols and Transport.Protocols, with unencrypted HTTP/2 (prior knowledge only). | gRPC inside a network needs no golang.org/x/net/http2. |
| 1.26 | new(expr). errors.AsType. | An optional field fills in one expression: Coupon: new("WELCOME"). |
| 1.27 | The HTTP/2 server accepts RFC 9218 priority signals. | Stream scheduling changed. Server.DisableClientPriority restores round robin. |
| connect v2 | v2.0.0 changes the generated API, the transport and interceptors. v1 keeps its fixes. | Both modules can live in one program during a migration. |
| when | the moment | what to do or say |
|---|---|---|
| build | The 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.
0 of 10 known
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) }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)) }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)) }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")) }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()) } }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) }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) }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()) }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) }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) }
- 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.