Skip to main content

Aggregate Design Canvas

As built

Derived from network/model/model.yaml. This context's service is built; the model carries its as-built contracts, and identifiers (Err... names, routes, CloudEvents types) are the names the service uses.

Following the ddd-crew Aggregate Design Canvas v1.1. The context has three aggregate roots: DeliveryOffer (a quote), Promise (a commitment) and PromiseBook (a capacity ledger). They are deliberately small: a promise does not contain its book, and a book does not list its promises, because one book is shared by every promise on the same node pickup cutoff and is the most contended row in the context.

DeliveryOffer​

1. Name​

DeliveryOffer (proposed package internal/domain/offer, code offer.DeliveryOffer), identified by offerId.

2. Description​

A short-lived quote for (catalogue item, quantity, destination postal prefix, tier) with a delivery window, the witness path that proves it, and an expiry. It is the result of the promise search, persisted with a TTL so that checkout can honour exactly the window the shopper saw. It holds no capacity.

Value objects: DeliveryWindow{earliest, latest}, WitnessPath{nodeId, pickupDepartureId, legs[departureId], deliveryWaveId}, OfferConstraint(DESTINATION_NOT_SERVED | ITEM_QUANTITY_NOT_AVAILABLE | DELIVERY_SLA_UNAVAILABLE | NODE_CAPACITY_EXHAUSTED). A constraint is returned for a tier that has no offer; it is never stored on an offer.

3. State Transitions​

Derived from: model.yaml → contexts[delivery-promise].aggregates[DeliveryOffer].states, .transitions, .commands.

Omitted: nothing. The initial edge is labelled with the command that creates the offer (QuoteDeliveryOffers), which the model lists among the aggregate's commands but not as a transition.

4. Enforced Invariants​

InvariantEnforced by
expiresAt <= min(quotedAt + offerTtl, the latest instant the witness pickup cutoff can still be met)ErrOfferExpiryTooLate
An expired or consumed offer cannot back a promiseErrOfferNotQuotable

5. Corrective Policies​

  • Expiry sweep (ExpireOffers): QUOTED offers past expiresAt move to EXPIRED. The read path also treats an offer past expiresAt as not quotable even before the sweep reaches it.
  • Re-quote at checkout (owned by customer-ordering, policy CheckoutPromising): if the offer expired, checkout re-quotes and shows the new window before placing.

6. Handled Commands​

CommandIssued byEffect
QuoteDeliveryOffersREST POST /delivery-quotes (storefront, customer-ordering)Runs PromisePolicy per tier; creates one QUOTED offer per feasible tier
MakePromiseREST POST /promises (customer-ordering)QUOTED → CONSUMED (the offer backs exactly one promise)
ExpireOffersinternal sweepQUOTED → EXPIRED

7. Created Events​

None on the integration topic. Quotes are high-volume query results; the model names one analytics-only event, DeliveryOfferQuoted, on retailnetwork.delivery-promise.analytics. The model gives it no data fields; see the domain events page.

8. Throughput​

Estimate (model). Very high: every product page and cart view. Writes are inserts only (no contention); the only update is the single CONSUMED or EXPIRED transition.

9. Size​

Estimate (model). TTL minutes; partitioned by day. A handful of lines and legs per offer.

Promise​

1. Name​

Promise (proposed package internal/domain/promise, code promise.Promise), identified by promiseId.

2. Description​

The network's commitment for one shipment group of one customer order: tier, ship-by at the witness node, deliver-by window, witness path, basis and policy version. It is created PROVISIONAL at checkout with a capacity hold, becomes CONFIRMED when the order is placed, may go AT_RISK and be revised, and ends judged KEPT or BROKEN, or RELEASED / CANCELLED.

Value objects: ShipmentGroup{lines[{catalogItemId, quantity}]}, PromiseTerms{tier (SAME_DAY|NEXT_DAY|TWO_DAY|STANDARD|CONSOLIDATED), shipBy, deliverByEarliest, deliverByLatest, basis(SCHEDULED|MEASURED|NOMINAL), policyVersion, consolidationEligible (optional, CONSOLIDATED only)}, WitnessPath{nodeId, pickupDepartureId, legs[departureId], deliveryWaveId}, Revision{revisionNo, previousTerms, reason, revisedAt}. Scalar fields carried on its events: offerId, orderId, groupNo, holdExpiresAt.

3. State Transitions​

Derived from: model.yaml → contexts[delivery-promise].aggregates[Promise].states, .transitions, .commands.

Omitted: nothing. A PROVISIONAL promise cannot be cancelled or revised: it either becomes CONFIRMED or is RELEASED when its hold expires.

4. Enforced Invariants​

InvariantEnforced by
deliverByEarliest <= deliverByLatest and shipBy < deliverByEarliestErrInvalidPromiseTerms
A fast-tier promise (SAME_DAY, NEXT_DAY, TWO_DAY) has basis SCHEDULED or MEASURED, never NOMINAL; STANDARD and CONSOLIDATED may be NOMINALErrNominalBasisNotAllowedForTier
A provisional promise is confirmed only before holdExpiresAtErrPromiseHoldExpired
A revision never moves deliverByLatest earlierErrRevisionMovesEarlier
KEPT, BROKEN, RELEASED and CANCELLED are terminalErrPromiseClosed
A promise covers lines shippable from one node (ship-complete group)ErrGroupSpansNodes
Concurrent writers do not overwrite each other (proposed, infrastructure)optimistic version check in the repository, surfaced as a stale-write conflict

5. Corrective Policies​

  • ReleaseExpiredHolds (sweep): a PROVISIONAL promise past holdExpiresAt becomes RELEASED and its provisional hold is returned to the book (ReleaseCapacity).
  • ConsolidatedTierQuote and ConsolidationEligibility: CONSOLIDATED is quoted only when a request lists it or names consolidatedDeliveryDay. From the group's own STANDARD candidates the quote takes the fastest window, picks the local day (the request's day, else two days after the fastest, never before it, at most 14 local days ahead), puts the final wave on that day (or a NOMINAL window of 09:00 to 21:00 local), and ranks the later shipBy first. The offer says consolidationEligible when the day is at least one local day after the fastest.
  • ConsolidatedRepromise: a CONSOLIDATED promise is re-promised only inside its own tier, walking forward day by day from the local day of its window; it never falls through to STANDARD.
  • SharedTrackingJudgement: one package event judges every promise that shares the tracking number, each on its own window; the capacity charge stays per promise, so a merged package is over-charged on the departure book on purpose.
  • RepromiseOnRisk: on FulfillmentUnsourceable, PackageExceptionRaised or a DepartureCancelled on the witness path, flag the promise at risk, recompute and RevisePromise; if nothing is feasible even at STANDARD, the promise stays AT_RISK and is reported PromiseBroken at judgement time.
  • JudgeOnDelivery: on PackageDelivered, judge every promise of the package's group: KEPT if deliveredAt <= deliverByLatest, else BROKEN with lateByMinutes.
  • Cancellation (this pack's reading of the CustomerOrderCancelled consumer; the model names no policy): cancel the promises of the cancelled groups and release their confirmed capacity.
  • Neighbours' reactions: customer-ordering updates the group's window on PromiseRevised (UpdateGroupPromise) and may cancel the group when no revised promise is feasible (CancelOnUnfulfillable); order-sourcing re-queues an UNSOURCEABLE assignment on PromiseRevised (ApplyRevisedPromise); node-performance counts PromiseKept / PromiseBroken into promiseKeptRate.

6. Handled Commands​

CommandIssued byTransition
MakePromiseREST POST /promises (customer-ordering checkout)[*] → PROVISIONAL
ConfirmPromiseKafka consumer of CustomerOrderPlacedPROVISIONAL → CONFIRMED
FlagPromiseAtRiskRepromiseOnRisk (consumers of FulfillmentUnsourceable, PackageExceptionRaised, DepartureCancelled) and the clock-driven FlagPredictedLate sweep (reason PREDICTED_LATE)CONFIRMED → AT_RISK
RevisePromiseRepromiseOnRisk, after a successful recomputeAT_RISK → CONFIRMED, CONFIRMED → CONFIRMED
JudgePromiseJudgeOnDelivery (consumer of PackageDelivered)CONFIRMED / AT_RISK → KEPT / BROKEN
CancelPromiseKafka consumer of CustomerOrderCancelledCONFIRMED / AT_RISK → CANCELLED
ReleaseExpiredHoldsinternal sweepPROVISIONAL → RELEASED

7. Created Events​

All on retailnetwork.delivery-promise.events, subject = promiseId.

EventRaised whenFull CloudEvents type
PromiseMadeMakePromise saved (PROVISIONAL)com.retailnetwork.commerce.delivery-promise.promise.PromiseMade
PromiseConfirmedConfirmPromise savedcom.retailnetwork.commerce.delivery-promise.promise.PromiseConfirmed
PromiseAtRiskFlagPromiseAtRisk savedcom.retailnetwork.commerce.delivery-promise.promise.PromiseAtRisk
PromiseRevisedRevisePromise savedcom.retailnetwork.commerce.delivery-promise.promise.PromiseRevised
PromiseKeptJudgePromise saved with KEPTcom.retailnetwork.commerce.delivery-promise.promise.PromiseKept
PromiseBrokenJudgePromise saved with BROKENcom.retailnetwork.commerce.delivery-promise.promise.PromiseBroken
PromiseReleasedReleaseExpiredHolds savedcom.retailnetwork.commerce.delivery-promise.promise.PromiseReleased
PromiseCancelledCancelPromise savedcom.retailnetwork.commerce.delivery-promise.promise.PromiseCancelled

Every transition raises exactly one event.

8. Throughput​

Estimate (model). Medium-high: one per shipment group at checkout. Each promise is written a few times over its life (make, confirm, perhaps flag and revise, judge), minutes to days apart. Contention on one promise is rare (a re-promise racing a judgement); an optimistic version resolves it.

9. Size​

Estimate (model). One row per group plus revisions. A handful of lines, one to four witness legs, and typically zero or one Revision. Events per instance: 3 on the happy path (PromiseMade, PromiseConfirmed, PromiseKept), 2 when released, more when re-promised.

PromiseBook​

1. Name​

PromiseBook (proposed package internal/domain/book, code book.PromiseBook), identified by bookId = nodeId + ':' + pickupDepartureId.

2. Description​

The promise-side capacity ledger of one node pickup cutoff: how many orders the network has promised onto it against the node's declared share. Value object: Capacity{share, provisional, confirmed} and BookTimes{cutoffAt, holdDeadline}. It counts orders, not packages (packages on the truck belong to linehaul-transportation's Departure).

3. State Transitions​

Derived from: model.yaml → contexts[delivery-promise].aggregates[PromiseBook].states, .transitions, .commands, .invariants.

Omitted: the model's only transition is OPEN → CLOSED: CloseBook. The creating edge is the command OpenBook, run by the first hold for the pickup (policy LazyBookOpening); the self-loops are counter changes, not state changes. ConfirmCapacity and ReleaseCapacity on a CLOSED book are needed because closing only stops new holds: an order placed after the close must still confirm a hold made before it, and a promise cancelled or released after the close must still return its count (see Open Questions on the canvas page).

4. Enforced Invariants​

InvariantEnforced by
provisional + confirmed <= shareErrPromiseCapacityExhausted
No hold once the book is CLOSED or from its holdDeadline (the pickup cutoff minus handling time)ErrBookClosed
A release never makes provisional or confirmed negativeErrCapacityUnderflow
Concurrent holds do not overbook (proposed, infrastructure)optimistic version check, retried by the use case

5. Corrective Policies​

  • Exhaustion signal: the hold that brings provisional + confirmed to share raises PromiseBookExhausted; order-sourcing adds book pressure to its AssignmentCost (bookPressurePenalty).
  • Holds expire: ReleaseExpiredHolds returns provisional capacity of promises never confirmed.
  • Close at the cutoff: a clock job runs CloseBook at cutoffAt (policy CloseBooksAtCutoff). Holds stop earlier, from the holdDeadline (cutoff minus handling time, the instant behind ErrBookClosed).
  • Share: fixed when the book opens, by BookShare: ceil(min(maxOrders, throughput cap x window) x capacitySharePercent / 100), at least 1.
  • A full book is not a dead end: the search moves on to the next pickup cutoff of the same node, or another node (constraint NODE_CAPACITY_EXHAUSTED only when every candidate book is full).

6. Handled Commands​

CommandIssued byEffect
OpenBookthe first HoldCapacity for a (node, pickup departure), in the same transactioncreates the book OPEN with its share, cutoffAt and holdDeadline
HoldCapacityMakePromise; RevisePromise on a new book (this pack's reading)provisional + 1
ConfirmCapacityConfirmPromiseprovisional - 1, confirmed + 1
ReleaseCapacityReleaseExpiredHolds (provisional), CancelPromise and RevisePromise on the old book (confirmed)provisional - 1 or confirmed - 1
CloseBookclock job at cutoffAtOPEN → CLOSED

7. Created Events​

EventRaised whenFull CloudEvents type
PromiseBookExhausteda HoldCapacity makes provisional + confirmed = sharecom.retailnetwork.commerce.delivery-promise.promisebook.PromiseBookExhausted

Subject = bookId. Data: bookId, nodeId, pickupDepartureId, share.

8. Throughput​

Estimate (model). High and contended: one hold per promise, one row per (node, cutoff). Every checkout for the same node and cutoff writes the same row, so the book is the hot spot of the context. Keeping it a three-counter aggregate (no list of promises inside) keeps each write a single-row update.

9. Size​

Estimate (model). Nodes × cutoffs × horizon days. Three integers and a state per row; at most one PromiseBookExhausted per book.

Read models​

Seven local projections, each fed only by events (no synchronous call). They are not aggregates: this context enforces no invariant on them, it never changes them by command, and their owner can overwrite any row at any time. The promise search reads them; the aggregates never contain them.

Read modelSource events (producer)Used forWhy it is not an aggregate
NodeProfileViewNodeRegistered, NodeOperationalProfileDeclared, NodeActivated, NodeSuspended, NodeRetired (node-topology)candidate nodes (ACTIVE, type, subtype, region), readyAt (handling time, operating hours, holidays, time zone), cutoffs, sort dwell, book shareThe node is node-topology's aggregate; DP keeps the latest profileRevision it has seen.
RegionAndServiceAreaViewServiceAreaAssigned, RegionDefined (node-topology)destination postal prefix → delivery station and region; in-region tie-breakVersioned by assignmentVersion upstream; DP keeps the highest.
LaneViewLaneOpened, LaneClosed (node-topology)nominal transit for the STANDARD fallback; lane open checknode-topology owns lanes.
AvailabilityViewListingCreated, ListingAvailabilityChanged, ListingSuppressed, ListingRestored, CatalogItemCreated, CatalogItemDiscontinued (offer-availability)which ACTIVE nodes can ship the quantity of every lineoffer-availability owns listings; DP keeps the newest asOf per listing.
DepartureViewDepartureScheduled, DepartureCapacityChanged, DepartureCancelled (linehaul-transportation)pickup departures (cutoff), the time-expanded graph of scheduled departures with remainingPackageslinehaul-transportation books packages; DP only reads remaining capacity.
DeliveryWaveViewDeliveryWaveScheduled, DeliveryWaveCapacityChanged (last-mile-delivery)first wave with inductCutoffAt >= arrival and remainingStops > 0; the promise windowlast-mile-delivery assigns stops.
ScorecardViewNodeScorecardUpdated (node-performance)ScorecardHandicap; grade tie-breaknode-performance computes grades.

Derived from: model.yaml → contexts[delivery-promise].read_models, .policies.

Not shown as read models: the PromiseBook is an aggregate, not a view of departures. DepartureView says how many packages a truck can still take; the book says how many orders the network has promised onto the node's cutoff. The two can disagree, and the search requires both to have room.