Skip to content

Multi-Service SaaS

This tutorial shows how to use the SIM (System Integration) model to architect a multi-service SaaS platform, then generate tests and recipes that span service boundaries.

SIM is designed for applications composed of multiple independently deployable services. If your project is a single service (monolith or single SvelteKit app), the five core models (DDD, USM, CBRL, SCM, DSM) are sufficient. Use SIM when:

  • You have three or more services that communicate with each other
  • Services have independent deployment cycles
  • You need to track data contracts between services
  • Constraint propagation across service boundaries matters

We will model an e-commerce platform with four services:

  • Catalog Service – product listings and search
  • Order Service – order management and lifecycle
  • Payment Service – payment processing and refunds
  • Notification Service – email and push notifications
Terminal window
ctxbrew init --name ecommerce-platform --type microservices
cd ecommerce-platform

SIM files are JSON (schema: ctxbrew schema sim). Author .contextbrew/specs/sim.json – four service contexts, their dependency edges (each bound to a typed contract), and cross-cutting invariants:

{
"kind": "sim-file",
"schemaVersion": "0.1.0",
"contexts": [
{ "kind": "system-context", "id": "ctx-catalog", "name": "Catalog Service",
"contextKind": "service",
"description": "Product listings, search, and inventory tracking",
"ownedAggregates": ["Product"], "ownedTables": ["products"] },
{ "kind": "system-context", "id": "ctx-orders", "name": "Order Service",
"contextKind": "service",
"description": "Order creation, updates, and lifecycle management",
"ownedAggregates": ["Order"], "ownedTables": ["orders"] },
{ "kind": "system-context", "id": "ctx-payments", "name": "Payment Service",
"contextKind": "service",
"description": "Payment processing, refunds, and transaction records",
"ownedAggregates": ["Payment"], "ownedTables": ["payments"] },
{ "kind": "system-context", "id": "ctx-notifications", "name": "Notification Service",
"contextKind": "service",
"description": "Email and push notification delivery",
"ownedAggregates": [], "ownedTables": ["notifications"] }
],
"edges": [
{ "kind": "dependency-edge", "id": "edge-orders-payments",
"sourceContextId": "ctx-orders", "targetContextId": "ctx-payments",
"edgeType": "synchronous", "criticality": "critical",
"contractId": "contract-payment-api",
"description": "Order Service requests payment for an order" },
{ "kind": "dependency-edge", "id": "edge-orders-catalog",
"sourceContextId": "ctx-orders", "targetContextId": "ctx-catalog",
"edgeType": "synchronous", "criticality": "high",
"contractId": "contract-inventory-api",
"description": "Order Service checks stock before confirming" },
{ "kind": "dependency-edge", "id": "edge-orders-notifications",
"sourceContextId": "ctx-orders", "targetContextId": "ctx-notifications",
"edgeType": "asynchronous", "criticality": "medium",
"contractId": "contract-order-events",
"description": "Notify customer when order is placed" },
{ "kind": "dependency-edge", "id": "edge-payments-notifications",
"sourceContextId": "ctx-payments", "targetContextId": "ctx-notifications",
"edgeType": "asynchronous", "criticality": "medium",
"contractId": "contract-payment-events",
"description": "Notify customer when payment succeeds" }
],
"contracts": [
{ "kind": "contract", "id": "contract-payment-api", "name": "Payment API",
"contractType": "api",
"schema": { "PaymentRequest": { "orderId": "uuid", "amount": "number", "currency": "string" },
"PaymentResult": { "paymentId": "uuid", "status": "pending | completed | failed" } },
"version": "1.0.0", "status": "active" },
{ "kind": "contract", "id": "contract-inventory-api", "name": "Inventory API",
"contractType": "api", "schema": {}, "version": "1.0.0", "status": "active" },
{ "kind": "contract", "id": "contract-order-events", "name": "Order Events",
"contractType": "event",
"schema": { "OrderPlacedEvent": { "orderId": "uuid", "total": "number" } },
"version": "1.0.0", "status": "active" },
{ "kind": "contract", "id": "contract-payment-events", "name": "Payment Events",
"contractType": "event",
"schema": { "PaymentConfirmedEvent": { "paymentId": "uuid", "orderId": "uuid" } },
"version": "1.0.0", "status": "active" }
],
"invariants": [
{ "kind": "cross-cutting-invariant", "id": "inv-no-db-sharing",
"name": "No direct database access across services",
"expression": "no context reads or writes tables owned by another context",
"involvedContexts": ["ctx-orders", "ctx-payments"],
"severity": "error", "category": "consistency" },
{ "kind": "cross-cutting-invariant", "id": "inv-catalog-async-only",
"name": "Catalog has no synchronous dependencies",
"expression": "no synchronous edge targets ctx-catalog",
"involvedContexts": ["ctx-catalog"],
"severity": "error", "category": "consistency" }
]
}

Validate and inspect it:

Terminal window
ctxbrew sim validate .contextbrew/specs/sim.json # exit 1 on any parse/validation error
ctxbrew sim stats .contextbrew/specs/sim.json # contexts: 4, edges: 4, contracts: 4

Already have services running? ctxbrew ingest-sim scans a codebase for service boundaries and produces the SIM file for you; the Structurizr import (ctxbrew import structurizr) also feeds the same underlying parser.

Each service owns its aggregates. Author one .domain file per service under .contextbrew/ddd/:

# catalog.domain — owned by Catalog Service (ctx-catalog)
AGGREGATE Product {
PROPERTY id: UUID [pk]
PROPERTY name: string [required]
PROPERTY price: number [required, min=0]
PROPERTY stockQuantity: number [required, min=0]
INVARIANT "stock-non-negative"
EXPRESSION "stockQuantity >= 0"
}
# orders.domain — owned by Order Service (ctx-orders)
AGGREGATE Order {
PROPERTY id: UUID [pk]
PROPERTY customerId: UUID [required]
PROPERTY status: string [default="pending"]
PROPERTY total: number [required, min=0]
INVARIANT "valid-status"
EXPRESSION "status IN ('pending', 'confirmed', 'shipped', 'completed')"
}
# payments.domain — owned by Payment Service (ctx-payments)
AGGREGATE Payment {
PROPERTY id: UUID [pk]
PROPERTY orderId: UUID [required]
PROPERTY amount: number [required]
PROPERTY status: string [default="pending"]
INVARIANT "amount-positive"
EXPRESSION "amount > 0"
}
Terminal window
ctxbrew ddd validate .contextbrew/ddd/catalog.domain
ctxbrew ddd validate .contextbrew/ddd/orders.domain
ctxbrew ddd validate .contextbrew/ddd/payments.domain

Create .contextbrew/cbrl/ecommerce.requirements – requirements that span aggregate boundaries:

REQUIREMENT REQ-050 "Order-to-payment flow"
ACCEPTANCE_CRITERIA AC-050 "A confirmed order triggers a PENDING payment in Payment Service"
ACCEPTANCE_CRITERIA AC-051 "Payment Service responds with a payment id"
TEST_CASE TC-050 "Order Service sends PaymentRequest and receives payment_id"
INVOLVES_AGGREGATE Order
INVOLVES_AGGREGATE Payment
ASPECT security(level: "critical")
ASPECT audit(action: "payment", entity: "transaction")
REQUIREMENT REQ-051 "Stock reservation during order"
ACCEPTANCE_CRITERIA AC-052 "Ordering 3 of 5 units reserves stock and leaves 2 available"
ACCEPTANCE_CRITERIA AC-053 "Ordering more units than available is rejected with INSUFFICIENT_STOCK"
TEST_CASE TC-051 "Order for 2 units with 1 in stock is rejected"
INVOLVES_AGGREGATE Order
INVOLVES_AGGREGATE Product
Terminal window
ctxbrew cbrl validate .contextbrew/cbrl/ecommerce.requirements
Terminal window
# Parse + validate the SIM model (cycles, unknown references, malformed edges)
ctxbrew sim validate .contextbrew/specs/sim.json
# Cross-model consistency: SIM criticality, context↔aggregate ownership,
# requirement↔aggregate resolution — one verdict, blocking on critical/major
ctxbrew validate-consistency \
--sim .contextbrew/specs/sim.json \
--ddd .contextbrew/ddd/orders.domain \
--cbrl .contextbrew/cbrl/ecommerce.requirements \
--cross-model

validate-consistency is the multi-service workhorse: it checks that contracts line up across services, that aggregates referenced by requirements exist, and (with --cross-model) runs the context-map↔DDD, context-map↔SIM, and C4↔SIM falsification packs. Exit 1 means a finding blocks. There is no separate deployment-order command – deployment sequencing reads straight off the dependency DAG in the file (the edges array is the order: services with no incoming edges deploy first).

Terminal window
ctxbrew generate --target vitest # failing-first invariant tests (all aggregates)
ctxbrew generate --target gherkin # Gherkin scenarios from acceptance criteria

The vitest scaffolds cover each aggregate’s invariants – per-service by construction, because each aggregate lives in the service that owns it:

// Generated scaffold — fails until the implementation enforces the invariant
describe('Payment invariants', () => {
it('amount-positive: rejects non-positive amounts', async () => {
expect.fail('not implemented');
});
});

Generation targets operate on the CBRL + DDD specs (see ctxbrew generate --help for the full target list). The SIM layer is verified by the consistency gate in Step 5, not by a test target – the contracts and invariants you declared there are what validate-consistency enforces.

Create one recipe per aggregate; each bundles the aggregate’s invariants, the linked requirements, and the failing tests:

Terminal window
ctxbrew recipe create --aggregate Product # Catalog Service scope
ctxbrew recipe create --aggregate Order # Order Service scope
ctxbrew recipe create --aggregate Payment # Payment Service scope
ctxbrew recipe list
ctxbrew recipe export --recipe recipe-002 --format markdown --output order.md

Dispatch them to your agents:

Terminal window
ctxbrew recipe execute recipe-002 --agent claude-code --run

For hosted, provider-backed runs (queueing, streaming, retries, artifact download), use the generation family: ctxbrew generation create, then ctxbrew generation stream <id> and ctxbrew generation download <id>. See Execution Engine.

When you update a spec in one service, SIM traces the impact – with real commands:

Terminal window
# 1. Edit the DDD file, then diff the two snapshots (semantic, report-only)
ctxbrew ddd diff .contextbrew/ddd/orders.domain.bak .contextbrew/ddd/orders.domain
# 2. Re-run the consistency gate: an Order change that touches a contract
# shows up as a finding against the Order→Payment edge
ctxbrew validate-consistency \
--sim .contextbrew/specs/sim.json \
--ddd .contextbrew/ddd/orders.domain \
--cbrl .contextbrew/cbrl/ecommerce.requirements
# 3. Ask the graph directly: everything linked to the Order aggregate
ctxbrew neighbourhood Order

This prevents the common microservice problem of “we changed our API and broke three downstream services we did not know about.”

You modeled a multi-service e-commerce platform using SIM:

  1. SIM – Four services with sync/async dependency edges, typed contracts, and cross-cutting invariants
  2. DDD – Aggregates scoped to the services that own them, one file per service
  3. CBRL – Cross-service requirements spanning aggregate boundaries
  4. Consistency gate – ctxbrew validate-consistency blocks on critical/major findings across the whole graph
  5. Recipes – One per aggregate, dispatched to agents or run through the hosted generation family