Skip to main content

Business Rules

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendix

Introduction

This document focuses on the modeling and implementation of "business rules", targeting business analysts and developers, systematically explaining how to define, encapsulate, and execute complex business rules in domain models, covering topics such as task state transitions, session lifecycle, aggregate consistency, and event sourcing. The document also provides practical suggestions on rule validation timing, error handling strategies, rule chain design, boundary cases, and evolution management, and helps readers quickly grasp key processes through diagrammatic representations.

Project Structure

This project adopts a clean architecture layering, with business rules primarily concentrated in the "entity layer" and "use case layer", and exposed externally through the interface adapter layer. Key modules directly related to business rules are as follows:

  • Entity layer: tasks, sessions, transactions, aggregate root base classes, domain event interfaces
  • Use case layer: session services, Saga transaction services
  • Error layer: unified error type definitions
  • Documentation and routing: aggregate root template usage instructions, HTTP route registration
  • Task Entity: Defines task status enumerations and state transition methods, with built-in retry, expiration, execution duration, and other rules.
  • Session Entity: Defines session lifecycle rules (expiration, renewal, data reading/writing).
  • Aggregate Root Interface and Base Class: Provides event sourcing, version control, uncommitted event management, and consistency guarantees.
  • Domain Event Interface: Unifies event metadata to support event sourcing and projection.
  • Saga Transaction Entity and Service: Defines transaction steps and compensation mechanisms to achieve eventual consistency across boundaries.
  • Use Case Services: Encapsulate the execution timing and error handling of business rules, coordinating entities and repositories.
  • Error Types: Unify error semantics to facilitate diagnosis and recovery when rules fail.

The distribution and interaction of business rules in clean architecture are as follows:

  • The entity layer carries core business rules and invariants.
  • The use case layer orchestrates rule execution, handling errors and boundary conditions.
  • The interface adapter layer receives external requests and calls the use case layer.
  • The error layer provides unified error semantics for upper-level processing.

Task State Transition Rules

The task entity defines clear status enumerations and transition methods to ensure state transitions meet business constraints:

  • Initial state: Pending
  • Reachable states: Running, Completed, Failed, Cancelled
  • Key rules:
    • Retry can be performed after failure according to the maximum retry count
    • Expiration rule: Created time exceeding 24 hours is considered expired
    • Execution duration: Calculated only when both start and end times exist

The session entity and session service jointly define the session lifecycle rules:

  • Creation: Specify ID and TTL, initialize data container and expiration time
  • Access: When getting a session, if it has expired, delete it and return not found
  • Update: Automatically renew when saving the session
  • Data: Provide key-value access and deletion
  • Batch cleanup: Traverse and delete expired sessions

The aggregate root interface and base class provide event sourcing, version control, and consistency guarantees:

  • Version control: Optimistic locking to prevent concurrent overwrites
  • Event management: Uncommitted event list, cleared after commit
  • Event validation: Legality check of event ID/type/aggregate ID to avoid duplicate event IDs
  • Business validation: Reserved Validate interface, can extend complex rules in aggregate roots

The transaction entity and service define cross-boundary transaction execution and compensation mechanisms:

  • Transaction states: Pending, In Progress, Completed, Failed, Compensated
  • Execution process: Execute steps in order, compensate in reverse when failed
  • Compensation strategy: Execute compensation handlers one by one from the failed step forward
  • Validation Timing

    • Entity cohesion: Immediate validation within entity methods (e.g., task state transitions, session expiration checks)
    • Use case orchestration: Cross-entity business rule validation in use case services (e.g., expiration checks before session access)
    • Event sourcing: Ensure state consistency after event application in aggregate root ApplyEvent
  • Encapsulation Strategy

    • Encapsulate rules as entity methods (e.g., entity's IsExpired, CanRetry)
    • Encapsulate cross-entity rules as use case service methods (e.g., session service's GetSession)
    • Split complex rules into independent validators or strategy objects (recommended to implement in the use case layer)
  • Rule Chains

    • Session access chain: Find -> Expiration check -> Delete expired -> Return result
    • Task execution chain: Start -> Execute business logic -> Complete/Fail -> Possible retry
    • Saga chain: Execute steps sequentially -> Compensate on failure (reverse order)
  • Conditional Judgments

    • Time comparisons: Session expiration, task expiration
    • Count comparisons: Retry count vs. maximum retry
    • State machine: Valid paths for task state transitions
  • Session

    • Not found: Return not found error after expired session deletion
    • Invalid session: Return invalid session error when saving empty session
  • Repository

    • Not found entity, illegal entity, operation failure, etc. are uniformly wrapped as repository errors
  • Event Store

    • Concurrency conflicts, aggregate not found, custom error types
  • Snapshot

    • Not found snapshot error
  • Testing Methods

    • Unit tests: Target entity methods (e.g., IsExpired, CanRetry) and use case service methods (e.g., GetSession, ExecuteTransaction)
    • Integration tests: End-to-end verification of business rules through HTTP routes and handlers
    • Concurrency tests: Verify event store's optimistic locking and version control
  • Rule Evolution

    • Extend complex business validation through the aggregate root's Validate interface
    • Implement state replay after rule changes through event sourcing's LoadFromEvents and ApplyEvent
    • Optimize replay performance for large-scale historical events through snapshots
  • Entities depend on base entities to obtain standard fields and timestamps

  • Aggregate root interfaces and base classes provide event sourcing and version control capabilities

  • Use case services depend on entities and repositories, exposing business rules outward

  • Error types provide consistent error semantics for each layer

  • Event Sourcing and Snapshots: For aggregates with excessive historical events, it is recommended to generate snapshots periodically to reduce replay costs
  • Concurrency Control: Implement optimistic locking through aggregate root version numbers to avoid retry storms caused by write conflicts
  • Session Renewal: Automatically renew when saving sessions to reduce the risk of expiration due to frequent access
  • Saga Execution: The failure compensation of sequential steps should be as idempotent as possible to reduce additional overhead caused by compensation failures

Troubleshooting Guide

  • Session Related
    • 404 Not Found: Confirm if the session has expired and been cleaned up; check if the ID is correct
    • Invalid Session: Check if the incoming parameters are empty
  • Event Store
    • Concurrency Conflict: Check the expected version and current version, retry or rollback if necessary
    • Aggregate Not Found: Confirm if the aggregate ID exists
  • Repository
    • Entity Not Found: Confirm query conditions and indexes
    • Operation Failure: Check underlying storage exceptions
  • Snapshot
    • Snapshot Not Found: Confirm if the snapshot has been generated or cleaned up

This project, through clear layering and strongly constrained entity/aggregate root design, cohesively integrates complex business rules into the domain model, and orchestrates and governs errors through the use case layer. Rules such as task state transitions, session lifecycles, and Saga transaction compensation all have clear implementation and verification paths. It is recommended in actual implementation:

  • Encapsulate rules as entity methods and use case service methods to maintain high cohesion and low coupling
  • Ensure rule evolution and state consistency through event sourcing and snapshots
  • Establish a comprehensive testing system covering normal processes, boundaries, and exception scenarios

Appendix

  • Aggregate Root Template Usage Guide: Contains verification rules, event usage, and snapshot usage examples, facilitating the extension of complex business rules and state management