Skip to main content

Aggregate design canvas

One ddd-crew Aggregate Design Canvas (v1.1) per aggregate root in internal/domain. There are two aggregate roots — WorkPool and WorkUnit — plus one domain service (ReleasePolicy) and five shared value objects. Every invariant below is enforced inside the domain layer and has a failing-path unit test next to it (*_test.go in the same package).

The former ChargeForecast and ShiftPlan/PathPlan aggregates moved to warehouse-planning (ADR-0049): its workload forecast (PUT /workload-forecasts/{site_id}/{path_id}) and its LabourPlan (PUT /labour-plans/{site_id}/{shift_id}/{path_id}), which keeps the plannedHeads ≤ installedStations invariant.

Read models are not aggregates and are listed separately at the end of this page.

Shared value objects (internal/domain/shared)​

Value objectConstraintError on violation
CPTwraps a time.Time; ordering is the domain operation (Before, Equals)— (always valid)
PathIdmust be non-emptyErrInvalidPathId
Quantitymust be non-negativeErrInvalidQuantity

These exist so an illegal value cannot be constructed at all: a negative quantity never becomes a Quantity. (Rate and StationCount, the shift plan's value objects, left with it: ADR-0049.)

Every aggregate is one row (plus child rows) per process path or per work unit, and every aggregate-changing use case saves the aggregate and inserts its events into the transactional outbox in one Postgres transaction (UnitOfWork, ADR-0014).


WorkPool​

1. Name​

WorkPool — internal/domain/release/work_pool.go. Identity: PathId (exactly one pool per path; work_pools.path_id, with child rows in work_pool_entries). Carries an optimistic-concurrency version (ADR-0029).

2. Description​

The queue for one process path: entries keyed by work unit id, each with a CPT and an entry state, plus the feed mode (ReleaseFed or FlowFed), the WIP limit and the alarm threshold. Backlog depth, WIP and remaining capacity are computed from the entries on demand, never stored.

3. State transitions​

The pool itself has no status; its entries do (entryState: pending, released, completed).

Source: internal/domain/release/work_pool.go, internal/domain/release/errors.go. Omits: RestoreEntry, which only rehydrates stored rows in the repository adapter, the pool-level ErrEmptyPool / ErrUnknownEntry failures, and Configure (ADR-0034), which sets the pool's mode and WIP limit and never changes any entry's state, so it adds no transition: lowering the limit below the current WIP only makes the ErrWIPLimitReached self-loop above apply until completions drain WIP.

4. Enforced invariants​

#InvariantEnforced by
W1At-most-once handout of an entryRelease → release.ErrAlreadyReleased; ReleaseNext only considers pending entries
W2WIP limit is a hard invariant on a release-fed poolReleaseNext / Release when WIP() ≥ wipLimit and mode is ReleaseFed → release.ErrWIPLimitReached
W3No duplicate entriesEnqueue / RestoreEntry → release.ErrDuplicateEntry
W4Releasing from an empty pool is an errorReleaseNext → release.ErrEmptyPool
W5Releasing, completing or reconciling an unknown id is an errorRelease / Complete / Reconcile → release.ErrUnknownEntry
W6An entry completes only after it was releasedComplete → release.ErrNotReleased
W7Earliest CPT first — the priority functionnextPendingIndex
W8Concurrent saves never silently overwrite each otherWorkPoolRepo.Save matches version; zero rows → ports.ErrConcurrentModification, retried up to 12 times by retryOnPoolConflict, then HTTP 409 concurrent-modification
W9The WIP limit is a positive integer and the mode a known FeedMode; reconfiguring never evicts workConfigure → release.ErrInvalidWIPLimit / release.ErrUnknownFeedMode (HTTP 400); entries are untouched, so lowering the limit below the current WIP just pauses releases (W2) until WIP < limit (ADR-0034)

W2 is conditional by design: on a flow-fed pool the WIP limit is not enforced and only alarmThreshold applies (IsOverAlarmThreshold). You can only enforce a limit on an input you control (ADR-0003). A pool becomes flow-fed only through ConfigurePool (W9); an unconfigured path keeps the ReleaseFed / 1000 fallback.

5. Corrective policies​

  • Stale-entry healing on release: if ReleasePolicy.Apply picks an entry whose WorkUnit is already Released or Completed, ReleaseNextWork calls Reconcile and picks again, instead of wedging the path.
  • Completion frees the WIP slot: RecordCompletion reconciles the pool entry to completed in the same transaction as the WorkUnit save.
  • Flow balancing (ADR-0003): RebalanceDecision recommends ThrottleUpstream (flow-fed, over alarm threshold) or ReassignLabor (release-fed, at WIP limit with backlog).
  • Optimistic-concurrency retry (W8).

6. Handled commands​

CommandEntry pointsPool method
EnqueueWorkUnitPOST /paths/{pathId}/work-units (Idempotency-Key with Postgres); ApplyOrderAllocated from KafkaEnqueue (creates the pool on first enqueue if none was configured: ReleaseFed, WIP limit and alarm threshold 1000)
ConfigurePoolPUT /paths/{pathId}/pool (REST only, no MCP tool; ADR-0034)Configure (creates the pool if absent; idempotent; raises no event)
ReleaseNextWorkPOST /paths/{pathId}/work-releases; MCP release_next_workReleasePolicy.Apply → ReleaseNext, plus Reconcile
RecordCompletionPOST /work-units/{id}/completions; ApplyTaskCompleted from KafkaReconcile
SampleBacklogGET /paths/{pathId}/telemetry; MCP get_backlog_telemetryread-only: BacklogDepth, WIP, IsOverAlarmThreshold, RemainingCapacity
RebalanceDecisionPOST /paths/{pathId}/rebalance-decisions (keyed); MCP get_rebalance_recommendationcomputes a decision, publishes events (no aggregate write)

7. Created events​

EventFull CloudEvents typeRaised by
BacklogThresholdBreachedcom.warehouse.wes.work-planning.workpool.BacklogThresholdBreachedSampleBacklog, when backlog depth exceeds the alarm threshold
PathCapacityChangedcom.warehouse.wes.work-planning.workpool.PathCapacityChangedSampleBacklog, only when cutoffAt is supplied (ADR-0018)
PathThrottledcom.warehouse.wes.work-planning.workpool.PathThrottledRebalanceDecision
LaborReassignmentFlaggedcom.warehouse.wes.work-planning.workpool.LaborReassignmentFlaggedRebalanceDecision
RateDeviationDetectedcom.warehouse.wes.work-planning.workpool.RateDeviationDetectedreserved — declared for a future detection rule, not emitted (decided 2026-10-06; ADR-0020 defers it)

WorkUnitCreated and WorkReleased are raised in the same use cases that change the pool, but they describe the WorkUnit and are typed under workunit.

8. Throughput (estimate)​

Estimate: the hottest aggregate. Every enqueue, release and completion on a path writes the same pool row, so contention scales with per-path release rate (on the order of one write per unit handled on that path). This is exactly why ADR-0029 added the version guard and bounded retry.

9. Size (estimate)​

Estimate: one entry per work unit ever enqueued on the path — entries are never deleted, and WorkPoolRepo.Save rewrites every entry row. Lifetime: unbounded (the life of the path). Pool growth is a known scaling hotspot; see EventStorming.


WorkUnit​

1. Name​

WorkUnit — internal/domain/workunit/work_unit.go. Identity: the caller-supplied id (or {order_id}-line-{line_no} when created from OrderAllocated).

2. Description​

A releasable unit of work with a deadline: pathId, cpt, reference (the external source, e.g. an order id), optional sku, giftWrap and lineNo (the order line it was made for, 1 to 2147483647, NULL when unknown, carried as line_no on WorkReleased — ADR-0036; it never alters the id; range checked by workunit.ValidateLineNo), and its lifecycle timestamps releasedAt / completedAt. Not the downstream Task of fulfillment-execution.

3. State transitions​

Source: internal/domain/workunit/work_unit.go, internal/domain/workunit/errors.go. Omits: SetSKU / SetGiftWrap / SetLineNo, which set optional characteristics at enqueue time and do not change state.

4. Enforced invariants​

#InvariantEnforced by
U1At most one active assignment — released only from PendingRelease → workunit.ErrAlreadyReleased
U2No double-completeComplete → workunit.ErrAlreadyCompleted
U3Must be released before completingComplete → workunit.ErrNotReleased
U4Id must be non-emptyNewWorkUnit → workunit.ErrEmptyId
U5Reference must be non-emptyNewWorkUnit → workunit.ErrEmptyReference
U6Line number is unknown (0) or 1 to 2147483647 (the 32-bit line_no column)workunit.ValidateLineNo → workunit.ErrInvalidLineNo (REST enqueue 400 invalid-line-no; an inbound OrderAllocated line out of range is stored as unknown, never rejected)

U2 matters beyond tidiness: completion arrives over Kafka as TaskCompleted, which is at-least-once. ApplyTaskCompleted deduplicates on the CloudEvents id atomically with the effect (ADR-0028) and the aggregate rejects a second completion — defence in depth.

5. Corrective policies​

  • An unknown work_unit_id on TaskCompleted (for example a PACK task keyed by order id) is an INFO-logged, processed skip (TaskCompletedUnknownWorkUnit).
  • A TaskCompleted with a new event id for a work unit that is already completed is an INFO-logged, processed skip (TaskCompletedAlreadyCompleted, ADR-0043) — never retried, never dead-lettered.
  • A line of OrderAllocated that is already enqueued (ErrDuplicateEntry) is skipped as a benign no-op (ADR-0031).

6. Handled commands​

CommandEntry points
EnqueueWorkUnitPOST /paths/{pathId}/work-units; ApplyOrderAllocated
ReleaseNextWorkPOST /paths/{pathId}/work-releases; MCP release_next_work
RecordCompletionPOST /work-units/{id}/completions; ApplyTaskCompleted

7. Created events​

EventFull CloudEvents type
WorkUnitCreatedcom.warehouse.wes.work-planning.workunit.WorkUnitCreated
WorkReleasedcom.warehouse.wes.work-planning.workunit.WorkReleased
WorkUnitCompletedcom.warehouse.wes.work-planning.workunit.WorkUnitCompleted

8. Throughput (estimate)​

Estimate: high volume, low contention — one unit per order line, each written about three times in its life by different use cases.

9. Size (estimate)​

Estimate: exactly three events per instance in the happy path (created, released, completed). Lifetime: minutes to hours, bounded by the CPT.


ReleasePolicy — domain service​

type ReleasePolicy struct{}

func (ReleasePolicy) Apply(pool *WorkPool) (string, error) {
return pool.ReleaseNext()
}

Deliberately thin today and deliberately a separate object: release admission is the decision most likely to change (customer tiering, cold chain, aisle batching), and naming it means changing one object rather than the pool aggregate (ADR-0002).

Aggregate boundaries: what is not one aggregate​

  • WorkPool and WorkUnit are separate. The pool holds entry records keyed by work unit id, not WorkUnit objects. They are updated in the same use case and the same transaction, but each has its own invariants.

Not aggregates: read models and views​

These are plain structs with exported fields and no invariants, because the facts belong to someone else or are computed on read. See Read models.

TypePackageKind
LaborPlanObservedinternal/domain/laborviewKafka projection of Workforce's ShiftPlanCommitted, persisted in labor_plan_view; its drift fields are deprecated read-backs (ADR-0049)
UsableInventoryObservedinternal/domain/inventoryviewKafka projection of StockReserved / ReservationRevoked, persisted in usable_inventory_view. Decided 2026-10-06: read-only context by design (ADR-0006); gating release on it would be a new business rule
ProductClassificationViewinternal/domain/productclassificationviewread at release from product_classification_copy, a version-guarded local copy of product-master's ProductClassified (ADR-0035)
PathDefinition / Catalogueinternal/domain/pathcatalogin-memory copy of process-path-management's catalogue
BacklogSnapshot, RebalanceRecommendationinternal/application/usecasescomputed on read from a WorkPool