> Every Pyahu Initializer guide: https://initializer.pyahu.io/llms.txt. Every Pyahu Community project: https://pyahu.io/llms.txt.

# Protobuf contracts

Write the .proto contract of a gRPC service so it stays readable, validates its input and can change for years without breaking a client.

On the web: https://initializer.pyahu.io/guides/protobuf-contracts/. Written for baseline v0.1-b10: Java 25, Spring Boot 4.2.0.

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.

## What you'll learn

1. Where do the .proto files live and who compiles them?
2. How should I name packages, services and messages?
3. How do I declare fields that can change later?
4. How do I shape list, update and create methods?
5. How do I reject bad input?
6. How does a client know which errors to expect?
7. How do I change the contract without breaking clients?

## 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.

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

### 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

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](https://initializer.pyahu.io/guides/monorepo/#mono-contracts)).
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:

   ```kotlin
   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.

### When this is not for you

- 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](https://initializer.pyahu.io/guides/grpc-frontend/#gweb-codegen) does for TypeScript.

## 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.

```proto
rpc GetOrder(GetOrderRequest) returns (GetOrderResponse);
```

### 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

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:

   ```proto
   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:

   ```yaml
   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.

### 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`, `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?

**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.

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

### 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

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.

### 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`: 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?

**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.

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

### 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

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.
### 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.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.

## 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.

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

### 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

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`:

   ```yaml
   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.

### 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?

**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.

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

### 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

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](https://initializer.pyahu.io/guides/grpc/#grpc-status) shows.

### 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?

**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.

```sh
buf breaking api --against ".git#ref=$BASE_SHA,subdir=api"
```

### 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

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:

   ```sh
   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](https://initializer.pyahu.io/guides/monorepo/#mono-contracts) does, and reserve both its number and its name:

   ```proto
   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.

### 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-action` runs lint, format and breaking against the pull
  request's base in one step.

## 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

- `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).

From [`buf.yaml`](https://github.com/pyahu/initializer/blob/main/fixtures/monorepo/verticals/billing/api/buf.yaml):

```yaml
version: v2
modules:
  - path: src/main/proto
lint:
  use:
    - STANDARD
breaking:
  use:
    - FILE
```

From [`ping_service.proto`](https://github.com/pyahu/initializer/blob/main/fixtures/monorepo/verticals/billing/api/src/main/proto/io/pyahu/fixture/billing/v1/ping_service.proto):

```protobuf
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 {
```

From [`platform.api.gradle.kts`](https://github.com/pyahu/initializer/blob/main/fixtures/monorepo/build-logic/src/main/kotlin/platform.api.gradle.kts):

```kotlin
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

- 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.

### In CI

- `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.

## 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. (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)

## References

- [Proto3 language guide](https://protobuf.dev/programming-guides/proto3/) (not in the baseline yet): Proto3 language guide: field numbers, reserved, enums, deprecated fields.
- [Proto best practices (dos and don'ts)](https://protobuf.dev/best-practices/dos-donts/) (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](https://docs.cloud.google.com/apis/design/) (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](https://docs.spring.io/spring-boot/4.2/gradle-plugin/reacting.html) (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](https://docs.spring.io/spring-boot/4.2/appendix/dependency-versions/coordinates.html) (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](https://google.aip.dev/193) (not in the baseline yet): Errors as google.rpc.Status with an ErrorInfo reason and domain on every error.
- [Buf style guide](https://buf.build/docs/best-practices/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](https://buf.build/docs/lint/rules/) (not in the baseline yet): What the STANDARD lint category enforces, rule by rule.
- [Buf breaking change rules](https://buf.build/docs/breaking/rules/) (not in the baseline yet): FILE, PACKAGE, WIRE_JSON and WIRE, and which to use when JSON is read.
- [buf.yaml v2 configuration](https://buf.build/docs/configuration/v2/buf-yaml/) (not in the baseline yet): Modules, deps, lint and breaking settings of a Buf workspace.
- [buf format](https://buf.build/docs/format/) (not in the baseline yet): The fixed Protobuf format and how to check it in CI.
- [Buf GitHub Action](https://buf.build/docs/bsr/ci-cd/github-actions/) (not in the baseline yet): bufbuild/buf-action: lint, format and breaking checks against the pull request base.
- [Buf inputs](https://buf.build/docs/reference/inputs/) (not in the baseline yet): The .git#branch=main,subdir=... input used to compare with the main branch.
- [Protobuf Gradle plugin](https://github.com/google/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](https://protobuf.dev/programming-guides/field_presence/) (not in the baseline yet): Why proto3 fields cannot tell zero from unset and when to use optional.
- [Protobuf editions overview](https://protobuf.dev/editions/overview/) (not in the baseline yet): Editions, the successor of proto2 and proto3, and the latest released edition.
- [Buf: Protobuf editions are here](https://buf.build/blog/protobuf-editions-are-here) (not in the baseline yet): Buf on editions and on staying with proto3 for now (2024).
- [Protobuf style guide](https://protobuf.dev/programming-guides/style/) (not in the baseline yet): Naming of files, messages, fields and enums from the Protocol Buffers team.
- [ProtoJSON format](https://protobuf.dev/programming-guides/json/) (not in the baseline yet): How messages map to JSON: field names, int64 as strings, enum names.
- [AIP-191: file and directory structure](https://google.aip.dev/191) (not in the baseline yet): proto3 syntax, versioned packages, matching folders and the Java options.
- [AIP-121: resource-oriented design](https://google.aip.dev/121) (not in the baseline yet): Standard methods before custom ones.
- [AIP-131: standard methods, Get](https://google.aip.dev/131) (not in the baseline yet): Google returns the resource itself from Get; the contract guide explains why it follows Buf instead.
- [AIP-158: pagination](https://google.aip.dev/158) (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](https://google.aip.dev/134) (not in the baseline yet): Updates with a FieldMask update_mask.
- [AIP-155: request identification](https://google.aip.dev/155) (not in the baseline yet): A client-chosen request_id that makes a create safe to retry.
- [AIP-151: long-running operations](https://google.aip.dev/151) (not in the baseline yet): Return an Operation for work that takes more than a few seconds.
- [AIP-180: backwards compatibility](https://google.aip.dev/180) (not in the baseline yet): What breaks a client inside one major version: removing, renaming, changing types.
- [AIP-185: API versioning](https://google.aip.dev/185) (not in the baseline yet): The major version in the package, and v2 next to v1 for a breaking change.
- [protovalidate-java](https://github.com/bufbuild/protovalidate-java) (not in the baseline yet): The Java protovalidate library, build.buf:protovalidate.
- [protovalidate quickstart for gRPC Java](https://protovalidate.com/quickstart/grpc-java/) (not in the baseline yet): Annotations, the buf.yaml dependency and Buf's sample validating ServerInterceptor.
- [protoc-gen-validate (archived)](https://github.com/bufbuild/protoc-gen-validate) (not in the baseline yet): The archived predecessor of protovalidate.
