Skip to content

Protobuf contracts

Three teams call the orders service. Each copied orders.proto into its own repository a year ago, and now each copy is a little different. GetOrder returns an Order directly, so there is no room to add the warnings field product asked for. A list method that returned 20 orders in testing returns 40,000 in production, and a field someone deleted last month came back with a new meaning and the same number.

The .proto file is the contract of a gRPC service: once clients compile against it, every mistake in it is expensive to undo. This guide sets the rules that keep it cheap to change: one owner, consistent names, fields and methods that leave room to grow, validation and errors in the contract, and a check that stops breaking changes.

1. Where do the .proto files live and who compiles them?

Section titled “1. Where do the .proto files live and who compiles them?”

In short: in a contract project owned by the service that implements them. It compiles them once and publishes one jar with the .proto files and the generated Java; consumers depend on that jar.

dependencies { implementation(project(":orders-api")) }

When every consumer keeps its own copy of the files, or compiles a shared folder by itself, the copies drift and the same classes end up in several jars, generated at different times. Nobody can tell which copy is the contract.

The Protobuf Gradle plugin already solves the sharing part. It puts the .proto files into the jar next to the compiled classes. A project that depends on that jar can import those files from its own .proto files, and the plugin does not compile them again.

  1. Give the service a contract project, a small Java library next to it. In a monorepo it is verticals/<vertical>/api/ (Monorepos, step 4).

  2. Put the files under src/main/proto, in folders that match their package (step 2).

  3. Apply java-library and com.google.protobuf there, and set the compiler and the gRPC generator to the versions Spring Boot’s BOM manages, so the contract and the services use the same Protocol Buffers:

    protobuf {
    protoc { artifact = "com.google.protobuf:protoc:4.36.2" }
    plugins { create("grpc") { artifact = "io.grpc:protoc-gen-grpc-java:1.84.1" } }
    generateProtoTasks {
    all().configureEach { plugins { create("grpc") { option("@generated=omit") } } }
    }
    }
  4. Declare io.grpc:grpc-protobuf and io.grpc:grpc-stub as api dependencies, so consumers get what the generated code needs.

  5. Consumers, the service itself included, depend on the contract project. They never copy its files.

  • The service is the only one that will ever use the contract: the .proto files can live in the service’s own src/main/proto, as in a project of one service from start.pyahu.io, whose frontend generates its TypeScript from them. Move them out when the first other service needs them.
  • Clients in other languages need the contract too: they generate their own code from the same files, as gRPC behind a Next.js frontend does for TypeScript.

2. How should I name packages, services and messages?

Section titled “2. How should I name packages, services and messages?”

In short: follow Buf’s style guide and let buf lint enforce it: a versioned package such as shop.orders.v1, folders that match it, and a request and a response message of its own for every method.

rpc GetOrder(GetOrderRequest) returns (GetOrderResponse);

Names in Protocol Buffers are global. Two teams that both define Order in a package called orders cannot be compiled together. A version at the end of the package, v1, leaves room for a v2 that lives next to it.

A method that returns Order directly, or google.protobuf.Empty, has no room to grow: to add a field to the answer you need a new method. A GetOrderResponse that wraps the order can take new fields at any time. Google’s API guidelines return the resource itself from Get; Buf’s default lint rules ask for the wrapper. We follow Buf, because the wrapper never forces a new method.

  1. Name the package <company or product>.<service>.v1, all lower case, and put the files in the matching folder: src/main/proto/shop/orders/v1/order_service.proto.

  2. Set the Java options Google’s guidelines ask for:

    option java_multiple_files = true;
    option java_outer_classname = "OrderServiceProto";
    option java_package = "com.example.shop.api.orders.v1";
  3. Name the service OrderService and give every method its own <Method>Request and <Method>Response.

  4. Add a buf.yaml that checks the folder with Buf’s default rules:

    version: v2
    modules:
    - path: src/main/proto
    lint:
    use: [STANDARD]
    breaking:
    use: [FILE]
  5. Run buf lint and buf format -d --exit-code in CI. The format is fixed, so nobody argues about it.

  • You follow Google’s API guidelines to the letter, for example to publish on Google Cloud: return the resource from Get, Create and Update, and exclude RPC_RESPONSE_STANDARD_NAME and RPC_REQUEST_RESPONSE_UNIQUE in buf.yaml.
  • An older contract that breaks the rules already: fix new files first, and list the old ones under ignore in buf.yaml until they move to a new version.

3. How do I declare fields that can change later?

Section titled “3. How do I declare fields that can change later?”

In short: write proto3, mark a field optional when “not set” must differ from zero, start every enum with an _UNSPECIFIED value and use the well known types for time.

enum OrderStatus {
ORDER_STATUS_UNSPECIFIED = 0;
ORDER_STATUS_PLACED = 1;
}

A plain proto3 field cannot tell “zero” from “not sent”: a discount of 0 and no discount look the same. optional adds presence, so the Java code gets a hasDiscount() method. The Protocol Buffers team recommends optional unless you have a reason not to.

An enum’s first value is what a client sees when the field is not set. If that value means something real, such as PLACED, a client cannot tell a placed order from a missing status. A value the client does not know yet is not turned into it: the number is kept, and Java’s getter returns UNRECOGNIZED.

Editions are the successor of proto2 and proto3; the latest is 2024, and protoc and Buf support it. Google’s API guidelines still require proto3, and Buf said in 2024 it would stay with proto3 for now, so new contracts start there.

  1. Start every file with syntax = "proto3";.
  2. Mark a scalar field optional when its zero value is a valid answer, such as a quantity or a discount.
  3. Give every enum a first value <ENUM>_UNSPECIFIED = 0 and prefix every value with the enum name. In a switch on an enum, handle UNRECOGNIZED and the unspecified value, so a new value does not crash old code.
  4. Use google.protobuf.Timestamp for points in time and google.protobuf.Duration for lengths of time.
  5. Give fields numbers in order and keep 1 to 15, which take one byte on the wire, for the fields sent most often.
  • You need a feature only editions have, such as closed enums in a contract that used to be proto2: use edition = "2024" and check that every client’s generator supports it.
  • A field holds money: a google.type.Money, or an integer of the smallest unit with the currency next to it, never a double.

4. How do I shape list, update and create methods?

Section titled “4. How do I shape list, update and create methods?”

In short: follow Google’s API guidelines: lists are paged from the first version, updates take a field mask and creates take a request_id so they can be retried.

message ListOrdersRequest {
int32 page_size = 1;
string page_token = 2;
}

A list without paging returns everything. It works in testing and then returns 40,000 orders in production, and Google’s guidelines warn that adding paging later breaks existing clients.

An update that takes the whole resource overwrites fields the client did not mean to touch, including fields added after the client was built. A field mask names the fields to change.

A create that times out leaves the client unsure whether it worked. If it sends again, the order may exist twice. A request_id chosen by the client lets the server recognise the second attempt and return the first answer.

  1. Prefer the standard methods Get, List, Create, Update and Delete over custom ones.
  2. Give every list page_size and page_token, and its response next_page_token, empty on the last page. Cap page_size on the server and reject a negative one with INVALID_ARGUMENT.
  3. Give every update a google.protobuf.FieldMask update_mask and change only the fields it names.
  4. Give every create a string request_id, a UUID the client sets. Store it with the result and return the stored result when the same id comes back.
  • A list that can never grow past a few dozen items, such as the countries you ship to: a plain list is fine, but add paging if there is any doubt.
  • Work that takes more than a few seconds: Google’s guidelines return a google.longrunning.Operation that the client polls. It needs the operation_info annotation, the Operations service, and lint exceptions above each of those methods, // buf:lint:ignore RPC_RESPONSE_STANDARD_NAME and // buf:lint:ignore RPC_REQUEST_RESPONSE_UNIQUE, since several methods share one response type.

In short: write the rules in the contract with protovalidate and check every request in one server interceptor, which answers INVALID_ARGUMENT with the list of violations.

string customer_id = 1 [(buf.validate.field).string.uuid = true];

Rules written in Java exist only in the server. Every client learns them by failing. Rules in the .proto file are part of the contract: clients can read them, and the server checks them before your code runs.

protovalidate is Buf’s validation library, with rules written as annotations and in CEL, a small expression language. It replaces protoc-gen-validate, which is archived. The Java library is build.buf:protovalidate; its jar also carries buf/validate/validate.proto, so Gradle can compile the annotations without extra steps.

  1. Add build.buf:protovalidate to the contract project as an api dependency.

  2. Add Buf’s module to buf.yaml, so buf lint also knows the annotations, and run buf dep update:

    deps:
    - buf.build/bufbuild/protovalidate
  3. Annotate the fields: string.uuid, string.min_len, int32.gt, repeated.min_items and the like.

  4. Register one ServerInterceptor that validates each request with a Validator from ValidatorFactory and closes the call with INVALID_ARGUMENT when it fails. Buf publishes a sample interceptor that packs the violations into the error details, the same format Buf’s Connect interceptor uses.

  5. Keep the checks that need the database, such as “this customer exists”, in the use case.

  • A rule depends on state the request does not carry: it belongs in the use case, not the contract.
  • Callers in other languages: protovalidate also has libraries for Go, TypeScript, Python and C++, so they can check a request before they send it.

6. How does a client know which errors to expect?

Section titled “6. How does a client know which errors to expect?”

In short: document, on every method, the status codes and the ErrorInfo reasons it returns. A reason is a constant such as ORDER_ALREADY_SHIPPED, and once published it never changes.

// Errors: NOT_FOUND (ORDER_NOT_FOUND), FAILED_PRECONDITION (ORDER_ALREADY_SHIPPED).
rpc CancelOrder(CancelOrderRequest) returns (CancelOrderResponse);

The status code tells a client what kind of failure happened. The reason tells it which one, so the frontend can show “this order has already shipped” instead of a generic error. Google’s API guidelines put the reason in an ErrorInfo detail, in upper snake case and at most 63 characters, next to a domain that names the service.

A reason that clients match on is part of the contract like a field name: renaming it breaks them, and no tool will notice.

  1. List the codes and reasons in the comment above each method.
  2. Use one domain per service, such as orders.shop.example.com.
  3. Add new reasons when you need them. Never rename or reuse one.
  4. Return them from the server as the gRPC services guide, step 6 shows.
  • An internal method that only one client calls, and that client only needs the code: the reason can wait.
  • Validation errors: their details list the fields (step 5), so they need no reason of their own.

7. How do I change the contract without breaking clients?

Section titled “7. How do I change the contract without breaking clients?”

In short: only add. Never change a type, let buf breaking compare every change with the commit it starts from, and approve a removal on purpose. A change that must break goes into a new v2 package.

Terminal window
buf breaking api --against ".git#ref=$BASE_SHA,subdir=api"

A field travels by its number. Reuse a number or change a field’s type and old clients read the wrong value without any error. Google’s guidelines go further: inside one version, nothing may be removed or renamed, and no type may change, even to one that looks compatible on the wire.

buf breaking knows these rules. Its default, FILE, also protects the generated code, so a renamed message breaks the check even if the bytes would still match. Use it, since consumers compile against the generated Java. It also fails when a field is deleted, even a reserved one: reserved stops a number from being reused, but the Java code that called the field’s getter still stops compiling. When something reads the messages as JSON, such as a browser through Connect or a REST gateway that transcodes, field names travel too: Buf calls WIRE_JSON the minimum then.

  1. Add fields with new numbers. Do not change the type, the number or the name of an existing one.

  2. Mark a field you want gone as deprecated = true, which Java turns into @Deprecated.

  3. Run buf breaking from the repository root, on the contract project, the folder with buf.yaml and buf.lock. Compare with the pull request’s base, or with the commit before the push on main; comparing with main after a push to main compares the change with itself. CI usually checks out one commit, so fetch the base first. In a GitHub Actions step:

    Terminal window
    BASE_SHA=${{ github.event.pull_request.base.sha || github.event.before }}
    git fetch --depth=1 origin "$BASE_SHA"
    buf breaking api --against ".git#ref=$BASE_SHA,subdir=api"
  4. Remove the field only once no client reads it. That change fails the check: approve it explicitly, as the Monorepos guide, step 4 does, and reserve both its number and its name:

    reserved 4;
    reserved "discount_code";
  5. For a change that must break more than that, add shop.orders.v2 next to v1, serve both and remove v1 when its last client has moved.

  • The method is not released yet and has no clients: change it freely until the first release, then follow the rules.
  • On GitHub without a monorepo: Buf’s bufbuild/buf-action runs lint, format and breaking against the pull request’s base in one step.

This is where each step lands. The quoted files are from the monorepo fixture, as start.pyahu.io generates them: the contract project, its buf.yaml, the sample service and the CI checks. Paging, field masks, protovalidate and the error reasons are yours to add as your methods need them.

  • src/main/proto/<package path>/*.proto, proto3, one request and one response per method, enums starting at _UNSPECIFIED (steps 2 and 3).
  • java-library and com.google.protobuf, with protoc and protoc-gen-grpc-java at the versions Boot manages, and grpc-protobuf, grpc-stub and build.buf:protovalidate as api dependencies (steps 1 and 5).
  • buf.yaml with STANDARD lint, FILE breaking and the protovalidate module (steps 2, 5 and 7).
buf.yaml
version: v2
modules:
- path: src/main/proto
lint:
use:
- STANDARD
breaking:
use:
- FILE

See the whole file

ping_service.proto
syntax = "proto3";
package io.pyahu.fixture.billing.v1;
option java_multiple_files = true;
option java_outer_classname = "PingServiceProto";
option java_package = "io.pyahu.fixture.api.billing.v1";
// The sample service of billing: replace it with your first real one (Protobuf contracts guide).
service PingService {
// Answers with pong.
// Errors: UNAUTHENTICATED (no valid token).
rpc Ping(PingRequest) returns (PingResponse);
}
// No fields yet. A request of its own leaves room for them (Protobuf contracts guide, step 2).
message PingRequest {}
message PingResponse {

See the whole file

platform.api.gradle.kts
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:${version("protobuf")}"
}
plugins {
create("grpc") {
artifact = "io.grpc:protoc-gen-grpc-java:${version("grpc")}"
}
}
generateProtoTasks {
all().configureEach {
plugins {
create("grpc") {
option("@generated=omit")
}
}
}
}
}
// The classes protoc writes are not @NullMarked: the build checks handwritten code and the OpenAPI models only.
tasks.withType<JavaCompile>().configureEach {
options.errorprone.excludedPaths = ".*/build/generated/sources?/proto/.*"

See the whole file

Check it: run buf lint on a method that returns its resource directly: it fails and names RPC_RESPONSE_STANDARD_NAME.

  • Paging on every list, a field mask on every update, a request_id on every create (step 4).
  • protovalidate rules on the fields and one validating interceptor in the server (step 5).
  • The codes and reasons each method returns, in its comment (step 6).

Check it: send a create with an invalid UUID: the answer is INVALID_ARGUMENT with the field in the violations, before your code runs.

  • buf lint, buf format -d --exit-code and buf breaking against the commit the change starts from (steps 2 and 7).

Check it: delete a field in a branch: the pull request fails until the removal is approved.

Generated configuration

  • PROTO-01 The .proto files live in one contract project owned by the service; consumers depend on its jar and never copy the files.

    Step 1 · When api: grpc

  • PROTO-02 Packages end in a version such as v1, folders match them, and every method has its own request and response message.

    Step 2 · When api: grpc

Verified behaviour

  • PROTO-03 Every enum starts with an _UNSPECIFIED value; fields whose zero is a valid answer are optional; time uses Timestamp and Duration.

    Step 3 · When api: grpc

  • PROTO-04 Every list is paged with page_size and page_token, every update takes an update_mask and every create a request_id.

    Step 4 · When api: grpc

  • PROTO-05 Field rules are protovalidate annotations, checked by one server interceptor that answers INVALID_ARGUMENT with the violations.

    Step 5 · When api: grpc

  • PROTO-06 Each method's comment lists the status codes and ErrorInfo reasons it returns; no published reason is renamed or reused.

    Step 6 · When api: grpc

  • PROTO-07 Deleted fields have their numbers and names reserved; a breaking change goes into a new versioned package served next to the old one.

    Step 7 · When api: grpc

Official documentation

The full list is on Reference docs.