Protobuf contracts in Go

You can define an RPC contract and trace how generated Go code connects it to a server, preparing the existing order domain for gRPC.

Learning outcomes

  • Define versioned protobuf messages and RPC methods, then generate Go message types and service interfaces with Buf.
  • Connect a gRPC server to the existing order domain through a Go interface without duplicating business logic.
  • Handle authentication, idempotency metadata, domain errors, and request logging through gRPC metadata and interceptors.
  • Implement unary and server-streaming RPCs with correct cancellation and status code behaviour.
  • Test gRPC services using bufconn and inspect a running service with grpcurl.
Prerequisite conceptsGo interfaces

Your order domain already knows how to place orders, apply state transitions, and publish order updates. Now other backend services need to call those operations through gRPC, while the existing HTTP API continues serving the Expo application. The challenge is to add another transport without creating another implementation of the order business logic.

Two transport contracts

Your existing HTTP API exchanges JSON messages. A client sends an HTTP request, the server decodes its body, calls application logic, and serializes the response.

That approach works well for the Expo application. However, backend services also need a contract that describes exactly which operations exist and what data they accept.

Protocol Buffers provides that contract. You define messages and their fields in a .proto file, then generate language-specific code from the schema.

gRPC uses Protocol Buffers as its message format and provides remote procedure calls. A client invokes a method on a remote service through a generated client rather than manually constructing HTTP requests and parsing JSON.

The two technologies solve different parts of the problem:

  • Protobuf defines the structure of requests and responses.
  • gRPC defines how clients invoke service methods and receive responses.

For this project, HTTP and gRPC expose the same underlying order domain.

InterfaceResponsibility
HTTP on port 8080Serves the Expo application and existing HTTP clients
gRPC on port 9090Exposes typed order operations to RPC clients

A gRPC service does not replace your HTTP handlers. Both transports should delegate to the same application and domain operations.

Protobuf messages

A .proto file defines the messages exchanged between clients and servers.

Consider the contract for retrieving an order:

proto
syntax = "proto3";

package orders.v1;

option go_package = "github.com/yashdagar/zomato-prep/backend/gen/orders/v1;ordersv1";

message GetOrderRequest {
  int64 id = 1;
}

message GetOrderResponse {
  Order order = 1;
}

The schema defines two messages.

GetOrderRequest carries the order ID. GetOrderResponse contains the retrieved order.

Each field has a type, a name, and a numeric identifier.

The int64 type represents a signed 64-bit integer. The number after = is the field number used by protobuf's binary encoding.

The go_package option specifies the generated Go import path and package name. In this project, generated files live under backend/gen/orders/v1 and use the package name ordersv1.

Service definitions

A protobuf service groups related RPC methods into one contract.

The order service exposes four operations:

proto
service OrderService {
  rpc GetOrder(GetOrderRequest) returns (GetOrderResponse);
  rpc PlaceOrder(PlaceOrderRequest) returns (PlaceOrderResponse);
  rpc Transition(TransitionRequest) returns (TransitionResponse);
  rpc WatchOrder(WatchOrderRequest) returns (stream WatchOrderResponse);
}

Each method has a request type and a response type.

The first three methods are unary RPCs. They receive one request and return one response.

WatchOrder uses the stream keyword because one request can produce multiple responses over the lifetime of the connection.

The generated service interface makes this contract available to Go code.

Field numbers and compatibility

Field numbers are part of the protobuf wire format. They identify fields independently of their textual names.

Consider the order message:

proto
message Order {
  int64 id = 1;
  int64 user_id = 2;
  int64 restaurant_id = 3;
  Status status = 4;
  int64 version = 5;
  int64 total_paise = 6;
}

When one service serializes this message, protobuf encodes the field identifiers and values. Another service can decode the message using its generated schema.

Field numbers must remain stable after publication.

Suppose an older version uses field number 2 for user_id. A newer version must not reuse that number for payment_id. An older serialized message could then be interpreted incorrectly.

When you remove a field, reserve its old number and name rather than assigning them to something else.

Proto3 also assigns default values to absent scalar fields. For an ordinary int64, the default is zero.

This means a zero value does not tell you whether the client explicitly supplied zero or omitted the field. Use optional when your application needs to distinguish those cases.

proto
message PricingExample {
  optional int64 discount_paise = 1;
  repeated Line lines = 2;
}

An optional scalar provides presence information. A repeated field represents zero or more values.

Your order messages use repeated Line fields because an order can contain multiple menu items.

Dedicated request and response messages

Give each RPC its own request and response messages.

For example, GetOrder uses GetOrderRequest and GetOrderResponse. PlaceOrder uses PlaceOrderRequest and PlaceOrderResponse.

This keeps the contract for each operation independently understandable and easier to evolve.

Buf's STANDARD lint rules also enforce RPC response naming conventions. Reusing Order directly as the response to every RPC does not satisfy the expected response naming convention.

You can reuse message types inside different request and response messages without reusing the RPC response message itself.

Buf and protobuf generation

A .proto file is not directly usable as an ordinary Go implementation. Go needs generated message structures, serialization methods, client code, and server interfaces.

Buf provides tooling for validating protobuf schemas and generating code.

It replaces much of the manual compiler setup with a configuration-driven workflow.

Generation plugins

Two Go plugins generate the code required by this service:

  • protoc-gen-go generates Go message structures and protobuf serialization support.
  • protoc-gen-go-grpc generates gRPC clients, server interfaces, and registration functions.

Install Buf and the plugins:

bash
brew install bufbuild/buf/buf

go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

Make sure the Go binary directory is available on your PATH, so Buf can locate the installed plugins.

Buf configuration

The project stores its configuration in backend/buf.yaml.

A simplified example of the module and lint configuration is:

yaml
version: v2

modules:
  - path: proto

lint:
  use:
    - STANDARD

The module path tells Buf where the protobuf source files live.

The STANDARD lint rules enforce conventions for package names, enum values, RPC naming, and message definitions.

The project also uses a breaking-change configuration with file-level compatibility checks. This establishes a policy for detecting incompatible schema changes when a comparison reference is available.

Generation uses backend/buf.gen.yaml.

The important plugin configuration looks like this:

yaml
version: v2

plugins:
  - local: protoc-gen-go
    out: gen
    opt:
      - paths=source_relative

The local setting tells Buf to use an installed plugin.

The out setting places generated files under gen/. The paths=source_relative option preserves the source file's relative directory structure.

The gRPC plugin uses the same output directory and source-relative option.

Consequently, proto/orders/v1/orders.proto produces Go source files under gen/orders/v1/.

Linting before generation

Run these commands from backend/:

bash
buf lint
buf generate

The first command validates the schema. Fix lint failures before generating code.

The second command invokes the configured plugins and writes the generated files.

A generated directory should contain files for both protobuf messages and gRPC service definitions.

Generated code as a repository dependency

The generated gen/ directory is committed to this repository.

This means developers and CI can build the application without installing protobuf plugins every time they compile it.

Generated files are ordinary Go source files. Your compiler uses them like the rest of the project.

However, generated code must remain consistent with the schema.

When you change a protobuf definition, regenerate the Go files before committing the change. Otherwise, the schema and the compiled service may describe different contracts.

Generated Go types and services

Buf generates two important categories of code.

Message structures

The protobuf plugin generates Go types such as:

  • ordersv1.Order
  • ordersv1.Line
  • ordersv1.GetOrderRequest
  • ordersv1.GetOrderResponse
  • ordersv1.PlaceOrderRequest

These types provide serialization, deserialization, getters, and protobuf reflection support.

For example, you can construct an order response using generated types:

go
order := &ordersv1.Order{
    Id:           101,
    UserId:       42,
    RestaurantId: 8,
    Status:       ordersv1.Status_STATUS_PLACED,
    TotalPaise:   45000,
}

fmt.Println(order.GetId())
fmt.Println(order.GetStatus())

The generated getter methods provide a consistent way to read message fields.

You do not need to write custom serialization code for these messages.

Generated service interfaces

The gRPC plugin generates an OrderServiceServer interface.

Your server implementation must satisfy this interface by implementing the four RPC methods.

The generated package also provides:

  • UnimplementedOrderServiceServer
  • RegisterOrderServiceServer
  • NewOrderServiceClient

Embed UnimplementedOrderServiceServer in your implementation.

This provides default unimplemented responses for service methods that have not been implemented. It also helps your server remain compatible when new RPC methods are added to the generated contract.

The registration function connects your implementation to a gRPC server. The generated client constructor creates a client that can invoke the service.

The important distinction is that generated code defines the transport contract. Your implementation supplies the application behaviour.

The Store interface

The gRPC handler should not own order persistence or state-transition rules.

Those responsibilities already exist in the application built during previous weeks. Reimplementing them inside the gRPC server would create two sources of truth.

Use Go interfaces to make the transport depend on the operations it needs rather than a specific persistence implementation.

The Store interface represents the domain-facing operations required by the RPC handlers.

Its methods have these responsibilities:

MethodResponsibility
GetRetrieve an order using its ID
PlacePlace an order using the authenticated user ID and idempotency key
TransitionApply a domain event using the authenticated principal
SubscribeSubscribe to order updates through a channel

The contract uses ordinary Go types, including generated protobuf messages and existing domain types.

For example, the placement operation receives the authenticated user's ID and the idempotency key as separate arguments.

This is deliberate. The domain does not need to know how gRPC metadata works.

The transport extracts request metadata and passes the values to the Store.

Principal propagation

The existing authentication package contains auth.Signer and auth.Principal.

The signer validates an access token and produces a principal representing the authenticated user.

The principal carries the identity and role information needed by the order domain.

The gRPC authentication layer stores this principal in the request context.

A context helper such as PrincipalFrom(ctx) lets handlers retrieve the authenticated principal without passing it through every method signature.

The Transition operation needs the principal because the order domain checks whether the caller's role permits the requested event.

Place needs the authenticated user's ID. It must never trust an identity supplied as an ordinary client input.

Get does not need a principal argument because the production configuration deliberately makes GetOrder public.

Subscribe receives the request context and order ID. Its subscription must respect request cancellation.

Unary RPC handlers

A unary RPC follows the request-response pattern.

The client sends one request. The server processes it and returns one response or a gRPC error.

Consider GetOrder.

The generated request contains an order ID. The handler extracts it, calls the Store, and wraps the returned order in GetOrderResponse.

The transport handler should not implement SQL queries or order-state rules.

For PlaceOrder, the handler has additional responsibilities:

  1. Retrieve the authenticated principal from the request context.
  2. Read the idempotency key from incoming metadata.
  3. Obtain the authenticated user's ID.
  4. Pass the request and extracted values to the Store.
  5. Return the generated response message.

The Store receives the original idempotency key. It must not receive a newly generated key for each retry.

For Transition, the handler converts the event string from the protobuf request into the existing order.Event type.

It passes the authenticated principal, order ID, event ID, and domain event to the Store.

The order domain remains responsible for deciding whether the transition is legal.

This separation means both transports can use the same business rules.

gRPC status codes

Your HTTP handlers communicate failures through HTTP status codes.

For example, a missing order normally produces HTTP 404. An authentication failure produces HTTP 401.

gRPC uses status codes to communicate operation results.

The order service needs consistent mappings between domain failures and transport errors.

Domain or request failuregRPC status code
ErrNotFoundNotFound
ErrConflictAborted
*order.IllegalTransitionErrorFailedPrecondition
*order.ForbiddenErrorPermissionDenied
Missing or invalid Bearer tokenUnauthenticated
Missing idempotency-keyInvalidArgument
Unexpected internal failureInternal

Each code communicates a different type of failure.

NotFound

NotFound means the requested order does not exist.

For example, retrieving order ID 99 from a Store that reports ErrNotFound should produce this code.

InvalidArgument

InvalidArgument means the client has not supplied a required input.

In this service, a valid authenticated request to PlaceOrder without an idempotency-key must receive InvalidArgument.

It is not an authentication failure because the token may already be valid.

Unauthenticated and PermissionDenied

These codes represent different security failures.

Unauthenticated means the request has no valid credentials.

PermissionDenied means the caller is authenticated but lacks permission to perform the operation.

For example, a customer attempting to send the ACCEPT event must receive PermissionDenied.

FailedPrecondition and Aborted

FailedPrecondition indicates that the operation is invalid for the resource's current state.

A rider attempting to send DELIVER while the order is still PLACED is an example.

Aborted represents a conflict that prevents the operation from completing.

The two codes should not be interchangeable. An illegal state transition is a domain rule failure, whereas a conflict represents a conflicting operation.

Internal

Internal represents an unexpected server-side failure.

The client-facing message must be the fixed string internal error.

Never return raw database errors or internal implementation details to the client.

Wrapped errors

Go supports wrapping errors with additional context.

For this reason, use errors.Is when checking sentinel errors and errors.As when checking typed domain errors.

A wrapped ErrNotFound must still map to NotFound.

The same applies to wrapped *order.IllegalTransitionError and *order.ForbiddenError values.

go
switch {
case errors.Is(err, ErrNotFound):
    return status.Error(codes.NotFound, "order not found")
case errors.Is(err, ErrConflict):
    return status.Error(codes.Aborted, "conflict")
}

Typed errors require errors.As:

go
var forbidden *order.ForbiddenError

if errors.As(err, &forbidden) {
    return status.Error(codes.PermissionDenied, "permission denied")
}

Centralize this conversion instead of repeating error handling in every RPC.

Existing gRPC status errors should pass through unchanged. They may already contain an intentional status and message.

For unexpected errors, use slog to record the actual error on the server. Return only the stable client-facing message.

gRPC metadata

HTTP clients send headers alongside their request bodies.

Your HTTP authentication middleware already reads the Authorization header. The gRPC equivalent is metadata.

Metadata consists of key-value pairs attached to an RPC. It carries information that belongs to the request but is not part of the protobuf message.

The order service uses two metadata keys:

KeyPurpose
authorizationCarries the Bearer access token
idempotency-keyIdentifies a logical order-placement attempt

Metadata keys use lowercase names.

A gRPC server retrieves incoming metadata from the request context:

go
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
    return status.Error(codes.Unauthenticated, "authentication required")
}

authorization := md.Get("authorization")
keys := md.Get("idempotency-key")

The authorization value contains a Bearer token.

For example, the logical header value is:

authorization: Bearer <access-token>

The existing JWT signer validates the token. Do not introduce another token format or authentication implementation.

The idempotency key is separate from the protobuf request body because it describes the operation attempt rather than the order's business data.

Idempotent placement

Your existing HTTP API already supports idempotent order placement.

The same rule applies to gRPC.

Suppose a client sends an order-placement request for restaurant 3 with two lines and an idempotency key of k-1.

The client times out before receiving the response. It retries using the same key.

Both calls must refer to the same logical operation. The Store must return the same order ID rather than creating another order.

The gRPC handler must pass the key unchanged to Store.Place.

It must also derive the user ID from the verified principal, not from an untrusted client-supplied identity.

This preserves the retry-safety behaviour already built into your order service.

Interceptors

HTTP middleware handles work that applies across multiple handlers, such as authentication and request logging.

gRPC provides interceptors for the same purpose.

An interceptor wraps RPC execution. It can inspect a request, apply a policy, invoke the next handler, and inspect the result.

There are two relevant interceptor types.

Unary interceptors

A unary interceptor surrounds a single request-response operation.

Its function signature receives a context, request, method information, and the next handler.

Conceptually, execution looks like this:

  1. The client invokes an RPC.
  2. The interceptor receives the request.
  3. It performs shared checks or logging.
  4. It calls the next handler.
  5. It observes the response or error.
  6. It returns the result.

The order service uses two unary interceptors.

Authentication

The authentication interceptor reads the incoming authorization metadata.

It checks that the value contains a Bearer token and passes that token to the existing auth.Signer.

If token validation succeeds, the interceptor stores the resulting auth.Principal in the request context.

If the token is missing or invalid, the interceptor returns Unauthenticated.

The application handler should never need to parse JWTs itself.

Logging

The logging interceptor records the method name, gRPC status code, and latency.

Capture the start time before executing the next handler. Record the status code and elapsed time after the handler returns.

Use slog so the information is available as structured log fields.

This is particularly useful when an RPC fails outside the HTTP request path. You can identify the method, inspect its result, and measure how long the call took.

Public methods

Not every RPC needs authentication.

The production order service deliberately makes GetOrder public. PlaceOrder, Transition, and WatchOrder require valid Bearer authentication.

An explicit public-method allowlist makes this policy clear.

The unary authentication interceptor checks the full RPC method name against that allowlist.

Avoid broad rules such as allowing every method whose name contains Get. A newly added RPC could accidentally become public.

The allowlist should contain the generated full method name for OrderService.GetOrder.

Interceptor chaining

The gRPC server supports multiple unary interceptors through grpc.ChainUnaryInterceptor.

The order service chains logging before authentication:

go
grpc.ChainUnaryInterceptor(
    grpcapi.LogUnary(log),
    grpcapi.AuthUnary(signer, public),
)

The order matters.

The logging interceptor surrounds authentication and handler execution. It can therefore record the final status even when authentication rejects the request.

The stream authentication interceptor is registered separately:

go
grpc.StreamInterceptor(
    grpcapi.AuthStream(signer),
)

Unary and streaming authentication have different function signatures because their handlers receive different argument types.

Streaming authentication

A streaming handler receives a grpc.ServerStream rather than an ordinary context.

The interceptor can inspect the stream's original context, validate the token, and create a new context containing the principal.

However, replacing the local context variable is not enough.

The handler still receives the original ServerStream. Its Context() method would continue returning the original context.

You need a wrapper that embeds the original stream and overrides Context().

go
type authenticatedStream struct {
    grpc.ServerStream
    ctx context.Context
}

func (s *authenticatedStream) Context() context.Context {
    return s.ctx
}

After creating the authenticated context, the interceptor passes this wrapper to the next handler.

Now the streaming handler can access the principal through its normal context helper.

This is why a unary authentication interceptor alone cannot secure WatchOrder.

Server-streaming RPCs

Unary RPCs return one response. Order tracking has a different requirement.

A customer may keep an order-tracking screen open while the order progresses through its state machine.

The customer needs to receive updates as they happen, without repeatedly creating HTTP requests.

Server-streaming RPCs allow the client to send one request and receive multiple messages from the server over the same RPC.

The protobuf declaration identifies the streaming response:

proto
rpc WatchOrder(
    WatchOrderRequest
) returns (stream WatchOrderResponse);

The client sends one order ID.

The server subscribes to updates for that order through Store.Subscribe.

The Store returns a channel:

go
updates, err := store.Subscribe(ctx, orderID)
if err != nil {
    return err
}

The handler forwards messages from the channel to the client through the generated stream's Send method.

Stream lifecycle

A server stream has a lifetime that may extend beyond the initial request processing.

You must handle three events correctly.

An update arrives

The handler receives an event from the Store channel and sends it to the client.

For example, the order may transition from PLACED to ACCEPTED, then from ACCEPTED to PREPARING.

The server should forward every event in the order supplied by the channel.

The client disconnects

The stream context is cancelled when the client disconnects or its deadline expires.

The handler must observe stream.Context().Done() and stop waiting for updates.

The subscription must receive the same context so that the Store can stop its work when the RPC ends.

The Store channel closes

The Store may finish the subscription and close its channel.

A clean channel closure means the server stream has completed successfully. Return nil.

The client observes the successful completion through io.EOF on its next Recv() call.

The central loop uses a select to handle these cases:

go
for {
    select {
    case <-ctx.Done():
        return ctx.Err()
    case event, ok := <-updates:
        if !ok {
            return nil
        }
        if err := stream.Send(event); err != nil {
            return err
        }
    }
}

A failed Send must also terminate the handler with that error.

The server should not continue consuming updates after a client disconnects.

Event order

The order service's stream carries WatchOrderResponse messages.

Each event contains:

  • order_id, identifying the order.
  • event_id, identifying the event.
  • from, representing the previous status.
  • to, representing the resulting status.

The event IDs let a client distinguish updates.

For example, a test can push two updates with IDs e1 and e2 into the Store channel, close the channel, and verify that the client receives those IDs in the same order before receiving EOF.

Streaming does not change the underlying order state machine. It exposes events produced by the existing order application.

Running gRPC alongside HTTP

The API process exposes both transports.

The HTTP server continues listening on port 8080. The gRPC server listens on port 9090.

The gRPC server belongs in cmd/api, alongside the existing application dependencies. The worker remains responsible for its existing outbox and notification work.

The server needs four things:

  1. A configured gRPC server.
  2. The unary logging and authentication interceptors.
  3. The streaming authentication interceptor.
  4. The registered generated order service.

The generated registration function connects the handler to the gRPC server.

go
ordersv1.RegisterOrderServiceServer(
    grpcServer,
    grpcapi.New(store),
)

The Store passed to the handler must be the real application implementation, not a fake used for tests.

Reflection

gRPC reflection exposes information about the registered service definitions.

This allows tools such as grpcurl to inspect the running server without requiring you to manually provide the protobuf files.

Enable reflection on the server:

go
reflection.Register(grpcServer)

With reflection enabled, grpcurl can discover the registered services.

List services:

bash
grpcurl -plaintext localhost:9090 list

You should see orders.v1.OrderService.

List its methods:

bash
grpcurl -plaintext localhost:9090 \
  list orders.v1.OrderService

Inspect the GetOrder schema:

bash
grpcurl -plaintext localhost:9090 \
  describe orders.v1.OrderService.GetOrder

These commands verify that the gRPC endpoint is reachable and that the generated service contract has been registered.

They do not prove that every method implements the correct business behaviour. That requires actual RPC tests.

Testing with bufconn

Opening a real TCP port for every gRPC unit test creates unnecessary dependencies.

A test should be able to verify authentication, error conversion, and streaming behaviour without starting the production API or connecting to MySQL.

The gRPC Go library provides bufconn, an in-memory connection that allows a client and server to communicate without a real network listener.

This makes service tests independent of local port availability.

In-memory server setup

A typical test uses four components:

  1. A fake Store implementing the production Store interface.
  2. An in-memory listener created using bufconn.Listen.
  3. A gRPC server with the order service registered.
  4. A generated client connected through an in-memory dialer.

The client still invokes the generated RPC methods. The difference is that its connection never leaves the process.

The resulting test exercises the actual gRPC request and response path.

Fake stores in tests

The Store controls the results returned to the RPC handlers.

A fake implementation can return:

  • An order with a known ID.
  • ErrNotFound for a missing order.
  • A typed domain error for an illegal transition.
  • A channel containing controlled order updates.

This lets you isolate transport behaviour from persistence.

For example, you can test that a Store returning ErrNotFound produces a gRPC NotFound response.

The assertion should inspect the structured status code:

go
_, err := client.GetOrder(
    ctx,
    &ordersv1.GetOrderRequest{Id: 99},
)

if status.Code(err) != codes.NotFound {
    t.Fatalf("got %v, want NotFound", status.Code(err))
}

Do not compare the entire error string. The status code is the contract clients use to distinguish failures.

Testing metadata and authentication

A generated gRPC client can attach outgoing metadata to its context.

The server receives that metadata as incoming metadata.

For authenticated tests, supply the Bearer token produced using the same signer used by the test server.

For order placement, also supply the idempotency-key.

This allows separate tests for:

  • Missing authentication.
  • Invalid authentication.
  • Missing idempotency metadata.
  • Repeated placement with the same key.

An important detail is the order of validation.

An unauthenticated PlaceOrder call should fail with Unauthenticated before it reaches the idempotency check.

A call with valid authentication but no idempotency key should instead fail with InvalidArgument.

Testing these independently verifies that the server applies the correct security boundary.

Testing status conversion

Use status.Code(err) to inspect the returned gRPC code.

The expected code is more important than the human-readable message for most client-side error handling.

The order service should distinguish:

  • NotFound for missing orders.
  • Aborted for conflicts.
  • FailedPrecondition for illegal transitions.
  • PermissionDenied for forbidden domain actions.
  • Internal for unexpected failures.

The error-conversion tests should also account for wrapped sentinel and typed errors.

Testing streams

A streaming test can control the Store's event channel directly.

Send two events with IDs e1 and e2, then close the channel.

The client repeatedly calls Recv() until it receives io.EOF.

The collected event IDs should be:

e1
e2

The order matters. The server must forward every event without changing the sequence.

Also test an unauthenticated WatchOrder call. The streaming authentication interceptor should reject it with Unauthenticated.

Finally, test cancellation when the client disconnects. This verifies that the handler observes the stream context rather than waiting indefinitely for another event.

Common implementation failures

Several mistakes cause transport tests to fail even when the protobuf schema compiles.

Applying authentication to every unary method

GetOrder is explicitly public.

If the authentication interceptor requires a token for every unary RPC, GetOrder without credentials returns Unauthenticated instead of reaching the Store.

Use an explicit allowlist of public method names.

At the same time, do not accidentally allow PlaceOrder or Transition through the same exception.

Trusting client identity

A protobuf request describes the operation, not the authenticated identity.

If you take a user ID from untrusted client input rather than the verified principal, a caller could attempt to place an order as another user.

Read the principal from the authenticated request context. Pass its user ID to the Store.

Confusing authentication and request validation

A missing Bearer token and a missing idempotency key are different failures.

The first requires Unauthenticated. The second requires InvalidArgument.

Perform authentication before the handler validates operation-specific metadata.

Forgetting the streaming context wrapper

A stream interceptor cannot replace the context simply by creating a new local variable.

The handler receives the ServerStream, whose original Context() still returns the old context.

Without a wrapper, the authenticated principal is unavailable to the stream handler.

Treating channel closure as an error

Closing the Store channel is a normal way to finish a subscription.

Returning an artificial error when the channel closes causes a successful stream to appear to have failed.

Return nil on a closed channel. The client receives EOF when it calls Recv() again.

Returning internal errors to clients

Database errors may expose SQL statements, infrastructure details, or internal implementation information.

Log unexpected errors with slog, but return the fixed message internal error with the Internal status code.

Existing gRPC status errors should pass through unchanged.

From contract to service

The gRPC order service exercise connects these pieces to the existing application.

The protobuf contract defines the four RPC methods. Buf generates the Go messages and service interfaces. Your transport implementation delegates order operations to the existing Store rather than duplicating business rules.

Pay particular attention to the authentication boundary: GetOrder remains public, while PlaceOrder, Transition, and WatchOrder require a valid Bearer token.

The unary and streaming interceptors establish that boundary differently. The handlers then use metadata and the authenticated principal to perform their work.

Finally, bufconn tests verify the service without a network dependency, while the end-to-end tests exercise the gRPC server running beside the HTTP API.

Check your understanding

Question 1 of 4

Your generated protobuf code contains an Order message. A developer removes user_id = 2 and uses field number 2 for payment_id in a later schema version. What is the problem?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Go, gRPC, buf).

Finished Lesson 7.12?