Domains, Subdomains (Core, Supporting, Generic) & Domain Experts
"Boil the model down. Define a core domain and provide a means of easily distinguishing it from the mass of supporting model and code. Bring the most valuable and specialized concepts into sharp relief. Make the core small." — Eric Evans, Domain-Driven Design Reference (2015), pattern "Core Domain"
Summary: A business is a domain made of subdomains, and they are not equal: the core is where the company wins, supporting subdomains are necessary but not a reason anyone buys from you, and generic subdomains are problems the whole industry has already solved. Spend your best people and your richest models on the core, build supporting parts simply, and buy the generic ones. Focus: Problem space vs solution space and why subdomains and bounded contexts are not 1:1; the three subdomain types and the heuristics behind them (differentiation, complexity, volatility, who else has this problem); how types drift over time; Core Domain Charts and Wardley evolution; Evans's distillation patterns (Domain Vision Statement, Highlighted Core, Cohesive Mechanisms, Segregated Core, Abstract Core); domain experts and how to interview them; discovering subdomains; and how all of this shows up in Go and Laravel repositories and in build-vs-buy decisions. Learning goal: Given a business, list its subdomains, classify each with explicit, re-runnable reasons, place them on a Core Domain Chart, write a Domain Vision Statement for the core, and turn the result into investment (who works where), architecture style (rich model vs CRUD vs vendor adapter) and dependency rules your build enforces.
This chapter is the second step of the DDD learning path. The previous chapter asked why a business should care about DDD at all; this one asks where in the business DDD is worth its cost. It stays in the problem space: what the business does. The solution-space chapters own the rest: the words of each model (Ubiquitous Language), the model boundaries (Bounded Context), the relations between them (Context Maps), and the workshop most teams use to discover all of it (Event Storming). On the architecture side, Service Boundaries explains how these lines become teams and deployables.
The running example used across the whole DDD path: an online ordering and fulfilment business. Customers browse a catalogue, place orders at prices shaped by promotions and flash sales, pay, receive invoices and get parcels the same day. The five bounded contexts used in every chapter are Sales, Fulfilment, Billing, Catalog and Identity.
Page map
| If you are looking for | Go to |
|---|---|
| The whole chapter in three tables | Everything in one minute |
| Why not all parts of a system deserve equal effort | Why it exists |
| Evans 2003 to Core Domain Charts and Wardley maps | Where it comes from |
| Domain, subdomain, problem space vs solution space | Domain, Subdomain, Problem vs solution space |
| Core, supporting, generic in depth | Core domain, Supporting, Generic |
| Differentiation, complexity, volatility, "who else has this problem?" | Classification heuristics |
| Why last year's core is this year's commodity | Types change over time |
| Complexity × differentiation picture | Core Domain Chart |
| One page that says what the core is | Domain Vision Statement |
| Highlighted, segregated, abstract core, cohesive mechanisms | Distillation techniques |
| Who the experts are and how to talk to them | Domain experts, Interviewing and knowledge crunching, The proxy expert |
| Capability maps, org charts, value chains, event storming | Discovering subdomains |
| The ordering business classified, with alternatives | The running example in full |
| Workshop steps, investment mapping, schema per subdomain | Mechanics |
| Repository layout by subdomain type, with tests | Go, Laravel |
| Everything-is-core, home-made auth, outsourced core | Solving the classic problems |
| Build vs buy vs outsource | Choosing |
| Monolith to distributed system | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example (running example) | What goes wrong without it |
|---|---|---|---|
| Domain | The business area the company works in | Online ordering and same-day fulfilment | Software built for "a shop" in general, good at nothing |
| Subdomain | One distinct area of activity the business needs | Sales ordering, Fulfilment, Billing, Catalog, Identity, Notifications | One big model where invoices and pricing rules tangle |
| Problem space | What the business does and needs, regardless of software | "We promise delivery by 18:00 if ordered by 12:00" | Teams design classes before they understand the problem |
| Solution space | What we build: models, bounded contexts, services | The Fulfilment context and its Shipment aggregate | Architecture mirrors guesses, not the business |
| Core domain | Where the company wins against rivals | Pricing, promotions and order acceptance at checkout | Best engineers polish the login page; pricing rots |
| Supporting subdomain | Needed, specific to us, not a reason customers choose us | Invoice numbering and layout | Gold-plated back office, slow core |
| Generic subdomain | Everyone has it; already solved | Sign-in, card payments, sending email | Home-made auth with a security hole |
| Domain expert | The person who knows how the business really works | The pricing manager, the warehouse shift lead | Developers invent rules, users work around the software |
| Domain Vision Statement | One page that says what the core is and why it matters | "We win on fair, dynamic prices at a checkout customers trust" (Sales is the core) | Every team believes its part is the core |
| Core Domain Chart | Subdomains plotted on differentiation × complexity | Sales top right, Identity left strip | Investment decided by who shouts loudest |
The three types side by side (sources: Evans's DDD Reference, Khononov's 2018 post, Kaiser's Architecture for Flow excerpt; see history):
| Core | Supporting | Generic | |
|---|---|---|---|
| Competitive advantage | Yes, the reason customers pick you | No | No |
| Specific to your business | Yes | Yes | No, everyone has it |
| Typical complexity | High (rules, invariants, algorithms) | Low (CRUD plus validation) | Can be high, but solved by someone else |
| Volatility | High: rules are tuned constantly | Low to medium | Low |
| Sourcing | Build in-house | Build cheaply, low-code, outsource, or configure a product | Buy, adopt open source, use SaaS |
| People | Your best engineers, close to experts | Any competent team, juniors with review | Integration skill, not domain skill |
| Design style | Rich domain model, deep tests | Transaction script, Active Record | Thin adapter behind a port |
| Wardley stage (Kaiser) | Genesis or custom-built | Custom-built or product | Product or commodity |
The running example at a glance (reasoning in The running example in full):
| Subdomain | Type | Served by | Alternative if the business differs |
|---|---|---|---|
| Sales ordering (pricing, promotions, flash sales, acceptance) | Core | Sales context, rich model | None: if this is not core, the company has no software edge |
| Fulfilment (slotting, same-day promise, carrier choice) | Core or supporting | Fulfilment context | Supporting if shipping is handed to a third-party logistics (3PL) partner |
| Billing and invoicing | Supporting | Billing context, transaction scripts | Generic if Stripe Invoicing or an ERP covers local tax rules |
| Catalog | Supporting | Catalog context, CRUD | Core for a marketplace that competes on search and merchandising |
| Identity and access | Generic | Identity context over Laravel Fortify / Socialite or an IdP | Core only for an identity vendor |
| Notifications | Generic | Laravel Notifications / Go adapter + email provider | Supporting if messages carry complex, regulated content |
| Payment processing | Generic | Stripe, behind a port in Billing | Core only for a payment company |
Why it exists
Every non-trivial system contains far more code than its owners can make excellent. A shop needs login, invoices, catalogue screens, emails, a pricing engine, warehouse logic and a dozen reports. Time, money and the best people are scarce. If effort is spread evenly, the part that decides whether the company wins gets the same attention as the password-reset email. Evans names the trap directly: "scarce, highly skilled developers tend to gravitate to technical infrastructure or neatly definable domain problems that can be understood without specialized domain knowledge." The subdomain types are a tool for spending unevenly, on purpose.
| Treat every part the same | Classify subdomains and invest by type |
|---|---|
| Every module gets the same patterns and the same review rigour | Rich model and heavy testing in the core; plain CRUD elsewhere |
| The best engineers pick the most interesting technical work | The best engineers are assigned to the core, and hired for it |
| Auth, payments and email are built "because we can" | Generic problems are bought; the saved budget goes to the core |
| Architecture debates are about technology | Architecture debates start from "is this core?" |
| Easier at first: no classification meeting | Harder at first: you must understand the business and agree |
| Good for: a tiny product with one obvious job | Good for: anything with more than one team or more than a year of life |
The analogy we reuse on this page: a family restaurant. People come for the grandmother's signature stew: that recipe, how it is cooked and adjusted every season, is the core. The reservation book and the weekly staff rota are specific to this restaurant and must work, but nobody visits for them: supporting. Electricity, the card terminal, the accountant and the dishwasher are needed by every restaurant on the street and are bought, not invented: generic. A restaurant that builds its own card terminal while the stew recipe sits on a sticky note is the classic failure this chapter is about. The grandmother is the domain expert; the new manager who "knows what she wants" is the proxy.
The picture shows the two spaces. On the left, the business: one domain, seven subdomains, each with a type. On the right, what the team builds: five bounded contexts and two external services. The lines are not one-to-one. Payment processing is served by Stripe behind the Billing context; Notifications is a library that several contexts call; Sales ordering maps cleanly onto the Sales context. That mismatch is normal and is explained in problem space vs solution space.
Three common misunderstandings, up front
- "Our whole system is core; we are special." If everything is core, nothing is. Evans's advice is "Make the core small." Khononov's post adds that a company can even have no core in software at all when its edge lies elsewhere (for example, relationships).
- "Generic means simple." Identity and payments are among the hardest software problems there are. Generic means solved by someone else, not easy. Kaiser: generic subdomains "could be complex, but their solutions have already been created by someone else."
- "A subdomain is a microservice." A subdomain is part of the business (problem space). A bounded context is a model boundary (solution space). A service is a deployment unit. They often line up; they do not have to.
Where it comes from
Evans, 2003 and 2015. Eric Evans's Domain-Driven Design (2003) has a part on strategic design whose distillation chapter introduces the core domain, generic subdomains, the domain vision statement, highlighted core, cohesive mechanisms, segregated core and abstract core. His free DDD Reference (2015, CC BY 4.0) restates each as a pattern summary; that is the version we quote. Note what is not there: the Reference has no pattern called "supporting subdomain". The word "supporting" appears as an adjective ("the mass of supporting model and code", "Factor all generic or supporting elements into other objects"). The three-way taxonomy as practitioners use it today came later.
Vernon, 2013. Vaughn Vernon's Implementing Domain-Driven Design (2013), chapter 2 "Domains, Subdomains, and Bounded Contexts", is the usual citation for core, supporting and generic as a triad and for the advice that bounded contexts should ideally align with subdomains. We could not read that chapter (the publisher's preview is blocked to automated readers), so we do not quote it; the claims we make about the triad are quoted from the sources below. Fowler's bliki entry on DDD (22 April 2020) calls Vernon's book "a good next step, describing some later thinking and focusing particularly on the strategic design aspect."
Nickolaisen, 2009. Niel Nickolaisen's Purpose Alignment Model (published on InformIT, 20 August 2009, from Stand Back and Deliver) classifies business processes on two axes: "The extent to which the process or requirement will differentiate us in the marketplace" and "The extent to which the process or requirement is mission-critical". Its four quadrants (Differentiating, Parity, Partner, Who Cares?) are a close cousin of the subdomain types, from a non-DDD source.
Khononov, 2018. Vlad Khononov's post Revisiting the Basics of Domain-Driven Design (26 January 2018) proposed the complexity-based categorisation many teams now use, explicitly as his own view: "the last time we spoke about it, Eric and Vaughn were not fans of my theory." His later book Learning Domain-Driven Design (O'Reilly) builds on it; we quote only the post.
Wardley maps. Simon Wardley's maps put components of a value chain on an evolution axis with four stages; the Learn Wardley Mapping introduction lists them as "Genesis, Custom, Product, and Commodity". The idea that everything evolves is the reason subdomain types drift.
Core Domain Charts. The DDD-Crew repository core-domain-charts (Nick Tune and contributors, CC BY 4.0) plots subdomains on business differentiation (x) and model complexity (y). The README says it "was inspired heavily by" Wardley Mapping and Team Topologies. The DDD-Crew DDD Starter Modelling Process uses it in its "Strategize" step.
Team Topologies. Matthew Skelton and Manuel Pais's four team types (stream-aligned, enabling, complicated-subsystem, platform) and their focus on cognitive load give the team side of the same decision; see Service Boundaries.
Kaiser. Susanne Kaiser's Architecture for Flow combines DDD, Wardley Mapping and Team Topologies. Its chapter 2 excerpt on InformIT, "Exploring the Problem Space with Strategic Domain-Driven Design and Wardley Mapping", maps each subdomain type to Wardley evolution stages and to build-or-buy advice; we quote it for problem space vs solution space.
Year Source What it added
1 2003 Evans, Domain-Driven Design (book) Core domain, generic subdomains, distillation patterns
2 2009 Nickolaisen, Purpose Alignment Model Differentiating vs mission-critical, outside DDD
3 2013 Vernon, Implementing DDD (ch. 2) Core / supporting / generic as a triad (not read here)
4 2015 Evans, DDD Reference (free) Pattern summaries we quote on this page
5 2018 Khononov, "Revisiting the Basics" Classification by complexity and "can we buy it?"
6 n.d. Skelton & Pais, Team Topologies (book) Team types, cognitive load
7 2026 Kaiser excerpt on InformIT Subdomain types mapped to Wardley stages
8 n.d. DDD-Crew Core Domain Charts (GitHub) Differentiation x complexity, movement over timeThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, a comparison table, and the fix or how to use it.
Domain Must-know
In plain words: the domain is the business you are in: the area of activity the software exists to serve.
Common misunderstanding: "The domain is the data model" or "the domain layer". In DDD the domain is the real-world business area; the domain model is our software abstraction of part of it, and the domain layer is where that model lives in code.
Definition: Khononov defines the domain as "a company's overall business area". Kaiser uses problem domain and business domain as synonyms and defines the problem domain as "an organization's scope or area of focus". A company may work in more than one domain; Khononov's example is Amazon in retail and in cloud computing.
Question to the CEO Answer What it tells you
1 "What do you sell, to whom?" Same-day delivery of home goods Domain: online ordering + fulfilment
2 "Why do customers pick you?" Promise kept, fair prices Candidate core: pricing, fulfilment promise
3 "What would you never outsource?" Pricing rules, delivery slots Strong core signal
4 "What do you just need to work?" Invoices, login, emails Supporting and generic candidatesReal scenario: a meal-kit company and a supermarket both "sell food online" but are in different domains: one designs recipes and subscription boxes, the other runs grocery logistics. A bank's domain is not "banking software" but lending, payments and deposits, each of which may be a domain of its own at scale.
| Word | Space | Example |
|---|---|---|
| Domain | Problem | Online ordering and fulfilment |
| Domain model | Solution | The classes and rules in the Sales context |
| Domain layer | Solution (code) | app/Modules/Sales/Domain, sales/ package |
| Domain expert | People | Pricing manager, warehouse lead |
How to use it: write the domain in one sentence that a new employee would recognise. If you need three sentences, you may have more than one domain.
Subdomain Must-know
In plain words: a subdomain is one area of work the business must do to succeed in its domain: selling, shipping, billing, keeping a catalogue, letting people sign in.
Common misunderstanding: "Subdomains are modules we chose." Subdomains are discovered, not designed. They exist even if the software is one PHP file, because the business does those activities anyway.
Definition: Khononov: subdomains "are called subdomains because by themselves they aren't enough for the company to succeed; together, they add up the company's business domain." Kaiser: "Subdomains are subparts of the problem domain; however, not all subdomains are equal." Subdomains can nest: Fulfilment contains slotting, picking and carrier selection.
One customer order, walked through the business (not the software)
1 Customer finds a product -> Catalog
2 Customer signs in -> Identity and access
3 Checkout prices the basket -> Sales ordering (promotions, flash-sale limits)
4 Card is charged -> Payment processing
5 Invoice is issued -> Billing and invoicing
6 Warehouse picks, packs, books courier -> Fulfilment
7 Customer gets "on its way" email -> NotificationsReal scenario: an insurer's subdomains are underwriting, claims, policy administration, broker commissions and document generation. A ride-hailing company has matching, pricing, payments, driver onboarding and support.
| Clue | Suggests a separate subdomain | Example |
|---|---|---|
| Different experts | Yes | The accountant vs the warehouse lead |
| Different vocabulary for the same word | Yes | "Order" in Sales vs "shipment order" in Fulfilment |
| Different rate of change | Often | Promotions weekly, invoice layout yearly |
| Different regulations | Often | Tax invoices, card data (PCI DSS) |
| Same data, same rules, same people | No, same subdomain | Product title and description |
How to use it: list subdomains as verbs or capability nouns ("pricing", "invoicing"), never as tables ("products", "users"). Tables lead to entity services; see Service Boundaries.
Problem space vs solution space Must-know
In plain words: first understand what the business must achieve (problem space), then decide how the software is shaped (solution space). Subdomains belong to the first; bounded contexts to the second.
Common misunderstanding: "Every subdomain becomes exactly one bounded context and one service." Often they line up, but not always, and forcing it creates odd models.
Definition: Kaiser: "While the problem space focuses on which problems to solve, the solution space concentrates on how to solve these problems. The solution space of strategic design is about making high-level design decisions, decomposing the system into modular components (the bounded contexts), and mapping the integrations between them (the context maps)." She warns that skipping the problem space "creates a risk of implementing the solution of a barely understood problem domain and investing in parts providing undifferentiating value."
Why they are not 1:1:
| Mapping | When it happens | Running example |
|---|---|---|
| 1 subdomain → 1 bounded context | The ideal; language and rules fit one model | Sales ordering → Sales context |
| 1 subdomain → 0 contexts we build | Generic, bought as a product or SaaS | Payment processing → Stripe |
| 1 subdomain → several contexts | Large or with conflicting models | Fulfilment → Slotting context + Carrier context at 10× scale |
| Several subdomains → 1 context | Small, same team, same language, early stage | Billing context also hosts the payment port |
| 1 subdomain spread across contexts | A capability every context uses | Notifications: a library called by Sales, Billing, Fulfilment |
| Legacy system covers many subdomains | A big ERP or monolith | One ERP does invoicing, stock and purchasing |
Workshop timeline: from problem to solution
1 Business walk-through with experts problem space: subdomains named
2 Classify: core / supporting / generic problem space: investment decided
3 Event storming per core subdomain problem space: rules and events found
4 Draw model boundaries where language shifts solution space: bounded contexts
5 Decide relations (ACL, OHS, conformist) solution space: context map
6 Decide deployables and teams solution space: services, team topologyReal scenario: a payments start-up's "fraud scoring" subdomain is served by two contexts (real-time rules and offline model training) owned by one complicated-subsystem team. A school-management product puts "timetabling" and "room booking" in one context for its first two years because one developer owns both and the vocabulary is shared.
How to use it: keep two lists: subdomains (with types) and bounded contexts (with owners). Draw lines between them. Lines that are not 1:1 are fine if you can explain them; lines nobody can explain usually mean a missing context or a context that does two jobs. The drawing of contexts is the subject of Bounded Context.
Core domain Must-know
In plain words: the core domain is the part of the business where the company beats its rivals; the reason customers come back. It deserves the best people, the deepest model and the most tests.
Common misunderstanding: "Core means the most important." Billing is critical (no invoices, no company), but it is rarely differentiating. Core means differentiating and worth investing in, not the thing that hurts most when it breaks.
Definition: Evans: "Define a core domain and provide a means of easily distinguishing it from the mass of supporting model and code. [...] Apply top talent to the core domain, and recruit accordingly. [...] Justify investment in any other part by how it supports the distilled core." Khononov: "Core subdomains are the secret sauce of your organization. [...] They bring competitive advantage to your company." He adds that they are complex by nature, because "No one will invest in something that their competitors might quickly copy", and that their logic "usually it changes often". Kaiser: the core domain "usually provides the most value to customers and differentiates the organization from its competitors", "is typically complex", and "also tends to change quite often."
Pricing change in the Sales core (one week)
1 Mon Pricing manager: "cap Black Friday discounts at 100 EUR per line"
2 Mon Engineer + manager write the rule as a test in the Sales package
3 Tue Rule added to Promotion; floor-price invariant still holds (tests green)
4 Wed Flash-sale limit raised for consoles; one-line policy change
5 Thu Deploy Sales alone; Billing, Catalog, Identity untouched
6 Fri Manager reads conversion numbers; asks for a second tweak next week
Volatile, expert-driven, tested, isolated: the signature of a healthy coreReal scenario: Netflix-style recommendation and encoding, an insurer's risk pricing, a marketplace's matching or ranking, a logistics company's routing and promise engine, a bank's credit decisioning. Khononov's own company had several cores: "Campaign Optimization, Lead Prioritization, Agents' Commissions Management".
| Signal | Core | Not core |
|---|---|---|
| Would a competitor copying it hurt you? | Yes | No |
| Does the business tune its rules often? | Weekly or monthly | Yearly, or by regulation |
| Can you buy it off the shelf? | Not without losing the edge | Yes |
| Who decides the rules? | Your own experts | Law, standards, vendors |
| Do you measure its business performance? | Conversion, margin, promise kept | Uptime only |
How to use it: name one to three core subdomains, write them into a Domain Vision Statement, put them in their own packages with a rich model (Anemic vs Rich Models, Aggregates), staff them with your strongest engineers, and run them close to the experts. See the Go sales package and the Laravel Sales\Domain namespace.
Supporting subdomain Must-know
In plain words: a supporting subdomain is specific to your business and needed by the core, but nobody chooses you because of it. Build it simply and cheaply, or outsource it.
Common misunderstanding: "Supporting means unimportant, so quality does not matter." It must still be correct; an invoice with the wrong tax is a legal problem. It means no extra investment beyond correct and maintainable.
Definition: Khononov: "Supporting subdomains, like Generic subdomains, do not offer any competitive edge for the company. On the other hand, there are no existing off-the-shelf solutions." Their logic "should be simple enough to be rolled out with some rapid application development framework, or outsourced altogether". If the logic turns out complex: "this complexity is accidental and should be simplified", unless there are real reasons, in which case "it might be a Core subdomain in disguise." Kaiser's variant differs on one point: she calls the supporting subdomain "specialized but non-differentiating" and says that "If highly customizable products or open-source software solutions are available, buying or using existing products is a good approach". Both agree: no competitive advantage, keep investment low.
Billing request handled as a supporting subdomain
1 Accountant: "invoice numbers must have no gaps per legal entity"
2 Developer adds a sequence table + one locked UPDATE (transaction script)
3 Tests: one happy path, one concurrency test
4 Done in a day; no aggregate, no events beyond "InvoiceIssued"
If step 2 needed 3 weeks of modelling: stop and ask "is this accidental complexity?"Real scenario: a back-office screen to manage delivery zones; a returns form; a supplier contact list; Khononov's "Creatives Catalog" that manages banners and landing pages, which "We don't make any money from" but had to be built because no product fitted.
| Choice for a supporting subdomain | When | Cost / risk |
|---|---|---|
CRUD in the main framework (Eloquent, database/sql) | Default | Low; drifts into a mess if rules grow |
| Low-code or admin generator (Filament, Laravel Nova) | Mostly forms and lists | Vendor lock-in for screens |
| Configure a product (ERP module, ticketing tool) | A product fits 80% | Over-customisation (Kaiser's warning) |
| Outsource to another team or vendor | Clear contract, low change | Hand-off latency, less control |
| Rich domain model | Almost never; reconsider the type first | Steals effort from the core |
How to use it: use transaction scripts or Active Record (Data Persistence in Design), keep it behind a narrow interface so it can be replaced, and watch two numbers: how often it changes and how many rules it has. Rising numbers mean either simplify or promote it. See catalog and billing.
Generic subdomain Must-know
In plain words: a generic subdomain is a problem every company has and someone has already solved well: sign-in, card payments, email, PDF rendering, accounting ledgers. Buy it, adopt open source, or use a service.
Common misunderstanding: "If it is generic, we can build a small version quickly." Home-made password storage, token handling and card processing are classic sources of breaches and audits. Generic means the industry has paid for the hard lessons already.
Definition: Evans: "Identify cohesive subdomains that are not the motivation for your project. Factor out generic models of these subdomains and place them in separate modules. Leave no trace of your specialties in them." He adds: "avoid assigning your core developers to the tasks (because they will gain little domain knowledge from them). Also consider off-the-shelf solutions or published models for these generic subdomains." Khononov: "Generic subdomains are those things that all companies do the same way." He calls them solved problems. Kaiser names "authentication or payment handling" as examples and says buying, open source or "outsourcing to utility suppliers makes sense for generic subdomains."
Adding passkeys to sign-in, generic subdomain bought
1 Security asks for passkeys (WebAuthn)
2 Upgrade laravel/fortify; enable Features::passkeys() in config
3 Run vendor migrations; add the trait to User
4 Done; Sales, Billing, Fulfilment never knew
Same task in a home-made auth module: weeks, a security review, and new bugsReal scenario: identity via Auth0, Okta, Keycloak, AWS Cognito or framework packages; payments via Stripe, Adyen or PayPal; email via Amazon SES, Postmark or SendGrid; search via Elasticsearch or OpenSearch (for a shop whose edge is not search); tax rates via a tax API.
| Generic subdomain | Laravel 13 option | Go option | Hosted / SaaS options |
|---|---|---|---|
| Password sign-in, reset, verification, 2FA, passkeys | Laravel Fortify (headless) | Use an IdP; golang.org/x/oauth2 for OAuth flows | Auth0, Okta, Keycloak (self-hosted), AWS Cognito |
| Social / OAuth sign-in | Laravel Socialite | golang.org/x/oauth2 (+ provider endpoint packages) | Same IdPs |
| Card payments, subscriptions | Laravel Cashier (Stripe; a Paddle edition exists) | github.com/stripe/stripe-go/v87 | Stripe, Adyen, PayPal |
| Transactional email / SMS | Laravel Notifications + Mail drivers | net/smtp or a provider SDK | Amazon SES, Postmark, SendGrid, Twilio |
| API tokens | Laravel Sanctum / Passport | golang.org/x/oauth2/clientcredentials | IdP machine-to-machine tokens |
How to use it: wrap each generic capability behind a port your code owns (PaymentGateway, Notifier), keep vendor SDK imports inside one adapter package or module, and enforce that with an architecture test (Go, Laravel). Kaiser's caution applies: "over-customizing off-the-shelf products beyond their core purpose can be costly".
Classification heuristics Must-know
In plain words: four questions decide the type: does it make us different, is it complex, does it change often, and does everyone else have the same problem?
Common misunderstanding: "Classification is a one-off architect's opinion." It is a conversation between business and engineering, recorded with reasons, and repeated. The Core Domain Charts README: "Complexity is something that engineers can gauge whereas business differentiation is provided by product managers or business stakeholders."
Definition: Khononov's "easy categorization", quoted: "Can you buy/adopt an off-the-shelf product without compromising the company's competitive advantage? - Generic Subdomain. Is the business logic simple? - Supporting Subdomain. Finally, if you can't buy a product, and the subdomains' business logic is complex, then it's a Core Subdomain." His complexity checks: CRUD-like and "described by the Domain Experts in CRUD terms" means simple; "complex algorithms and calculations" or "business rules and invariants that should be enforced" mean complex. The Core Domain Charts README adds differentiation probes, among them "How hard would it be for a new entrant to the market to match or exceed the capability?" and "What damage would occur to the brand if major or recurring failures happened in the domain?"
| Heuristic | Question to ask | Points to core | Points to supporting | Points to generic |
|---|---|---|---|---|
| Business differentiation | Would customers pick us over a rival because of it? | Yes | No | No |
| Complexity | Rules, invariants, algorithms, or CRUD plus validation? | Complex | Simple | Either (solved) |
| Volatility | How often do the rules change? | Often (tuned) | Rarely | Rarely, by standards |
| Who else has this problem? | Does every company in every industry need it? | Only us (this way) | Companies like us | Everyone |
| Can we buy it? | Without losing the edge? | No | Not quite; nothing fits | Yes |
| Expertise | Is scarce specialist knowledge needed? | Our own experts | Ordinary | Vendor's experts |
| Failure damage | Brand damage if it fails repeatedly? | High and unique | Moderate | High but shared (vendor SLA) |
The flow starts with Khononov's first question (can we buy it without losing our edge? then generic), adds a differentiation question taken from the Core Domain Chart probes, and ends with Khononov's complexity question. His own order is only buy → simple → otherwise core. The bottom box is the interesting case: a supporting subdomain that refuses to be simple is either accidental complexity to remove or a core in disguise.
Classifying "Returns" in a workshop
1 Engineer: 14 rules, refund depends on condition, age, promotion used complexity 5
2 Product: customers don't pick us for returns differentiation 3
3 Ops: rules change every season volatility 4
4 Buy? no product handles our promotion-aware refunds not generic
5 Flow says supporting + warning "core in disguise or accidental"
6 Business decision: simplify to 4 rules (accidental), stays supportingReal scenario: an e-commerce "returns" area that grew 14 rules because each campaign added one; a "delivery zones" screen that suddenly needs travel-time polygons (a signal to re-score Fulfilment: core if same-day becomes why customers buy); a "loyalty points" feature that marketing calls strategic but is copied from a competitor (likely supporting, possibly first-to-market core).
How to use it: score each subdomain 1–5 on differentiation, complexity and volatility, plus a yes/no for "buyable without losing the edge", and keep the scores in the repository next to the code. The Go classify package turns these answers into a verdict and a warning so the conversation can be re-run.
Subdomain types change over time Important
In plain words: today's core becomes tomorrow's commodity once competitors catch up, and a boring supporting area can become core when the strategy changes.
Common misunderstanding: "Once classified, a subdomain keeps its type." Types are a bet on the current market. Kaiser: "today's core domain won't perpetually remain core", and "each component of a system is always in a state of change and evolves over time—and that also includes the subdomains."
Definition: the subdomain type follows market evolution. Kaiser maps types to Wardley stages: core mostly "genesis or custom-built"; supporting in the custom-built or product stage; generic in "product + rental or commodity + utility". As the core matures, "it can evolve to the product evolution stage and potentially become a commodity", and its differentiation advantage decreases while cost advantage can increase. The DDD-Crew example "First-to-Market Core" describes a core that will not last: early music streaming, where having "a catalogue with all of the world's top artists was the key", until "most platforms had the world's top artists in their catalogue. Now the core domain was discovery".
The arrows are illustrations: a same-day promise that drifts from core to supporting as rivals match it, card payments that moved from in-house code to a commodity API, and a dashed arrow for the opposite move, a bought capability rebuilt in-house because the company decides to compete on it.
Fulfilment over four years (its type follows the differentiator)
1 Year 1 Same-day promise is rare; we built slotting and routing core
2 Year 2 Two rivals copy same-day in big cities still core, edge shrinking
3 Year 3 3PL vendors sell same-day as a product cost advantage now matters
4 Year 4 We switch to a 3PL API, keep a thin promise calculator supporting
Team moves from Fulfilment to the new core (dynamic pricing)Real scenario: online payments (core for early web shops that built their own gateways, now generic via Stripe-style APIs); search (generic for most shops via Elasticsearch, core for a marketplace that competes on ranking); in Khononov's post, a "Creatives Catalog" that is supporting for one company and "would be a Core subdomain" for a company specialised in managing creative materials.
| Drift | Trigger | What to do in code | What to do with people |
|---|---|---|---|
| Core → supporting | Competitors match it, market productised | Freeze the rich model; simplify; consider buying | Move senior engineers to the new core |
| Core → generic | A product or API now does it | Replace with an adapter; strangle the old code | Retire the module; keep one maintainer |
| Supporting → core | Strategy change, new edge found | Extract to its own package; add a rich model and tests | Assign strong engineers; find the experts |
| Generic → core | You decide to compete on it (rare) | Build in-house behind the existing port | Hire specialists |
How to use it: review the classification on a schedule (quarterly works) and whenever strategy changes. Record movement in the Core Domain Chart with arrows, as the DDD-Crew notation does with "Movement over time".
Core Domain Chart Important
In plain words: a picture that places each subdomain by how much it differentiates the business (left to right) and how complex its model is (bottom to top), so a room of people can argue about the dots instead of in the abstract.
Common misunderstanding: "The chart is the deliverable." The README is explicit: "The true power of this technique is the conversations that it triggers, especially cross-discipline."
Definition: a Core Domain Chart (DDD-Crew, Nick Tune and contributors) has Business Differentiation on the x-axis and Model Complexity on the y-axis (read from the template image in the repository). The template shades a narrow Generic strip at low differentiation for all complexities, a Core area at high differentiation and medium-to-high complexity, and Supporting everywhere else. Its notation adds current and future positions, "Movement over time", "Big-bet sub-domain", "Platform sub-domain", "Outsourced/Purchased sub-domain", team size and Team Topologies interaction modes. The README says measuring both axes "is hard and is usually quite subjective", and that "Strategy is a bet on the future".
The chart places the running example. Sales ordering is top right: highest differentiation and complexity, and the one core subdomain. Fulfilment sits on the Core/Supporting border, "core or supporting": core only while same-day delivery is why customers choose the shop, with a dashed arrow toward Supporting over two to four years as same-day delivery becomes table stakes. Billing and Catalog are Supporting. Identity sits high in the Generic strip (complex but bought); Notifications low in it.
A 90-minute Core Domain Chart session
1 00:00 Engineers place every subdomain on the y-axis (complexity)
2 00:20 Product/business place them on the x-axis (differentiation)
3 00:40 Discuss the dots that moved most between the two passes
4 01:00 Draw future positions and arrows (2-4 year horizon)
5 01:15 Mark bought/outsourced, big bets, team sizes
6 01:30 Agree actions: who moves, what we buy, what we stop buildingReal scenario: a scale-up deciding which of three teams to grow; an architecture migration, where the README suggests that "With a slight tweak of the y-axis label" the chart can plan migration order; a portfolio review that finds the best engineers on a Supporting subdomain.
| Flavour (from the README) | What you plot | Question it answers |
|---|---|---|
| Portfolio | Each subdomain or bounded context | Where should effort go? |
| Context map with Team Topologies | Dots + dependencies + interaction modes | Which teams depend on which, and how? |
| Architecture migration | Dots with a changed y-axis label | In which order do we migrate? |
| Pioneers / experiments area (example) | An experimental zone right of Core | Where is the next core coming from? |
How to use it: run it with engineers and business people, use relative placement rather than precise scores, photograph it, keep it in the repository, and update it with arrows. The Go cmd/chart prints the same placement from the scores.
Domain Vision Statement Important
In plain words: one page that says what the core domain is and why it is worth money, so every team can check "does my work serve that?"
Common misunderstanding: "It is the company mission statement." A mission statement is for customers and staff; the domain vision statement is for the people building the model and ignores what does not differentiate.
Definition: Evans: "Write a short description (about one page) of the core domain and the value it will bring, the “value proposition.” Ignore those aspects that do not distinguish this domain model from others. Show how the domain model serves and balances diverse interests. Keep it narrow. Write this statement early and revise it as you gain new insight."
Domain Vision Statement for the running example (draft v3)
1 We win when a customer trusts our checkout: the price shown is fair and final,
2 promotions never sell below the floor price, flash sales are fair per customer,
3 and the delivery slot promised at checkout is kept.
4 Sales owns prices, promotions, limits and order acceptance.
5 Fulfilment owns the promise calculation and slot capacity.
6 Not in scope: how we invoice, how users sign in, how emails are sent.
7 Measured by: conversion, margin after promotions, promise-kept rate.Real scenario: a new hire asks why Billing uses plain SQL while Sales has aggregates: the statement answers it. A product manager proposes a home-made loyalty engine: the statement shows loyalty is not in the differentiating list, so the default is to buy.
| Domain Vision Statement | Not a domain vision statement |
|---|---|
| About one page | A 40-page requirements document |
| Names the core and its value proposition | Lists every feature |
| Narrow; ignores undifferentiating parts | Covers login and invoices equally |
| Revised as insight grows | Written once, filed away |
| Read by developers and experts | Read only by executives |
How to use it: keep it as docs/vision.md or at the top of the core package's documentation, link it from pull-request templates for the core, and revise it after every classification review.
Distillation techniques: highlighted, segregated and abstract core, cohesive mechanisms Good to know
In plain words: once you know what the core is, make it visible and separate in the code, so nobody has to guess what matters most and the core is not buried under helpers.
Common misunderstanding: "Distillation is a big refactoring project." Evans orders the techniques from cheap to expensive: a document or flags first, structural moves only when they pay.
Definition (Evans, DDD Reference, quoted):
| Technique | Evans's instruction | Cheap version | Expensive version |
|---|---|---|---|
| Domain Vision Statement | "Write a short description (about one page) of the core domain" | One page in the repo | Revised each quarter with experts |
| Highlighted Core | A distillation document of "three to seven sparse pages", and/or "Flag the elements of the core domain within the primary repository of the model [...] Make it effortless for a developer to know what is in or out of the core." | // core: comment, CODEOWNERS entry | Separate core document with change notification |
| Cohesive Mechanisms | "Partition a conceptually cohesive mechanism into a separate lightweight framework [...] Expose the capabilities of the framework with an intention-revealing interface." | Move an algorithm into its own package | A reusable engine (rules, scheduling, graph search) |
| Generic Subdomains | "Factor out generic models of these subdomains and place them in separate modules." | Vendor adapters in their own package | Buy the whole capability |
| Segregated Core | "Refactor the model to separate the core concepts from supporting players (including ill-defined ones) and strengthen the cohesion of the core while reducing its coupling to other code." | Move core types into one package | Split a tangled model across modules |
| Abstract Core | "Identify the most fundamental differentiating concepts in the model and factor them into distinct classes, abstract classes, or interfaces." | Interfaces for the key concepts | An abstract model module, implementations per subdomain |
Distillation, step by step, in the Sales code
1 Week 1 Domain Vision Statement written with the pricing manager
2 Week 2 Highlighted core: "core:" package comment + CODEOWNERS for sales/
3 Week 4 Cohesive mechanism: discount math moved behind Promotion.discountFor
4 Week 6 Generic split: Stripe and email code moved out of sales/
5 Week 8 Segregated core: arch test fails the build if sales/ imports vendors
6 Later Abstract core only if many subdomains share one concept (rare)Real scenario: a route-optimisation algorithm inside Fulfilment extracted as a cohesive mechanism (the "how") so the Fulfilment model can talk about promises and slots (the "what"); a pricing model whose discount code was mixed with tax and currency formatting, segregated so pricing rules stand alone.
How to use it: start with the vision statement and highlighted core; move to segregated core when the core is tangled with supporting code, and enforce it with dependency rules. Evans notes that with a highlighted core, changes outside it "can be integrated without consultation or notification", which gives teams autonomy where it matters least to coordinate.
Domain experts Must-know
In plain words: domain experts are the people who know how the business really works, because they do the work, decide the rules or carry the consequences.
Common misunderstanding: "The domain expert is whoever writes the tickets" (the product owner, the business analyst). Those people are valuable, but often they relay knowledge second-hand. The expert for promotions is the pricing manager who sets them and answers for margin.
Definition: in DDD, domain experts are the people whose knowledge the model must capture; Evans's Reference says "Domain experts should object to terms or structures that are awkward or inadequate to convey domain understanding; developers should watch for ambiguity or inconsistency that will trip up design." The DDD-Crew process asks, for discovery, for "People who have domain knowledge" and "Real end users, not only their representatives in your organisation".
| Subdomain | Likely expert | Good second voice | Proxy to be careful with |
|---|---|---|---|
| Sales ordering | Pricing manager, head of e-commerce | Customer-support lead (sees complaints) | Product owner relaying requests |
| Fulfilment | Warehouse shift lead, transport planner | Courier account manager | Operations director who never works a shift |
| Billing | Accountant, tax adviser | Collections clerk | Finance-system vendor consultant |
| Catalog | Merchandiser, content editor | Supplier manager | Marketing agency |
| Identity | Security engineer (internal) | Support (account-recovery tickets) | Anyone reinventing standards |
Finding the expert for "flash-sale limits"
1 Ticket says: "limit flash sales to 2 per customer" (product owner)
2 Ask: who set "2"? who gets the complaint if it is wrong? -> pricing manager
3 Pricing manager: "2 per household, not per account" new rule appears
4 Support lead: "people open second accounts with new emails" new edge case
5 Rule in code: per verified address, not per CustomerID the model changesHow to find them: follow the money (who signs off on margin, refunds, write-offs?), follow the exceptions (who is called at 2 a.m. when it breaks?), follow the spreadsheets (who keeps the shadow Excel file the system cannot replace?), and follow the complaints (support tickets name the rule that hurts). Org charts give names, not experts; see Discovering subdomains.
Interviewing and knowledge crunching Important
In plain words: knowledge crunching is the repeated loop of talking with experts, sketching a model, trying it on real cases and fixing it, until the model explains the business without translation.
Common misunderstanding: "One requirements workshop at the start is enough." Evans's Reference says "Translation blunts communication and makes knowledge crunching anemic"; the DDD-Crew process states "Discovery is Continuous".
Definition: knowledge crunching is Evans's term for distilling a large amount of domain information into a useful model through collaboration. The Reference's advice for doing it: "Play with the model as you talk about the system. Describe scenarios out loud using the elements and interactions of the model". The interview techniques below are this chapter's own practice, drawn from the sources where marked.
| Technique | What you ask or do | Why it works |
|---|---|---|
| Concrete last case | "Tell me about the last order that went wrong." | Real cases expose rules that summaries hide |
| Walk the process | Sit with a warehouse shift; watch a pricing change go live | You see workarounds nobody mentions |
| Ask for exceptions | "When does this rule not apply?" | Exceptions are where the model is |
| Ask for numbers | "How many per day? How often does it change?" | Separates core volatility from rare edge cases |
| Pre-mortem | "It is a year from now and this failed. Why?" | Klein (HBR, 2007): team members "assume that the project they are planning has just failed" |
| What would make this fail? | "What would make a customer leave us over this?" | Finds differentiation and failure damage |
| Play the model back | Read the rule aloud in the model's words | Experts correct words on the spot |
| Domain Storytelling | Expert tells a story; you draw actors, work items, activities | Its site: "The domain experts can see immediately whether you understand their story correctly." |
| Event storming | Sticky notes of domain events on a timeline | Large-group discovery; see Event Storming |
| Example mapping | Rules with concrete examples and open questions | Turns rules into tests |
One knowledge-crunching loop (90 minutes)
1 Expert tells the story of last week's oversold flash sale
2 Developer sketches: Order, Line, FlashSalePolicy.remaining(customer, sku)
3 Expert: "it's per household, and staff orders don't count"
4 Sketch changes: policy keyed by verified address; staff flag
5 Developer reads a scenario aloud in model words; expert nods
6 Rule becomes a failing test, then code; next loop next weekReal scenario: a team learns in a pre-mortem that the real fear is not downtime but showing a price at checkout and charging a different one ("price changed" complaints). That fear becomes the core invariant "the price shown is final for 15 minutes".
How to use it: schedule short, frequent sessions; bring examples, not forms; record new words in the Ubiquitous Language glossary; turn every rule into a test in the core package.
The proxy expert and the product owner Important
In plain words: a proxy expert is someone who speaks for the experts. Useful for priorities, risky for rules: every relay loses detail.
Common misunderstanding: "Our product owner is the domain expert, so developers need not talk to users." In Scrum the product owner owns the backlog; that does not make them the source of every rule.
Definition: a proxy expert is an intermediary (product owner, business analyst, account manager, consultant) whose knowledge of the rules is second-hand. Team Topologies' principles describe the cost: "Many teams never talk to the people using their products—they receive directives filtered through three layers of management. This game of telephone distorts customer needs and slows everything down."
Telephone game for one rule
1 Warehouse lead: "same-day only if picked by 14:00 AND the van has capacity"
2 Ops director to PO: "same-day if ordered before 14:00"
3 PO ticket: "show same-day badge before 14:00"
4 Developer ships the badge; capacity is ignored
5 Friday: 300 same-day promises, 180 vans slots; promise-kept rate collapsesReal scenario: a bank's compliance rules relayed by an analyst who never read the regulation; a fulfilment rule relayed by a director who has not worked a shift in years; a vendor consultant who describes the vendor's model as the business's.
| Role | Use them for | Do not use them as |
|---|---|---|
| Product owner | Priorities, outcomes, saying no | The only source of core rules |
| Business analyst | Organising findings, facilitation | A substitute for meeting experts |
| Real expert | Rules, exceptions, numbers, words | A backlog manager |
| End user | How work is really done, workarounds | The decider of strategy |
How to use it: keep the product owner in the room and bring the real expert in too, at least for the core. For supporting and generic subdomains a proxy is often enough; that is another reason classification matters.
Discovering subdomains Important
In plain words: find subdomains by looking at what the business does: its capabilities, its value chain from customer need to delivery, and the events on its timeline, then use the org chart as a hint, not a map.
Common misunderstanding: "Departments are subdomains." Departments are shaped by history, politics and headcount. One department can host three subdomains (Finance: billing, accounting, collections), and one subdomain can span departments (Fulfilment: warehouse and transport).
Definition and techniques:
| Technique | What you produce | Strength | Trap |
|---|---|---|---|
| Business capability mapping | A tree of what the business can do ("Price products", "Promise delivery") | Stable over reorganisations; listed as a tool in the DDD-Crew Decompose step | Capabilities named after IT systems |
| Value chain (Wardley) | Users → needs → capabilities, anchored on the user | Shows what the customer sees first; adds evolution | Too abstract without real users |
| Event storming | Domain events on a timeline, then clustered | Finds rules and language shifts; DDD-Crew suggests "carving up your event storm into sub-domains" | Needs a facilitator and the right people |
| Domain Storytelling | Pictographic stories of real work | Great with one or two experts | Not for 30 people |
| Org chart hints | Departments, roles, reporting lines | Who to invite, where language differs | Mirrors old structure (Conway); politics |
| Business Model Canvas | Value proposition, key activities | Ties subdomains to how money is made | Too coarse alone; see Why DDD |
| Existing systems | Legacy modules, SaaS bills, spreadsheets | Shows what is already bought or built | Copies old boundaries |
Discovery in a brownfield ordering company (two days)
1 Day 1 am Business Model Canvas with the founders: value = fair price + same-day
2 Day 1 pm Capability map: 7 top capabilities, 24 below
3 Day 2 am Big-picture event storming: 140 events, 6 clusters
4 Day 2 pm Compare clusters with capabilities and the org chart
5 Finance dept hosts 2 subdomains; warehouse+transport are 1 subdomain
6 Day 2 end Classify, draw the Core Domain Chart, draft the vision statementReal scenario: an insurer whose "IT department" structure suggested a "Documents" subdomain; event storming showed documents were a generic mechanism used by underwriting and claims, not a subdomain. A retailer whose org chart split "online" and "store" sales; capability mapping showed one pricing capability used by both.
How to use it: combine at least two techniques; where they disagree, ask the experts. Org-chart boundaries that do not match the domain are a Conway's law warning, not a reason to copy them into software.
The running example in full
The business: an online shop for home goods that competes on fair, dynamic prices at checkout (its core) and also promises same-day delivery in its cities. Its Domain Vision Statement is the one drafted above.
| Subdomain | Differentiation (1–5) | Complexity (1–5) | Volatility (1–5) | Buyable without losing edge? | Type | Reasoning | Alternative and when |
|---|---|---|---|---|---|---|---|
| Sales ordering | 5 | 5 | 5 | No | Core | Pricing, promotion caps, floor prices and flash-sale fairness are why customers trust the checkout; tuned weekly | None for this business |
| Fulfilment | 3 | 4 | 4 | No | Core or supporting | Same-day promise and slot capacity matter and change often, but customers say they choose us for prices; scored 3, it lands in Supporting with the "core in disguise" warning | Core if same-day delivery becomes why customers buy (differentiation 4+); plain supporting if shipping goes to a 3PL and the promise becomes their SLA |
| Billing and invoicing | 2 | 3 | 2 | Not fully (local tax rules) | Supporting | Must be correct and legal; no customer picks us for invoices | Generic if Stripe Invoicing or an ERP covers local rules |
| Catalog | 2 | 2 | 3 | Not quite | Supporting | Titles, descriptions, images, prices fed to Sales; CRUD | Core for a marketplace competing on search and merchandising |
| Identity and access | 1 | 4 | 1 | Yes | Generic | Everyone needs sign-in; complex but solved (Fortify, Socialite, IdPs) | Core only for an identity vendor |
| Notifications | 1 | 2 | 1 | Yes | Generic | Sending mail/SMS is solved; templates hold no rules | Supporting if messages carry regulated content (e.g. pharmacy) |
| Payment processing | 1 | 5 | 1 | Yes | Generic | Card networks, PCI DSS, fraud tooling: Stripe does it | Core only for a payments company |
Why Fulfilment is the interesting row. For this company, the promise "ordered by 12:00, delivered by 18:00" matters, and the rules (pick waves, slot capacity, cut-off times, van routes) change with the season, but the checkout is why customers choose the shop: Sales is the core. Fulfilment is therefore core or supporting, depending on the differentiator: a shop whose customers buy because of same-day delivery scores it 4 or 5 and treats it as core. A competitor that ships through a third-party logistics provider sells the same goods with a "2–4 days" promise; for them Fulfilment is supporting: an API call, a tracking page, and a returns form. Same domain words, different type, because the type depends on strategy, not on the activity's name. Khononov makes the same point: "a subdomain's complexity is not an absolute value. It depends heavily on the given company's needs."
Why not everything is core here. Billing is critical: a wrong VAT amount is a legal problem. But being critical does not make it differentiating. The Purpose Alignment Model calls this Parity: "mission-critical but not market-differentiating", to be designed "in a best-practices, simplified, streamlined, and standardized way."
Mapping to the solution space. Sales gets its own bounded context with the richest model; Fulfilment gets its own bounded context whose depth follows its type (a rich model once it is core for you). Billing hosts the payment port and calls Stripe. Catalog is a CRUD module. Identity wraps Fortify, Socialite or an IdP. Notifications is a library and an email provider used by Sales, Billing and Fulfilment, not a context of its own. See the diagram.
Mechanics
Running a classification workshop step by step Must-know
- Invite engineers, product/business people and at least one real expert per candidate core subdomain (the DDD-Crew "Strategize" step lists "People who understand product and business strategy", "People who design, build, test software", "People who have domain knowledge").
- List subdomains from a capability map or an event storm (verbs and capabilities, not tables).
- Score complexity (engineers) and differentiation (business) separately, then compare.
- Ask "who else has this problem?" and "can we buy it without losing our edge?" for each.
- Classify with the decision flow; write one sentence of reasoning per row.
- Draw the Core Domain Chart with current and future positions.
- Write or revise the Domain Vision Statement for the core.
- Decide investment: staffing, sourcing, design style, test depth (table below).
- Encode it: package layout, CODEOWNERS, architecture tests, schema per subdomain.
- Schedule the review (quarterly, and on strategy change).
Mapping types to investment and architecture style Must-know
Khononov's alignment, quoted: "For Core subdomains, use the heavy artillery. Implement the Domain Model or Event-Sourced Domain Model pattern." "For Supporting subdomains, use simple solutions. Transaction Script or Active Record patterns are enough." "And of course, Generic subdomains are cheaper to buy or adopt than to implement yourself."
| Dimension | Core | Supporting | Generic |
|---|---|---|---|
| Staffing | Best engineers, stable stream-aligned team, near experts | Any competent team; can be shared or outsourced | Integration skills; platform team may own adapters |
| Team Topologies fit | Stream-aligned; complicated-subsystem for heavy algorithms | Stream-aligned (shared) or outsourced | Platform or X-as-a-Service from a vendor |
| Design pattern | Rich domain model, aggregates, domain events; event sourcing if history matters | Transaction script, Active Record, admin generator | Adapter behind a port; anti-corruption layer for vendor models |
| Tests | Many fast unit tests of rules; property tests; mutation testing | Happy path + key edge cases | Contract tests against the vendor sandbox |
| Persistence | Repository over its own schema (Data Persistence in Design) | ORM directly | Vendor's storage; local mirror only if needed |
| Change process | Experts in the loop; vision statement checks | Normal backlog | Upgrade vendor versions; watch deprecations |
| Metrics | Business outcome (conversion, margin, promise kept) | Correctness, cost | Vendor SLA, cost per use |
| Documentation | Vision statement, highlighted core, glossary | README | Link to vendor docs + our config |
Enforcing types in the database: a schema per subdomain
Separate schemas (PostgreSQL) or databases (MySQL) per subdomain make ownership visible and let you grant each module's role only its own tables. Generic subdomains often keep no tables of their own beyond a reference to the vendor.
-- PostgreSQL: one schema per subdomain, one role per module
CREATE SCHEMA sales; -- core: rich model, owned by the Sales team
CREATE SCHEMA billing; -- supporting: transaction scripts
CREATE SCHEMA catalog; -- supporting: CRUD
CREATE SCHEMA identity; -- generic: vendor tables (Fortify migrations) or none with an IdP
CREATE ROLE sales_app LOGIN;
CREATE ROLE billing_app LOGIN;
-- Supporting: gapless invoice numbering is one locked row, not a model
CREATE TABLE billing.invoice_sequence (last bigint NOT NULL);
INSERT INTO billing.invoice_sequence VALUES (0);
CREATE TABLE billing.invoices (
number bigint PRIMARY KEY,
order_id text NOT NULL UNIQUE,
net_cents bigint NOT NULL CHECK (net_cents >= 0),
vat_cents bigint NOT NULL CHECK (vat_cents >= 0),
issued_at timestamptz NOT NULL DEFAULT now()
);
-- Generic: payment collection lives at Stripe; we store only the reference
CREATE TABLE billing.payment_refs (
order_id text PRIMARY KEY,
provider text NOT NULL DEFAULT 'stripe',
payment_intent_id text NOT NULL UNIQUE
);
-- Grant after the tables exist (ALL TABLES covers existing tables only)
GRANT USAGE ON SCHEMA sales TO sales_app;
GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA sales TO sales_app;
GRANT USAGE ON SCHEMA billing TO billing_app;
GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA billing TO billing_app;
-- Billing's role cannot read Sales internals: this fails with
-- ERROR: permission denied for schema sales (SQLSTATE 42501)
SET ROLE billing_app;
SELECT * FROM sales.orders;Ownership across services is covered in Data Ownership in Microservices; this chapter only uses it to make the classification visible.
What failure looks like
When the classification is encoded, a wrong dependency fails the build instead of a review:
go test ./... (after someone imports stripe-go in the core)
1 --- FAIL: TestSubdomainDependencies (0.00s)
2 arch_test.go:39: sales/order.go imports github.com/stripe/stripe-go/v87; sales must not depend on it
3 FAIL academy/domains-subdomains 0.012s
./vendor/bin/pest tests/ArchitectureTest.php (after Order uses Laravel\Cashier)
4 the arch test "the core domain is plain PHP" fails and names the class and Laravel\Cashier
5 (illustrative: exact wording depends on the Pest version; not run for this page)| Symptom in the organisation | What it usually means | Check |
|---|---|---|
| Senior engineers busy on auth, PDFs, email templates | Generic subdomains being built | Count commits by type of subdomain |
| Core changes wait for "platform" work | Core coupled to generic code | Arch test; import graph |
| A supporting module has more rules than the core | Accidental complexity or core in disguise | Rule count per module; ask the experts |
| Nobody can say what the core is | No vision statement | Ask five people; compare answers |
| Vendor customisation backlog keeps growing | Over-customised product (Kaiser) | Customisation hours vs licence cost |
Go
The Go module makes the classification visible in the repository layout: one package per subdomain, rich and heavily tested in the core, plain in supporting packages, thin adapters for generic ones, and an architecture test that keeps the core free of vendors.
go/
classify/ workshop heuristics as code (+ tests)
cmd/chart/ prints the Core Domain Chart table
sales/ CORE: rich model, many tests
catalog/ SUPPORTING: struct + validation + store
billing/ SUPPORTING: transaction script + PaymentGateway port
payments/ GENERIC: stripe-go adapter
identity/ GENERIC: golang.org/x/oauth2 adapter
notifications/ GENERIC: net/smtp adapter
wrong/ everything-is-core anti-example
arch_test.go dependency rules per subdomain typeWrong: everything treated as core
Hand-rolled password hashing, raw card numbers, and the real differentiator (pricing) hidden in an HTTP handler with no cap, no floor and no test. It compiles; it is the wrong investment.
// Package wrong treats everything as core: the team hand-builds password
// hashing, card storage and email, while the real differentiator (pricing)
// hides as three lines in a handler with no tests. It compiles; it is still
// the wrong investment.
package wrong
import (
"crypto/sha256"
"encoding/hex"
"net/http"
"strconv"
)
// User stores a home-made password hash and raw card data (PCI DSS scope!).
type User struct {
Email string
PasswordHash string
CardNumber string
}
// HashPassword is a hand-rolled, unsalted, fast hash: a solved problem done badly.
func HashPassword(pw string) string {
sum := sha256.Sum256([]byte(pw))
return hex.EncodeToString(sum[:])
}
// Checkout buries the core rule (discounts) in HTTP plumbing.
func Checkout(w http.ResponseWriter, r *http.Request) {
price, _ := strconv.ParseInt(r.FormValue("price"), 10, 64)
if r.FormValue("promo") != "" {
price = price * 80 / 100 // no cap, no floor price, no test
}
w.Write([]byte(strconv.FormatInt(price, 10)))
}Classification as code
The workshop's answers recorded as data, with Khononov's order of questions and the "core in disguise" warning.
// Package classify turns the subdomain heuristics into code so a workshop's
// answers can be recorded, reviewed and re-run when the business changes.
// The rules follow Khononov's "easy categorization" plus the Core Domain
// Chart axes; they are a teaching aid, not an algorithm from Evans.
package classify
import "fmt"
// Type is the subdomain type.
type Type string
// The three subdomain types.
const (
Core Type = "core"
Supporting Type = "supporting"
Generic Type = "generic"
)
// Answers are what domain experts and engineers said in the workshop.
// Scores run from 1 (low) to 5 (high).
type Answers struct {
Name string
// Differentiation: would customers pick us over a rival because of it?
Differentiation int
// Complexity: rules, invariants, algorithms; not CRUD plus validation.
Complexity int
// Volatility: how often the rules change (per quarter, roughly).
Volatility int
// BuyableWithoutLosingEdge: a product or library solves it and using it
// costs no competitive advantage ("who else has this problem?" = everyone).
BuyableWithoutLosingEdge bool
}
// Verdict is the classification plus the investment it implies.
type Verdict struct {
Name string
Type Type
Investment string
Warning string
}
// Classify applies the heuristics in a fixed order.
func Classify(a Answers) (Verdict, error) {
for _, s := range []int{a.Differentiation, a.Complexity, a.Volatility} {
if s < 1 || s > 5 {
return Verdict{}, fmt.Errorf("%s: scores must be 1..5, got %d", a.Name, s)
}
}
v := Verdict{Name: a.Name}
switch {
case a.BuyableWithoutLosingEdge && a.Differentiation <= 2:
v.Type = Generic
v.Investment = "buy, adopt open source or use SaaS; wrap behind a port"
if a.Complexity >= 4 {
v.Warning = "complex but solved elsewhere: do not rebuild it"
}
case a.Differentiation >= 4:
v.Type = Core
v.Investment = "build in-house, best engineers, rich model, deep tests"
if a.Complexity <= 2 {
v.Warning = "differentiating but simple: easy to copy, expect a short-lived core"
}
default:
v.Type = Supporting
v.Investment = "build simply (CRUD, transaction script) or outsource"
if a.Complexity >= 4 || a.Volatility >= 4 {
v.Warning = "complex or volatile supporting: simplify it, or it is a core in disguise"
}
}
return v, nil
}package classify
import "testing"
// The running example: an online ordering and fulfilment business whose core
// is pricing and order acceptance at checkout (Sales). Fulfilment is core or
// supporting, depending on the differentiator: both variants are tested.
func TestRunningExample(t *testing.T) {
cases := []struct {
in Answers
want Type
}{
{Answers{"Sales ordering", 5, 5, 5, false}, Core},
{Answers{"Fulfilment (same-day is why customers buy)", 4, 4, 4, false}, Core},
{Answers{"Fulfilment (ships via a 3PL)", 2, 2, 2, false}, Supporting},
{Answers{"Billing and invoicing", 2, 3, 2, false}, Supporting},
{Answers{"Catalog", 2, 2, 3, false}, Supporting},
{Answers{"Identity and access", 1, 4, 1, true}, Generic},
{Answers{"Notifications", 1, 2, 1, true}, Generic},
{Answers{"Payment processing", 1, 5, 1, true}, Generic},
}
for _, c := range cases {
got, err := Classify(c.in)
if err != nil {
t.Fatal(err)
}
if got.Type != c.want {
t.Errorf("%s: got %s, want %s", c.in.Name, got.Type, c.want)
}
}
}
func TestCoreInDisguiseWarning(t *testing.T) {
v, _ := Classify(Answers{"Returns", 3, 5, 4, false})
if v.Type != Supporting || v.Warning == "" {
t.Fatalf("complex supporting subdomain must carry a warning, got %+v", v)
}
}
func TestRejectsBadScores(t *testing.T) {
if _, err := Classify(Answers{"X", 0, 3, 3, false}); err == nil {
t.Fatal("score 0 must be rejected")
}
}// Command chart prints the running example as a Core Domain Chart table:
// x = business differentiation, y = model complexity (both 1..5).
package main
import (
"fmt"
"os"
"text/tabwriter"
"academy/domains-subdomains/classify"
)
func main() {
rows := []classify.Answers{
{Name: "Sales ordering", Differentiation: 5, Complexity: 5, Volatility: 5},
{Name: "Fulfilment", Differentiation: 3, Complexity: 4, Volatility: 4},
{Name: "Billing", Differentiation: 2, Complexity: 3, Volatility: 2},
{Name: "Catalog", Differentiation: 2, Complexity: 2, Volatility: 3},
{Name: "Identity", Differentiation: 1, Complexity: 4, Volatility: 1, BuyableWithoutLosingEdge: true},
{Name: "Notifications", Differentiation: 1, Complexity: 2, Volatility: 1, BuyableWithoutLosingEdge: true},
}
w := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)
fmt.Fprintln(w, "SUBDOMAIN\tDIFF\tCPLX\tTYPE\tINVESTMENT\tWARNING")
for _, r := range rows {
v, err := classify.Classify(r)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Fprintf(w, "%s\t%d\t%d\t%s\t%s\t%s\n", v.Name, r.Differentiation, r.Complexity, v.Type, v.Investment, v.Warning)
}
w.Flush()
}Core: a rich, tested model
// Package sales is the CORE subdomain of the running example: how a basket
// becomes a priced, accepted Order. This is where the business competes, so
// the rules live in a rich model, not in controllers or SQL.
//
// core: every exported name here is in the Domain Vision Statement.
package sales
import (
"errors"
"fmt"
"time"
)
type (
// OrderID identifies an Order inside Sales.
OrderID string
// CustomerID identifies the buyer.
CustomerID string
// SKU is the stock keeping unit the shopper picked.
SKU string
// Cents is money in the smallest currency unit; never float.
Cents int64
)
// Line is one SKU at an agreed unit price.
type Line struct {
SKU SKU
Quantity int
UnitPrice Cents
// FloorPrice is the lowest unit price the business accepts (margin guard).
FloorPrice Cents
}
// Promotion is a percentage discount with a cap, as Sales defines it.
type Promotion struct {
Code string
Percent int
MaxPerLine Cents
}
// Business rule violations, phrased the way the pricing team phrases them.
var (
ErrEmptyBasket = errors.New("an order needs at least one line")
ErrBelowFloor = errors.New("the discounted price would fall below the floor price")
ErrFlashSaleLimit = errors.New("flash-sale items are limited per customer")
ErrAlreadyPlaced = errors.New("the order is already placed")
ErrInvalidPromotion = errors.New("promotion percent must be 1..90")
)
// Order is the aggregate root for one checkout.
type Order struct {
id OrderID
customer CustomerID
lines []Line
promotion *Promotion
placedAt time.Time
}
// OrderPlaced is the domain event other subdomains react to.
type OrderPlaced struct {
OrderID OrderID
CustomerID CustomerID
Total Cents
At time.Time
}
// NewOrder starts a basket for a customer.
func NewOrder(id OrderID, c CustomerID) *Order { return &Order{id: id, customer: c} }
// FlashSalePolicy answers how many units a customer may still buy.
type FlashSalePolicy interface {
Remaining(c CustomerID, s SKU) (int, bool)
}
// Add puts a line in the basket, enforcing the flash-sale rule.
func (o *Order) Add(l Line, policy FlashSalePolicy) error {
if !o.placedAt.IsZero() {
return ErrAlreadyPlaced
}
if l.Quantity <= 0 {
return fmt.Errorf("quantity must be positive, got %d", l.Quantity)
}
if left, limited := policy.Remaining(o.customer, l.SKU); limited && l.Quantity > left {
return fmt.Errorf("%w: %s allows %d more", ErrFlashSaleLimit, l.SKU, left)
}
o.lines = append(o.lines, l)
return nil
}
// Apply attaches a promotion only if no line would drop below its floor.
func (o *Order) Apply(p Promotion) error {
if p.Percent < 1 || p.Percent > 90 {
return ErrInvalidPromotion
}
for _, l := range o.lines {
if l.UnitPrice-discount(l.UnitPrice, p) < l.FloorPrice {
return fmt.Errorf("%w: %s", ErrBelowFloor, l.SKU)
}
}
o.promotion = &p
return nil
}
// Total is the price the customer pays.
func (o *Order) Total() Cents {
var sum Cents
for _, l := range o.lines {
unit := l.UnitPrice
if o.promotion != nil {
unit -= discount(l.UnitPrice, *o.promotion)
}
sum += unit * Cents(l.Quantity)
}
return sum
}
// Place accepts the order and returns the event to publish.
func (o *Order) Place(now time.Time) (OrderPlaced, error) {
if !o.placedAt.IsZero() {
return OrderPlaced{}, ErrAlreadyPlaced
}
if len(o.lines) == 0 {
return OrderPlaced{}, ErrEmptyBasket
}
o.placedAt = now
return OrderPlaced{OrderID: o.id, CustomerID: o.customer, Total: o.Total(), At: now}, nil
}
func discount(unit Cents, p Promotion) Cents {
d := unit * Cents(p.Percent) / 100
if p.MaxPerLine > 0 && d > p.MaxPerLine {
d = p.MaxPerLine
}
return d
}package sales
import (
"errors"
"testing"
"time"
)
type limits map[SKU]int
func (l limits) Remaining(_ CustomerID, s SKU) (int, bool) {
n, ok := l[s]
return n, ok
}
var now = time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
func TestPromotionIsCappedPerLine(t *testing.T) {
o := NewOrder("o-1", "c-1")
_ = o.Add(Line{SKU: "TV-55", Quantity: 1, UnitPrice: 80000, FloorPrice: 60000}, limits{})
if err := o.Apply(Promotion{Code: "BF26", Percent: 20, MaxPerLine: 10000}); err != nil {
t.Fatal(err)
}
if got := o.Total(); got != 70000 {
t.Fatalf("20%% of 80000 is 16000 but the cap is 10000; want 70000, got %d", got)
}
}
func TestPromotionNeverBreaksTheFloor(t *testing.T) {
o := NewOrder("o-2", "c-1")
_ = o.Add(Line{SKU: "CABLE", Quantity: 3, UnitPrice: 1000, FloorPrice: 900}, limits{})
if err := o.Apply(Promotion{Code: "HALF", Percent: 50}); !errors.Is(err, ErrBelowFloor) {
t.Fatalf("want ErrBelowFloor, got %v", err)
}
}
func TestFlashSaleLimit(t *testing.T) {
o := NewOrder("o-3", "c-2")
err := o.Add(Line{SKU: "CONSOLE", Quantity: 3, UnitPrice: 50000, FloorPrice: 45000}, limits{"CONSOLE": 2})
if !errors.Is(err, ErrFlashSaleLimit) {
t.Fatalf("want ErrFlashSaleLimit, got %v", err)
}
}
func TestPlaceTwiceIsRejected(t *testing.T) {
o := NewOrder("o-4", "c-3")
_ = o.Add(Line{SKU: "BOOK", Quantity: 1, UnitPrice: 2000, FloorPrice: 1500}, limits{})
ev, err := o.Place(now)
if err != nil || ev.Total != 2000 {
t.Fatalf("first place: %v %+v", err, ev)
}
if _, err := o.Place(now); !errors.Is(err, ErrAlreadyPlaced) {
t.Fatalf("want ErrAlreadyPlaced, got %v", err)
}
}
func TestEmptyBasketCannotBePlaced(t *testing.T) {
if _, err := NewOrder("o-5", "c-4").Place(now); !errors.Is(err, ErrEmptyBasket) {
t.Fatalf("want ErrEmptyBasket, got %v", err)
}
}Supporting: simple on purpose
// Package catalog is a SUPPORTING subdomain: necessary, not differentiating,
// close to CRUD. A plain struct, validation and a store are enough. Spending
// a rich model here would steal engineers from Sales.
package catalog
import (
"context"
"errors"
"strings"
"sync"
)
// Product is a row the merchandising team edits in a back-office screen.
type Product struct {
SKU string
Title string
Description string
PriceCents int64
Active bool
}
// ErrNotFound is returned for unknown SKUs.
var ErrNotFound = errors.New("product not found")
// Validate is the whole "business logic": input checks.
func (p Product) Validate() error {
switch {
case strings.TrimSpace(p.SKU) == "":
return errors.New("sku is required")
case strings.TrimSpace(p.Title) == "":
return errors.New("title is required")
case p.PriceCents <= 0:
return errors.New("price must be positive")
}
return nil
}
// Store is CRUD. In production this is one table behind database/sql.
type Store struct {
mu sync.RWMutex
rows map[string]Product
}
// NewStore returns an empty in-memory store.
func NewStore() *Store { return &Store{rows: map[string]Product{}} }
// Save creates or updates a product.
func (s *Store) Save(_ context.Context, p Product) error {
if err := p.Validate(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
s.rows[p.SKU] = p
return nil
}
// Get reads one product.
func (s *Store) Get(_ context.Context, sku string) (Product, error) {
s.mu.RLock()
defer s.mu.RUnlock()
p, ok := s.rows[sku]
if !ok {
return Product{}, ErrNotFound
}
return p, nil
}// Package billing is a SUPPORTING subdomain: invoices must be correct and
// legal, but nobody buys from us because of our invoices. A transaction
// script is the right amount of design. Payment collection itself is a
// GENERIC subdomain, reached only through the PaymentGateway port.
package billing
import (
"context"
"database/sql"
"fmt"
)
// PaymentGateway is the port; payments/stripe.go is one adapter.
type PaymentGateway interface {
Collect(ctx context.Context, orderID string, amountCents int64, currency string) (reference string, err error)
}
// IssueInvoice is a transaction script: read, compute, write, collect.
func IssueInvoice(ctx context.Context, db *sql.DB, pay PaymentGateway, orderID string, netCents int64, vatPercent int64) (int64, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
vat := netCents * vatPercent / 100
var number int64
// Invoice numbers must be gapless per legal entity in many countries.
if err := tx.QueryRowContext(ctx,
`UPDATE billing.invoice_sequence SET last = last + 1 RETURNING last`).Scan(&number); err != nil {
return 0, fmt.Errorf("next invoice number: %w", err)
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO billing.invoices (number, order_id, net_cents, vat_cents) VALUES ($1, $2, $3, $4)`,
number, orderID, netCents, vat); err != nil {
return 0, err
}
if err := tx.Commit(); err != nil {
return 0, err
}
// Collect after commit; a failed charge is retried by a job, not rolled back.
if _, err := pay.Collect(ctx, orderID, netCents+vat, "eur"); err != nil {
return number, fmt.Errorf("invoice %d issued, collection pending: %w", number, err)
}
return number, nil
}Generic: thin adapters over solved problems
// Package payments adapts a GENERIC subdomain (card payments) that Stripe
// has already solved. We write glue, not a payment engine.
package payments
import (
"context"
"fmt"
"github.com/stripe/stripe-go/v87"
)
// Stripe implements billing.PaymentGateway with stripe-go.
type Stripe struct {
client *stripe.Client
}
// NewStripe builds the adapter from a secret key.
func NewStripe(secretKey string) *Stripe {
return &Stripe{client: stripe.NewClient(secretKey)}
}
// Collect creates a PaymentIntent tagged with our order id.
func (s *Stripe) Collect(ctx context.Context, orderID string, amountCents int64, currency string) (string, error) {
params := &stripe.PaymentIntentCreateParams{
Amount: stripe.Int64(amountCents),
Currency: stripe.String(currency),
}
params.AddMetadata("order_id", orderID)
params.SetIdempotencyKey("collect-" + orderID)
pi, err := s.client.V1PaymentIntents.Create(ctx, params)
if err != nil {
return "", fmt.Errorf("stripe: %w", err)
}
return pi.ID, nil
}// Package identity is a GENERIC subdomain. Sign-in with an OAuth 2.0 provider
// is a solved problem; golang.org/x/oauth2 implements the protocol and we
// only map the provider's user to our CustomerID.
package identity
import (
"context"
"crypto/rand"
"encoding/base64"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
)
// Provider wraps an oauth2.Config.
type Provider struct {
cfg *oauth2.Config
}
// NewGitHub configures GitHub sign-in.
func NewGitHub(clientID, clientSecret, redirectURL string) *Provider {
return &Provider{cfg: &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scopes: []string{"read:user", "user:email"},
Endpoint: github.Endpoint,
}}
}
// LoginURL returns the redirect URL and the state to store in the session.
func (p *Provider) LoginURL() (url, state string, err error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", "", err
}
state = base64.RawURLEncoding.EncodeToString(b)
return p.cfg.AuthCodeURL(state, oauth2.AccessTypeOnline), state, nil
}
// Exchange trades the callback code for a token.
func (p *Provider) Exchange(ctx context.Context, code string) (*oauth2.Token, error) {
return p.cfg.Exchange(ctx, code)
}// Package notifications is a GENERIC subdomain: sending an email is solved by
// SMTP and by providers (Amazon SES, Postmark, SendGrid). Keep it a port with
// a boring adapter; never let template logic grow business rules.
package notifications
import (
"fmt"
"net/smtp"
)
// Notifier is what Sales, Billing and Fulfilment depend on.
type Notifier interface {
Send(to, subject, body string) error
}
// SMTP is the stdlib adapter; swap it for a provider SDK without touching callers.
type SMTP struct {
Addr string
From string
Auth smtp.Auth
}
// Send delivers one plain-text message.
func (s SMTP) Send(to, subject, body string) error {
msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s\r\n", s.From, to, subject, body)
return smtp.SendMail(s.Addr, s.Auth, s.From, []string{to}, []byte(msg))
}Keeping the types honest
package layout_test
import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strings"
"testing"
)
// The core must not depend on generic vendors or infrastructure; generic and
// supporting packages must not reach into the core's internals.
var forbidden = map[string][]string{
"sales": {
"github.com/stripe/stripe-go", "golang.org/x/oauth2", "net/http", "database/sql",
"academy/domains-subdomains/payments", "academy/domains-subdomains/identity",
"academy/domains-subdomains/notifications",
},
"billing": {"academy/domains-subdomains/sales", "github.com/stripe/stripe-go"},
"catalog": {"academy/domains-subdomains/sales"},
"notifications": {"academy/domains-subdomains/sales"},
}
func TestSubdomainDependencies(t *testing.T) {
for dir, bans := range forbidden {
err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
return err
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, imp := range f.Imports {
p := strings.Trim(imp.Path.Value, `"`)
for _, ban := range bans {
if p == ban || strings.HasPrefix(p, ban+"/") {
t.Errorf("%s imports %s; %s must not depend on it", path, p, dir)
}
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
}The Go angle
- Packages are the unit of distillation. A
salespackage with unexported fields and methods that enforce rules is a segregated core; a// core:package comment plus a CODEOWNERS entry is a highlighted core. internal/can hide adapters so only the composition root wires them; we keep packages flat here for readability.- Generic libraries:
golang.org/x/oauth2implements the OAuth 2.0 client side;github.com/stripe/stripe-go/v87uses astripe.NewClientwith per-resource services (sc.V1PaymentIntents.Create) and supports idempotency keys on params. Pulling stripe-go v87 raised the module'sgodirective to 1.26 viago mod tidy; that is the vendor's requirement, another reminder that generic code brings its upgrade cadence with it. - Architecture tests with
go/parser(as in Service Boundaries) make "the core does not import vendors" a build failure. Tools such asgo-arch-lintordepguard(golangci-lint) express the same rules in config. - Supporting code is plain
database/sql(orsqlc,pgx): no repositories or aggregates unless the rules justify them.
Laravel
Same idea with Laravel 13 modules: App\Modules\Sales\Domain is plain PHP with Pest unit tests; Catalog is an Eloquent resource controller; Billing is a transaction script; Identity, payments and notifications are Laravel's own first-party packages.
app/
Modules/
Sales/Domain/ CORE: Order, OrderLine, Promotion, PricingRejected (plain PHP)
Sales/Application/ PlaceOrder (orchestration only)
Catalog/ SUPPORTING: Eloquent model + CRUD controller
Billing/ SUPPORTING: IssueInvoice script; GENERIC: Cashier checkout
Identity/ GENERIC: Socialite controller (+ Fortify config)
Notifications/ GENERIC: Laravel Notifications
tests/
Unit/Sales/ many fast tests for the core
ArchitectureTest.php Pest arch rules per subdomain typeWrong: one controller, everything home-made
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/**
* Everything treated as core, so nothing is: home-made login, raw card storage,
* hand-built mail, and the real differentiator (pricing) in four untested lines.
*/
class OrderController extends Controller
{
public function store(Request $request)
{
$user = DB::table('users')
->where('email', $request->input('email'))
->where('password_md5', md5($request->input('password')))
->first();
abort_if($user === null, 401);
$price = (int) $request->input('price');
if ($request->filled('promo')) {
$price = intdiv($price * 80, 100); // no cap, no floor, no test
}
DB::table('cards')->insert(['user_id' => $user->id, 'pan' => $request->input('card_number')]);
$id = DB::table('orders')->insertGetId(['user_id' => $user->id, 'total' => $price]);
Mail::raw("Order {$id} confirmed", fn ($m) => $m->to($user->email)->subject('Order'));
return response()->json(['id' => $id, 'total' => $price], 201);
}
}Core: plain PHP, many tests
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
/**
* CORE subdomain: the pricing and acceptance rules the business competes on.
* Plain PHP: no Eloquent, no facades, so the rules are testable in milliseconds.
*/
final class Order
{
/** @var list<OrderLine> */
private array $lines = [];
private ?Promotion $promotion = null;
private ?DateTimeImmutable $placedAt = null;
public function __construct(
public readonly string $id,
public readonly string $customerId,
) {}
public function add(OrderLine $line, FlashSalePolicy $policy): void
{
$this->assertOpen();
$remaining = $policy->remaining($this->customerId, $line->sku);
if ($remaining !== null && $line->quantity > $remaining) {
throw PricingRejected::flashSaleLimit($line->sku, $remaining);
}
$this->lines[] = $line;
}
public function apply(Promotion $promotion): void
{
$this->assertOpen();
foreach ($this->lines as $line) {
if ($line->unitPrice - $promotion->discountFor($line->unitPrice) < $line->floorPrice) {
throw PricingRejected::belowFloor($line->sku);
}
}
$this->promotion = $promotion;
}
public function total(): int
{
$sum = 0;
foreach ($this->lines as $line) {
$unit = $line->unitPrice - ($this->promotion?->discountFor($line->unitPrice) ?? 0);
$sum += $unit * $line->quantity;
}
return $sum;
}
public function place(DateTimeImmutable $now): OrderPlaced
{
$this->assertOpen();
if ($this->lines === []) {
throw PricingRejected::emptyBasket();
}
$this->placedAt = $now;
return new OrderPlaced($this->id, $this->customerId, $this->total(), $now);
}
private function assertOpen(): void
{
if ($this->placedAt !== null) {
throw PricingRejected::alreadyPlaced($this->id);
}
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use InvalidArgumentException;
/** Value object: amounts are integer cents, never float. */
final readonly class OrderLine
{
public function __construct(
public string $sku,
public int $quantity,
public int $unitPrice,
public int $floorPrice,
) {
if ($quantity <= 0) {
throw new InvalidArgumentException("Quantity must be positive, got {$quantity}.");
}
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use InvalidArgumentException;
final readonly class Promotion
{
public function __construct(
public string $code,
public int $percent,
public int $maxPerLine = 0,
) {
if ($percent < 1 || $percent > 90) {
throw new InvalidArgumentException('Promotion percent must be 1..90.');
}
}
public function discountFor(int $unitPrice): int
{
$discount = intdiv($unitPrice * $this->percent, 100);
return $this->maxPerLine > 0 ? min($discount, $this->maxPerLine) : $discount;
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
interface FlashSalePolicy
{
/** Units the customer may still buy, or null when the SKU is not limited. */
public function remaining(string $customerId, string $sku): ?int;
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
final readonly class OrderPlaced
{
public function __construct(
public string $orderId,
public string $customerId,
public int $totalCents,
public DateTimeImmutable $at,
) {}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DomainException;
/** Messages use the pricing team's words so support can read them aloud. */
final class PricingRejected extends DomainException
{
public static function belowFloor(string $sku): self
{
return new self("The discounted price of {$sku} would fall below the floor price.");
}
public static function flashSaleLimit(string $sku, int $remaining): self
{
return new self("Flash-sale item {$sku} allows {$remaining} more for this customer.");
}
public static function emptyBasket(): self
{
return new self('An order needs at least one line.');
}
public static function alreadyPlaced(string $orderId): self
{
return new self("Order {$orderId} is already placed.");
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application;
use App\Modules\Sales\Domain\FlashSalePolicy;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\Promotion;
use DateTimeImmutable;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Str;
/** Application service: orchestrates; the rules stay in Order. */
final readonly class PlaceOrder
{
public function __construct(
private FlashSalePolicy $flashSales,
private Dispatcher $events,
) {}
/** @param list<array{sku: string, quantity: int, unit_price: int, floor_price: int}> $lines */
public function __invoke(string $customerId, array $lines, ?string $promoCode, int $promoPercent = 0): string
{
$order = new Order((string) Str::ulid(), $customerId);
foreach ($lines as $line) {
$order->add(new OrderLine($line['sku'], $line['quantity'], $line['unit_price'], $line['floor_price']), $this->flashSales);
}
if ($promoCode !== null) {
$order->apply(new Promotion($promoCode, $promoPercent, maxPerLine: 10_000));
}
// Billing, Fulfilment and Notifications react to this event.
$this->events->dispatch($order->place(new DateTimeImmutable()));
return $order->id;
}
}<?php
use App\Modules\Sales\Domain\FlashSalePolicy;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\PricingRejected;
use App\Modules\Sales\Domain\Promotion;
// Core subdomain: many fast tests, no database, no framework boot.
function noLimits(): FlashSalePolicy
{
return new class implements FlashSalePolicy
{
public function remaining(string $customerId, string $sku): ?int
{
return null;
}
};
}
it('caps a promotion per line', function () {
$order = new Order('o-1', 'c-1');
$order->add(new OrderLine('TV-55', 1, 80_000, 60_000), noLimits());
$order->apply(new Promotion('BF26', 20, maxPerLine: 10_000));
expect($order->total())->toBe(70_000);
});
it('never sells below the floor price', function () {
$order = new Order('o-2', 'c-1');
$order->add(new OrderLine('CABLE', 3, 1_000, 900), noLimits());
$order->apply(new Promotion('HALF', 50));
})->throws(PricingRejected::class, 'below the floor price');
it('enforces the flash-sale limit', function () {
$limited = new class implements FlashSalePolicy
{
public function remaining(string $customerId, string $sku): ?int
{
return 2;
}
};
(new Order('o-3', 'c-2'))->add(new OrderLine('CONSOLE', 3, 50_000, 45_000), $limited);
})->throws(PricingRejected::class, 'allows 2 more');
it('cannot be placed twice', function () {
$order = new Order('o-4', 'c-3');
$order->add(new OrderLine('BOOK', 1, 2_000, 1_500), noLimits());
$order->place(new DateTimeImmutable());
$order->place(new DateTimeImmutable());
})->throws(PricingRejected::class, 'already placed');Supporting: Eloquent CRUD and a transaction script
<?php
declare(strict_types=1);
namespace App\Modules\Catalog;
use Illuminate\Database\Eloquent\Model;
final class Product extends Model
{
protected $table = 'catalog_products';
protected $fillable = ['sku', 'title', 'description', 'price_cents', 'active'];
protected function casts(): array
{
return ['price_cents' => 'integer', 'active' => 'boolean'];
}
}<?php
declare(strict_types=1);
namespace App\Modules\Catalog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* SUPPORTING subdomain: CRUD with validation is the whole job.
* Active Record (Eloquent) is the right tool here; no aggregate, no repository.
*/
final class ProductController
{
public function index(): JsonResponse
{
return response()->json(Product::query()->where('active', true)->paginate(50));
}
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'sku' => ['required', 'string', 'max:64', 'unique:catalog_products,sku'],
'title' => ['required', 'string', 'max:200'],
'description' => ['nullable', 'string'],
'price_cents' => ['required', 'integer', 'min:1'],
'active' => ['boolean'],
]);
return response()->json(Product::create($data), 201);
}
public function update(Request $request, Product $product): JsonResponse
{
$product->update($request->validate([
'title' => ['sometimes', 'string', 'max:200'],
'description' => ['nullable', 'string'],
'price_cents' => ['sometimes', 'integer', 'min:1'],
'active' => ['boolean'],
]));
return response()->json($product);
}
}<?php
declare(strict_types=1);
namespace App\Modules\Billing;
use App\Modules\Sales\Domain\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
/**
* SUPPORTING subdomain as a transaction script, run as a queued listener
* for the Sales core's OrderPlaced event. Correct and legal, nothing more.
*/
final class IssueInvoice implements ShouldQueue
{
public function handle(OrderPlaced $event): void
{
DB::transaction(function () use ($event) {
// Gapless numbering: lock the single sequence row.
$sequence = DB::table('billing_invoice_sequence')->lockForUpdate()->first();
$number = $sequence->last + 1;
DB::table('billing_invoice_sequence')->update(['last' => $number]);
$net = $event->totalCents;
$vat = intdiv($net * (int) config('billing.vat_percent', 20), 100);
DB::table('billing_invoices')->insert([
'number' => $number,
'order_id' => $event->orderId,
'net_cents' => $net,
'vat_cents' => $vat,
'issued_at' => now(),
]);
});
}
}Generic: Cashier, Socialite, Fortify, Notifications
<?php
declare(strict_types=1);
namespace App\Modules\Billing;
use Illuminate\Http\Request;
use Laravel\Cashier\Checkout;
/**
* GENERIC subdomain: card collection is Stripe's problem. Laravel Cashier
* (Billable trait on User) redirects to Stripe Checkout; we pass our order id.
*/
final class CheckoutController
{
public function __invoke(Request $request, string $orderId): Checkout
{
/** @var array<string, int> $priceIds Stripe price id => quantity */
$priceIds = $request->session()->get("checkout.{$orderId}.prices", []);
return $request->user()->checkout($priceIds, [
'success_url' => route('checkout-success').'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('checkout-cancel'),
'metadata' => ['order_id' => $orderId],
]);
}
}<?php
declare(strict_types=1);
namespace App\Modules\Identity;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Socialite;
use Symfony\Component\HttpFoundation\RedirectResponse as SymfonyRedirect;
/**
* GENERIC subdomain: OAuth sign-in via Laravel Socialite. Password login,
* reset, email verification and 2FA come from Laravel Fortify (config/fortify.php).
*/
final class SocialLoginController
{
public function redirect(): SymfonyRedirect
{
return Socialite::driver('github')->redirect();
}
public function callback(): RedirectResponse
{
$githubUser = Socialite::driver('github')->user();
$user = User::updateOrCreate(
['github_id' => $githubUser->id],
['name' => $githubUser->name, 'email' => $githubUser->email],
);
Auth::login($user);
return redirect()->intended('/account');
}
}<?php
// Excerpt of config/fortify.php: buy (adopt) the generic Identity subdomain.
use Laravel\Fortify\Features;
return [
'features' => [
Features::registration(),
Features::resetPasswords(),
Features::emailVerification(),
Features::twoFactorAuthentication(),
// Passkeys (WebAuthn): the generic subdomain keeps evolving, and we get it for free.
Features::passkeys([
'confirmPassword' => true,
]),
],
];<?php
declare(strict_types=1);
namespace App\Notifications;
use App\Modules\Sales\Domain\OrderPlaced;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
/**
* GENERIC subdomain: Laravel Notifications + a mail provider (SES, Postmark,
* Mailgun) already solve delivery, channels and queuing. No business rules here.
*/
final class OrderConfirmation extends Notification implements ShouldQueue
{
use Queueable;
public function __construct(private readonly OrderPlaced $event) {}
/** @return list<string> */
public function via(object $notifiable): array
{
return ['mail'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject("Order {$this->event->orderId} confirmed")
->line('Thank you for your order.')
->line('Total: '.number_format($this->event->totalCents / 100, 2).' EUR');
}
}Keeping the types honest
<?php
// Pest architecture tests: subdomain types become dependency rules.
arch('the core domain is plain PHP')
->expect('App\Modules\Sales\Domain')
->not->toUse([
'Illuminate\Support\Facades',
'Illuminate\Database\Eloquent\Model',
'Laravel\Cashier',
'Laravel\Socialite',
'Laravel\Fortify',
]);
arch('the core never calls generic adapters directly')
->expect('App\Modules\Sales')
->not->toUse([
'App\Modules\Billing',
'App\Modules\Identity',
'App\Notifications',
]);
arch('supporting modules see only the core event, not its internals')
->expect('App\Modules\Billing')
->not->toUse([
'App\Modules\Sales\Domain\OrderLine',
'App\Modules\Sales\Domain\Promotion',
'App\Modules\Sales\Application',
]);
arch('vendor SDKs stay in their generic module')
->expect('Laravel\Cashier')
->toOnlyBeUsedIn(['App\Modules\Billing', 'App\Models']);The Laravel angle
- Laravel ships generic subdomains as first-party packages. Fortify is "a headless authentication library" whose
featuresarray enables registration, password reset, email verification, two-factor authentication and passkeys; Socialite handles OAuth providers withSocialite::driver('github')->redirect()and->user(); Cashier adds aBillabletrait and acheckout()method that redirects to Stripe Checkout and "will automatically create a customer in Stripe" when needed. Using them is the "buy" decision for most Laravel shops. - Eloquent is the right tool for supporting subdomains (Active Record) and the wrong place for core rules; keep the core in plain PHP classes and map them in a repository (Repositories).
- Events connect the types: the core dispatches
OrderPlaced; supportingIssueInvoiceand genericOrderConfirmationreact, queued. For reliable delivery across processes use the outbox. - Pest
arch()enforces dependency rules per namespace; Deptrac does the same in config for larger codebases. - Package install for the generic parts:
composer require laravel/fortify laravel/socialite laravel/cashier.
Solving the classic problems
Everything is treated as core
Every module has aggregates, CQRS and event sourcing; delivery is slow everywhere; the actual differentiator gets the same attention as the admin screens.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Classification workshop | Steps above | Shared, explicit priorities | Two days of senior time |
| Downgrade supporting modules | Replace aggregates with CRUD where rules are trivial | Less code, faster changes | Migration effort; pride |
| Vision statement as a gate | PRs to "core" must cite it | Core stays small | Needs discipline |
A generic subdomain is built in-house
Home-made login, token signing, card storage. Fix: adopt Fortify/Socialite or an IdP; move card data to Stripe (reducing PCI DSS scope); keep a port so the vendor can change. See OAuth 2.0 & OIDC and Payment Processing Architecture.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Adopt a package | Fortify, Socialite, Cashier; x/oauth2, stripe-go | Security fixes from the vendor | Their upgrade cadence |
| Use SaaS / IdP | Auth0, Okta, Cognito, Keycloak | Least code | Cost per user; lock-in |
| Strangle the old module | Route new sign-ups to the vendor first | No big-bang | Two systems for a while |
The core is outsourced or bought
A company buys a pricing engine and configures it like everyone else does, or hands its core to an agency. Kaiser's cloud-provider example: building commodities in-house can still be right when they are core, and "Outsourcing its core domain would limit the cloud provider's differentiation opportunities". Fix: bring the core in-house; if a product is used, restrict it to its designed use and build the differentiating part beside it ("build and buy").
A supporting subdomain grows complex
Returns, loyalty or delivery-zone rules multiply. Khononov's two exits: simplify (accidental complexity) or recognise a core in disguise. Fix: run the decision flow with the business; either cut rules or promote the subdomain (own package, rich model, strong engineers).
The core is buried in generic code
Pricing rules live inside an ERP customisation or an email template. Fix: Evans's segregated core: extract the rules into a core package, leave the vendor as an adapter, and add an architecture test.
No access to real domain experts
Only a proxy is available. Fix: for the core, negotiate expert time as a project dependency (it is cheaper than rework); use observation, support tickets and data as indirect evidence; for supporting and generic subdomains, a proxy is often enough.
Choosing
Build vs buy vs outsource: the decision table.
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Core, still being discovered (genesis/custom) | Build in-house, best people | Rich model, experts in the loop, fast deploys | The edge is in the details only you know |
| Core, but a product covers the commodity part | Build and buy | Use the product for its designed use; build the differentiator beside it | Kaiser: decisions are "sometimes not either build or buy" |
| Supporting, nothing on the market fits | Build cheaply | CRUD, low-code admin, transaction scripts | No advantage from sophistication |
| Supporting, configurable product exists | Buy and configure lightly | Limit customisation; ACL around it | Over-customisation erodes the benefit |
| Supporting, stable and well specified | Outsource | Contract tests on the interface | Frees the team for the core |
| Generic, product or commodity stage | Buy / OSS / SaaS | Port + adapter; vendor sandbox tests | Solved; vendor carries security and compliance |
| Generic but regulation forces in-house hosting | Self-host OSS (Keycloak) | Platform team owns it | Data residency |
| You are the vendor of that generic thing | It is your core | Build | Identity companies build identity |
Which generic option, by product (verify pricing and limits with each vendor):
| Need | Package in the code | Hosted product | Self-hosted |
|---|---|---|---|
| Sign-in for a Laravel app | Fortify (+ Socialite for OAuth) | Auth0, Okta, Cognito | Keycloak |
| OAuth client in Go | golang.org/x/oauth2 | Any OIDC provider | Keycloak, Dex |
| Card payments | Cashier (Laravel), stripe-go (Go) | Stripe, Adyen, PayPal | Not advisable (PCI DSS) |
| Transactional email | Laravel Mail/Notifications, net/smtp | Amazon SES, Postmark, SendGrid | Postfix (rarely worth it) |
| Search for a non-search business | Laravel Scout | Algolia, Elastic Cloud | OpenSearch, Meilisearch |
Which investment per type is the table in Mechanics.
In architecture: from a single process to a distributed system
Subdomain types do not change with deployment style, but how they show up does.
Monolith: one process, one database
Types become packages and namespaces. The simplest correct version: sales/ (core, rich), catalog/ and billing/ (plain), vendor adapters in their own packages, an architecture test, and CODEOWNERS that put the best reviewers on the core. Example: the Laravel layout above in one deployable, one MySQL or PostgreSQL database with a table prefix per subdomain.
Modular monolith and multiple databases
Types become modules with owned schemas. Each module has its own schema and database role (SQL above); modules talk through public interfaces and in-process events. Generic modules are often just configuration of a package. Example: Sales and Fulfilment as modules with their own schemas and teams; Billing reads OrderPlaced events, never sales.* tables. See Modular Monolith.
Microservices: the boundary becomes a network
Types now drive which services exist and who runs them. Core subdomains justify their own services and stream-aligned teams; supporting ones are often grouped into one service; generic ones are usually not services you write at all but SaaS behind an adapter. Example flow:
Checkout across services (types in brackets)
1 Web -> Identity (generic: IdP) : verify session token
2 Web -> Sales (core) : POST /orders price, promotions, flash-sale limits
3 Sales -> outbox -> broker : sales.order.placed.v1
4 Billing (supporting) consumes : issue invoice, call Stripe (generic) via port
5 Fulfilment (core or supporting) consumes : reserve slot, plan pick wave
6 Notifications (generic: provider) : "order confirmed" emailCross-service consistency uses the outbox and sagas; the communication choices are in Service Communication.
Distributed data: replicas, caches and multi-region
Types tell you where to spend consistency and availability budget. The core's invariants (price shown is final; never below floor) need strong consistency on the write path and careful cache invalidation; read replicas or caches are fine for Catalog (supporting) with seconds of lag (Replication). Generic vendors bring their own regions and SLAs; multi-region for Identity means choosing an IdP region, not building replication. Example: Catalog served from a CDN and read replicas, Sales writes to the primary, Stripe in its own regions.
Scaling path: 1×, 10×, 100×
- 1×: one team, one deployable; classification lives in package layout, the vision statement and arch tests.
- 10×: several teams; core subdomains get dedicated stream-aligned teams; supporting subdomains share a team or are outsourced; generic ones are owned by a platform team as adapters. A large subdomain like Fulfilment may split into two bounded contexts (slotting, carriers).
- 100×: a complicated-subsystem team for algorithmic cores (routing, pricing optimisation); a pioneers/experiments area for the next core; the Core Domain Chart reviewed each quarter with movement arrows; former cores replaced by products.
Lab: classify, chart and enforce
Setup. Go 1.26+ (stripe-go v87 requires it), the snippet module from this chapter.
cd docs/snippets/ddd/domains-subdomains/go
go test ./...
# ok academy/domains-subdomains (arch test)
# ok academy/domains-subdomains/classify
# ok academy/domains-subdomains/sales
go run ./cmd/chart
# SUBDOMAIN DIFF CPLX TYPE INVESTMENT WARNING
# Sales ordering 5 5 core build in-house, best engineers, rich model, deep tests
# Fulfilment 3 4 supporting build simply (CRUD, transaction script) or outsource complex or volatile supporting: simplify it, or it is a core in disguise
# Billing 2 3 supporting build simply (CRUD, transaction script) or outsource
# Catalog 2 2 supporting build simply (CRUD, transaction script) or outsource
# Identity 1 4 generic buy, adopt open source or use SaaS; wrap behind a port complex but solved elsewhere: do not rebuild it
# Notifications 1 2 generic buy, adopt open source or use SaaS; wrap behind a port- Change strategy. In
cmd/chart/main.goset Fulfilment toDifferentiation: 4(a shop whose customers buy for same-day delivery). Run again: Fulfilment becomescore. Set it toDifferentiation: 2, Complexity: 2(the 3PL company): plainsupporting, no warning. Same activity, different strategy, different type. - Find a core in disguise. Add
{Name: "Returns", Differentiation: 3, Complexity: 5, Volatility: 4}. Expected:supportingwith the warning "complex or volatile supporting: simplify it, or it is a core in disguise". - Break the core boundary. In
sales/order.goaddimport _ "github.com/stripe/stripe-go/v87". Rungo test .. Expected:TestSubdomainDependenciesfails namingsales/order.go. Revert. - Test a core rule. In
sales/order_test.gochange the cap toMaxPerLine: 20000. Expected:TestPromotionIsCappedPerLinefails (want 70000, got 64000). This is the test the pricing manager reads. - Run your own workshop. Take your product, list 6–10 subdomains, score them, run
cmd/chart, draw the Core Domain Chart on paper, and write a one-page vision statement. Compare engineers' and business scores; the biggest disagreement is your next conversation. - Laravel (in an app with Pest). Copy
tests/ArchitectureTest.phpand adduse Laravel\Cashier\Billable;to a class inApp\Modules\Sales\Domain. Expected: running Pest makes the arch test named "the core domain is plain PHP" fail (we did not run PHP for this page; the exact message depends on your Pest version).
Common misconceptions
| Belief | Reality |
|---|---|
| Everything we build is core | Make the core small (Evans); most code is supporting or generic |
| Core means critical | Critical-but-not-differentiating is supporting ("Parity" in Nickolaisen's model) |
| Generic means simple | Generic means solved elsewhere; identity and payments are very complex |
| Supporting means low quality is fine | It must be correct; it just gets no extra sophistication |
| One subdomain = one bounded context = one microservice | Problem space and solution space differ; mappings are often not 1:1 |
| Subdomain types are permanent | Types drift with the market (Wardley evolution, first-to-market cores) |
| Departments are subdomains | Org charts are hints; capabilities and events are better evidence |
| The product owner is the domain expert | Often a proxy; meet the people who do the work |
| A Core Domain Chart gives objective scores | It is subjective by design; the conversation is the value |
| Buying a product for the core saves money | It removes your edge; build and buy instead |
| Every company must have a software core | Khononov describes a venture with only supporting and generic subdomains |
| Evans defined three subdomain types | The Reference names Core Domain and Generic Subdomains; "supporting" as a type comes from later practice |
Cheat sheet
| Topic | Remember |
|---|---|
| Domain | The business area: "online ordering and same-day fulfilment" |
| Subdomain | An area of activity the business needs; discovered, not designed |
| Problem vs solution space | Subdomains = what; bounded contexts = how; not 1:1 |
| Core | Differentiating, complex, volatile; build, best people, rich model |
| Supporting | Specific, not differentiating, simple; build cheaply or outsource |
| Generic | Everyone has it, solved; buy, OSS or SaaS behind a port |
| Order of questions | Buyable without losing edge? → differentiating? → simple? |
| Complex supporting | Simplify it, or it is a core in disguise |
| Drift | Review types quarterly; cores become commodities |
| Core Domain Chart | x = business differentiation, y = model complexity; arrows for movement |
| Vision statement | About one page; narrow; revised |
| Distillation | Highlighted → cohesive mechanisms → segregated → abstract core |
| Experts | Follow money, exceptions, spreadsheets, complaints |
| Proxy risk | Relayed rules lose detail; bring the real expert for the core |
| Code | Core package rich + tested; vendors only in adapters; arch test |
| Build vs buy | Build core, buy generic, keep supporting cheap; "build and buy" is allowed |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name the domain and three subdomains of a food-delivery app. Must-know
Answer
Answer: Domain: on-demand restaurant delivery. Subdomains: courier dispatch and routing (likely core), restaurant onboarding and menus (supporting), payments and sign-in (generic). Others: pricing and fees, customer support, notifications.
2 — Why is Billing in the running example supporting even though the company cannot run without it? Must-know
Answer
Answer: Because the type is about differentiation, not criticality. Customers do not choose the shop for its invoices; it must be correct and legal (Nickolaisen's "Parity"), so it is built simply.
3 — Give two reasons why subdomains and bounded contexts are not always 1:1. Must-know
Answer
Answer: A generic subdomain may be served by a vendor with no context of ours (payments via Stripe); a large subdomain may need several models (Fulfilment split into slotting and carriers); several small subdomains may share one context early on; a capability like notifications may be a library used by many contexts.
4 — In what order does Khononov's categorisation ask its questions, and why does the order matter? Important
Answer
Answer: Can we buy/adopt without losing competitive advantage (generic)? Is the logic simple (supporting)? Otherwise core. Ruling out generic first stops teams from calling solved-but-complex problems like identity "core" just because they are hard.
5 — What does a complex supporting subdomain tell you? Important
Answer
Answer: Either the complexity is accidental and should be simplified, or the subdomain is a core in disguise that the business could gain an edge from. Ask the business which.
6 — What are the axes of a Core Domain Chart, and who should score each? Good to know
Answer
Answer: x: business differentiation (scored by product/business people), y: model complexity (scored by engineers). The README stresses the cross-discipline conversation.
7 — Give an example of a core subdomain becoming supporting or generic. Good to know
Answer
Answer: Same-day delivery once rivals and 3PLs offer it; music catalogues in early streaming (DDD-Crew "First-to-Market Core"), after which discovery became the core; online card payments now bought from payment APIs.
8 — What is a Domain Vision Statement and how long is it? Important
Answer
Answer: Evans: a short description, about one page, of the core domain and its value proposition, ignoring undifferentiating aspects, kept narrow and revised as insight grows.
9 — How do highlighted core and segregated core differ? Important
Answer
Answer: Highlighted core makes the core visible (a brief distillation document or flags in the repository) without changing the model; segregated core refactors the code to separate core concepts from supporting ones and reduce coupling.
10 — Why is a product owner a risky sole source for core rules? Important
Answer
Answer: They often relay rules second-hand; each relay loses detail (Team Topologies' "game of telephone"). For the core, bring the people who do the work and carry the consequences.
11 — How do you enforce "the core never depends on vendor SDKs" in Go and in Laravel? Must-know
Answer
Answer: Go: an architecture test that parses imports with go/parser and fails if sales/ imports stripe-go or oauth2 (or depguard/go-arch-lint). Laravel: Pest arch() expecting App\Modules\Sales\Domain not to use Laravel\Cashier, Socialite, Fortify or facades (or Deptrac).
12 — When is building a "commodity" in-house still right? Good to know
Answer
Answer: When it is your core even at commodity stage, as in Kaiser's example of a cloud provider that would not outsource its cloud services to another cloud provider.
Glossary
| Term | Meaning |
|---|---|
| Domain | The company's overall business area (Khononov); the problem domain (Kaiser) |
| Subdomain | A distinct area of activity the business needs; part of the problem domain |
| Problem space | What problems the business must solve; subdomains live here |
| Solution space | How we solve them: models, bounded contexts, context maps, services |
| Core domain (core subdomain) | The differentiating, complex, volatile part where the company wins |
| Supporting subdomain | Specific to the business, needed by the core, not differentiating; simple |
| Generic subdomain | A problem all companies share, already solved; buy or adopt |
| Bounded context | A boundary within which one model applies (solution space); see Bounded Context |
| Domain expert | A person with first-hand knowledge of how the business works |
| Proxy expert | An intermediary relaying experts' knowledge (product owner, analyst, consultant) |
| Knowledge crunching | Iterative distillation of domain knowledge into a model with experts |
| Distillation | Separating the essence (the core) from the rest of the model |
| Domain Vision Statement | About one page describing the core and its value proposition |
| Highlighted core | A brief distillation document and/or flags marking core elements |
| Cohesive mechanism | A complex algorithm factored into a lightweight framework with an intention-revealing interface |
| Segregated core | Refactoring that separates core concepts from supporting ones |
| Abstract core | The most fundamental concepts as interfaces/abstract classes in their own module |
| Core Domain Chart | DDD-Crew chart of business differentiation (x) vs model complexity (y) |
| Business differentiation | How much a capability makes customers choose you over rivals |
| Model complexity | Essential difficulty of the rules, invariants and algorithms |
| Volatility | How often a subdomain's rules change |
| Core in disguise | A supporting subdomain whose real complexity signals a missed competitive edge |
| First-to-market core | A core whose advantage lasts only until rivals copy it |
| Big-bet sub-domain | Core Domain Chart notation for a strategic gamble on future differentiation |
| Wardley map | Value chain of user needs placed on an evolution axis |
| Evolution stages | Genesis, custom-built, product (+ rental), commodity (+ utility) |
| Value chain | Users → needs → capabilities, the anchor of a Wardley map |
| Business capability mapping | A hierarchy of what the business can do, used to find subdomains |
| Purpose Alignment Model | Nickolaisen's differentiating × mission-critical model (Differentiating, Parity, Partner, Who cares?) |
| Build vs buy | The sourcing decision: build in-house, buy/adopt, or outsource |
| Off-the-shelf | A ready-made product or library |
| Transaction script | Procedure per use case; fits supporting subdomains |
| Active Record | Objects that wrap a table row (Eloquent); fits supporting subdomains |
| Domain model | Rich object model of rules and behaviour; fits the core |
| Pre-mortem | Imagining a project has failed, then listing why (Klein) |
| Domain Storytelling | Pictographic modelling of experts' stories |
| Event storming | Workshop of domain events on a timeline; see Event Storming |
| Stream-aligned team | Team Topologies team aligned to a flow of business change |
| Complicated-subsystem team | Team for components needing specialist knowledge |
| Cognitive load | How much a team must hold in mind; limits ownership |
| Laravel Fortify | Headless authentication backend for Laravel |
| Laravel Socialite | OAuth sign-in with providers for Laravel |
| Laravel Cashier | Stripe (or Paddle) billing integration for Laravel |
| golang.org/x/oauth2 | Go OAuth 2.0 client library |
| stripe-go | Stripe's official Go library |
References
- Eric Evans, Domain-Driven Design Reference: Definitions and Pattern Summaries (2015), patterns Core Domain, Generic Subdomains, Domain Vision Statement, Highlighted Core, Cohesive Mechanisms, Segregated Core, Abstract Core: https://www.domainlanguage.com/wp-content/uploads/2016/05/DDD_Reference_2015-03.pdf
- Domain Language, DDD resources: https://www.domainlanguage.com/ddd/
- Vlad Khononov, Revisiting the Basics of Domain-Driven Design (26 January 2018): https://vladikk.com/2018/01/26/revisiting-the-basics-of-ddd/
- Susanne Kaiser, Exploring the Problem Space with Strategic Domain-Driven Design and Wardley Mapping (chapter 2 excerpt of Architecture for Flow, InformIT): https://www.informit.com/articles/article.aspx?p=3222355
- DDD-Crew, Core Domain Charts (README, template, examples): https://github.com/ddd-crew/core-domain-charts
- DDD-Crew, DDD Starter Modelling Process: https://github.com/ddd-crew/ddd-starter-modelling-process
- Martin Fowler, DomainDrivenDesign (bliki, 22 April 2020): https://martinfowler.com/bliki/DomainDrivenDesign.html
- Martin Fowler, BoundedContext (bliki): https://martinfowler.com/bliki/BoundedContext.html
- Niel Nickolaisen, The Purpose Alignment Model (InformIT, 20 August 2009, archived): https://web.archive.org/web/20241202160527/https://www.informit.com/articles/article.aspx?p=1384195&seqNum=2
- Learn Wardley Mapping, introduction: https://learnwardleymapping.com/introduction/
- Team Topologies, key concepts: https://teamtopologies.com/key-concepts
- Gary Klein, Performing a Project Premortem (HBR, September 2007): https://hbr.org/2007/09/performing-a-project-premortem
- Domain Storytelling: https://domainstorytelling.org/
- Laravel 13 documentation: Fortify https://laravel.com/docs/13.x/fortify, Socialite https://laravel.com/docs/13.x/socialite, Cashier (Stripe) https://laravel.com/docs/13.x/billing
- stripe-go README: https://github.com/stripe/stripe-go
- golang.org/x/oauth2 source: https://github.com/golang/oauth2
- Vaughn Vernon, Implementing Domain-Driven Design (2013), chapter 2 (cited, not quoted; not read for this page): https://www.informit.com/store/implementing-domain-driven-design-9780133039894