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")) }What’s going on
Section titled “What’s going on”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.
Do this
Section titled “Do this”-
Give the service a contract project, a small Java library next to it. In a monorepo it is
verticals/<vertical>/api/(Monorepos, step 4). -
Put the files under
src/main/proto, in folders that match their package (step 2). -
Apply
java-libraryandcom.google.protobufthere, 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") } } }}} -
Declare
io.grpc:grpc-protobufandio.grpc:grpc-stubasapidependencies, so consumers get what the generated code needs. -
Consumers, the service itself included, depend on the contract project. They never copy its files.
When this is not for you
Section titled “When this is not for you”- The service is the only one that will ever use the contract: the
.protofiles can live in the service’s ownsrc/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);What’s going on
Section titled “What’s going on”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.
Do this
Section titled “Do this”-
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. -
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"; -
Name the service
OrderServiceand give every method its own<Method>Requestand<Method>Response. -
Add a
buf.yamlthat checks the folder with Buf’s default rules:version: v2modules:- path: src/main/protolint:use: [STANDARD]breaking:use: [FILE] -
Run
buf lintandbuf format -d --exit-codein CI. The format is fixed, so nobody argues about it.
When this is not for you
Section titled “When this is not for you”- You follow Google’s API guidelines to the letter, for example to publish on Google Cloud: return the resource
from
Get,CreateandUpdate, and excludeRPC_RESPONSE_STANDARD_NAMEandRPC_REQUEST_RESPONSE_UNIQUEinbuf.yaml. - An older contract that breaks the rules already: fix new files first, and list the old ones under
ignoreinbuf.yamluntil 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;}What’s going on
Section titled “What’s going on”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.
Do this
Section titled “Do this”- Start every file with
syntax = "proto3";. - Mark a scalar field
optionalwhen its zero value is a valid answer, such as a quantity or a discount. - Give every enum a first value
<ENUM>_UNSPECIFIED = 0and prefix every value with the enum name. In aswitchon an enum, handleUNRECOGNIZEDand the unspecified value, so a new value does not crash old code. - Use
google.protobuf.Timestampfor points in time andgoogle.protobuf.Durationfor lengths of time. - Give fields numbers in order and keep 1 to 15, which take one byte on the wire, for the fields sent most often.
When this is not for you
Section titled “When this is not for you”- You need a feature only editions have, such as closed enums in a contract that used to be
proto2: useedition = "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 adouble.
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;}What’s going on
Section titled “What’s going on”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.
Do this
Section titled “Do this”- Prefer the standard methods
Get,List,Create,UpdateandDeleteover custom ones. - Give every list
page_sizeandpage_token, and its responsenext_page_token, empty on the last page. Cappage_sizeon the server and reject a negative one withINVALID_ARGUMENT. - Give every update a
google.protobuf.FieldMask update_maskand change only the fields it names. - 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.
When this is not for you
Section titled “When this is not for you”- 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.Operationthat the client polls. It needs theoperation_infoannotation, theOperationsservice, and lint exceptions above each of those methods,// buf:lint:ignore RPC_RESPONSE_STANDARD_NAMEand// buf:lint:ignore RPC_REQUEST_RESPONSE_UNIQUE, since several methods share one response type.
5. How do I reject bad input?
Section titled “5. How do I reject bad input?”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];What’s going on
Section titled “What’s going on”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.
Do this
Section titled “Do this”-
Add
build.buf:protovalidateto the contract project as anapidependency. -
Add Buf’s module to
buf.yaml, sobuf lintalso knows the annotations, and runbuf dep update:deps:- buf.build/bufbuild/protovalidate -
Annotate the fields:
string.uuid,string.min_len,int32.gt,repeated.min_itemsand the like. -
Register one
ServerInterceptorthat validates each request with aValidatorfromValidatorFactoryand closes the call withINVALID_ARGUMENTwhen it fails. Buf publishes a sample interceptor that packs the violations into the error details, the same format Buf’s Connect interceptor uses. -
Keep the checks that need the database, such as “this customer exists”, in the use case.
When this is not for you
Section titled “When this is not for you”- 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);What’s going on
Section titled “What’s going on”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.
Do this
Section titled “Do this”- List the codes and reasons in the comment above each method.
- Use one
domainper service, such asorders.shop.example.com. - Add new reasons when you need them. Never rename or reuse one.
- Return them from the server as the gRPC services guide, step 6 shows.
When this is not for you
Section titled “When this is not for you”- 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.
buf breaking api --against ".git#ref=$BASE_SHA,subdir=api"What’s going on
Section titled “What’s going on”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.
Do this
Section titled “Do this”-
Add fields with new numbers. Do not change the type, the number or the name of an existing one.
-
Mark a field you want gone as
deprecated = true, which Java turns into@Deprecated. -
Run
buf breakingfrom the repository root, on the contract project, the folder withbuf.yamlandbuf.lock. Compare with the pull request’s base, or with the commit before the push onmain; comparing withmainafter a push tomaincompares 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" -
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"; -
For a change that must break more than that, add
shop.orders.v2next tov1, serve both and removev1when its last client has moved.
When this is not for you
Section titled “When this is not for you”- 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-actionruns lint, format and breaking against the pull request’s base in one step.
Put it all together
Section titled “Put it all together”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.
In the contract project
Section titled “In the contract project”src/main/proto/<package path>/*.proto,proto3, one request and one response per method, enums starting at_UNSPECIFIED(steps 2 and 3).java-libraryandcom.google.protobuf, withprotocandprotoc-gen-grpc-javaat the versions Boot manages, andgrpc-protobuf,grpc-stubandbuild.buf:protovalidateasapidependencies (steps 1 and 5).buf.yamlwithSTANDARDlint,FILEbreaking and the protovalidate module (steps 2, 5 and 7).
version: v2modules: - path: src/main/protolint: use: - STANDARDbreaking: use: - FILEsyntax = "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 {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/.*"Check it: run buf lint on a method that returns its resource directly: it fails and names
RPC_RESPONSE_STANDARD_NAME.
In the methods
Section titled “In the methods”- Paging on every list, a field mask on every update, a
request_idon 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-codeandbuf breakingagainst 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.
Checklist
Section titled “Checklist”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.
PROTO-02 Packages end in a version such as v1, folders match them, and every method has its own request and response message.
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.
PROTO-04 Every list is paged with page_size and page_token, every update takes an update_mask and every create a request_id.
PROTO-05 Field rules are protovalidate annotations, checked by one server interceptor that answers INVALID_ARGUMENT with the violations.
PROTO-06 Each method's comment lists the status codes and ErrorInfo reasons it returns; no published reason is renamed or reused.
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.
References
Section titled “References”Official documentation
The full list is on Reference docs.
- Proto3 language guide (not in the baseline yet). Proto3 language guide: field numbers, reserved, enums, deprecated fields.
- Proto best practices (dos and don'ts) (not in the baseline yet). Proto best practices (dos and don'ts): never reuse a tag, reserve deleted fields, UNSPECIFIED zero values.
- Google API design guide (not in the baseline yet). How Google designs APIs in Protocol Buffers and serves JSON over HTTP from the same contract.
- Spring Boot Gradle plugin: reacting to the Protobuf plugin (not in the baseline yet). How the Boot plugin sets protoc and protoc-gen-grpc-java to the versions on the classpath.
- Spring Boot 4.2 managed dependency coordinates (not in the baseline yet). The versions Boot 4.2 manages: gRPC Java 1.84.1, Protocol Buffers 4.36.2, Spring gRPC 1.1.2.
- AIP-193: errors (not in the baseline yet). Errors as google.rpc.Status with an ErrorInfo reason and domain on every error.
- Buf style guide (not in the baseline yet). Package versions, folder layout, one request and response per method, no Empty, avoid streaming.
- Buf lint rules and categories (not in the baseline yet). What the STANDARD lint category enforces, rule by rule.
- Buf breaking change rules (not in the baseline yet). FILE, PACKAGE, WIRE_JSON and WIRE, and which to use when JSON is read.
- buf.yaml v2 configuration (not in the baseline yet). Modules, deps, lint and breaking settings of a Buf workspace.
- buf format (not in the baseline yet). The fixed Protobuf format and how to check it in CI.
- Buf GitHub Action (not in the baseline yet). bufbuild/buf-action: lint, format and breaking checks against the pull request base.
- Buf inputs (not in the baseline yet). The .git#branch=main,subdir=... input used to compare with the main branch.
- Protobuf Gradle plugin (not in the baseline yet). Code generation in Gradle; .proto files packaged in the jar and imported, not compiled, by consumers.
- Protobuf field presence (not in the baseline yet). Why proto3 fields cannot tell zero from unset and when to use optional.
- Protobuf editions overview (not in the baseline yet). Editions, the successor of proto2 and proto3, and the latest released edition.
- Buf: Protobuf editions are here (not in the baseline yet). Buf on editions and on staying with proto3 for now (2024).
- Protobuf style guide (not in the baseline yet). Naming of files, messages, fields and enums from the Protocol Buffers team.
- ProtoJSON format (not in the baseline yet). How messages map to JSON: field names, int64 as strings, enum names.
- AIP-191: file and directory structure (not in the baseline yet). proto3 syntax, versioned packages, matching folders and the Java options.
- AIP-121: resource-oriented design (not in the baseline yet). Standard methods before custom ones.
- AIP-131: standard methods, Get (not in the baseline yet). Google returns the resource itself from Get; the contract guide explains why it follows Buf instead.
- AIP-158: pagination (not in the baseline yet). page_size, page_token and next_page_token, and why adding paging later breaks clients.
- AIP-134: standard methods, Update (not in the baseline yet). Updates with a FieldMask update_mask.
- AIP-155: request identification (not in the baseline yet). A client-chosen request_id that makes a create safe to retry.
- AIP-151: long-running operations (not in the baseline yet). Return an Operation for work that takes more than a few seconds.
- AIP-180: backwards compatibility (not in the baseline yet). What breaks a client inside one major version: removing, renaming, changing types.
- AIP-185: API versioning (not in the baseline yet). The major version in the package, and v2 next to v1 for a breaking change.
- protovalidate-java (not in the baseline yet). The Java protovalidate library, build.buf:protovalidate.
- protovalidate quickstart for gRPC Java (not in the baseline yet). Annotations, the buf.yaml dependency and Buf's sample validating ServerInterceptor.
- protoc-gen-validate (archived) (not in the baseline yet). The archived predecessor of protovalidate.