Software Architecture

Domain-Driven Design: Published Language, how to establish contracts and a common language between Bounded Contexts.

Design PaymentConfirmedV1 for Sales, Billing, and Analytics. Define identities, units, and meaning, validate with Zod and JSON Schema, and learn to evolve contracts without leaking the internal model or changing their promises.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

Valid JSON that three teams understand differently

Payments communicates that a payment is confirmed. Sales interprets this as permission to continue the sale. Billing understands it should issue an invoice. Analytics records the amount as net revenue.

All three consumers receive the same document, but are assuming different things: does confirmed mean authorized or captured, does the amount include fees, and does the date refer to payment or message delivery?

Choosing prettier field names does not solve the problem. We need a published exchange language, with explicit structure and meaning.

We will build a contract called PaymentConfirmedV1. We will define what it asserts and does not assert, validate it with Zod, and represent it conceptually in JSON Schema. We will not implement transport or messaging infrastructure.

What a Published Language is

A Published Language is a documented exchange representation allowing different contexts to interpret information consistently.

Evans presents it as a common exchange language for communication between models. It may use an existing standard or a specification agreed for the particular problem. DDD Reference: Published Language, page 36 of the document.

“Published” does not mean available to everyone on the Internet. It means accessible and understandable to the integration's authorized participants.

Nor does it require a shared class. A TypeScript consumer and another in a different language can interpret the same contract without sharing implementation.

What must be published

For our case, we need to know:

  • Which occurrence the message represents.
  • What each reference identifies.
  • How amount, currency, and date are expressed.
  • Which states and values are valid.
  • Which properties are required and how extensions are accepted.
  • Which version is in use.
  • Which facts cannot be inferred from the message.

An automated schema checks part of that. Semantics also need definitions and examples people can review.

Separate internal language from exchange

Payments may have an internal model with authorizations, captures, attempts, refunds, and references from different gateways.

Sales does not need that entire model. Billing does not need credentials or technical responses from the financial provider either.

Internal Payments model
           |
           | explicit selection and translation
           v
PaymentConfirmedV1 + published rules
           |
           +----> Sales: interprets for its commercial process
           +----> Billing: interprets for its document process
           +----> Analytics: interprets for its metrics

The lines show information exchange. They imply neither a common transaction nor an obligation to use a broker.

An internal domain event may motivate creating the message without having to be its public contract. Changing an internal detail should not automatically force every consumer to change.

First define what “confirmed” means

For this hypothetical store, we agree that PaymentConfirmedV1 asserts:

Payments recorded a complete, successful capture for a payment and order, for the indicated amount and currency.

It does not represent an authorization awaiting capture. It does not represent a current balance or guarantee there will never be refunds or disputes.

The example contract accepts only positive EUR payments and one logical confirmation per payment. Partial captures are outside this version.

These are the example's decisions, not universal gateway rules. If the business needs another guarantee, another agreement must be designed.

Minimal dictionary

messageId: UUID identifying this published occurrence. Resending the same confirmation retains that identity; generating a new one for every delivery would make recognizing the same fact harder.

paymentId: public payment identifier in Payments. It is not the identifier of a gateway transaction.

orderId: public reference to the order Payments associates with the payment. It does not itself demonstrate Sales has already confirmed that order.

amountMinor: gross amount captured for this payment, before deducting gateway fees. In EUR it is expressed in cents: 7000 means 70 euros. It is neither a net-revenue calculation nor a tax breakdown.

currency: the amount's currency. This version accepts EUR only. Extending it requires agreeing on each currency's units, not assuming all are divided into one hundred.

status: the literal CONFIRMED. In this contract, it is redundant with message type but makes the communicated state explicit. It is not an open enumeration to which rejections or refunds can be added without reviewing the design.

occurredAt: the instant Payments recorded capture confirmation, in UTC with three millisecond digits and a Z suffix. It is neither the time a consumer receives the message nor a local business date.

Nor does a timestamp necessarily order all facts from different systems. Consumers must not invent that guarantee.

The document we exchange

{
  "type": "payment.confirmed",
  "schemaVersion": 1,
  "messageId": "79a1db8e-4f56-4e69-972b-9ca7d06c1d18",
  "paymentId": "payment-100",
  "orderId": "order-100",
  "amountMinor": 7000,
  "currency": "EUR",
  "status": "CONFIRMED",
  "occurredAt": "2026-01-15T10:30:00.000Z"
}

The document represents a concrete fact, not an instruction to every recipient.

Sales must still check its own process. Billing must apply its issuance rules. Analytics must distinguish gross amount from net revenue.

The common language allows sharing the assertion; it does not require consumers to make the same decision.

Runtime validation with Zod

The following payment-confirmed-v1.ts file uses Zod 4 APIs. It assumes that dependency is available in a TypeScript project with Node.js; it includes no configuration and installs no packages.

import * as z from "zod";

const PublicReference = z.string()
  .min(1)
  .max(64)
  .regex(/^[A-Za-z0-9_-]+$/);

export const PaymentConfirmedV1Schema = z.object({
  type: z.literal("payment.confirmed"),
  schemaVersion: z.literal(1),
  messageId: z.uuid(),
  paymentId: PublicReference,
  orderId: PublicReference,
  amountMinor: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
  currency: z.literal("EUR"),
  status: z.literal("CONFIRMED"),
  occurredAt: z.iso.datetime({ precision: 3 }),
});

export type PaymentConfirmedV1 =
  z.infer<typeof PaymentConfirmedV1Schema>;

export function parsePaymentConfirmedV1(
  input: unknown,
): PaymentConfirmedV1 {
  return PaymentConfirmedV1Schema.parse(input);
}

The inferred type helps during development. The parser checks received data at runtime. We do not use coercion to silently convert "7000" into 7000.

Date configuration requires milliseconds and uses the UTC format accepted by default. z.object removes unknown properties from the validated result: the consumer accepts extensions but uses only fields it knows. Zod: schemas, dates, and objects.

That policy is a compatibility decision, not the only possibility. A consumer rejecting every new property will have other restrictions and must document them.

Validating structure does not demonstrate an actual capture occurred. Sender authenticity, authorization, and producer-model decisions need their own controls.

Publish from a different internal model

To demonstrate separation, we use an instructional internal projection, not a complete aggregate or financial implementation.

In publish-payment-confirmed.ts:

import {
  PaymentConfirmedV1Schema,
  type PaymentConfirmedV1,
} from "./payment-confirmed-v1.js";

interface InternalCaptureRecord {
  readonly paymentReference: string;
  readonly salesReference: string;
  readonly grossCapturedCents: number;
  readonly lifecycle: "CAPTURED" | "AUTHORIZED";
  readonly confirmationRegisteredAt: Date;
  readonly providerTransactionReference: string;
}

export function createPaymentConfirmedV1(
  record: InternalCaptureRecord,
  messageId: string,
): PaymentConfirmedV1 {
  if (record.lifecycle !== "CAPTURED") {
    throw new Error("La autorización no permite publicar confirmación");
  }

  return PaymentConfirmedV1Schema.parse({
    type: "payment.confirmed",
    schemaVersion: 1,
    messageId,
    paymentId: record.paymentReference,
    orderId: record.salesReference,
    amountMinor: record.grossCapturedCents,
    currency: "EUR",
    status: "CONFIRMED",
    occurredAt: record.confirmationRegisteredAt.toISOString(),
  });
}

export function serializePaymentConfirmedV1(
  message: PaymentConfirmedV1,
): string {
  return JSON.stringify(PaymentConfirmedV1Schema.parse(message));
}

We do not serialize the internal object with a spread. The private gateway reference stays outside the contract, even though it exists in the producer model.

The caller must provide a message identity stably associated with the fact. These functions do not implement retaining it or durable sending; nor do they ensure publication and a state change are recorded together.

The CAPTURED condition illustrates a precondition; it does not replace the rules allowing that state to be reached.

Receive without importing the Payments domain

A consumer can validate a JSON string at its boundary:

import { parsePaymentConfirmedV1 } from "./payment-confirmed-v1.js";

export function readPaymentMessage(serialized: string) {
  const raw: unknown = JSON.parse(serialized);
  const message = parsePaymentConfirmedV1(raw);

  return {
    paymentReference: message.paymentId,
    orderReference: message.orderId,
    grossCapturedCents: message.amountMinor,
    confirmationTime: message.occurredAt,
  };
}

This snippet only shows receiving and selecting data. It does not query orders or update their state.

The examples reuse the schema to shorten the tutorial. In real integrations, each consumer can maintain its validator and translate through its ACL, using a common published specification. It need not import Payments entities.

Nor should it trust an arbitrary body merely because it passes Zod. The channel must ensure it comes from a permitted sender, with appropriate size limits and error handling.

Represent the contract through JSON Schema

A published language can provide machine-readable artifacts. This conceptual JSON Schema reflects acceptance of additional properties and our version's main restrictions.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "PaymentConfirmedV1",
  "type": "object",
  "required": [
    "type",
    "schemaVersion",
    "messageId",
    "paymentId",
    "orderId",
    "amountMinor",
    "currency",
    "status",
    "occurredAt"
  ],
  "properties": {
    "type": { "const": "payment.confirmed" },
    "schemaVersion": { "const": 1 },
    "messageId": { "type": "string", "format": "uuid" },
    "paymentId": {
      "type": "string",
      "minLength": 1,
      "maxLength": 64,
      "pattern": "^[A-Za-z0-9_-]+$"
    },
    "orderId": {
      "type": "string",
      "minLength": 1,
      "maxLength": 64,
      "pattern": "^[A-Za-z0-9_-]+$"
    },
    "amountMinor": {
      "type": "integer",
      "minimum": 1,
      "maximum": 9007199254740991
    },
    "currency": { "const": "EUR" },
    "status": { "const": "CONFIRMED" },
    "occurredAt": {
      "type": "string",
      "format": "date-time",
      "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$"
    }
  },
  "additionalProperties": true
}

This is a manually reviewed conceptual representation, not an automated Zod export or proof of equivalence between validators.

In JSON Schema, handling of format depends on the validator and its configuration. Check that UUIDs and dates are validated as expected. The date pattern fixes the form but does not by itself prove the day exists. JSON Schema: string formats.

There is also a deliberate difference: JSON Schema describes whether input is accepted; the Zod parser additionally produces an object without unknown properties.

Do not manually maintain divergent specifications in production. Define a source of truth or controlled generation, and verify the same valid and invalid examples against all published artifacts.

OpenAPI, AsyncAPI, and the conceptual pattern

If the document is part of an HTTP API, OpenAPI can describe its operation and schema. If exchanged through messaging, AsyncAPI can describe channels, messages, and their contracts.

These tools help distribute specifications. They do not decide what “confirmed” means or who is responsible for its evolution.

Having a file named openapi.yaml does not demonstrate a coherent published language exists. It may perfectly document a field named amount without explaining its unit or meaning.

A small specification, examples, a dictionary, and validators suffice for this version. There is no need to build a universal event catalog.

Contract tests and their limits

These proposed examples use Zod 4 and built-in Node.js APIs. They assume compilation to ESM JavaScript. They have not been run as part of the article.

In payment-confirmed-v1.test.ts:

import test from "node:test";
import assert from "node:assert/strict";
import {
  PaymentConfirmedV1Schema,
} from "./payment-confirmed-v1.js";

const validMessage = {
  type: "payment.confirmed",
  schemaVersion: 1,
  messageId: "79a1db8e-4f56-4e69-972b-9ca7d06c1d18",
  paymentId: "payment-100",
  orderId: "order-100",
  amountMinor: 7000,
  currency: "EUR",
  status: "CONFIRMED",
  occurredAt: "2026-01-15T10:30:00.000Z",
};

test("conserva el importe y la unidad acordados", () => {
  const parsed = PaymentConfirmedV1Schema.parse(validMessage);
  assert.equal(parsed.amountMinor, 7000);
  assert.equal(parsed.currency, "EUR");
});

test("rechaza importes como texto y valores fraccionarios", () => {
  assert.equal(PaymentConfirmedV1Schema.safeParse({
    ...validMessage,
    amountMinor: "7000",
  }).success, false);

  assert.equal(PaymentConfirmedV1Schema.safeParse({
    ...validMessage,
    amountMinor: 70.5,
  }).success, false);
});

test("una autorización no es una confirmación", () => {
  assert.equal(PaymentConfirmedV1Schema.safeParse({
    ...validMessage,
    status: "AUTHORIZED",
  }).success, false);
});

test("acepta una propiedad adicional sin utilizarla", () => {
  const parsed = PaymentConfirmedV1Schema.parse({
    ...validMessage,
    sourceChannel: "checkout",
  });

  assert.equal("sourceChannel" in parsed, false);
});

test("rechaza una versión distinta y una fecha sin zona", () => {
  assert.equal(PaymentConfirmedV1Schema.safeParse({
    ...validMessage,
    schemaVersion: 2,
  }).success, false);

  assert.equal(PaymentConfirmedV1Schema.safeParse({
    ...validMessage,
    occurredAt: "2026-01-15T10:30:00.000",
  }).success, false);
});

These are schema tests against examples, not a demonstration of compatibility between real implementations.

To verify integration, Payments must produce documents from known cases, and consumers must interpret them using their validators and expectations. Also test that an internal authorization does not produce the message and that no private fields leak during serialization.

No structural validation will detect that 7000 now means net revenue rather than gross amount. That difference requires a semantic agreement and examples keeping it visible.

Evolve without secretly changing meaning

We can distinguish three kinds of change.

Compatible extension for a particular consumer. Adding an optional field such as sourceChannel may be compatible with our parser because it ignores unknown fields. Check other consumers; not all will have that policy.

Incompatible structural change. Renaming paymentId, requiring a new field, or converting amountMinor to a string requires reviewing consumers.

Incompatible semantic change. Keeping every type while starting to report authorizations instead of captures breaks the promise even if the schema still validates.

Adding another currency is not automatically harmless either. The shown consumer accepts EUR only, and interpretation of units must be agreed.

A new version does not retrospectively modify the previous one

If a new capability needs to distinguish captured and refunded amounts, do not turn amountMinor into a net balance within V1.

Design another representation with explicit meaning and decide whether it belongs to another version or another type of fact. Refunds are not simply another way of confirming payment.

A transition plan must identify consumers, examples by version, a coexistence period, and a retirement criterion. It must not resend old facts as if they had happened again solely because their format changed.

Schema version differs from the version of the package containing a validator. Updating a library does not itself change the language of documents in circulation.

Differences from earlier concepts

Ubiquitous Language: maintains consistency within a context's model. Published Language expresses an agreement for exchange between models. They can share terms without exposing the same details.

Shared Kernel: deliberately shares part of the model and its evolution. Sharing a message specification does not require sharing domain classes or behavior.

Open Host Service: offers integration capabilities through a protocol. Published Language defines how its exchanges are interpreted; both can complement each other.

Anti-Corruption Layer: translates the published exchange into the consumer's own language. A well-documented contract facilitates that translation but does not make it unnecessary when models differ.

A common interface does not authorize direct queries to Payments tables or import its aggregates. Boundaries remain even if everyone understands the document.

Two examples that help detect ambiguities

Logistics: “delivered” to whom

A carrier publishes a completed delivery. Support needs to know whether it was to the recipient, a pickup point, or an authorized neighbor.

A DELIVERED state without a definition can produce incorrect complaint decisions. A published language must specify what is known and preserve as unknown what was not recorded.

There is no need to copy the carrier's entire model. A claim consumers can interpret is needed.

Education: a grade without a scale

An academic system communicates grade: 6. Another interprets it as six out of ten, and a third as six out of seven.

The exchange needs the assessment's scale, scope, and status. Nor is a provisional grade equivalent to a final result.

If only a human-readable report is exported to a single recipient, a brief specification may suffice. Value lies in clarifying meaning, not introducing heavy tools unnecessarily.

A useful specification for AI

For Cursor, Claude, or Codex, provide the schema, semantic dictionary, examples, and compatibility rules.

To design:

Define PaymentConfirmedV1 from this agreement: complete capture in EUR, gross amount in cents, UTC date when confirmation was recorded, and public identities. Separate assertions from what cannot be inferred. Do not serialize the aggregate or invent gateway states.

To generate validators:

Implement Zod 4 validation from this specification. Do not convert numeric strings. Accept new properties without propagating them into the local model. Propose valid and invalid examples and identify differences to check against JSON Schema.

To review an evolution:

Compare these two specifications and known consumers. Classify structural and semantic changes, identify who would stop correctly interpreting the document, and propose a transition. Do not change V1's definition to make tests pass.

A person must verify business facts and equivalence between tools. Automated generation can accelerate implementation; it does not decide the agreement's meaning.

Exercises

1. The same name, a different amount

Analytics asks that amountMinor subtract fees while retaining the rest of V1. Is this a compatible extension?

2. A new field for everyone

Payments adds sourceChannel and claims no consumer can break because the field is optional. What must be checked?

3. A convenient internal type

A team proposes directly publishing the Payment aggregate because it already has all message fields. What problem does that introduce?

Reasoned solutions

1. No. V1 promises gross captured amount. Converting it to net changes its meaning even if name and type remain. Another explicit representation or a new field with defined scope is needed, without changing the earlier promise.

2. Each consumer's deserialization and validation policy. This article's parser accepts and discards unknown properties; a strict one could reject them. Also check the change does not alter interpretation of existing fields.

3. It couples exchange to the internal evolution lifecycle and can expose unnecessary information. Build a selected public representation and maintain its contract independently of the aggregate.

Publish meaning, not just structure

A Published Language is useful when several consumers need to interpret the same information without separately reconstructing its assumptions.

Check every relevant field has a definition, unit, and scope; that examples can be verified; and that a policy exists for evolving the agreement.

The published document enables sharing an assertion. Each context retains its model and responsibility for decisions it makes from it.

Loading conversation…

Keep learning