Domain-Driven Design

127 Reusable Domain Models

The foundation for adaptive, composable UIs

Stop reinventing common patterns. ProtoFlow provides a comprehensive library of typed, versioned domain models for authentication, billing, notifications, and more. Domain models provide semantic contracts that work across any interface.

What Are Domain Models?

Domain models are reusable, typed data structures that represent core business concepts in your application. Instead of recreating "User", "Subscription", or "Notification" entities from scratch in every project, ProtoFlow provides pre-built models with:

  • Strong typing: TypeScript interfaces and Python type hints for compile-time safety
  • Atomic design: Models decomposed into reusable primitives (Address, Money, PhoneNumber)
  • Versioning: Track model changes with semantic versioning
  • YAML schema: Human-readable definitions with automatic code generation

The Missing Layer: Semantic Interoperability

The Gap

We have syntax interoperability (OpenAPI, GraphQL, REST) but NOT semantic interoperability.

The Problem

APIs describe endpoints, not meaning. They define HOW to call, not WHAT it means.

Example: Two providers can both have a "User" endpoint, but they mean different things (social profile vs. account holder vs. system user). Without semantic contracts, consumers must learn each provider's unique interpretation.

ProtoFlow's Solution

Shared domain models provide semantic contracts. When a provider implements the standard "User" domain model, consumers know exactly what fields exist, what they mean, and how to use them. Same vocabulary, same structure, same meaning.

Semantic Interface Layer Architecture

Domain models live in the semantic interface layer, providing contracts that enable different UIs to consume the same semantic data while storage remains an implementation detail.

Layer 1: Adaptive UI Consumers

Context-aware interfaces that adapt to device, environment, and user preference

Car Mode Desktop Voice Assistant AR/VR Mobile Custom Apps

Layer 2: Semantic Interface Layer

Domain models provide contracts, semantics, and interoperability

This is where domain models live

Providers expose semantic contracts. Consumers interact with meaning, not endpoints. Storage is abstracted away.

Layer 3: Providers (Implementation Detail)

Storage backend doesn't matter - it's abstracted by semantic contracts

PostgreSQL DynamoDB S3 MongoDB Custom API

Key Insight: Domain models enable different UIs to consume the same semantic data. Same "User" model serves car dashboard, mobile app, and voice assistant.

Four Key Insights

🔌

API-First Interfaces

  • Providers expose semantic contracts (domain models), not screens
  • Storage is an implementation detail (PostgreSQL, DynamoDB, S3 - doesn't matter)
  • Consumers interact with meaning, not endpoints
🎨

Consumer-Composed UIs

  • Users and apps assemble interfaces however they want
  • UI becomes a commodity - competition shifts to data quality
  • Same domain model, infinite interface possibilities
🌐

Public Microservices

  • Microservices pattern goes public across organizations
  • Domain models enable cross-organization interoperability
  • What was internal architecture becomes universal contracts
🎯

Context-Aware Rendering

  • Device, environment, user preference drive presentation
  • Same domain model data, infinite interfaces
  • Car mode vs normal mode - same semantic contract

Practical Example: Context-Aware UIs

The same domain model serves different contexts with different presentations. The semantic contract remains consistent while the interface adapts.

🚗 Car Mode

Large buttons, voice-first, simplified

Navigate Home
Find Gas Station
Same "Navigation" domain model

💻 Normal Mode

Full features, touch-optimized

Same "Navigation" domain model

Same Semantic Contract, Different Presentations

The Navigation domain model provides: location, destination, route, preferences. The interface adapts to context.

Why Domain Models Matter

Semantic Consistency

Same terminology and structure across all interfaces. When you see "User", you know exactly what it means - no ambiguity.

Future-Proof

New interfaces consume existing models without changes. Build once, use everywhere - from smartwatches to VR headsets.

Interoperability

Cross-provider semantic agreements enable true ecosystem interoperability. Providers compete on quality, not lock-in.

AI-Friendly

LLMs understand semantic contracts better than arbitrary APIs. Domain models provide clear, consistent context for AI agents.

Domain Categories

127 models organized across 15 categories

Authentication (12 models)

User, Session, Token, MFA, OAuth Provider, Password Policy, Login Attempt, Permission, Role

User { id: UUID email: Email roles: Role[] sessions: Session[] created_at: DateTime }

Billing & Payments (15 models)

Subscription, Invoice, Payment, Card, Plan, Discount, Tax, Refund, Webhook Event

Subscription { id: UUID user_id: UUID plan: Plan status: enum billing_cycle: Duration next_billing: DateTime }

Notifications (9 models)

Notification, NotificationPreference, Channel, Template, Digest, Alert, Trigger

Notification { id: UUID user_id: UUID type: NotificationType channels: Channel[] status: DeliveryStatus sent_at: DateTime }

Content Management (11 models)

Post, Page, Media, Category, Tag, Comment, Author, Revision, SEO Metadata

Post { id: UUID title: string content: RichText author: Author tags: Tag[] published_at: DateTime seo: SEOMetadata }

E-commerce (18 models)

Product, Order, Cart, Inventory, Shipping, Warehouse, SKU, Variant, Coupon, Review

Order { id: UUID customer: User items: OrderItem[] total: Money status: OrderStatus shipping: ShippingAddress }

Organizations (8 models)

Organization, Team, Member, Invitation, Workspace, Department, Hierarchy

Organization { id: UUID name: string teams: Team[] members: Member[] settings: OrgSettings created_at: DateTime }

Scheduling (7 models)

Event, Calendar, Appointment, Availability, Booking, Recurrence, TimeZone

Event { id: UUID title: string start: DateTime end: DateTime attendees: User[] recurrence: RecurrenceRule }

Analytics (10 models)

Event, Metric, Dashboard, Chart, Dimension, Measure, Funnel, Cohort, Report

Metric { id: UUID name: string value: number dimensions: Dimension[] timestamp: DateTime tags: string[] }

Workflow (6 models)

Workflow, Step, Transition, State, Approval, Trigger, Condition

Workflow { id: UUID name: string steps: Step[] current_state: State transitions: Transition[] }

Messaging (8 models)

Message, Conversation, Thread, Participant, Attachment, Reaction, Read Receipt

Message { id: UUID conversation_id: UUID sender: User content: RichText attachments: Attachment[] sent_at: DateTime }

Media & Assets (9 models)

File, Image, Video, Audio, Document, Thumbnail, Metadata, Transform, Storage

Image { id: UUID url: URL width: number height: number format: ImageFormat thumbnails: Thumbnail[] }

Audit & Compliance (7 models)

AuditLog, Change, Version, Approval, Policy, Compliance, Evidence

AuditLog { id: UUID entity_type: string entity_id: UUID action: AuditAction actor: User changes: Change[] timestamp: DateTime }

Location & Geography (7 models)

Address, Coordinate, Region, Country, TimeZone, Geofence, Distance

Address { street: string city: string state: string postal_code: string country: Country coordinates: Coordinate }

Primitives (20 models)

Money, Email, PhoneNumber, URL, UUID, Color, Duration, Range, Percentage, Currency

Money { amount: Decimal currency: Currency formatted: string display(): string }

Core Tenets: First-Principles Thinking

Domain models built on principles from physics, philosophy, and biology

⚛️

1. Irreducible Primitives

Physics: Matter, Energy, Space, Time.

Our primitives: Entity (what exists), State (condition), Event (what happened), Relation (how connected), Quantity (how much).

🔗

2. Composition Over Inheritance

Build complex concepts by combining primitives: Order = Entity + State + Relation(Customer) + Quantity(total). Never deep inheritance trees.

📜

3. Events Over Mutations

Prefer OrderPlaced → OrderPaid → OrderShipped over order.status = 'shipped'. Events are auditable, replayable, debuggable.

🎯

4. Single Responsibility

Each primitive models ONE concept: entity = identity, state = condition, event = occurrence, quantity = measurement.

🤖

5. Agent-Centric (AITR)

Actor (who acts) + Intent (why) + Tool (how) + Resource (with what). Every action has an agent.

🌳

6. Graph-Native

Everything is triples: Subject → Predicate → Object. Maps directly to RDF, Neo4j, knowledge graphs. Queryable, federatable.

Atomic Hierarchy

From irreducible primitives to full applications—like Atomic Design for data

Applications (Pages)
Online Store Patient Portal Fleet Tracker
Industry Patterns (Templates)
E-commerce Healthcare SaaS Logistics
Domains (Organisms) — 127 domains
finance auth booking workflow email geo-point llm-conversation +120 more
Compositions (Molecules)
lifecycle flow exchange structure measure
Primitives (Atoms) — The 9 Irreducibles
Entity State Event Relation Quantity Actor Intent Tool Resource

Real-World Compositions

See how primitives combine into complete domain models

🛒

E-commerce (Converse Website)

Product catalog, shopping cart, checkout, fulfillment

Order = Entity + State(pending→paid→shipped→delivered)
      + Relation(Customer, Products)
      + Quantity(total: Money)
      + Event(OrderPlaced, OrderPaid, OrderShipped)
      + Actor(buyer) + Resource(payment, inventory)
core.Entity core.Money workflow.State events.DomainEvent
🚚

Fleet Management

Vehicles, routes, tracking, maintenance

Vehicle = tracking-asset.Vehicle
        + State(available→in_transit→maintenance)
        + geo-point.Position(lat, lng)
        + routing-route.Route(waypoints)

Trip = Entity + tracking-position.Track
     + Actor(driver) + Resource(fuel, time)
tracking-asset.Vehicle geo-point.Point routing-route.Route
🍺

Pub Management System

Menu, orders, tabs, inventory, events

Tab = Entity + State(open→paid→closed)
    + Relation(Customer, Table, Server)
    + Quantity(total, tip)
    + Event(TabOpened, ItemAdded, TabClosed)

MenuItem = material.Material(ingredients)
         + Quantity(price, abv)
core.Entity finance.Payment material.Material
🤖

AI/LLM Application

Conversations, tool use, memory, evaluation

Conversation = llm-conversation.Session
             + llm-message.Message[]
             + llm-participant.Actor(user, assistant)
             + llm-tool-use.Tool[]
             + llm-memory.MemoryBank
llm-conversation.Session llm-message.Message llm-tool-use.Tool

Domain Modeling Agent

ProtoFlow includes a specialized domain modeling agent that automatically generates typed domain models from natural language descriptions or existing schemas. The agent:

Capabilities

  • Decomposes complex entities into atomic primitives
  • Generates TypeScript and Python type definitions
  • Creates YAML schema definitions
  • Identifies reusable models from domain library
  • Validates model consistency and relationships

Benefits

  • Consistent data structures across projects
  • Reduced duplication through reuse
  • Type safety in backend and frontend
  • Automatic documentation generation
  • Semantic versioning for model evolution

Example: Building a Task Management App

# In Claude Code: /generate-domain Task Management App # Agent automatically composes: Task { id: UUID title: string description: RichText assignee: User # Reuses auth.User model status: TaskStatus priority: Priority due_date: DateTime tags: Tag[] attachments: File[] # Reuses media.File model created_at: DateTime updated_at: DateTime }

The agent recognizes User and File already exist in the domain library and reuses them instead of creating duplicates.

Start Building with Domain Models

Stop writing the same User, Product, and Order models in every project. Let ProtoFlow's domain library accelerate your development.