{
    "slug": "ddd_aggregates",
    "term": "DDD Aggregates & Aggregate Roots",
    "category": "architecture",
    "difficulty": "advanced",
    "short": "A cluster of domain objects treated as a single unit with one root entity controlling access and enforcing invariants across the cluster.",
    "long": "An Aggregate is a cluster of related domain objects (entities and value objects) with a single Aggregate Root — the only entity that external objects can hold a reference to. The root ensures all invariants are maintained: an Order (root) controls its OrderItems — you can't add an OrderItem without going through Order::addItem(), which validates business rules like maximum quantity. Aggregates define transactional boundaries: you load and save an aggregate atomically; two aggregates in the same transaction is a design smell. Keep aggregates small — an Order with thousands of items should be reconsidered. Reference other aggregates by ID (not direct object reference) to enforce boundaries. Events crossing aggregate boundaries use domain events.",
    "aliases": [
        "DDD aggregate",
        "aggregate root",
        "domain aggregate"
    ],
    "tags": [
        "architecture",
        "ddd",
        "oop",
        "design-pattern"
    ],
    "misconception": "Aggregates should be as large as possible to keep related data together. Large aggregates cause contention — every operation locks the whole aggregate. Aggregates should be as small as possible while still enforcing their invariants consistently.",
    "why_it_matters": "Aggregates define consistency boundaries — all changes within an aggregate are atomic, and external objects can only reference aggregates by ID, enforcing invariants and preventing inconsistent state.",
    "common_mistakes": [
        "Aggregates that are too large — every entity in a domain is not part of one aggregate; keep them small.",
        "Referencing aggregate internals from outside the aggregate root — go through the root always.",
        "Saving multiple aggregates in a single transaction — use eventual consistency via domain events instead.",
        "Exposing internal collection references from the aggregate root — callers can modify state without invariant checks."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "ddd_value_objects",
        "ddd_repositories",
        "event_sourcing",
        "bounded_context"
    ],
    "prerequisites": [
        "domain_driven_design",
        "aggregate_design",
        "bounded_context"
    ],
    "refs": [
        "https://martinfowler.com/bliki/DDD_Aggregate.html"
    ],
    "bad_code": "// Modifying aggregate internals directly — bypasses invariants:\n$order->items[] = new OrderItem($product, $qty); // Direct collection mutation\n// Should be: $order->addItem($product, $qty) — root enforces invariants",
    "good_code": "// Aggregate — cluster of domain objects treated as a single unit\n// All changes go through the Aggregate Root\n\nclass Order { // Aggregate Root\n    private array \\$items = [];\n    private OrderStatus \\$status;\n\n    // Only Order can add items — enforces invariants\n    public function addItem(Product \\$product, int \\$qty): void {\n        if (\\$this->status !== OrderStatus::Draft) throw new OrderNotEditableException();\n        if (\\$qty < 1) throw new InvalidQuantityException();\n        \\$this->items[] = new OrderItem(\\$product, \\$qty);\n    }\n\n    public function getTotal(): Money {\n        return array_reduce(\\$this->items, fn(\\$sum, \\$i) => \\$sum->add(\\$i->getTotal()), Money::zero());\n    }\n}\n\n// Never manipulate OrderItem directly from outside — always go through Order\n// Repository saves/loads the entire aggregate atomically",
    "quick_fix": "Design small aggregates — each should fit in a single DB transaction; if two aggregates always change together, they may be one; if one aggregate needs another to validate, consider domain events instead",
    "severity": "medium",
    "effort": "high",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/ddd_aggregates",
        "html_url": "https://codeclaritylab.com/glossary/ddd_aggregates",
        "json_url": "https://codeclaritylab.com/glossary/ddd_aggregates.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[DDD Aggregates & Aggregate Roots](https://codeclaritylab.com/glossary/ddd_aggregates) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/ddd_aggregates"
            }
        }
    }
}