Multi-Service SaaS
Multi-Service SaaS
Section titled “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.
When to Use SIM
Section titled “When to Use SIM”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
Scenario: E-Commerce Platform
Section titled “Scenario: E-Commerce Platform”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
Step 1: Create the Project
Section titled “Step 1: Create the Project”ctxbrew init --name ecommerce-platform --type microservicescd ecommerce-platformStep 2: Define the SIM Topology
Section titled “Step 2: Define the SIM Topology”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:
ctxbrew sim validate .contextbrew/specs/sim.json # exit 1 on any parse/validation errorctxbrew sim stats .contextbrew/specs/sim.json # contexts: 4, edges: 4, contracts: 4Already 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.
Step 3: Define DDD Aggregates per Service
Section titled “Step 3: Define DDD Aggregates per Service”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"}ctxbrew ddd validate .contextbrew/ddd/catalog.domainctxbrew ddd validate .contextbrew/ddd/orders.domainctxbrew ddd validate .contextbrew/ddd/payments.domainStep 4: Define Cross-Service Requirements
Section titled “Step 4: Define Cross-Service Requirements”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 Productctxbrew cbrl validate .contextbrew/cbrl/ecommerce.requirementsStep 5: Validate the Topology
Section titled “Step 5: Validate the Topology”# 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/majorctxbrew validate-consistency \ --sim .contextbrew/specs/sim.json \ --ddd .contextbrew/ddd/orders.domain \ --cbrl .contextbrew/cbrl/ecommerce.requirements \ --cross-modelvalidate-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).
Step 6: Generate Cross-Service Tests
Section titled “Step 6: Generate Cross-Service Tests”ctxbrew generate --target vitest # failing-first invariant tests (all aggregates)ctxbrew generate --target gherkin # Gherkin scenarios from acceptance criteriaThe 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 invariantdescribe('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.
Step 7: Create Service-Scoped Recipes
Section titled “Step 7: Create Service-Scoped Recipes”Create one recipe per aggregate; each bundles the aggregate’s invariants, the linked requirements, and the failing tests:
ctxbrew recipe create --aggregate Product # Catalog Service scopectxbrew recipe create --aggregate Order # Order Service scopectxbrew recipe create --aggregate Payment # Payment Service scope
ctxbrew recipe listctxbrew recipe export --recipe recipe-002 --format markdown --output order.mdDispatch them to your agents:
ctxbrew recipe execute recipe-002 --agent claude-code --runFor 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.
Constraint Propagation in Practice
Section titled “Constraint Propagation in Practice”When you update a spec in one service, SIM traces the impact – with real commands:
# 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 edgectxbrew 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 aggregatectxbrew neighbourhood OrderThis 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:
- SIM – Four services with sync/async dependency edges, typed contracts, and cross-cutting invariants
- DDD – Aggregates scoped to the services that own them, one file per service
- CBRL – Cross-service requirements spanning aggregate boundaries
- Consistency gate –
ctxbrew validate-consistencyblocks on critical/major findings across the whole graph - Recipes – One per aggregate, dispatched to agents or run through the hosted generation family
Next Steps
Section titled “Next Steps”- SIM Model for the full SIM reference
- Travel Booking Tutorial for a single-service example
- Recipe Repos for versioning multi-service specs
- Import & Export for Structurizr and other inbound paths
