Skip to main content

Aggregate design canvas

Following the ddd-crew Aggregate Design Canvas v1.1. The context has one aggregate root, FulfillmentAssignment. Everything else it holds is a read model fed by sibling events. Source: internal/domain/assignment (assignment.go, commands.go, errors.go, events.go, types.go) and ADR 0002.

FulfillmentAssignment​

1. Name​

FulfillmentAssignment, the Go type assignment.Assignment in internal/domain/assignment, identified by assignmentId (asg-<uuid>, minted by internal/adapters/outbound/ids).

2. Description​

One shipment group of one customer order, its promise constraint, the current candidate node and path, and the history of releases. It carries:

PartShape
Identity and correlationassignmentId; orderId, groupNo (unique together)
DestinationdestinationPostalPrefix from CustomerOrderPlaced, matched exactly to a service area to find the delivery station
Promise constraintPromiseConstraint{promiseId, tier, deliverByLatest, witnessNodeId, revisionNo}
LinesLine{lineNo, catalogItemId, listingId, quantity}, at most 200; listingId is set from the first release
Current candidateCandidate{nodeId, pickupDepartureId, pickupCutoffAt, legs[], deliveryWaveId, eta, cost}
Release pointreleaseAt (virtual queue)
Release historyRelease{no, nodeId, releasedAt, requiredShipBy, outcome, reasonCode}
ExclusionsExcludedNode{nodeId, reason}, reset by a higher promise revisionNo
Concurrencyversion, strictly increasing
Lock and outcome factslockedAt, lockReason, pickupDepartureId, trackingNumbers, shippedAt, delivered packages, deliveredAt, cancelReason

It owns no stock and no capacity. It does not compute the promise, and it does not run the purchase-order clock (ackBy belongs to vendor-connectivity).

3. State transitions​

Source: internal/domain/assignment/commands.go, assignment.go (Queue). DELIVERED and CANCELLED are terminal (State.Terminal). ApplyRevisedPromise also changes the constraint in RELEASED, LOCKED and SHIPPED and a QUEUED assignment with no candidate under the new constraint becomes UNSOURCEABLE. RefuseCancel and MovePickup keep the state. In RELEASED exactly one release is PENDING; from LOCKED on, the node never changes.

4. Enforced invariants​

InvariantEnforced by
A released candidate's eta is not after deliverByLatestcheckCandidate in every method that sets a candidate: ErrCandidateBreaksPromise
No change of node after LOCKEDReoptimise (guardMovable) and RefuseRelease on a committed state: ErrAssignmentLocked
A node that refused this group is not chosen again for the same promise revisioncheckCandidate: ErrNodeExcluded
At most one release PENDINGReoptimise and Release while RELEASED: ErrReleaseInFlight
version strictly increasesthe repository compare-and-swap (ErrConcurrentUpdate) and the optional caller version of Reoptimise (ErrStaleAssignmentVersion)
Cancel only before LOCKED; a later request is refusedCancel: ErrCancelAfterLock, then RefuseCancel
A late outcome of an old release is not appliedpendingRelease: ErrReleaseNotPending
A promise revision must be above the applied oneApplyRevisedPromise: ErrStaleRevision

5. Corrective policies​

Own policies (internal/domain/sourcing, the use cases and the Kafka handlers):

  • VirtualQueue: releaseAt is the best candidate's pickup cutoff minus the node's handling time minus a 30 minute vendor ack budget, never before now; a SAME_DAY group is released at once. A re-optimisation that changes the best candidate moves releaseAt with it.
  • AssignmentCost: 100 per onward leg, 10 per hour between pickup departure and wave start, 1000 for a node outside the destination's region, a scorecard penalty on the 30d window (A 0, B 50, C 200, D 500), 500 for book pressure on the node and pickup; ties go to the witness node, then the lower node id, then the lower pickup departure id.
  • ReassignOnRefusal: on PurchaseOrderRejected or PurchaseOrderExpired, exclude the node and re-queue; if no candidate meets deliverByLatest, UNSOURCEABLE.
  • LockOnCommit: on PurchaseOrderAccepted the assignment is LOCKED.

Neighbours' reactions that close the loops:

Neighbour policyTrigger from this aggregateEffect
vendor-connectivity IssueOnReleaseFulfillmentReleasedToNodeIssues a purchase order, idempotent on assignmentId + releaseNo
vendor-connectivity ExpireUnacknowledgedits own sweepPast ackBy, PurchaseOrderExpired, which drives HandleNodeRefusal
vendor-connectivity CancelOnSourcingCancelFulfillmentCancelledCancels the issued purchase order of that release
delivery-promise RepromiseOnRiskFulfillmentUnsourceableRecomputes and revises the promise (PromiseRevised, then ApplyRevisedPromise)
linehaul-transportation BookOnLockFulfillmentLocked, FulfillmentCancelled, FulfillmentReassignedBooks one package on the pickup departure and releases it on cancel or reassignment
customer-orderingFulfillmentLocked, FulfillmentShipped, FulfillmentUnsourceable, FulfillmentCancelled, FulfillmentCancelRefusedReflects the facts in the order status

The neighbour policies are those named by the neighbours' own design; the handlers that react are listed on Integration.

6. Handled commands​

CommandTransitionIssued by
Queue (QueueAssignment)initial to QUEUED or UNSOURCEABLEKafka consumer of CustomerOrderPlaced, one per group
ReoptimiseQUEUED to QUEUED or UNSOURCEABLEsweep; planner POST /assignments/{id}/reoptimisations
ReleaseQUEUED to RELEASED or UNSOURCEABLEsweep at releaseAt; right after Queue for SAME_DAY
RefuseReleaseRELEASED to QUEUED or UNSOURCEABLEconsumer of PurchaseOrderRejected, PurchaseOrderExpired
LockRELEASED to LOCKEDconsumer of PurchaseOrderAccepted
MarkShippedLOCKED to SHIPPEDconsumer of VendorShipmentConfirmed
MarkDeliveredSHIPPED to DELIVERED on the last packageconsumer of PackageDelivered
CancelQUEUED, RELEASED, UNSOURCEABLE to CANCELLEDconsumer of CustomerOrderCancelled, per groupNos
RefuseCancelLOCKED, SHIPPED, DELIVERED unchanged (version + 1)same consumer, after ErrCancelAfterLock
ApplyRevisedPromiseany non-terminal state; UNSOURCEABLE to QUEUED when a candidate existsconsumer of PromiseRevised
MovePickupLOCKED unchangedconsumer of BookingMoved

7. Created events​

All are published as com.retailnetwork.commerce.order-sourcing.assignment.<EventName>, subject assignmentId.

EventRaised whenTopic
FulfillmentQueuedQueueanalytics
FulfillmentReleasedToNodeRelease to RELEASEDevents
FulfillmentReassignedthe candidate node changes in Reoptimise, Release, RefuseRelease or ApplyRevisedPromiseevents
FulfillmentUnsourceableno candidate left in Queue, Reoptimise, Release, RefuseRelease or ApplyRevisedPromiseevents
FulfillmentLockedLockevents
FulfillmentShippedMarkShippedevents
FulfillmentDeliveredMarkDelivered, last packageanalytics
FulfillmentCancelledCancelevents
FulfillmentCancelRefusedRefuseCancelevents
FulfillmentConstraintRevisedApplyRevisedPromise appliedevents

A Reoptimise that keeps the same candidate and release point raises nothing and does not move the version; MovePickup raises nothing. Fields are on the event catalogue.

8. Throughput​

Estimate. One Queue per shipment group at the order rate; one release, one lock, one shipment and one delivery per group on the happy path. The sweep (every SWEEP_INTERVAL, pages of 100 rows) dominates writes while the queue is long, because each QUEUED row is re-optimised on every pass but written only when the candidate or release point changed. Contention points: a sweep and a purchase-order outcome on the same assignment, and the planner's re-optimise. The version check turns every such race into ErrConcurrentUpdate, one in-process retry from a fresh load, then a skipped row or a redelivered message. Kafka keys by assignmentId, so one assignment's events are ordered.

9. Size​

Estimate. One row per shipment group with the lines, releases and exclusions embedded as JSON. Releases are usually one and are bounded by the number of candidate nodes, because each refusal excludes a node. Lifetime: from checkout to delivery (days), then a closed record; nothing in the code deletes rows. Events per instance on the happy path: FulfillmentQueued, FulfillmentReleasedToNode, FulfillmentLocked, FulfillmentShipped, FulfillmentDelivered; each refusal adds a FulfillmentReassigned (or FulfillmentUnsourceable) and another release.

Read models​

These hold state but are not aggregates: they enforce no invariant of this context, they are derived only from other contexts' events, and each can be rebuilt by replaying its topics. They are local because the context calls no sibling.

Read modelTablesSource eventsUsed by
NodeProfileViewrm_nodesnode-topology node eventseligible nodes (active vendor fulfilment centres with a declared profile), handling time and dwell for releaseAt
NetworkGraphViewrm_lanes, rm_departures, rm_waves, rm_service_areas, rm_regionsnode-topology, linehaul-transportation, last-mile-deliverycandidate paths, legs, eta, the cross-region penalty
AvailabilityViewrm_listings, rm_discontinued_itemsoffer-availabilitywhich nodes can ship every line in full, and the listingId for the release
ScorecardViewrm_scorecardsnode-performancethe scorecard penalty
PromiseBookPressureViewrm_book_pressuredelivery-promise PromiseBookExhaustedthe book-pressure penalty

The rules are in internal/domain/network/network.go and internal/application/usecases/projector.go; the tables are on Entity relationship. The virtual queue is not a separate store: it is the assignments rows in QUEUED, ordered by release_at.