Skip to content

🎯 Architecture Patterns & Core Concepts¢

Welcome to architecture patterns! This section explains the patterns and principles that Neuroglia is built upon. Each pattern is explained for beginners - you don't need prior knowledge.

πŸ“– Note: Pattern documentation includes beginner-friendly What & Why sections showing problems and solutions, Common Mistakes with anti-patterns, and When NOT to Use guidance.

🎯 Why These Patterns?¢

Neuroglia enforces specific architectural patterns because they solve real problems in software development:

  • Maintainability: Code that's easy to change as requirements evolve
  • Testability: Components that can be tested in isolation
  • Scalability: Architecture that grows with your application
  • Clarity: Clear separation of concerns and responsibilities

οΏ½ Quick Start Learning PathΒΆ

New to these patterns? Follow this recommended path:

  1. Foundation: Clean Architecture - Organizing code in layers
  2. Dependencies: Dependency Injection - Managing components
  3. Domain Logic: Domain-Driven Design - Modeling business rules
  4. Application Layer: CQRS - Separating reads from writes
  5. Integration: Event-Driven Architecture - Reacting to events
  6. Data Access: Repository - Abstracting persistence

Already familiar? Jump to any pattern for Neuroglia-specific implementation details.

πŸ’‘ What Each Guide IncludesΒΆ

  • ❌ The Problem: What happens without this pattern
  • βœ… The Solution: How the pattern solves it
  • πŸ”§ In Neuroglia: Framework implementation details
  • πŸ§ͺ Testing: How to test code using this pattern
  • ⚠️ Common Mistakes: Pitfalls to avoid
  • 🚫 When NOT to Use: Scenarios where simpler approaches work better

πŸ—οΈ Architectural Approaches: A Comparative IntroductionΒΆ

Before diving into specific patterns, it's essential to understand the different architectural philosophies that drive modern system design. The Neuroglia framework draws from multiple architectural approaches, each with distinct strengths and use cases.

🎯 Core Philosophy Comparison¢

Domain-Driven Design (DDD) and Declarative Resource-Oriented Architecture represent two powerful but different approaches to managing complex system states:

  • DDD: Models systems around business domains, focusing on behavior and state transitions
  • Declarative Architecture: Defines desired end states and uses automated processes to achieve them

πŸ”„ Architectural Patterns OverviewΒΆ

Architecture Core Philosophy Primary Actor Unit of Work Source of Truth Flow of Logic Error Handling Typical Domain
πŸ›οΈ Domain-Driven Design Model around business domain with AggregateRoot as guardian enforcing business rules Imperative Command: User/system issues explicit commands (AddToppingToPizza) Aggregate: Boundary around business objects with atomic transactions Application Database: Current aggregate state in database Synchronous & Explicit: CommandHandler β†’ Repository.Get() β†’ Aggregate.Method() β†’ Repository.Update() Throws Exceptions: Business rule violations cause immediate failures Complex Business Logic: E-commerce, banking, booking systems
🌐 Declarative Resource-Oriented Define desired state and let automated processes achieve it Declarative Reconciliation: Automated Controller continuously matches actual to desired state Resource: Self-contained state declaration (e.g., Kubernetes Pod manifest) Declarative Manifest: Configuration file (YAML) defines desired state Asynchronous & Looping: Watcher detects change β†’ Controller triggers β†’ Reconciliation Loop β†’ Client.UpdateActualState() Retries and Converges: Failed operations retry in next reconciliation cycle Infrastructure & Systems Management: Kubernetes, Terraform, CloudFormation

🎨 Practical Analogies¢

  • DDD is like giving a chef specific recipe instructions: "Add 20g of cheese to the pizza" - explicit commands executed immediately
  • Declarative Architecture is like giving the chef a photograph of the final pizza: "Make it look like this" - continuous checking and adjustment until the goal is achieved

πŸ“‘ Event-Driven Architecture: The FoundationΒΆ

Event-Driven Architecture (EDA) serves as the postal service πŸ“¬ of your system - a foundational pattern enabling reactive communication without tight coupling between components.

πŸ›οΈ EDA in Domain-Driven DesignΒΆ

In DDD, EDA handles side effects and communication between different business domains (Bounded Contexts):

  • Purpose: Reacting to significant business moments
  • Mechanism: AggregateRoot publishes DomainEvents (e.g., OrderPaid, PizzaBaked)
  • Benefit: Highly decoupled systems where services don't need direct knowledge of each other

Example: Orders service publishes OrderPaid β†’ Kitchen service receives event and starts pizza preparation

🌐 EDA in Declarative Architecture¢

In declarative systems, EDA powers the reconciliation loop:

  • Purpose: Reacting to changes in configuration or state
  • Mechanism: Watcher monitors resources β†’ generates events β†’ Controller consumes events and reconciles state
  • Benefit: Automated state management with continuous convergence toward desired state

Example: YAML file creates Deployment β†’ API server generates "resource created" event β†’ Deployment controller creates required pods

πŸ”„ Integration SummaryΒΆ

Architecture How it uses Event-Driven Architecture (EDA)
πŸ›οΈ Domain-Driven Design Uses Domain Events to announce significant business actions, triggering workflows in decoupled business domains
🌐 Declarative Architecture Uses State Change Events (from watchers) to trigger controller reconciliation loops, ensuring actual state matches desired state

🎯 Choosing Your Approach¢

Both patterns leverage EDA for reactive, decoupled systems but differ in event nature and granularity:

  • DDD: Focus on high-level business events with rich domain behavior
  • Declarative: Focus on low-level resource state changes with automated convergence

The Neuroglia framework provides implementations for both approaches, allowing you to choose the right pattern for each part of your system.

οΏ½πŸ›οΈ Pattern OverviewΒΆ

Pattern Purpose Key Concepts What You'll Learn Mario's Pizzeria Use Case When to Use
πŸ—οΈ Clean Architecture Foundation pattern that organizes code into layers with clear dependency rules β€’ Domain-driven layer separation
β€’ Dependency inversion principle
β€’ Business logic isolation
β€’ Infrastructure abstraction
β€’ Four-layer architecture implementation
β€’ Dependency flow and injection patterns
β€’ Domain entity design with business logic
β€’ Integration layer abstraction
Order processing across API, Application, Domain, and Integration layers All applications - structural foundation
πŸ›οΈ Domain Driven Design Core domain abstractions and patterns for rich business models with event-driven capabilities β€’ Rich domain entities with business logic
β€’ Aggregate roots and consistency boundaries
β€’ Domain events and integration events
β€’ Event sourcing vs traditional approaches
β€’ Entity and aggregate root implementation
β€’ Domain event design and handling
β€’ Transaction flows with multiple events
β€’ Data flow across architectural layers
Pizza orders with business rules, events, and cross-layer data flow Complex business domains, rich models
πŸ›οΈ Persistence Patterns Alternative persistence approaches with different complexity levels and capabilities β€’ Simple Entity + State Persistence
β€’ Complex AggregateRoot + Event Sourcing
β€’ Hybrid approaches
β€’ Pattern decision frameworks
β€’ Complexity level comparison
β€’ Implementation patterns for each approach
β€’ Decision criteria and guidelines
β€’ Migration strategies between patterns
Customer profiles (simple) vs Order processing (complex) patterns All applications - choose right complexity
πŸ”„ Unit of Work Pattern Coordination layer for domain event collection and dispatching across persistence patterns β€’ Aggregate registration and tracking
β€’ Automatic event collection
β€’ Pipeline integration
β€’ Flexible entity support
β€’ UnitOfWork implementation and usage
β€’ Event coordination patterns
β€’ Pipeline behavior integration
β€’ Testing strategies for event workflows
Order processing with automatic event dispatching after state persistence Event-driven systems, domain coordination
οΏ½ Pipeline Behaviors Cross-cutting concerns implemented as composable behaviors around command/query execution β€’ Decorator pattern implementation
β€’ Behavior chaining and ordering
β€’ Cross-cutting concerns
β€’ Pre/post processing logic
β€’ Creating custom pipeline behaviors
β€’ Behavior registration and ordering
β€’ Validation, logging, caching patterns
β€’ Transaction and error handling
Validation, logging, and transaction management around order processing Cross-cutting concerns, AOP patterns
οΏ½πŸ’‰ Dependency Injection Manages object dependencies and lifecycle through inversion of control patterns β€’ Service registration and resolution
β€’ Lifetime management patterns
β€’ Constructor injection
β€’ Interface-based abstractions
β€’ Service container configuration
β€’ Lifetime scope patterns
β€’ Testing with mock dependencies
β€’ Clean dependency management
PizzeriaService dependencies managed through DI container Complex dependency graphs, testability
πŸ“‘ CQRS & Mediation Separates read/write operations with mediator pattern for decoupled request handling β€’ Command/Query separation
β€’ Mediator request routing
β€’ Pipeline behaviors
β€’ Handler-based processing
β€’ Command and query handler implementation
β€’ Mediation pattern usage
β€’ Cross-cutting concerns via behaviors
β€’ Event integration with CQRS
PlaceOrderCommand vs GetOrderQuery with mediator routing Complex business logic, high-scale systems
πŸ”„ Event-Driven Architecture Implements reactive systems using domain events and event handlers β€’ Domain event patterns
β€’ Event handlers and workflows
β€’ Asynchronous processing
β€’ System decoupling
β€’ Domain event design and publishing
β€’ Event handler implementation
β€’ Kitchen workflow automation
β€’ CloudEvents integration
OrderPlaced β†’ Kitchen processing β†’ OrderReady β†’ Customer notification Loose coupling, reactive workflows
🎯 Event Sourcing Stores state changes as immutable events for complete audit trails and temporal queries β€’ Event-based persistence
β€’ Aggregate state reconstruction
β€’ Temporal queries
β€’ Event replay capabilities
β€’ Event-sourced aggregate design
β€’ Event store integration
β€’ Read model projections
β€’ Business intelligence from events
Order lifecycle tracked through immutable events with full history Audit requirements, temporal analysis
🌊 Reactive Programming Enables asynchronous event-driven architectures using Observable streams β€’ Observable stream patterns
β€’ Asynchronous event processing
β€’ Stream transformations
β€’ Background service integration
β€’ RxPY integration patterns
β€’ Stream processing and subscription
β€’ Real-time data flows
β€’ Background service implementation
Real-time order tracking and kitchen capacity monitoring Real-time systems, high-throughput events
πŸ’Ύ Repository Pattern Abstracts data access logic with multiple storage implementations β€’ Data access abstraction
β€’ Storage implementation flexibility
β€’ Consistent query interfaces
β€’ Testing with mock repositories
β€’ Repository interface design
β€’ Multiple storage backend implementation
β€’ Async data access patterns
β€’ Repository testing strategies
OrderRepository with File, MongoDB, and InMemory implementations Data persistence, testability
🌐 Resource-Oriented Architecture Resource-oriented design principles for building RESTful APIs and resource-centric applications β€’ Resource identification and modeling
β€’ RESTful API design principles
β€’ HTTP verb mapping and semantics
β€’ Resource lifecycle management
β€’ Resource-oriented design principles
β€’ RESTful API architecture patterns
β€’ HTTP protocol integration
β€’ Resource state management
Orders, Menu, Kitchen as REST resources with full CRUD operations RESTful APIs, microservices
πŸ‘€ Watcher & Reconciliation Patterns Kubernetes-inspired patterns for watching resource changes and implementing reconciliation loops β€’ Resource state observation
β€’ Reconciliation loop patterns
β€’ Event-driven state management
β€’ Declarative resource management
β€’ Resource watching implementation
β€’ Reconciliation loop design
β€’ Event-driven update patterns
β€’ State synchronization strategies
Kitchen capacity monitoring and order queue reconciliation Reactive systems, state synchronization
⚑ Watcher & Reconciliation Execution Execution engine for watcher and reconciliation patterns with error handling and monitoring β€’ Execution orchestration
β€’ Error handling and recovery
β€’ Performance monitoring
β€’ Reliable state persistence
β€’ Execution pipeline design
β€’ Error handling strategies
β€’ Monitoring and observability
β€’ Performance optimization
Automated kitchen workflow execution with retry logic and monitoring Production systems, reliability requirements

πŸ• Mario's Pizzeria: Unified ExampleΒΆ

All patterns use Mario's Pizzeria as a consistent domain example, showing how patterns work together in a real-world system:

graph TB
    subgraph "πŸ—οΈ Clean Architecture Layers"
        API[🌐 API Layer<br/>Controllers & DTOs]
        APP[πŸ’Ό Application Layer<br/>Commands & Queries]
        DOM[πŸ›οΈ Domain Layer<br/>Entities & Events]
        INT[πŸ”Œ Integration Layer<br/>Repositories & Services]
    end

    subgraph "πŸ“‘ CQRS Implementation"
        CMD[Commands<br/>PlaceOrder, StartCooking]
        QRY[Queries<br/>GetOrder, GetMenu]
    end

    subgraph "πŸ”„ Event-Driven Flow"
        EVT[Domain Events<br/>OrderPlaced, OrderReady]
        HDL[Event Handlers<br/>Kitchen, Notifications]
    end

    subgraph "πŸ’Ύ Data Access"
        REPO[Repositories<br/>Order, Menu, Customer]
        STOR[Storage<br/>File, MongoDB, Memory]
    end

    API --> APP
    APP --> DOM
    APP --> INT

    APP --> CMD
    APP --> QRY

    DOM --> EVT
    EVT --> HDL

    INT --> REPO
    REPO --> STOR

    style API fill:#e3f2fd
    style APP fill:#f3e5f5
    style DOM fill:#e8f5e8
    style INT fill:#fff3e0

πŸš€ Pattern IntegrationΒΆ

How Patterns Work TogetherΒΆ

Order Pattern Role in System Dependencies Integration Points
1 Clean Architecture Structural foundation None Provides layer structure for all other patterns
2 Dependency Injection Service management foundation Clean Architecture Manages service lifetimes across all layers
3 CQRS & Mediation Application layer organization Clean Architecture, DI Commands/Queries with mediator routing
4 Event-Driven Reactive domain workflows Clean Architecture, CQRS, DI Domain events published by command handlers
5 Event Sourcing Event-based persistence Event-Driven, Repository, DI Events as source of truth with aggregate patterns
6 Reactive Programming Asynchronous stream processing Event-Driven, DI Observable streams for real-time event processing
7 Repository Infrastructure abstraction Clean Architecture, DI Implements Integration layer data access
8 Resource-Oriented API contract definition Clean Architecture, CQRS, DI REST endpoints expose commands/queries
9 Watcher & Reconciliation Reactive resource management Event-Driven, Repository, DI Observes events, updates via repositories

Implementation OrderΒΆ

flowchart LR
    A[1. Clean Architecture<br/>πŸ—οΈ Layer Structure] --> B[2. Dependency Injection<br/>πŸ’‰ Service Management]
    B --> C[3. CQRS & Mediation<br/>πŸ“‘ Commands & Queries]
    C --> D[4. Event-Driven<br/>πŸ”„ Domain Events]
    D --> E[5. Event Sourcing<br/>🎯 Event Persistence]
    E --> F[6. Reactive Programming<br/>🌊 Stream Processing]
    F --> G[7. Repository Pattern<br/>πŸ’Ύ Data Access]
    G --> H[8. Resource-Oriented<br/>🌐 API Design]
    H --> I[9. Watcher Patterns<br/>πŸ‘€ Reactive Management]

    style A fill:#e8f5e8
    style B fill:#f8bbd9
    style C fill:#e3f2fd
    style D fill:#fff3e0
    style E fill:#ffecb5
    style F fill:#b3e5fc
    style G fill:#f3e5f5
    style H fill:#e1f5fe
    style I fill:#fce4ec

🎯 Business Domain Examples¢

Domain Area Pattern Application Implementation Details Benefits Demonstrated
πŸ• Order Processing Clean Architecture + CQRS + Event Sourcing + DI Complete workflow from placement to delivery with event history Layer separation, mediation routing, audit trails, service management
πŸ“‹ Menu Management Repository + Resource-Oriented + DI Product catalog with pricing and availability via REST API Data abstraction, RESTful design, dependency management
πŸ‘¨β€πŸ³ Kitchen Operations Event-Driven + Reactive Programming + Watcher Patterns Real-time queue management with stream processing Reactive processing, observable streams, state synchronization
πŸ“± Customer Communications Event-Driven + Reactive Programming Real-time notifications through reactive event streams Stream processing, asynchronous messaging, real-time updates
πŸ’³ Payment Processing Clean Architecture + Repository + DI External service integration with proper abstraction Infrastructure abstraction, testability, service integration
πŸ“Š Analytics & Reporting Event Sourcing + Reactive Programming Business intelligence from event streams with real-time views Temporal queries, stream aggregation, historical analysis

πŸ§ͺ Testing StrategiesΒΆ

Testing Type Scope Pattern Focus Tools & Techniques Example Scenarios
πŸ”¬ Unit Testing Individual components All patterns with isolated mocks pytest, Mock objects, dependency injection Test OrderEntity business logic, Command handlers
πŸ”— Integration Testing Cross-layer interactions Clean Architecture layer communication TestClient, database containers Test API β†’ Application β†’ Domain flow
🌐 End-to-End Testing Complete workflows Full pattern integration Automated scenarios, real dependencies Complete pizza order workflow validation
⚑ Performance Testing Scalability validation CQRS read optimization, Event throughput Load testing, metrics collection Query performance, event processing rates

πŸ“š Pattern Learning PathsΒΆ

Level Focus Area Recommended Patterns Learning Objectives Practical Outcomes
🌱 Beginner Foundation & Structure 1. Clean Architecture
2. Domain Driven Design
3. Dependency Injection
4. Repository Pattern
β€’ Layer separation principles
β€’ Rich domain model design
β€’ Service lifetime management
β€’ Data access abstraction
Pizza ordering system with rich domain models and proper DI
πŸš€ Intermediate Separation & Optimization 1. CQRS & Mediation
2. Event-Driven Architecture
3. Resource-Oriented Architecture
β€’ Read/write operation separation
β€’ Mediator pattern usage
β€’ Event-driven workflows
β€’ RESTful API design
Scalable pizza API with command/query separation and events
⚑ Advanced Reactive & Distributed 1. Event Sourcing
2. Reactive Programming
3. Watcher & Reconciliation
β€’ Event-based persistence
β€’ Stream processing patterns
β€’ Reactive system design
β€’ State reconciliation strategies
Complete event-sourced pizzeria with real-time capabilities

These patterns form the architectural foundation for building maintainable, testable, and scalable applications. Each pattern page includes detailed code examples, Mermaid diagrams, and practical implementation guidance using the Mario's Pizzeria domain.