Skip to content

    System Design

    gRPC and Protobuf: Contracts, Status Codes and Schema Evolution

    Write a gRPC contract in Protobuf, set deadlines, return the right status codes and change a schema safely, with output captured from an in-process Java lab.

    By Published 13 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: REST, gRPC, GraphQL and WebSockets: Choosing an API Style

    What you'll learn: By the end of this lesson you will be able to turn a .proto contract into a working gRPC server and client in Java, choose the status code a caller should see for each kind of failure, set a deadline and say what the server must do when it passes, read Protobuf bytes by hand (tag, wire type, payload), and apply the field-number rules that decide whether a schema change is safe, using captured output that shows what each mistake does.

    A cloakroom hands you a numbered ticket. The venue may repaint the hooks, rename the rows or move the whole rack, and ticket 7 still returns your coat. But if the venue reuses ticket 7 for a new guest's coat while an old ticket 7 is still in someone's pocket, the wrong coat comes back, and nobody sees an error. Protobuf field numbers are those tickets, and gRPC is the counter that hands things over.

    The API styles lesson compares gRPC with REST, GraphQL and WebSockets. This lesson goes deeper on gRPC and Protobuf itself: the contract, status codes, deadlines and cancellation, and schema-evolution rules, each checked by running Java.

    Verified with grpc-java 1.84.1 and protobuf-java 4.36.2 (the versions Spring Boot 4.1.2 manages), compiled with --release 25 and run on a JDK 27, against the Protocol Buffers and gRPC documentation, on 2026-12-01.

    The core idea

    gRPC is a contract (a .proto file), code generated from it, and a call model with two failure vocabularies: a status code and a deadline. Protobuf is the contract's encoding, and its main rule is that a field's number, not its name, is its identity.

    Three illustrations run through the lesson: a minimal example (one GetOrder call and its failures, in process), a realistic example (ShopStream adds a currency while three callers deploy independently, in "In practice") and a failure example (a reused field number silently misreads old data).

    From a .proto file to a call

    The core concepts page says "By default, gRPC uses protocol buffers as the Interface Definition Language (IDL)" and lists four kinds of call: unary, server streaming, client streaming and bidirectional streaming. This lesson uses unary calls. The Java basics page says the code comes from the protocol buffer compiler protoc with a special gRPC Java plugin, and that a Gradle or Maven build plugin can run it as part of the build. The generated OrderServiceGrpc class holds a base class for servers and the client stubs.

    service OrderService {
      rpc GetOrder(GetOrderRequest) returns (Order);
      rpc CancelOrder(CancelOrderRequest) returns (CancelOrderReply);
    }
    
    message GetOrderRequest {
      string order_id = 1;
    }
    
    message Order {
      string order_id = 1;
      string status = 2;
      int64 total_minor = 3;
    }

    A server extends the generated base class and answers through a StreamObserver: onNext() sends the reply and onCompleted() ends the call (or onError() ends it with a failure). A client builds a channel and a stub, blocking or non-blocking. Stub configuration is immutable: changing it, in the AbstractStub Javadoc's words, "returns a new stub with updated configuration".

    Figure 1. From contract to call. How to read this: the top row happens at build time and the bottom row at run time. The contract is the only thing the two sides share; each side gets its own generated code from it.

    A .proto file is compiled into generated code that the client stub and the server base class both useorders.proto to protoc (reads); protoc to Generated code (writes); Generated code to Client stub (used by); Client stub to Order service (gRPC call)BUILD TIMERUN TIMEorders.proto: the contractorders.protothe contractprotoc: and gRPC pluginprotocand gRPC pluginGenerated code: messages, stubsGenerated codemessages, stubsClient stub: blockingClient stubblockingOrder service: extends base classOrder serviceextends baseclassreadswritesused bygRPC call

    For tests, grpc-java can run the whole call path inside one JVM. The InProcessServerBuilder Javadoc describes "a server that services in-process requests. Clients identify the in-process server by its name." The lab builds both ends from a name and no port:

    server = InProcessServerBuilder.forName(name).addService(service).build().start();
    channel = InProcessChannelBuilder.forName(name).build();
    stub = OrderServiceGrpc.newBlockingStub(channel);

    What the caller sees: status codes

    The error handling guide says a failed call returns one of the gRPC status codes and an optional string message; with a blocking stub, Java raises a StatusRuntimeException carrying the Status. The status codes page lists 17 codes and says the libraries never generate seven of them: INVALID_ARGUMENT, NOT_FOUND, ALREADY_EXISTS, FAILED_PRECONDITION, ABORTED, OUT_OF_RANGE and DATA_LOSS. Those are the application's to choose, which is why they carry meaning.

    Code Number The page's meaning, shortened A caller's usual reaction
    INVALID_ARGUMENT 3 The request is invalid regardless of system state Fix the request
    NOT_FOUND 5 A requested entity was not found A normal "no"
    FAILED_PRECONDITION 9 The system is not in a state the operation needs Retry only after the state is fixed
    ABORTED 10 Aborted, typically a concurrency issue Retry at a higher level
    UNAVAILABLE 14 Currently unavailable, usually transient Retry with backoff; not always safe for non-idempotent calls
    UNIMPLEMENTED 12 Not implemented or not enabled in this service Do not retry
    flowchart TD accTitle: Choosing a gRPC status code for a server-side failure accDescr: A decision flow. If the request itself is wrong, return INVALID_ARGUMENT. If the thing asked for does not exist, NOT_FOUND. If the request is fine but the system is in the wrong state, FAILED_PRECONDITION. If a concurrent change caused the failure and the caller can retry, ABORTED. If the service or a dependency is temporarily unable to answer, UNAVAILABLE. Anything else is a bug, which the caller sees as UNKNOWN. S["The server cannot do what was asked"] --> A{"Is the request itself wrong?"} A -->|"yes"| IA["INVALID_ARGUMENT"] A -->|"no"| B{"Does the thing asked for exist?"} B -->|"no"| NF["NOT_FOUND"] B -->|"yes"| C{"Is the system in the wrong state for it?"} C -->|"yes"| FP["FAILED_PRECONDITION"] C -->|"no"| D{"Did a concurrent change cause it?"} D -->|"yes"| AB["ABORTED"] D -->|"no"| E{"Is the service or a dependency temporarily down?"} E -->|"yes"| UA["UNAVAILABLE"] E -->|"no"| UK["A bug: the caller sees UNKNOWN"]

    Figure 2. Picking a code at the server. How to read this: each question separates a different caller reaction. A code is only useful if a retry policy or a monitor can act on it, so choose by what the caller should do next.

    Deadlines and cancellation

    The deadlines guide says "By default, gRPC does not set a deadline" and "you should always explicitly set a realistic deadline in your clients". The core concepts page says that when the deadline passes, the RPC ends with DEADLINE_EXCEEDED, and that "both the client and server make independent and local determinations of the success of the call": one side can finish successfully while the other records a failure. The same page says either side can cancel at any time and "Changes made before a cancellation are not rolled back."

    So a deadline ends the client's wait; it does not undo the server's work. The deadlines guide says the server "is responsible for stopping any activity it has spawned to service the RPC". In Java, a handler sees this through ServerCallStreamObserver: isCancelled() returns true when "the server is encouraged to abort processing to save resources", and setOnCancelHandler registers code to run. The Javadoc says exactly one of the close handler and the cancel handler is called when the call ends.

    sequenceDiagram accTitle: A gRPC call that passes its deadline accDescr: The client sets a deadline on its stub and calls the server. The server's handler starts work and does not answer in time. The client ends the call with DEADLINE_EXCEEDED. The server is told the call was cancelled and must stop the work it started, and anything it changed before that is not rolled back. participant C as Client stub participant S as Server handler C->>S: GetOrder, deadline 500 ms Note over S: starts work Note over C: deadline passes C-->>C: DEADLINE_EXCEEDED C--xS: call cancelled Note over S: cancel handler runs, stop the work

    Figure 3. A call that passes its deadline. How to read this: the client's failure is immediate and local. The server learns about it as a cancellation and has to stop its own work; writes it already made stay.

    The guide adds that propagating a deadline from an incoming call to an outgoing one is enabled by default in Java and Go and explicit in C++, so a service should know which its language gives it.

    What is on the wire

    The encoding guide says each field becomes a record of "the field number, a wire type and a payload", with a tag of (field_number << 3) | wire_type. Wire type 0 is a varint (ints, bools, enums), 2 is length-delimited (strings, bytes, sub-messages) and the guide's example is a field 1 set to 150, encoded as 08 96 01. The wire type tells a parser how big a payload is, so old parsers can skip fields they do not understand. For a scalar that appears more than once, the parser keeps the last value. Field order in the .proto file has no effect on serialization.

    The proto3 guide says a number must be between 1 and 536,870,911, must be unique in the message, that 19,000 to 19,999 are reserved for the implementation, and that "field numbers in the range 1 through 15 take one byte to encode", so the most frequently set fields should use them. It also says the number cannot change once the type is in use, and "Field numbers should never be reused."

    Evolving a schema

    The proto3 guide's "Updating A Message Type" section is short. "Adding new fields is safe." "Removing fields is safe", provided the same number is never used again. "Changing field numbers for any existing field is not safe." Some type changes are compatible (int32, uint32, int64, uint64 and bool among themselves, with truncation as in a C++ cast) if the rollout is carefully managed. The Dos and Don'ts page adds: never reuse a tag number, reserve the number and name of a deleted field, and "Almost never change the type of a field". Reserved names affect only protoc, not runtime behaviour.

    For readers that have not been upgraded, the guide says "Proto3 messages preserve unknown fields and include them during parsing and in the serialized output", and a missing scalar reads as its default (empty string, zero, false). With optional, a field also tracks whether it was set; without it "you cannot determine whether the default (zero) value was set". Unknown enum values are preserved, and in Java "a case in the enum is used to represent an unrecognized value".

    flowchart TD accTitle: Is this Protobuf schema change safe? accDescr: A decision flow. Adding a field or an enum value is safe, but readers must tolerate defaults and unknown values. Removing a field is safe only if its number and name are reserved. Renumbering, or reusing a number for a different field, is never safe. Changing a type is safe only inside the documented compatible groups and needs a managed rollout. C["A change to a message"] --> K{"What kind of change?"} K -->|"add a field or enum value"| ADD["Safe: old readers keep it as unknown,
    new readers see defaults for old data"] K -->|"remove a field"| REM{"Number and name reserved?"} REM -->|"yes"| OK["Safe"] REM -->|"no"| BAD1["Unsafe: the number can be reused later"] K -->|"renumber, or reuse a number"| BAD2["Never safe: no error, wrong data"] K -->|"change a type"| T{"Inside a documented compatible group?"} T -->|"yes"| MG["Possible, with a managed rollout
    and a check for truncation"] T -->|"no"| BAD3["Unsafe"]

    Figure 4. A first test for any schema edit. How to read this: the safe branches end in a condition (reserve it, roll it out carefully). The unsafe branches are the ones that fail silently, which is why they need a review rule and a test.

    Build it: one contract, six calls, six edits

    This is the minimal example you can run, with no Docker and no network port. The gRPC server and channel are in-process; no Spring application context is started, so the lab uses plain grpc-java (the Spring labs build only supplies the pinned versions).

    Setup. From the repository's examples/spring-labs folder:

    ./gradlew :labs:grpc-protobuf:test

    It runs 18 tests, including a golden-file comparison; the first build downloads protoc and the gRPC plugin from Maven Central. Under src/main/proto/, orders/orders.proto is the service and evolution/v1, v2, reuse, renumber and narrow are changed copies of one Order message, each in its own proto package (names do not travel, so they stand for versions of one message).

    How it works. CancelOrder is declared but not overridden, so the generated base class answers it. Order o_slow never answers; its handler only registers for cancellation. Evolution writes bytes with one generated class and parses them with another.

    Expected output, captured from a real run (grpc-java 1.84.1, protobuf-java 4.36.2, 2026-12-01), part 1:

    Part 1. gRPC Java, in-process server and channel (no network port). What the caller sees.
    
    1  GetOrder("o_123")                                 OK                 reply: order_id: "o_123" status: "PAID" total_minor: 150 description: (none)
    2  GetOrder("o_404")                                 NOT_FOUND          description: order o_404 not found
    3  GetOrder("")                                      INVALID_ARGUMENT   description: order_id must not be blank
    4  GetOrder("o_boom") server throws                  UNKNOWN            description: Application error processing RPC
    5  CancelOrder("o_123") not implemented              UNIMPLEMENTED      description: Method shopstream.orders.v1.OrderService/CancelOrder is unimplemented
    
    Deadlines
      default stub deadline: null
      stub.withDeadlineAfter(500 ms) has a deadline: true, the original stub still has none: true
    6  GetOrder("o_slow") with a 500 ms deadline         DEADLINE_EXCEEDED  description: (varies: it includes the elapsed time)
       the server was told the call was cancelled: true
    Row What it shows
    2, 3 The server's own choices, each with the description it attached.
    4 An exception on the server reaches the caller as UNKNOWN with a generic description, not the exception text; the Status Javadoc adds that a cause "is not transmitted from server to client".
    5 UNIMPLEMENTED, from the generated base class for a method the server does not override.
    6 A stub has no deadline until one is set. The slow call ends with DEADLINE_EXCEEDED and the server is told it was cancelled.

    Expected output, captured from a real run (the same run), part 2:

    Part 2. Protobuf schema evolution: bytes written by one schema, read by another.
    
    v1 writes order_id="o_123" status=PAID total_minor=150 coupon="SAVE5"
      bytes (19): 0a056f5f313233100218960122055341564535
      0a = field 1, length-delimited; 10 = field 2, varint; 18 = field 3, varint; 22 = field 4, length-delimited
    
    A  v1 bytes read by v2 (new reader, old data; v2 added currency and reserved 4)
       order_id=o_123 status=STATUS_PAID total_minor=150 hasCurrency=false currency=""
       unknown field numbers kept: [4]; re-serialised bytes identical to the input: true
    B  v2 bytes read by v1 (old reader, new data; v2 wrote currency="EUR" and status=SHIPPED)
       bytes (17): 0a056f5f31323410031896012a03455552
       order_id=o_124 status=UNRECOGNIZED statusValue=3 coupon=""
       unknown field numbers kept: [5]; re-serialised bytes identical to the input: true
    C  v1 bytes read by a schema that REUSED number 4 for `string region`
       region="SAVE5" (the old coupon, read as a region; no error)
    D  v1 bytes read by a schema that RENUMBERED status from 2 to 6
       status=STATUS_UNSPECIFIED unknown field numbers kept: [2] (the status the writer sent is not read as status)
    E  int64 total_minor=5000000000 read as int32 (a type change the guide lists as compatible)
       total_minor=705032704 (truncated to 32 bits, no error)
    F  empty message read as v2 (missing scalar fields read as defaults)
       order_id="" total_minor=0 status=STATUS_UNSPECIFIED hasCurrency=false
       currency set to "" on purpose: hasCurrency=true, serialised size 2 bytes; unset: 0 bytes
    Row What it shows
    A New reader, old data: the new field reads as its default (and optional shows it was unset); the removed field's bytes are kept as unknown field 4 and written back unchanged.
    B Old reader, new data: the new field survives as unknown field 5, the new enum value reads as UNRECOGNIZED but keeps number 3, and the bytes round-trip.
    C Number 4 reused for a string: the old coupon SAVE5 is read as a region, with no error.
    D status renumbered from 2 to 6: the old value is lost, with no error.
    E int64 read as int32: 5000000000 becomes 705032704, as a cast would.
    F An empty message reads as defaults; an optional field set to "" is present and costs 2 bytes.

    Reading the bytes in part 2 by the tag formula: 0a is field 1 with wire type 2 (a string of 5 bytes, o_123), 10 is field 2 as a varint (02, PAID), 18 is field 3 as a varint (9601, which is 150, the same varint as in the guide), and 22 is field 4, a string of 5 bytes (SAVE5).

    What the lab leaves out. The in-process transport shows the call model and status handling, but nothing specific to HTTP/2 framing, headers such as grpc-timeout, TLS or real network timing. It does not test streaming, interceptors, retries or deadline propagation between services.

    Break it. In evolution/v2/order.proto, change optional string currency = 5; to = 4; and delete the two reserved lines. Three evolution tests and the golden test fail, because the old coupon is now read as a currency. Restore the file and run the tests again.

    Trade-offs

    Choice Gain Cost Wrong when
    A .proto contract and generated code One source of truth; typed calls in many languages A build step; every consumer needs the contract A small team owns both ends and changes daily
    Status codes for errors Retry layers and monitors can read the outcome Codes are coarse You need structured detail (a richer error model)
    Deadlines on every call A slow dependency cannot hold callers forever A value to choose and maintain The value is guessed, never measured
    Strict field-number rules Old and new versions meet safely Review discipline; reserved numbers pile up Nothing is stored and everything deploys together

    The other side of this topic

    A browser cannot speak plain gRPC to a server; the gRPC-Web project and its proxy are covered in the API styles lesson, and the front-end view of choosing a style is in Consuming REST, GraphQL and tRPC from a Client.

    In practice: adding a currency to ShopStream's order reply

    This is the realistic example, an educational scenario on ShopStream, the course's running project. Every number in it is an illustrative assumption.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's Order service answers GetOrder over gRPC for three callers owned by different teams: the BFF, Delivery and Notifications. A second currency means the reply needs a currency, and the team wants to drop a legacy coupon field. The callers deploy independently, and some replies sit in a cache as raw Protobuf bytes.

    Starting architecture

    Figure 5. One contract, three callers. How to read this: all three callers share the Order service's contract but not its release schedule. The cache holds serialized messages, so old bytes meet new code.

    Three callers and a cache of serialized messages share the Order service contractBFF to Order service (gRPC); Delivery to Order service (gRPC); Notifications to Order service (gRPC); Order service to Cache (stores replies)BFFBFFDeliveryDeliveryNotificationsNotificationsOrder service: GetOrderOrder serviceGetOrderCache: stored bytesCachestored bytesgRPCgRPCgRPCstores replies

    Options considered

    Option Gain Cost
    A. New optional currency with a fresh number; reserve coupon's number and name Safe for every deploy order (rows A, B) Reserve discipline
    B. Reuse number 4 for currency Tidier file Cached bytes read as the wrong thing (row C)
    C. A new v2 service A clean break Two services; every caller migrates

    The decision

    Option A. The new field gets a fresh number, the old one is reserved, and callers read hasCurrency() before trusting the value.

    Rollout and verification

    Adding a field works whichever side deploys first (rows A and B). A test that parses the byte string written by the previous release with the new classes catches a renumbering before it ships, as the lab's tests do. Dashboards count responses by status code.

    The 2 a.m. failure

    The page reads: "delivery notes show promo codes in the region field". A change merged last week removed coupon = 4 and added region = 4 with no reserved line; the cache still holds older replies and the new code parses them. Both are strings, so nothing fails (row C). Checks: the proto history for number 4, and a sampled cached value's bytes. Mitigation: flush the cache and roll the contract back. Lasting fix: a new number for region, reserved 4; reserved "coupon";, and a test that fails when a number disappears unreserved.

    Architect's notes

    • Treat field numbers as permanent, and reserve every deleted number and name in the same change.
    • Choose a status code by the caller's next action, and let monitors read it.
    • Set a deadline on every client call, and make servers stop work when cancelled.
    • Remember stored bytes: caches, queues and files keep old schemas alive.

    Common mistakes

    • Reusing or renumbering a field: it looks tidy and fails silently.
    • Returning UNKNOWN or INTERNAL for business failures, hiding them from retry logic.
    • Assuming a deadline undoes the server's work.
    • Treating 0 or "" as "not set" instead of using optional.
    • Changing an integer type without checking for truncation.

    Key takeaways

    • A gRPC contract is a .proto file; both sides generate code from it.
    • A failed call is a status code and an optional message; choose the code by the caller's next action.
    • No deadline is set by default; set one, and make the server stop when cancelled.
    • A field's number is its identity on the wire; names do not travel.
    • Adding fields is safe, removing is safe with reserved, renumbering or reusing a number fails silently.
    • Test schema changes with real bytes from the previous release.

    Practice exercises

    Exercise 1 (30 min). Decode 0a05 6f5f313233 1002 189601 by hand with the tag formula, then run the lab and compare.

    Exercise 2 (45 min). Add optional string note = 6; to the v2 contract, write the byte string with v2 and read it with v1, and predict the unknown field numbers before running.

    Exercise 4 (2 hours). Write a test that fails when a field number in one .proto version disappears from the next without a reserved line, using the descriptors of the generated classes.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments