Domain-Driven Design: Customer/Supplier, coordinating dependencies and agreements between Bounded Contexts.
Learn to coordinate Inventory and Sales through team commitments, explicit contracts, and runtime validation. Design a TypeScript consumer, distinguish local tests from provider verification, and plan compatible changes.
The indicator keeps the furthest percentage explored; marking the article complete is your choice.
When the supplier delivers and the consumer is still blocked
Inventory publishes a new availability API. Its tests pass and its team considers delivery complete. Sales tries to use it to sell two backpacks, but discovers that “available” includes units that cannot be reserved because they are held for inspection.
Nobody has broken the JSON format. However, the teams had not agreed on what Sales needed to make its decision.
The Customer/Supplier Development pattern is precisely about coordinating a dependency between teams. The API is part of the result; the priorities, responsibilities, and commitments that make it useful matter too.
We will work with Inventory as the supplier and Sales as the consumer. We will build a small query contract, a Sales adapter, and verification examples. Then we will see how to negotiate its evolution without turning every internal change into an approval between departments.
A dependency with real collaboration
Inventory is Upstream with respect to the availability capability it offers. Sales is Downstream because its process depends on that contract and its meaning.
The arrow shows the consumer's dependency on the supplier. Sales can initiate the HTTP request and still be Downstream. “Customer” here describes the consuming team, not the store's buyer.
The defining characteristic of the pattern is that Downstream needs influence Upstream planning. Both negotiate the work, their expectations, and when they can rely on what was agreed. Evans also proposes joint acceptance tests to verify the expected interface. DDD Reference: Customer/Supplier Development, page 32 of the document.
This avoids two extremes: a supplier that ignores the consumer and a consumer that tries to veto any evolution of the supplier.
A published API, a chat channel, or a monthly meeting do not by themselves demonstrate Customer/Supplier. You need evidence that a need becomes a commitment and that both parties can verify its fulfillment.
Negotiate a need before designing the DTO
Sales initially says: “we need the stock for each product.” Inventory asks what for.
The real need is to show whether a specific quantity appears reservable before starting the reservation. Sales does not need to know warehouse locations, internal holds, or movements.
The teams agree on this scope:
Sales identifies the SKU and requested quantity.
Inventory reports how many units are reservable at the time of the query.
A query neither holds units nor guarantees a later reservation.
An unknown SKU produces a different response from zero availability.
A technical failure is not interpreted as “out of stock.”
Inventory retains control over its internal availability rules.
This is the example's agreement. Another store might prefer Inventory to evaluate a quantity directly and return a decision. What matters is choosing deliberately and documenting the semantics.
Assign responsibilities
Inventory implements the query using its rules, validates parameters, and preserves the meaning of the public field. It neither exposes its warehouse entity nor forces the consumer to reconstruct its calculations.
Sales validates its business input, checks responses, and maintains the distinction between a queried estimate and an accepted reservation.
Both teams agree on examples, compatibility, delivery date, and version retirement criteria.
The supplier can change how it calculates availability without asking permission for every refactor. It must coordinate a change when it alters what the consumer can expect from the contract.
The HTTP contract both can review
We propose this query for a store with a simple SKU:
GET /api/v1/availability?sku=BAG-URBAN
Accept: application/json
Known response:
{"sku":"BAG-URBAN","reservableQuantity":3}
The two teams establish these rules:
The SKU contains between one and 64 alphanumeric characters, hyphens, or underscores.
reservableQuantity is a nonnegative safe integer.
A known SKU with no units returns 200 with quantity zero.
An unknown SKU returns 404.
An invalid parameter returns 400.
A supplier error is reported as a technical error, not as quantity zero.
The response is an observation, not a reservation promise.
A real contract must also specify authorization, usage limits, caching, and response times. The DTO does not resolve these. This example does not show credentials or infrastructure configuration.
A consumer that does not import the supplier's model
Sales defines a port according to its need. The network representation remains localized in its adapter, without importing Inventory's internal entities or repositories.
These interfaces help write and review code, but they do not control the remote process. JSON can contain a string where TypeScript expects a number.
The following function checks unknown data and builds the local representation. The snippets in this section can be organized in a single inventory-availability.ts file; they are not an implementation of the Inventory server.
functionisRecord(value: unknown): value is Record<string, unknown> {
returntypeof value === "object" && value !== null &&
!Array.isArray(value);
}
exportfunctionparseAvailability(raw: unknown,
requestedSku: string,
): AvailabilitySnapshot {
if (!isRecord(raw) || raw.sku !== requestedSku) {
thrownewError("La respuesta no corresponde al SKU solicitado");
}
const quantity = raw.reservableQuantity;
if (
typeof quantity !== "number" ||
!Number.isSafeInteger(quantity) ||
quantity < 0
) {
thrownewError("Disponibilidad inválida");
}
return {
sku: requestedSku,
reservableQuantity: quantity,
};
}
The consumer accepts additional properties because the agreement permits extensions that do not change the meaning of known fields. It neither retains nor uses those properties.
The HTTP adapter
This snippet complements the preceding ones. It assumes a Node.js environment with fetch, URL, and AbortSignal.timeout available and TypeScript configuration suitable for those APIs.
The base URL comes from controlled configuration, not from user-submitted data. The timeout is a teaching decision; it must be negotiated according to actual usage.
We do not follow redirects or turn network failures, invalid JSON, or timeouts into acceptance. A production version must specify authentication and, if its exposure requires them, response size limits and observability.
The adapter acts as Sales' translation boundary. Its purpose here is to demonstrate the explicit dependency; we do not need to develop an integration framework.
If the query returns three units and Sales needs two, the result is true: it can attempt the reservation. This does not mean the order is confirmed.
We do not show persistence because this operation only queries. A future reservation operation must have its own contract and confirm the actual outcome. Between the query and that operation, another buyer may have consumed the units.
Even if both contexts are within a modular monolith, the HTTP call does not create a shared transaction. Do not let a function name promise a guarantee the contract does not offer.
Tests that make the agreement visible
We need to distinguish three checks:
Sales interprets responses and errors correctly.
Inventory produces agreed responses for known states.
The real exchange preserves the route, parameters, HTTP statuses, and expected body.
A mock written by Sales only demonstrates its own expectation. Compatibility must be verified against Inventory. Contract testing tools such as Pact organize this relationship between consumer interactions and provider verification; adopting one is not required to understand the mechanism. Pact: how it works.
Consumer unit tests
These examples use Node.js built-in APIs and assume compilation to JavaScript ESM. They complement the previous file; they have not been run as part of this article.
import test from"node:test";
import assert from"node:assert/strict";
import {
parseAvailability,
canAttemptReservation,
} from"./inventory-availability.js";
test("acepta un campo adicional sin cambiar la interpretación", () => {
assert.deepEqual(parseAvailability({
sku: "BAG-URBAN",
reservableQuantity: 3,
observedAt: "2026-01-01T10:00:00Z",
}, "BAG-URBAN"), {
sku: "BAG-URBAN",
reservableQuantity: 3,
});
});
test("rechaza una cantidad enviada como texto", () => {
assert.throws(() =>parseAvailability({
sku: "BAG-URBAN",
reservableQuantity: "3",
}, "BAG-URBAN"));
});
test("rechaza la respuesta de otro SKU", () => {
assert.throws(() =>parseAvailability({
sku: "OTHER",
reservableQuantity: 3,
}, "BAG-URBAN"));
});
test("Sales permite intentar dos unidades cuando observa tres", async () => {
const result = awaitcanAttemptReservation("BAG-URBAN", 2, {
asyncread(sku) {
return { sku, reservableQuantity: 3 };
},
});
assert.equal(result, true);
});
These tests do not start Inventory. They protect Sales' interpretation; they do not demonstrate that the endpoint exists or that its supplier honors the contract.
Verification against the actual test provider
The teams can agree on a test state: BAG-URBAN exists and has three reservable units. Preparation belongs to Inventory and must take place in an isolated test environment.
The following verifier receives that environment's URL and queries its actual endpoint. It must not run against production or assume data from a real store.
This is minimal verification of one interaction, not a complete suite or a Pact configuration. Provider startup, state preparation, credentials if applicable, and the zero-unit, 404, and 400 scenarios are missing.
Inventory must include those scenarios in its verification before delivering a version. Sales, in turn, needs adapter tests that check the outgoing request and error handling. Maintaining both sides prevents a test double and an implementation from evolving with different assumptions.
Contract tests also do not replace Inventory's internal tests for stock calculations. A correctly formatted response could contain a miscalculated quantity.
Evolve without breaking Sales
Suppose Inventory wants to add an observation time:
For the consumer shown, adding that field is compatible: it allows new properties and preserves known fields. This does not prove compatibility with all consumers; some might reject additional properties.
The change proposal must verify:
Whether known consumers tolerate the field.
Whether the meaning, type, and required status of previous fields are preserved.
Whether the added cost of calculating it changes response expectations.
Whether documentation and examples need updating.
By contrast, these changes require further negotiation:
Renaming reservableQuantity and removing the old field.
Returning the quantity as a string.
Turning 404 into 200 with a different body without updating the agreement.
Including held units in a quantity previously defined as reservable.
The last is especially dangerous: it can pass structural validation while still breaking the business decision.
A concrete transition plan
To replace a field, one option is to add the new representation first, temporarily retain the old one, and check that all consumers migrate. Only then is the old one removed according to a verifiable agreement.
If semantics change significantly, offering a separate version or capability may be clearer. A v2 suffix does not by itself resolve what each response means or how long they will coexist.
Planning must record owners, acceptance criteria, and the retirement condition. “We notified them in chat” does not demonstrate that Sales can adopt the change in time.
Maintain the relationship throughout the work
A brief record helps manage collaboration:
Supplier: Inventory team. Consumer: Sales team. Need: observe reservable units to guide a reservation attempt. Functional commitment: fields and errors described through agreed examples. Evolution: review changes that alter those expectations and verify affected consumers. Delivery: negotiated date and evidence of acceptance scenarios. Boundary: no promise that a query secures units.
Do not invent dates or service levels to fill in the document. If they have not yet been agreed, record them as pending.
The supplier must be able to say that a need does not fit the current delivery and negotiate an alternative. This is more useful than accepting requests that never enter planning.
Collaboration also does not depend on being two huge departments. In a small team, there can be clear owners for both contexts and a brief contract review.
Differences from related relationships
Conformist: the consumer adopts the offered model without the same ability to influence its evolution. If Sales can only wait for whatever Inventory decides, do not describe the relationship as Customer/Supplier out of courtesy.
Partnership: the teams coordinate a relationship where the outcome depends on joint success. Customer/Supplier maintains an asymmetry: the consumer depends on the supplier, whose priorities must incorporate negotiated commitments.
Shared Kernel: deliberately shares part of the model under joint governance. Customer/Supplier can work with explicit contracts and independent models, without a common entity library.
An ACL can protect Sales within a Customer/Supplier relationship. It does not replace negotiation; it translates the agreed contract. Likewise, integration events can carry information, but switching from HTTP to events does not automatically create collaboration between teams.
Two situations where the decision changes
Education: enrollment needs payment confirmation
Enrollment depends on Payments to enable registration. Both teams agree on which status permits that action and what information they need to identify the operation.
Customer/Supplier makes sense if Payments incorporates that need into its planning and both verify acceptance examples. The word “payment” is not enough: an initiated attempt is not equivalent to confirmed funds.
This example teaches negotiating meaning before automating a decision with consequences for the user.
Logistics: a carrier that does not accept changes
A store consumes a public tracking API. The carrier does not negotiate its contract with that small customer.
A commercial relationship may exist, but this does not demonstrate Customer/Supplier Development between the teams. The store must decide whether to adopt the offered model or maintain a local translation, documenting the limitations.
For a page that only displays a tracking link, deep integration may not be worthwhile. The simple option can meet the need without pretending an agreement exists.
Useful context for an AI
These prompts can be used with Cursor, Claude, or Codex after attaching real agreements and examples:
To analyze the relationship:
Inventory offers availability to Sales. Using these meeting minutes and contracts, distinguish confirmed commitments from assumptions. Explain whether real Customer/Supplier exists and which needs are missing from planning. Do not infer Upstream from who initiates HTTP.
To implement the consumer:
Implement an HTTP adapter owned by Sales for this contract. Treat the body as unknown and validate SKU and quantity. Distinguish unknown SKU, zero units, and technical failure. Do not import Inventory entities or repositories. The query does not guarantee a reservation.
To review a change:
Compare this supplier version with Sales' expectations. Identify structural and semantic changes, affected consumers, and missing tests. Propose a compatible transition with retirement criteria. Do not invent that the teams approved the plan.
The responsible person must verify that the contract exists, that its meaning matches the business, and that the commitments are accepted. AI can analyze dependencies; it cannot commit another team's capacity.
Application exercises
1. The field that changes meaning
Inventory keeps reservableQuantity, but now includes held units. The JSON tests still pass. Is it compatible?
2. The always-green mock
Sales tests all its decisions with a double that returns three units. Inventory changes the field name. What check is missing?
3. The ignored request
Sales requests reservations with expiration. Inventory replies that it might implement them someday, without a plan or commitment. What should be documented?
Reasoned solutions
1. Not for the example's agreement. Sales interprets that quantity as reservable. The previous semantics must be preserved, or another representation negotiated and decisions and tests adapted. Keeping a number does not guarantee compatibility.
2. Verification of the interaction against the supplier and testing of the consumer adapter are missing. The double only reproduces a local expectation. Agreed scenarios must be checked against a real Inventory version in a prepared environment.
3. That the capability is not committed and Sales cannot depend on it as if it existed. They must negotiate scope and date or choose a viable alternative. Labeling the relationship does not replace the delivery agreement.
Recognize an agreement that works
Customer/Supplier adds value when a technical dependency needs influence and concrete commitments between owners.
Check whether a consumer need can reach the supplier's planning, whether both understand the meaning of responses, and whether evidence of compatibility exists before delivering changes.
When these three things are visible, the contract stops being an interface written by a single team and becomes a collaboration both can sustain.
Integrate the collection by building an order API with TypeScript, Express, Zod, and SQLite. Includes project files, domain rules, events, version control, Vitest tests, and commands to run and verify it locally.
Learn to guide AI agents with business rules, context boundaries, and verifiable criteria. A TypeScript case shows how to prepare instructions, protect Order, design tests, and review changes without delegating architectural judgment.
Compare a modular monolith with separating Sales, Payments, and Inventory. Design contracts in TypeScript and Express and understand partial failures, eventual consistency, idempotency, Outbox, and Sagas without introducing complex infrastructure.