Jereme Evans Hike. Travel. Code. Thoughts.
Code

Contract-first development: when it's worth it and why

Jereme Evans (opens in a new tab)

TL;DR

  • Contract-first development means writing down exactly how two pieces of software talk to each other before writing either piece.

  • Taproot writes those agreements first, then has tools generate much of the code on both sides automatically.

  • Automatic checks catch it when the two sides drift apart, before anyone sees a broken page.

  • A written agreement can't catch everything. Some rules still need hand-written code and careful review.

Why I chose contract-first development with gRPC

I wanted to use contract-first development because it helps define the shape of the API. It also lets us generate a lot of the boilerplate, and anything we can generate saves tokens in the future.

I chose gRPC as the base because gRPC seems to have a sane way to handle versioning. My experience has taught me that versioning is probably the most important thing to get right if you want an API to survive the future.

A frontend and a backend can each look reasonable on their own and still disagree about how to talk to each other: which fields a request carries, what comes back, which URL it goes to. Answer those separately on each side and you have two copies of the same decision to keep in sync.

Contract-first development (also called contract-driven or API-first development) means you write the interface down once, in a shared contract, and generate the code on each side from it. In Taproot that contract is a set of Protocol Buffers (protobuf) files, and our C# backend, TypeScript frontend and Node services all get their interfaces from them.

This post is about whether that's worth doing. For the actual config, I follow one endpoint from the .proto file to the browser in a walkthrough of our proto-to-TypeScript pipeline.

It's been especially useful while building with AI. Claude Code, one of the two AI tools we build with, can follow an existing interface from the contract to the screen instead of guessing what the other side expects.

Cartoon of a cheerful yellow light bulb with arms and legs walking between two lightning bolts

What does contract-first look like in practice?

A contract describes the operations one part of the software offers and the messages each one accepts and returns. Ours are .proto files, one per service area, and a new client-facing endpoint starts there, before any C# or TypeScript.

Writing the contract first pulls questions forward. Does this screen need the full record or a lightweight search result? Which identifier does the caller supply? What happens when an input is missing? Those answers are much cheaper to settle in one small file than after they've spread across two codebases.

What gets generated from one contract

From the contracts we generate C# message types and service base classes for the API. gRPC JSON transcoding serves the same methods as HTTP and JSON for the browser, a committed OpenAPI snapshot describes them, and Hey API turns that snapshot into TypeScript client functions. Node services that call the API over gRPC get clients from ts-proto instead.

A real example: searching for a place

Taproot's place picker lets an author search for a location as they type. Its contract starts with this operation:

rpc SearchPlaces(SearchPlacesRequest) returns (SearchPlacesResponse) {
  option (google.api.http) = {get: "/v1/places/search"};
}

The request carries the query, optional coordinates, a result limit and a session token. The response is a list of lightweight predictions (a Google place ID, a name and an address). Choosing one is a separate operation that returns the full place record, because typing and picking need different data.

We implement the generated SearchPlaces method in C# and tag it with [OpenApiOperation("SearchPlaces")], a small attribute of ours that sets the OpenAPI operation ID. The picker imports a generated searchPlaces function named after that ID. Typing, loading states and stale results are still handwritten; generation supplies the connection underneath.

Why contract-first helps AI tools

Our rule is to change the source and regenerate. If a generated client is missing an operation, we fix the contract or the generator, because the next run would erase a hand edit anyway.

That gives an AI tool a clear path through a change: edit the contract, update the service, regenerate, fix the consumers. Remove a field from a response and every component still reading it fails the TypeScript build before anyone loads the page. That only works if the code actually uses the generated types; a quick cast to any throws the benefit away.

Keeping the contract, implementation and consumer in one repository helps too, since one pull request shows all three. More on that in why moving to a monorepo made development with AI tools easier.

How do you keep generated clients from drifting?

A generator will happily produce code from a stale input, so each link needs its own check. We regenerate the clients in a temporary folder and diff them, compare the committed OpenAPI snapshot with the document the running API serves, and fail lint on raw fetch() calls so browser code goes through the generated SDK. The walkthrough shows each script.

It's the same idea behind how we enforce coding standards: a convention is worth a lot more once a machine can tell you you've broken it.

What a contract can't check

A generated request type can tell you a search has a string field called query. It can't tell you the string has anything in it. That's the implementation's job:

[OpenApiOperation("SearchPlaces")]
public override async Task<SearchPlacesResponse> SearchPlaces(
    SearchPlacesRequest request, ServerCallContext context)
{
    var authority = await RequireCallerAsync(request.SiteId, context);
    if (string.IsNullOrWhiteSpace(request.Query))
    {
        throw new RpcException(new Status(
            StatusCode.InvalidArgument,
            "query is required and cannot be empty."));
    }

    var maxResults = request.MaxResults > 0 ? request.MaxResults : 5;
    // ...
}

Checking the caller, rejecting an empty query and defaulting the result count all live in code we write, and they still need behavior tests and review. A response can have every right field and still hold the wrong data.

Compatibility needs attention too, since a browser tab can stay open across a deploy. Protobuf identifies fields by number in its binary format, so a number must never be reused. The protobuf best-practices guide (opens in a new tab) recommends reserving deleted field numbers, and we do:

message GetPublishingReadinessRequest {
  reserved 4, 6, 7;

  string site_id = 1; // Site whose release candidates should be checked.
  // ...
}

The browser talks JSON, though, where fields go by name, so a rename breaks a JSON caller even when the number stays put. That interface gets its own compatibility review.

When is contract-first worth it?

It isn't free. We maintain generators, config, a committed snapshot and the checks around them, refreshing the snapshot needs a running API, and a contract change can produce a big generated diff that someone has to read. The walkthrough has real numbers.

It pays off for Taproot because the same interfaces cross several services, two languages and two transports. My rough guide:

  • Several services or languages share an API: contract-first with generated clients on every side is worth the setup.

  • One browser app talking to one backend: an OpenAPI contract and one generated client probably gets you most of the benefit.

  • Everything is TypeScript: sharing the types directly may be enough.

Even on a smaller project, I'd give the gRPC pipeline a look. Every call, gRPC or transcoded JSON, passes through the same server pipeline, so there's one place for logging and one set of rules for turning exceptions into errors. In Taproot that's one interceptor:

builder.Services.AddGrpc(options =>
    options.Interceptors.Add<ServerLoggerInterceptor>());

// Inside ServerLoggerInterceptor.UnaryServerHandler (trimmed)
try
{
    var response = await continuation(request, context);
    LogCallCompleted(method, (int)StatusCode.OK, durationMs);
    return response;
}
catch (ValidationException ex)
{
    LogCallValidationFailed(method, (int)StatusCode.InvalidArgument, ex.Errors.Length, durationMs);
    throw BuildValidationException(ex.Errors);
}
// ... NotAuthorizedException becomes Unauthenticated; anything unexpected logs at Error

A service method throws a ValidationException and the caller gets InvalidArgument with the details, logged with the method, status, duration and correlation ID like every other call. Nobody has to remember it per method, and that consistency is worth having before you need it.

How to try contract-first on one endpoint

Don't convert everything at once. Pick one feature that crosses your frontend and backend, write its request and response down, generate a client and use it. Then rename a field and see whether the compiler leads you to every caller, and decide how you'll catch a stale schema. The walkthrough ends with a six-step version of this for ASP.NET Core.

A schema describes the messages, but the next contributor (person or AI tool) also needs examples to use them well. That's the subject of why documentation-first development helped us build with AI.

Jereme Evans Jereme Evans