📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

How do you design the API contracts between modules and between services? Explain when you choose synchronous calls vs asynchronous messages, who owns a contract, how consumer-driven contract tests work, and how you version contracts without breaking consumers.

Contracts between modules and services: sync vs async, provider vs consumer ownership, consumer-driven contract testing with Pact, and backward-compatible versioning.

Senior Theory Advanced api-contracts architecture consumer-driven-contracts messaging pact versioning

🎯 Key points

  • A contract is the only thing others may depend on: module public interface, HTTP/gRPC API, or event schema, published as OpenAPI, .proto or AsyncAPI/JSON Schema
  • Sync (HTTP/gRPC) when the caller needs an answer now; async (events/commands over Service Bus) for decoupling in time and load levelling
  • The provider owns the contract, but it is shaped by consumer needs; events belong to the publisher, commands to the receiver
  • Consumer-driven contract tests (PactNet with a Pact Broker): consumers publish expectations, the provider verifies them and `can-i-deploy` gates the release
  • Tolerant reader: a consumer reads only the fields it needs and ignores unknown ones (System.Text.Json's default), so providers can add fields without breaking it
  • Backward compatibility: additive changes only (new optional fields, new endpoints), never repurpose a field, expand-and-contract for renames
  • SemVer thinking: additive = minor, breaking = major; for APIs a breaking change means a new version (URL or header via Asp.Versioning), for events a new type/version, with Deprecation/Sunset and a migration window

⏱ 30-second answer

A contract is the only surface others may depend on: a module's public interface, an HTTP or gRPC API, or an event schema. I choose synchronous calls when the caller needs an answer to continue, and asynchronous messages when it doesn't, because messages decouple availability and absorb load spikes.

The provider owns the contract but designs it from consumer needs; for events, the publisher owns the schema. To change safely I use consumer-driven contract tests (Pact): each consumer records what it relies on, and the provider's pipeline verifies those expectations before deploying.

Versioning rule: additive changes by default, tolerant readers, and an explicit new version with a deprecation window only for breaking changes.

The trade-off: sync is simpler but couples availability; async is resilient but harder to trace and reason about.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"I treat every boundary as having one contract and nothing else exposed. Inside a modular monolith that's a Contracts project with interfaces and records; between services it's an OpenAPI or protobuf definition for request/response, and an AsyncAPI or JSON Schema definition for events. The first decision is sync or async. If the caller genuinely needs the answer to continue, like checking stock before showing a price, I use HTTP or gRPC with timeouts and resilience. If it's telling others something happened, or work can complete later, I publish an event or send a command over Azure Service Bus, so the provider can be down for a minute without the caller failing.

Ownership matters. The provider owns its API, but a good provider designs it from what consumers actually need, not from its database tables. For events, the publisher owns the schema and consumers adapt. For example, at [company] the Pricing team renamed a field in their API and [three] consumers broke in production on a Friday. I introduced consumer-driven contract tests with PactNet: each consumer published a pact describing the fields and responses it used to a Pact Broker, and Pricing's pipeline ran can-i-deploy before release. In the next [six] months we had [zero] contract-break incidents, and Pricing could delete fields confidently because they knew which ones were unused.

The mistake I see is sharing a NuGet package of DTOs and calling that the contract, which couples release cycles, or versioning everything as v2 at the first change. My senior line is: make changes additive, let consumers prove what they depend on, and reserve a new version for the rare change you can't make additive."


Sync vs async

Synchronous (HTTP/gRPC) Asynchronous (events/commands)
Caller needs answer now Yes No
Availability coupling Caller fails if provider is down Provider can be down; messages wait
Latency Adds to request path Off the request path
Load levelling No Yes (queue absorbs spikes)
Debugging Easier Needs tracing and correlation
.NET tools HttpClient + resilience handler, gRPC Azure Service Bus, MassTransit/Wolverine/NServiceBus, outbox

Who owns what

Contract Owner Consumers
Module interface Module team Other modules via Contracts project
HTTP/gRPC API Provider Influence via consumer-driven tests
Event Publisher Adapt; tolerant readers
Command Receiver (it defines what it accepts) Senders

Change types

Change Breaking? How
Add optional field / endpoint No Just ship
Add required request field Yes Make optional with a default, or new version
Rename or remove field Yes Expand-and-contract: add new, migrate consumers, remove old
Change meaning of a field Yes (silently!) Never; add a new field

Production example

Adding PactNet consumer-driven tests and a can-i-deploy gate between [Pricing] and its [three] consumers removed contract-break incidents ([four] in the previous half-year to [zero]) and let Pricing retire [11] unused fields safely.

πŸ” What the interviewer is checking

Checks whether the candidate can choose integration styles deliberately, assign contract ownership, and evolve contracts safely with evidence.

Green flags

  • Chooses sync vs async based on whether an answer is needed now
  • Clear ownership rules for APIs, events and commands
  • Knows consumer-driven contract testing and a deploy gate
  • Prefers additive changes, tolerant readers and expand-and-contract

Red flags

  • Shared DTO libraries as the contract
  • Versioning by "just create v2"
  • No awareness of semantic breaks

πŸ“š Learn in depth

1. What a contract includes

A contract is more than a shape. It includes:

  • Syntax: fields, types, required/optional (OpenAPI, .proto, JSON Schema).
  • Semantics: what a field means, units, currency, time zone.
  • Behaviour: status codes, error format (ProblemDetails), idempotency, ordering guarantees.
  • Quality of service: latency, rate limits, availability.

Most production breaks are semantic ("amount was in cents, now in dollars"), which schema checks alone don't catch.

2. Choosing sync or async

Sync request/response:
  Checkout ──GET /prices──► Pricing        (checkout waits; Pricing down = checkout degraded)

Async event:
  Ordering ──OrderPlaced──► Service Bus topic ──► Billing, Shipping, Loyalty
                                (each consumes at its own pace)

Long synchronous call chains multiply failure: three services at 99.9% each give roughly 99.7% for the chain. Prefer async for anything that doesn't need an immediate answer, and keep sync chains to one or two hops.

3. Provider-driven vs consumer-driven

In a provider-driven model the provider publishes a spec and hopes consumers use it correctly. In a consumer-driven model, each consumer writes tests that generate a pact (the requests it sends and the parts of the response it reads). The provider verifies all pacts against its real implementation.

Consumer CI:  unit test with Pact mock ──► pact file ──► Pact Broker
Provider CI:  fetch pacts ──► replay against provider ──► publish results
Deploy gate:  pact-broker can-i-deploy --pacticipant Pricing --version $SHA --to production

This tells the provider exactly which fields are used, so unused ones can be removed. Pact supports HTTP and message (event) contracts.

4. Backward and forward compatibility

  • Backward compatible: new provider works with old consumers (additive changes).
  • Forward compatible: old consumers tolerate new data (tolerant reader: ignore unknown fields). System.Text.Json ignores unknown properties by default; don't turn on UnmappedMemberHandling.Disallow for contracts from other teams.
  • Expand-and-contract: add the new field, dual-write/read, migrate consumers (pacts show when none use the old field), then remove.

5. Versioning mechanics

  • HTTP: Asp.Versioning.Http with URL segment (/v2/) or header; publish both versions in OpenAPI; set Sunset/Deprecation headers.
  • gRPC: protobuf field numbers make additive changes safe; never reuse a field number; new package for breaking changes.
  • Events: a version in the type name or envelope (CloudEvents type: com.shop.order.placed.v2); publish both during migration.

6. Contracts inside a modular monolith

The same rules apply at lower cost: a Contracts project per module, records for requests and results, and architecture tests preventing references to internals. Because it's one repo and one deploy, breaking changes are a refactor, but treating the contract seriously keeps extraction possible.

Try it yourself

  1. Write a PactNet consumer test for an HTTP client and inspect the generated pact JSON.
  2. Verify that pact against a minimal ASP.NET Core provider using WebApplicationFactory.
  3. Rename a field in the provider and watch verification fail.
  4. Add Asp.Versioning.Http to a Minimal API and expose v1 and v2 side by side in OpenAPI.
  5. Deserialise a payload with an extra unknown property and confirm your consumer still works.

πŸ’» Code

A consumer-driven contract test with PactNet: the consumer states exactly what it relies on.

namespace Checkout.Tests;

using System.Net;
using System.Net.Http.Json;
using PactNet;
using PactNet.Matchers;

public sealed record PriceDto(string Sku, decimal Amount, string Currency);

public class PricingClientPactTests
{
    private readonly IPactBuilderV4 _pact = Pact.V4("Checkout", "Pricing", new PactConfig())
                                                .WithHttpInteractions();

    [Fact]
    public async Task Gets_price_for_sku()
    {
        _pact.UponReceiving("a price request for an existing SKU")
             .Given("SKU ABC-1 exists")
             .WithRequest(HttpMethod.Get, "/v1/prices/ABC-1")
             .WillRespond()
             .WithStatus(HttpStatusCode.OK)
             .WithJsonBody(new
             {
                 sku = "ABC-1",
                 amount = Match.Decimal(19.95m),   // only the fields Checkout reads
                 currency = Match.Regex("AUD", "^[A-Z]{3}$")
             });

        await _pact.VerifyAsync(async ctx =>
        {
            using var http = new HttpClient { BaseAddress = ctx.MockServerUri };
            var price = await http.GetFromJsonAsync<PriceDto>("/v1/prices/ABC-1");
            Assert.Equal("AUD", price!.Currency);
        });
    }
}
# Provider pipeline: verify all consumer pacts, then gate the deploy.
pact-broker can-i-deploy --pacticipant Pricing --version "$GIT_SHA" --to-environment production

⚠ Common mistakes

  • Mistake: Sharing a NuGet package of DTOs as "the contract". Why it is wrong: It couples releases and hides which fields consumers really use. Instead: Publish specs (OpenAPI, AsyncAPI, .proto) and verify usage with consumer-driven tests.
  • Mistake: Using synchronous calls for everything. Why it is wrong: Availability and latency multiply across call chains. Instead: Use async messages for notifications and work that can finish later; keep sync chains short.
  • Mistake: Designing the API from the provider's database tables. Why it is wrong: Internal schema leaks out, and every refactor becomes a breaking change. Instead: Design from consumer use cases and keep internals hidden.
  • Mistake: Changing the meaning of an existing field. Why it is wrong: Schema checks pass while consumers silently compute wrong results. Instead: Add a new field and deprecate the old one.
  • Mistake: Bumping to v2 for every change. Why it is wrong: You maintain many versions and consumers churn. Instead: Make additive changes; version only for unavoidable breaks.
  • Mistake: Strict deserialisation of other teams' payloads. Why it is wrong: An added field breaks the consumer. Instead: Tolerant reader: ignore unknown fields, validate only what you use.
  • Mistake: No deprecation process. Why it is wrong: Old versions live forever or are removed under consumers' feet. Instead: Announce, add Deprecation/Sunset headers, track usage, then remove.

πŸ› Senior insight: trade-offs

Contract testing shifts the conversation from "please don't break us" to evidence: the provider can see exactly which consumer depends on which field and decide quickly. I pair that with ownership rules written into the architecture docs: the provider owns APIs, the publisher owns events, and the receiver owns commands. That avoids the common stalemate where nobody feels allowed to change anything.

Pact needs some investment (a broker, provider states, CI wiring), so for one internal consumer in the same repo I may rely on integration tests instead. It pays off once there are several consumers or several teams.

Option When it fits Cost When not to
Sync HTTP/gRPC Caller needs an immediate answer Availability coupling Notifications, long-running work
Async events Fan-out, decoupling, load levelling Eventual consistency, tracing Caller needs answer now
Consumer-driven contract tests Several consumers or teams Broker, CI setup Single consumer in same repo
Explicit versioning Unavoidable breaking change Running two versions Additive changes would do

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate talks about event schemas or CloudEvents Why: Checks event contract versioning and ownership in depth
    How to answer

    An integration event is a public API owned by the publisher. Within a version I only make backward-compatible changes: add optional (nullable or defaulted) fields. I never add a required field mid-version (messages already in queues won't have it), and never rename, remove or retype. Consumers are tolerant readers: they ignore unknown fields and default missing optional ones. A breaking change becomes a new event type (orders.order-placed.v2), published alongside v1 until consumers move, then deprecated with a date.

    I wrap events in a CloudEvents envelope (id, source, type, time, dataschema). Each publisher ships its own contracts package or JSON Schema; one shared events library for every service forces lockstep upgrades.

    The trade-off: discipline and some duplication in exchange for independent deployments.

  2. When: Candidate mentions shared libraries coupling services Why: Checks how deployment boundaries and shared code interact
    How to answer

    A logical boundary decides what code may depend on: a module, an assembly, a namespace, a database schema. A deployment boundary decides what ships and runs together: one App Service, one container, one Function app.

    They don't have to match. A modular monolith has many logical boundaries in one deployable. Microservices add deployment boundaries so units can be deployed independently, which only works if contracts stay backward compatible.

    The quiet killer is shared libraries: a NuGet package with shared domain models or contracts that every service must upgrade together turns separate deployables back into a distributed monolith.

    Monorepo vs polyrepo is about workflow, not architecture: a monorepo makes cross-cutting changes easy; a polyrepo forces versioning. The trade-off is coordination cost vs isolation.

  3. When: Candidate mentions Pact or contract tests Why: Checks they understand the testing pyramid for distributed systems
    How to answer

    A consumer-driven contract test checks one consumer-provider pair in isolation. The consumer's tests run against a Pact mock and record what it actually uses; the provider replays those expectations against its real code (dependencies stubbed) in its own CI. Because the provider must keep passing every consumer's contract, it can evolve and version its API without silently breaking anyone, which preserves team autonomy.

    An end-to-end test deploys many services together and drives a real user journey. It catches wiring, configuration and infrastructure problems contract tests can't, but it needs a shared environment, runs for minutes, fails for unrelated reasons and slows every deployment pipeline that waits on it.

    So: a contract test for every consumer-provider pair as the main safety net, and only a handful of end-to-end smoke tests for the few journeys that make money. The trade-off is fast, precise feedback versus realistic but slow, flaky coverage.

πŸ›  Real-world problems: how you handle them

A renamed field breaks three consumers on a Friday
Situation
A [retail] platform's Pricing service was consumed by [Checkout, Catalogue and Promotions], each owned by a different team, with a shared OpenAPI spec but no automated checks.
Signals
After a Pricing release, Checkout returned 500s for [20 minutes], Catalogue showed $0 prices, and Promotions logged deserialisation errors; Application Insights showed failures across [three] services at the same timestamp.
Investigation
I correlated the failures with the Pricing deployment in Application Insights, diffed the OpenAPI spec between versions, and found a renamed field (`price` to `amount`) that the provider team believed was unused.
Resolution
Immediate: rolled back Pricing. Long-term: introduced PactNet consumer tests in each consumer, a self-hosted Pact Broker, provider verification in Pricing's pipeline, a `can-i-deploy` gate, and an expand-and-contract process for renames.
Prevention
Contract verification required for every provider deploy, API change guidelines in the architecture docs, `Deprecation` headers and usage tracking before removing fields.

How to tell it (STAR)

**S:** At [company] a field rename in Pricing broke [three] consumer services in production on a Friday afternoon. **T:** I was asked to stop contract breaks without slowing teams down. **A:** I set up PactNet consumer tests with the first consumer myself, ran a session with the other teams to add theirs, added a Pact Broker and a `can-i-deploy` gate to Pricing's pipeline, and wrote a short expand-and-contract guideline. **R:** Contract-break incidents went from [four] in the previous six months to [zero], and Pricing safely removed [11] unused fields.

↩ Usually asked after

More in Senior-Level Architecture

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me