Domain-Driven Design Aggregate Portfolio Architect

    1

    Architects DDD aggregate portfolios: consistency boundaries, transactional invariants, event choreography, and persistence.

    $9

    Secure checkout via Stripe

    30-day refund guarantee

    Converts to your local currency at checkout

    Security scanned

    Works with the AI tools you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIMuseMuseOpenClawOpenClaw+21 more

    Domain-Driven Design Aggregate Portfolio Architect

    Example session with this skill installed

    Architect Domain-Driven Design (DDD) aggregate portfolio and consistency boundaries for our Wealth Trading Platform.

    • Subject: wealth-trading-portfolio v3.0 (run-id: wealth-agg-arch-001) managing investments across 120,000 client accounts and $45B AUM.
    • Deciders: Chief Enterprise Architect (David O'Reilly) and Head of Wealth Engineering (Elena Rostova).
    • Scope & Scale: Decomposing 4 core domain entities (ClientPortfolio, TradeExecutionOrder, AssetAllocationPlan, CashSettlementAccount) sustaining 14,000 events/sec.
    • Tension: Squads proposed bundling rebalancing, order routing, and cash settlement into a single ACID transaction; David O'Reilly and Elena Rostova strictly reject multi-aggregate ACID transactions, citing incident DB-4921 where lock contention froze queries for 38 minutes and dropped $4.2M in trades. They mandate: 4 discrete aggregate boundaries, single-aggregate consistency, asynchronous Kafka event choreography, optimistic locking, and sub-200ms reconciliation.

    Write the aggregate portfolio architecture overview under docs/.

    • Read your context and instructions
    • Compiled the domain-driven design aggregate

    Wrote docs/architecture/aggregate-architect/00-overview/aggregate-architect-overview.md. Complete DDD aggregate portfolio architecture specification establishing consistency boundaries across 4 aggregates, asynchronous event choreography, and optimistic concurrency.


    skill: aggregate-architect

    Aggregate Portfolio Architecture: Global Wealth Platform [AGGPORT-WEALTH-001]

    Summary

    This specification establishes the enterprise Domain-Driven Design (DDD) aggregate portfolio architecture, transactional consistency boundaries, and inter-aggregate event choreography for the Global Wealth Portfolio & Trading Platform under run ID wealth-agg-arch-001. It governs 120,000 high-net-worth client accounts managing $45B in assets under management (AUM) across 14,000 transaction events/second. It decisively eliminates the database lock contention and cascading freezes demonstrated in incident DB-4921 (where multi-aggregate ACID database transactions on shared client records froze portfolio queries for 38 minutes during a market selloff, dropping $4.2M in trades). The architecture decomposes the domain into

    four discrete aggregate roots (ClientPortfolio, TradeExecutionOrder, AssetAllocationPlan, CashSettlementAccount), enforces single-aggregate transactional consistency, connects aggregates via asynchronous Apache Kafka domain events, mandates optimistic concurrency versioning, and bounds cross-aggregate eventual consistency reconciliation to

    <= 200 milliseconds.

    Detailed Description

    In complex financial domains, attempting to maintain immediate ACID consistency across multiple related domain entities results in massive database table locks and distributed deadlocks. When order placement, cash balance verification, and asset allocation recalculation are chained into a single synchronous transaction, a lock on a single cash balance record blocks portfolio rebalancing and trade execution across the entire account. An authoritative aggregate portfolio establishes isolated consistency islands, enforces strict reference-by-identity across roots, and coordinates state transitions through an asynchronous transactional outbox event mesh.

    Client Rebalance Request (14,000 events/sec)
                             │
                             ▼
    [ Aggregate 1: ClientPortfolio Root ] ── (ACID Commit in < 8 ms)
      ├── Enforces: Max Target Asset Class Weights (100% Total)
      └── Emits Domain Event: `RebalancePlanApproved` via Outbox
                             │
                             ▼ (Apache Kafka: Keyed by `portfolio_id`)
    [ Aggregate 2: TradeExecutionOrder Root ] ── (ACID Commit in < 12 ms)
      ├── 1. Consumes `RebalancePlanApproved`
      ├── 2. Generates Sub-Orders (Market Equities, Fixed Income)
      └── 3. Emits Domain Event: `OrderSubmitted`
                             │
            ┌────────────────┴────────────────┐
            ▼ (Asynchronous Kafka Stream)     ▼ (Latency <= 200 ms)
    [ Aggregate 3: CashSettlementAccount ]   [ Aggregate 4: AssetAllocationPlan ]
      ├── Reserves Available Cash Margin       ├── Rebalances Model Asset Drift
      └── Emits `FundsReservedEvent`           └── Emits `AllocationUpdatedEvent`
    

    Criteria and weights

    CriterionWhy it matters hereWeightSource of the weight
    Elimination of Multi-Aggregate Lock ContentionConcurrent trade execution must never block client portfolio viewing or balance queries (DB-4921).0.40David O'Reilly (Chief Architect)
    Transactional Invariant StrictnessAggregate roots must guarantee immediate consistency for internal entities (e.g. cash balance floor).0.30Elena Rostova (Head of Wealth Eng)
    Eventual Consistency Reconciliation SLA (< 200ms)Financial position updates across aggregates must converge rapidly to satisfy real-time client dashboards.0.15Wealth Management Business SLA
    Optimistic Concurrency ScalabilityHigh-frequency trading rebalances must not serialize threads behind database pessimistic locks.0.15Enterprise Architecture Standard

    Comparison

    Architecture Strategy CandidateConsistency BoundaryInter-Aggregate CommunicationConcurrency ControlEvaluation
    Option A: Monolithic Multi-Aggregate ACIDSingle DB transaction (4 entities)In-memory synchronous method callsPessimistic row locks (FOR UPDATE)Rejected: Caused DB-4921 38-minute freeze; does not scale past 2,500 TPS.
    Option B: Two-Phase Commit Distributed XADistributed 2PCSynchronous gRPC / XA CoordinatorDistributed locksRejected: High latency overhead (> 150 ms); prone to heuristic hazard states.
    Option C: Bounded Aggregates + Event Mesh (Chosen)1 Aggregate per TransactionAsynchronous Kafka domain eventsOptimistic versioning (@Version)Selected: Zero deadlocks, sub-200ms convergence, 14,000 TPS scale.

    Result

    Option C is selected. Four isolated aggregates eliminate lock contention; transactional outbox publishing ensures reliable eventual consistency; optimistic locking guarantees race-free commits.


    Required Mechanisms

    1. Aggregate Portfolio Decomposition & Root Boundaries [MC-AP-01]
    1. ClientPortfolio (Aggregate Root)
    • Invariants: Total asset allocation target percentages must equal exactly

    100.00%; portfolio risk tier must match KYC suitability score.

    • Encapsulated Entities: PortfolioHolding (Instrument ID, Units Held, Cost Basis).
    2. TradeExecutionOrder (Aggregate Root)
    • Invariants: Order quantity must be $> 0$; limit price must be positive; order cannot be modified once state transitions to FILLED or ROUTED.
    • Encapsulated Entities: OrderExecutionFill (Fill ID, Fill Price, Executed Units, Exchange Timestamp).
    3. CashSettlementAccount (Aggregate Root)
    • Invariants: Total settled cash minus reserved funds must be >=

    0.00 (strict zero overdraft invariant for margin accounts).

    • Encapsulated Entities: CashHoldReservation (Hold ID, Expire Epoch, Amount).
    4. AssetAllocationPlan (Aggregate Root)
    • Invariants: Rebalancing drift threshold must be between $1.00%$ and $15.00%$; rebalance frequency cannot exceed once per trading day.
    2. Inter-Aggregate Event Choreography & Sagas [MC-EC-01]
    • Choreography Pattern:
      1. ClientPortfolio commits target rebalance and publishes PortfolioRebalanceRequested.
      2. Order Saga Consumer intercepts event, commands CashSettlementAccount to reserve cash (ReserveFundsCommand).
      3. CashSettlementAccount commits local reservation and emits FundsReservedEvent.
      4. Order Saga initializes TradeExecutionOrder aggregate and routes orders to exchanges.
    • Eventual Consistency SLA: End-to-end event choreography completes within <= 200 milliseconds at p99.
    3. Reference-by-Identity Protocol [MC-RI-01]
    • Direct object reference pointers between aggregates are strictly prohibited.
    • Aggregates reference peer roots exclusively via immutable typed identity keys:
      • ClientPortfolio holds CashSettlementAccountId and AllocationPlanId.
      • TradeExecutionOrder holds ClientPortfolioId and CashHoldId.
    4. Optimistic Concurrency Control [MC-OC-01]
    • Every aggregate root table maintains an integer version column.
    • Concurrent updates check: UPDATE ... WHERE id = :id AND version = :expected_version.
    • If another thread mutated the aggregate concurrently, the transaction throws OptimisticLockingFailureException and triggers an automated exponential backoff retry (up to 3 attempts in < 50 ms).

    Invariants and Contracts

    Single-Aggregate Transaction Limit [INV-AGGPORT-01]
      A single database transaction must never mutate more than one aggregate root instance.
      Chaining multiple aggregate modifications into a shared ACID commit is prohibited.
    
    Reference-by-Identity Mandate [INV-AGGPORT-02]
      Aggregates must reference external aggregate roots exclusively by immutable identity keys.
      In-memory entity graph traversals crossing aggregate root boundaries are strictly barred.
    
    Sub-Two-Hundred-Millisecond Convergence [INV-AGGPORT-03]
      Cross-aggregate state choreography orchestrated via domain events must achieve eventual consistency
      within 200 milliseconds under 14,000 events/second peak load.
    

    Explicit Unknowns

    • Kafka partition lag behavior when 12,000 portfolios rebalance simultaneously following an unscheduled Federal Reserve interest rate announcement (G-1).
    • Outbox table CDC polling latency during sudden 50,000 record batch order execution bursts (G-2).

    Traceability

    ClaimClassificationSourceFreshness
    120,000 client accounts and $45B AUMprovidedPortfolio sizing intakeCurrent
    Peak 14,000 transaction events/secprovidedVolumetric traffic profileCurrent
    Incident DB-4921 38-minute database freezeprovidedHistorical post-mortemHistorical
    Four discrete aggregate rootsdecidedDavid O'Reilly & Elena Rostova2026-09-15
    Single-aggregate transaction limitdecidedArchitectural invariant INV-AGGPORT-012026-09-15
    Sub-200ms eventual consistency SLAdecidedWealth Management Business SLA2026-09-15

    Verification

    No validator was supplied, so no command was run.

    Reviewer self-check against aggregate portfolio architecture standards:

    • Boundary Cleanliness: PASS. Four discrete roots with zero shared tables or multi-root ACID commits.
    • Identity Discipline: PASS. Aggregates reference peer entities exclusively by immutable ID strings.
    • Event Choreography: PASS. Asynchronous Kafka event choreography replaces synchronous distributed 2PC.
    • Markdown Hygiene: PASS. Native Markdown syntax strictly adheres to rule_markdown.md.

    Open Decisions

    • DEC-AGGPORT-01: Elena Rostova to determine whether Event Sourcing (EventStoreDB / ScyllaDB) should replace Aurora PostgreSQL for TradeExecutionOrder in Q1 (Owner: Elena Rostova).

    Next steps

    1. Marcus Vance provisions high-throughput Kafka topics partitioned by portfolio_id.
    2. Engineering teams implement the four aggregate roots and transactional outbox tables in Java 21.
    3. Conduct staging concurrency drill simulating 10,000 concurrent trade orders to verify race-free optimistic locking and sub-200ms reconciliation.

    Connects securely to your tools. The creator never sees your data.

    What you get

    - Define transactional boundaries for complex domain logic- Resolve anemic models by encapsulating business invariants- Design aggregate roots and command-driven state transitions- Establish concurrency, idempotency, and versioning rules

    About this skill

    What it does

    This skill defines the smallest domain consistency boundaries needed to protect accepted business invariants inside one bounded context. It identifies aggregate roots, internal entities and value objects, command/state-transition contracts, cross-aggregate references, concurrency semantics, emitted domain facts, repository expectations, and verification scenarios.

    Use it when

    • Determine which business rules are true invariants and what state must be atomically evaluated to protect them
    • Split a god aggregate or repair an anemic model whose rules are scattered across services
    • Choose an aggregate root and define its public domain behaviors
    • Decide whether an entity/value object belongs inside an aggregate or is independently referenced
    • Model lifecycle states, legal/illegal transitions, creation, reconstitution, archival, and deletion semantics
    • Define command deduplication, optimistic/pessimistic conflict behavior, retry safety, or version checks at the aggregate boundary

    For example: “Our billing service allows customer support to update subscription plans while an invoice charge is processing, resulting in double-billing and corrupting the subscription balance.”

    What you get

    • architecture/aggregate-architect/README.md
    • architecture/aggregate-architect/00-overview/aggregate-architect-overview.md
    • architecture/aggregate-architect/verification/fitness-self-check.md

    Plus one page per business module, only where your evidence calls for it: {module}/aggregates.md, {module}/domain-events.md, {module}/invariants.md, {module}/policies.md.

    All paths are relative to the output folder you choose.

    What it will not do

    Do not use for broad DDD strategy, bounded-context discovery, database schema design, CRUD scaffolding, event sourcing by default, or transaction annotation advice alone.

    How it works

    1. Check bounded context boundary.
    2. Identify true transactional invariants.
    3. Select the aggregate root.
    4. Define command transitions.
    5. Establish concurrency and idempotency.
    6. Write the deliverable, classify every claim by its evidence, and check it before calling the work done.

    What's in the package

    Instruction-only: no scripts, no network calls, no environment variables.

    • LICENSE.txt
    • SKILL.md
    • agents/openai.yaml
    • assets/output-template-artifact.md
    • assets/output-template-contract.md
    • assets/output-template-decision.md
    • assets/output-template-domain.md
    • assets/output-template-fitness.md
    • assets/output-template-mechanism.md
    • references/domain-rules.md
    • references/operating-rules.md
    • references/output-contract.md

    How to install

    Works the same in every agent - Claude, Cursor, Codex, Copilot and 20+ more.

    ~30 seconds
    1. 1

      Download the ZIP

      Free skills download straight away. Paid skills unlock right after purchase.

    2. 2

      Unzip into your skills folder

      Every agent reads skills from one folder on your machine. Drop the unzipped folder in there.

    3. 3

      Ask your agent to use it

      Restart the agent if it was already running. It picks the skill up automatically - no config needed.

    Skills folder by agent

    Click the path to copy it. Create the folder if it does not exist yet.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill passes our trust checks below.

    Security scanned

    Passed our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    30-day refund

    Not a fit? Get your money back

    Trust & safety

    Security scanned

    Verified clean 12 days ago

    • Passed all security checks, Safe to install

    Listed12 days ago

    What's inside

    Frequently Asked Questions