Software Architecture

Domain-Driven Design: Shared Kernel, when to share the domain model between Bounded Contexts.

Learn to recognize which part of the model deserves sharing between Sales and Billing. Implement a small monetary concept in TypeScript and understand the agreements, tests, and versions needed to control this deliberate coupling.

Updated on October 29, 2026

Content explored 0%
18px

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

Two teams fix the same calculation

Sales calculates an order amount. Billing prepares invoice amounts. Both represent euros in cents and reject negative amounts for the operations we are studying.

One team fixes overflow detection; the other retains an earlier version. Then someone proposes moving Money, Customer, Order, and repositories into a package called shared to prevent this from recurring.

The first observation may justify sharing something. The second proposal needs a boundary: two contexts working with money does not mean they should share customers, orders, taxes, and persistence.

We will build a small Shared Kernel, identify the agreement that makes it possible, and check where it ends. The example is a hypothetical store with Sales and Billing; it does not propose changing an existing repository's dependency rules.

What is shared in a Shared Kernel

A Shared Kernel is a part of the model teams agree to share and maintain together. It is not just publishing a package: it includes the meaning of its concepts, their rules, and the commitment to evolve them together.

Eric Evans recommends explicitly bounding that subset, keeping it small, and coordinating changes and their integration. Sharing introduces deliberate interdependence; the pattern seeks to manage it, not eliminate it. DDD Reference: Shared Kernel, page 31 of the document.

We can represent it like this:

Sales  ------ depends on ------> commerce-money
Billing ------ depends on ----> commerce-money

commerce-money depends on neither Sales nor Billing.
Both teams agree on its meaning and evolution.

The arrows represent code dependencies. Sales and Billing retain their own models; neither imports the other's internal entities.

The benefit is maintaining a consistent definition where it is truly needed. The cost is that a kernel change stops being an exclusively local decision.

First check that the rules match

Before creating the package, both teams must be able to give the same answers for concrete cases.

For our example, they agree:

  • The value represents a nonnegative EUR amount, expressed in cents.
  • It accepts only JavaScript safe integers.
  • Adding amounts and multiplying by a nonnegative integer quantity must produce another valid amount.
  • It does not perform rounding, currency conversion, discounts, or tax calculations.
  • It does not represent debts, negative refunds, or signed accounting adjustments.
  • It makes no requests and accesses no database.

This list is the example's semantic contract. It is not a universal definition of money.

If Billing needs negative entries and Sales handles only positive amounts, saying “both use Money” is insufficient. They may retain a common positive concept for certain operations and a separate accounting model, or decide sharing is not worthwhile. What matters is not hiding the difference behind parameters such as allowNegativeWhenBilling.

The same fields do not mean the same concept

Two interfaces with amount and currency may represent an estimated price, a received payment, or an outstanding balance. The permitted operations and their meaning may differ.

The useful question is: if a rule changes, should both teams want the same change for the same reason?

An affirmative answer does not guarantee sharing is convenient. Stability, size, and coordination capacity still need consideration. A negative answer signals keeping separate models.

A small boundary for Sales and Billing

The package will be called @commerce/money-kernel. The name is illustrative and does not correspond to a dependency you should install.

The proposed minimal structure is:

packages/
  money-kernel/
    src/
      index.ts
    test/
      money.test.ts
    package.json
    README.md

contexts/
  sales/
    application/
      order-total.ts
    test/
      order-total.test.ts
  billing/
    application/
      invoice-subtotal.ts
    test/
      invoice-subtotal.test.ts

The README must record the preceding agreement, responsible teams, and exclusions. The package contains no Customer, Order, ORM entities, or repositories.

We do not show build or workspace configuration: imports by package name in the following sections assume each package is compiled and resolved by the project. They are design snippets, not a monorepo ready to copy and run.

In a project prohibiting shared domain code between contexts, introducing this pattern requires revisiting that decision. An educational example does not authorize bypassing its current boundaries.

Implement the agreed monetary concept

This is the proposed content of money-kernel/src/index.ts. The class is self-contained in the file and needs no external libraries.

export class NonNegativeEurAmount {
  readonly #cents: number;

  private constructor(cents: number) {
    this.#cents = cents;
    Object.freeze(this);
  }

  static fromCents(cents: number): NonNegativeEurAmount {
    if (!Number.isSafeInteger(cents) || cents < 0) {
      throw new Error("El importe debe ser un entero seguro no negativo");
    }

    return new NonNegativeEurAmount(cents);
  }

  get cents(): number {
    return this.#cents;
  }

  get currency(): "EUR" {
    return "EUR";
  }

  add(other: NonNegativeEurAmount): NonNegativeEurAmount {
    return NonNegativeEurAmount.fromCents(this.#cents + other.#cents);
  }

  multiply(quantity: number): NonNegativeEurAmount {
    if (!Number.isSafeInteger(quantity) || quantity < 0) {
      throw new Error("La cantidad debe ser un entero seguro no negativo");
    }

    return NonNegativeEurAmount.fromCents(this.#cents * quantity);
  }

  equals(other: NonNegativeEurAmount): boolean {
    return this.#cents === other.#cents;
  }
}

The name makes the restriction visible. It does not promise support for every currency or financial calculation.

fromCents(3500) represents 35 euros. The factory revalidates addition and multiplication results; if they leave the safe integer range, the operation fails. We do not use decimal arithmetic to calculate taxes or rates because that responsibility is outside the agreement.

The class exposes only its amount and bounded operations. The private field and absence of mutators prevent an operation from changing the previous object. Object.freeze also expresses the intention not to add properties to the instance.

TypeScript private constructors are compilation restrictions, not a security boundary against hostile code. And the cents getter does not turn arbitrary external JSON into a valid amount: each context must validate inputs and reconstruct the value through fromCents.

Two consumers with their own decisions

Sales calculates an order's lines

The shared package does not decide which products can be purchased or which promotions exist. Sales validates the commercial quantity and uses the agreed monetary operation.

import { NonNegativeEurAmount } from "@commerce/money-kernel";

export interface SalesLine {
  readonly unitPrice: NonNegativeEurAmount;
  readonly quantity: number;
}

export function calculateOrderTotal(
  lines: readonly SalesLine[],
): NonNegativeEurAmount {
  if (lines.length === 0) {
    throw new Error("El pedido necesita al menos una línea");
  }

  return lines.reduce((total, line) => {
    if (!Number.isSafeInteger(line.quantity) || line.quantity <= 0) {
      throw new Error("La cantidad de compra debe ser positiva");
    }

    return total.add(line.unitPrice.multiply(line.quantity));
  }, NonNegativeEurAmount.fromCents(0));
}

The kernel permits multiplication by zero because it is a valid monetary operation within the agreement. Sales prohibits buying zero units because that is a rule of that commercial operation.

This keeps the shared class from knowing concepts such as cart, reservation, or minimum order.

Billing calculates a subtotal, not the entire invoice

Billing can work with lines whose amounts are already calculated. Its local function decides which collection it needs to prepare the subtotal.

import { NonNegativeEurAmount } from "@commerce/money-kernel";

export function calculateInvoiceSubtotal(
  lineAmounts: readonly NonNegativeEurAmount[],
): NonNegativeEurAmount {
  if (lineAmounts.length === 0) {
    throw new Error("La factura necesita al menos una línea");
  }

  return lineAmounts.reduce(
    (subtotal, amount) => subtotal.add(amount),
    NonNegativeEurAmount.fromCents(0),
  );
}

Sales and Billing share arithmetic and representation, but not a generic Document entity with conditions for each context.

The example's result is limited: a subtotal. We have not calculated taxes, issued tax documents, or implemented refunds. If Billing requires those capabilities, it must model them locally or revisit a new, explicit agreement.

Test the agreement and test its uses

A shared suite checks the kernel's rules. Consumer suites check that each context uses it correctly. The first does not replace the others.

These are unit-test examples using built-in Node.js APIs. The files assume TypeScript compilation to ESM JavaScript and package resolution; they have not been run as part of this article.

Kernel rules

import test from "node:test";
import assert from "node:assert/strict";
import { NonNegativeEurAmount } from "../src/index.js";

test("suma sin cambiar los importes originales", () => {
  const first = NonNegativeEurAmount.fromCents(3500);
  const second = NonNegativeEurAmount.fromCents(500);

  assert.equal(first.add(second).cents, 4000);
  assert.equal(first.cents, 3500);
  assert.equal(second.cents, 500);
});

test("rechaza importes negativos y fracciones de céntimo", () => {
  assert.throws(() => NonNegativeEurAmount.fromCents(-1));
  assert.throws(() => NonNegativeEurAmount.fromCents(1.5));
});

test("rechaza cantidades inválidas y resultados no seguros", () => {
  const amount = NonNegativeEurAmount.fromCents(100);

  assert.throws(() => amount.multiply(-1));
  assert.throws(() => amount.multiply(0.5));

  const maximum = NonNegativeEurAmount.fromCents(Number.MAX_SAFE_INTEGER);
  assert.throws(() => maximum.add(NonNegativeEurAmount.fromCents(1)));
  assert.throws(() => maximum.multiply(2));
});

test("representa cero y compara por el importe acordado", () => {
  const zero = NonNegativeEurAmount.fromCents(0);

  assert.equal(zero.currency, "EUR");
  assert.equal(zero.multiply(4).cents, 0);
  assert.equal(zero.equals(NonNegativeEurAmount.fromCents(0)), true);
});

Consumer expectations

In Sales:

import test from "node:test";
import assert from "node:assert/strict";
import { NonNegativeEurAmount } from "@commerce/money-kernel";
import { calculateOrderTotal } from "../application/order-total.js";

test("Sales calcula dos unidades al precio aceptado", () => {
  const total = calculateOrderTotal([{
    unitPrice: NonNegativeEurAmount.fromCents(3500),
    quantity: 2,
  }]);

  assert.equal(total.cents, 7000);
});

test("Sales no acepta una línea con cero unidades", () => {
  assert.throws(() => calculateOrderTotal([{
    unitPrice: NonNegativeEurAmount.fromCents(3500),
    quantity: 0,
  }]));
});

In Billing:

import test from "node:test";
import assert from "node:assert/strict";
import { NonNegativeEurAmount } from "@commerce/money-kernel";
import { calculateInvoiceSubtotal } from "../application/invoice-subtotal.js";

test("Billing suma importes de líneas ya calculadas", () => {
  const subtotal = calculateInvoiceSubtotal([
    NonNegativeEurAmount.fromCents(7000),
    NonNegativeEurAmount.fromCents(500),
  ]);

  assert.equal(subtotal.cents, 7500);
});

test("Billing exige líneas para preparar el subtotal", () => {
  assert.throws(() => calculateInvoiceSubtotal([]));
});

These tests establish an important distinction: zero belongs to the shared model, while conditions for accepting a line or document remain in each context.

Package governance is also part of the pattern

Without a change agreement, money-kernel can become a library one team changes and the other suffers.

A simple policy for this example would be:

  1. Record the need motivating the change and whether it affects existing meaning.
  2. Request review from Sales and Billing owners before modifying the kernel.
  3. Update shared tests and affected use cases in both consumers.
  4. Publish an identifiable version with behavioral notes.
  5. Agree on how and when each consumer incorporates it.

Not every team needs the same process. What matters is that nobody unilaterally changes a rule whose meaning both promise to share.

Nor must the other team authorize every internal Sales change. Coordination belongs to the kernel and surrounding agreements, not all development.

Version without hiding a change in meaning

A package could declare these properties illustratively:

{
  "name": "@commerce/money-kernel",
  "version": "1.0.0",
  "type": "module",
  "exports": "./dist/index.js",
  "types": "./dist/index.d.ts"
}

This snippet assumes compilation generates the indicated files. It does not publish the package or configure a registry.

SemVer distinguishes incompatible API changes, compatible functionality, and compatible fixes through major, minor, and patch versions. To apply it, first define the public API; in this case, we also document the rules consumers expect. Semantic Versioning Specification.

Three possible decisions:

  • 1.0.0 → 1.0.1: correct documentation or a defect restoring documented behavior, reviewing the actual impact.
  • 1.0.0 → 1.1.0: add a compatible operation, such as a comparison retaining all existing rules.
  • 1.0.0 → 2.0.0: change the input unit or remove a public operation consumers use.

Accepting negatives is not a harmless improvement for a class called NonNegativeEurAmount. Before choosing a version number, review whether the proposal breaks the concept or should create another type outside the kernel.

A change can compile and still be semantically incompatible. Switching from cents to euros without changing the number type is an example: 3500 stops meaning the same thing.

Adopting a version requires checking it

In this example, an exact dependency such as "@commerce/money-kernel": "1.0.0", together with the project's lockfile, makes the selected version explicit. It does not make the agreement permanent or prevent vulnerabilities or errors on its own.

Before updating, run the kernel suite and both consumer suites against the candidate version. In a monolith, they can be integrated together. Applications with separate releases may need a compatibility period and an agreed adoption date.

Versioning is not about allowing each team to drift indefinitely with different rules. If that happens, review whether a genuinely shared model still exists.

Why Customer should not enter for convenience

Consider these local-model snippets:

interface SalesCustomer {
  readonly customerId: string;
  readonly purchasingEnabled: boolean;
}

interface BillingRecipient {
  readonly recipientId: string;
  readonly legalName: string;
  readonly taxIdentifier: string;
}

The first supports decisions about a commercial relationship. The second represents data needed for a billing document.

Creating a SharedCustomer with every field introduces unrelated questions into each context: can a buyer exist without tax identification, should a purchase be blocked by an issuance rule, and does correcting a name modify earlier documents?

Sharing entities often expands the coordination surface because it carries identity, behavior, and lifecycle. Agreeing on a shared part is not impossible, but requires much more evidence than finding two properties called id and name.

For this store, we retain separate models and agree on what information crosses the boundary. The consumer's translation need not import the other context's internal entity.

What the shared kernel is and is not

Utility library. Formatting logs or measuring time reuses technical code. It can have several consumers without necessarily sharing a business model.

Shared module. Describes a way to organize or distribute code. It becomes a Shared Kernel when a shared domain subset exists with agreed meaning and governance.

Integration contract. Describes what is exchanged. Two contexts can understand the same JSON and retain different implementations and models.

Published Language. Offers a documented exchange language. It does not require every participant to adopt a common class.

Anti-Corruption Layer. Translates into the consuming model. It is used precisely when retaining different interpretations is useful, although it may coexist with a shared kernel for other concepts.

Sharing NonNegativeEurAmount does not mean sending class instances over the network either. A contract could carry currency and cents; the receiver validates those data and reconstructs its value. The format and its evolution deserve their own agreement.

Two different decisions beyond the store

Reservations: sharing an interval when interpretations match

Planning and reservations use slots with inclusive starts and exclusive ends, expressed as UTC instants. If they share those rules and can coordinate changes, a small interval concept could be a candidate.

But if planning speaks of local calendar days and reservations of exact instants, an identical class would hide a difference. The lesson is to check concrete boundary examples before extracting the type.

Education: retaining two different grades

An academic module handles decimal grades and institutional rules. A game activity displays one to five stars. Both use a number and label, but share neither scale, rules, nor purpose.

Maintaining two small models is clearer than creating Score with options for each case. Structural duplication can cost less than coordinating a false abstraction.

Signs the kernel is growing too large

Stop if methods such as calculateSalesDiscount, repository dependencies, or conditions based on context names appear.

Other signs include every feature requiring a package release, one team accumulating exceptions to avoid breaking the other, or reviews being approved without understanding shared rules.

Do not solve everything by adding generic interfaces. Review whether responsibility is still common. Removing a rule from the kernel can be an improvement even if it adds some lines of code.

If changes can no longer be coordinated or needs diverge, prepare a separation: introduce local types, translate at boundaries, and gradually remove dependencies. Do not abruptly change units or the meaning of persisted data.

Guide AI without generating a global package

These prompts work for Cursor, Claude, or Codex, accompanied by business examples:

To evaluate candidates:

Compare Sales and Billing models. Identify only rules with the same meaning, valid inputs, and operations in both contexts. Distinguish evidence from assumptions. Propose a minimal kernel or justify keeping them separate. Do not extract entities because names match.

To implement the agreement:

Implement an independent package for nonnegative EUR amounts expressed in safe integer cents. Include addition, multiplication by a nonnegative integer, and overflow tests. Exclude taxes, discounts, conversion, repositories, and context dependencies. Separate local Sales and Billing rules.

To review an update:

Review this kernel change against its public contract and both consumers' cases. Look for unit changes, newly accepted values, and context-specific responsibilities introduced into the package. Propose the version and adoption steps with justification. Identify what the business must validate.

A person must confirm meaning, compatibility, and team commitment. AI can detect duplication; it cannot infer from it that a domain agreement exists.

Exercises

1. The negative refund

Billing needs to record a refund of −3500 cents and proposes removing negative-value validation. Sales uses the type for purchase prices. What would you decide before modifying it?

2. The shared discount

Sales wants to introduce applyCampaignDiscount into the kernel because it operates on money. Billing does not decide campaigns. Does that function belong in the package?

3. The compatible update that changes amounts

A version retains the same signatures but starts interpreting fromCents(100) as 100 euros. Its authors publish it as a patch. What went wrong?

Reasoned solutions

1. I would identify whether a refund represents another concept or both want a signed amount. I would not weaken a nonnegative type to satisfy a local need. Billing can model the refund as a direction and positive magnitude, or use its own signed type, according to its rules. Any agreement change requires joint review.

2. Operating on money does not make a rule shared. Campaign discounts belong to Sales while Billing does not have that exact responsibility. Sales can calculate the result and build a valid amount using the agreed operations.

3. The public API's semantics were ignored. Consumer code can compile and produce amounts one hundred times larger. Known-value tests, joint review, and an explicit plan were needed; a unit change is incompatible even if the signature still uses number.

When sharing deserves the commitment

A Shared Kernel makes sense when you can bound a small part of the model, demonstrate that its rules match, and sustain its evolution among all responsible parties.

Before extracting a class, write three things: what it means, what it will not do, and how a change will be approved. If they cannot agree on those, retaining independent models may be clearer.

The package is a consequence of the agreement. Keeping that agreement small and verifiable prevents it from becoming a global business model.

Loading conversation…

Keep learning