Skip to main content

Aggregate design canvas

Following the ddd-crew Aggregate Design Canvas v1.1. The context has two aggregate roots, ShippingLabel and PackageJourney (ADR 0002). They share the tracking number as a value, never as a reference: a label can be voided without a journey in memory, and the journey takes a scan per event without touching the label row or the encrypted address (the use case loads both only for VoidLabel).

ShippingLabel​

1. Name​

ShippingLabel in internal/domain/label, identified by labelRef (label.Ref).

2. Description​

The label for one package: tracking number, service tier, carrier, the opaque stopKey and the postal prefix. The address itself is not a field; the AES-256-GCM sealed snapshot lives behind the ShipToSnapshots port. The address is read once, at issue time, from customer-ordering (GetShipTo) and never published.

3. State transitions​

Source: internal/domain/label/label.go (Issue, Void). VOIDED has no outgoing transition. A repeated void is answered by the use case with the unchanged label before the aggregate is reached; at the aggregate it would be ErrIllegalTransition.

4. Enforced invariants​

InvariantEnforced by
One label per (poNumber, packageNo)label.ErrLabelAlreadyIssued, unique index shipping_labels_package_key, pre-check FindByPackage
trackingNumber is uniquelabel.ErrTrackingNumberTaken, unique index shipping_labels_tracking_key; one retry with a fresh number
Ids are 1 to 64 characters, packageNo is 1 to 2147483647, tier is one of fourcheckNew (shared.ErrValidation)
The carrier follows the tierlabel.CarrierFor, checked again by Restore
stopKey is 64 lower-case hex characters, the postal prefix 1 to 16 characters from A-Z0-9checkDerived
Void reason is 1 to 500 characters, trimmedshared.ValidTextN
The ship-to address is never publishedBy construction: no event data, response schema or read model has an address field (TestContractsCarryNoShipToField)

5. Corrective policies​

  • No policy of this context reacts to a label.
  • Neighbour reactions to LabelIssued: linehaul-transportation adds the package to its expected-volume view, customer-ordering to its order-tracking view, last-mile-delivery groups stops by stopKey (per the AsyncAPI).
  • LabelVoided is consumed by customer-ordering and linehaul-transportation per the AsyncAPI.

6. Handled commands​

CommandIssued byInbound adapter
IssueLabelvendor-connectivity, inside a vendor's label requestREST POST /labels
VoidLabelNo caller namedREST POST /labels/{labelRef}/voids

7. Created events​

EventRaised whenFull CloudEvents type
LabelIssuedIssue saves an ISSUED labelcom.retailnetwork.logistics.shipping-and-tracking.label.LabelIssued
LabelVoidedVoid moves the label to VOIDEDcom.retailnetwork.logistics.shipping-and-tracking.label.LabelVoided

Subject and Kafka key: labelRef.

8. Throughput​

One write per package at issue, rarely a second at void. The only contention is a retried label request for the same (poNumber, packageNo), resolved by the unique index and the Idempotency-Key. No load figure is measured in this repository.

9. Size​

One shipping_labels row plus one ship_to_snapshots row. At most two events in its life.

PackageJourney​

1. Name​

PackageJourney is the Go type journey.Journey in internal/domain/journey, identified by trackingNumber.

2. Description​

The customer-visible timeline of one package. It owns its Scan entities (ID, NodeID, Type, At, Applied) and folds facts from three producers into one forward-only state: the vendor's shipment confirmation and the first pickup scan, linehaul load departures and arrivals, and last-mile out-for-delivery, attempt and return facts. It ends in DELIVERED, RETURNED, LOST or VOIDED.

3. State transitions​

Source: internal/domain/journey/types.go (next, the single edge table), internal/domain/journey/journey.go (Start, RecordScan, ReturnToSender, DeclareLost, Void). RaiseException records a NO_SCAN exception in any open state without a transition and is not drawn. A scan with no edge from the state it meets, or older than the last applied scan, is stored with applied=false and does not move the state.

Which fact drives which scan. internal/adapters/inbound/kafka/handlers.go maps each consumed event:

Source factScan typeState beforeState afterNote
VendorShipmentConfirmed (per tracking number)SHIPMENT_CONFIRMEDLABELLEDLABELLEDApplied: raises PackageScanned, but is not the handover
LoadDeparted, departureKind PICKUP (or absent while LABELLED)PICKUP_DEPARTURELABELLEDHANDED_OVERRaises PackageHandedOver with handedOverAt and the origin node
LoadDeparted, other kindsDEPARTUREHANDED_OVER or IN_TRANSITIN_TRANSIT
LoadArrived, nodeType other than DELIVERY_STATIONTRANSIT_ARRIVALHANDED_OVER or IN_TRANSITIN_TRANSIT
LoadArrived, nodeType DELIVERY_STATIONSTATION_ARRIVALHANDED_OVER or IN_TRANSITAT_STATIONHANDED_OVER to AT_STATION is direct injection
PackageOutForDeliveryOUT_FOR_DELIVERYAT_STATIONOUT_FOR_DELIVERYNode is stationNodeId
DeliveryAttempted, outcome DELIVEREDDELIVEREDOUT_FOR_DELIVERYDELIVEREDRaises PackageDelivered, closes the journey
DeliveryAttempted, other outcomeDELIVERY_FAILEDOUT_FOR_DELIVERYAT_STATIONBack to the station for the next wave
PackageReturnInitiatednone (ReturnToSender)AT_STATIONRETURNEDRaises PackageReturned
REST POST /journeys/{trackingNumber}/scansthe caller's scanTypeper the edgesper the edgesNo caller named

Every applied scan raises PackageScanned with the new state.

4. Enforced invariants​

InvariantEnforced by
A scanId is applied once; nothing is stored for a repeatjourney.ErrDuplicateScan, unique (tracking_number, scan_id)
Scans apply in time order; an older one is stored but does not move the statejourney.ErrScanOutOfOrder
DELIVERED, RETURNED, LOST and VOIDED are terminaljourney.ErrJourneyClosed
Only the edges of next exist (forward only); a scan with no edge from the current state is stored unappliedshared.ErrIllegalTransition
A label can be voided only while the journey is LABELLED (an open journey past it: ErrVoidAfterHandover; a closed one: ErrJourneyClosed, checked first)journey.ErrVoidAfterHandover
Scan id 1 to 256 characters, node id 1 to 64, known scan type, at requiredScanInput.validate
Concurrent writers: the stored version must be the aggregate's version minus oneports.ErrConcurrentUpdate

5. Corrective policies​

  • Handover on first scan (this context): the first pickup departure scan at the vendor node sets handedOverAt, the instant node-performance scores vendors against.
  • Exception on silence (this context): no applied scan within the window of the state and tier raises PackageExceptionRaised, reason NO_SCAN; windows are 6, 24, 48 and 72 hours for SAME_DAY, NEXT_DAY, TWO_DAY and STANDARD, 12 hours while out for delivery (journey.SilenceWindow). One exception per silence; a new applied scan re-arms it.
  • Lost after an unanswered exception (this context): 48 hours after a NO_SCAN exception on an IN_TRANSIT journey with no applied scan since, DeclareLost runs.
  • Reactions elsewhere (per the AsyncAPI): delivery-promise re-promises on PackageExceptionRaised, judges on PackageDelivered, and judges broken on PackageReturned and PackageLost; order-sourcing marks the assignment delivered on PackageDelivered.

6. Handled commands​

CommandIssued byInbound adapter
Startthe IssueLabel use case, in the same transaction as the labelnone of its own
RecordScanthe Kafka consumers of five event types; an unnamed REST callerinternal/adapters/inbound/kafka; REST POST /journeys/{trackingNumber}/scans
RaiseExceptionthe silence-sweep jobinternal/scheduler
ReturnToSenderthe consumer of PackageReturnInitiatedinternal/adapters/inbound/kafka
DeclareLostthe silence-sweep jobinternal/scheduler
Voidthe VoidLabel use caseREST POST /labels/{labelRef}/voids

7. Created events​

EventRaised whenFull CloudEvents type
PackageScannedevery applied scancom.retailnetwork.logistics.shipping-and-tracking.journey.PackageScanned
PackageHandedOverLABELLED to HANDED_OVER...journey.PackageHandedOver
PackageDeliveredOUT_FOR_DELIVERY to DELIVERED...journey.PackageDelivered
PackageExceptionRaisedRaiseException, no transition...journey.PackageExceptionRaised
PackageReturnedAT_STATION to RETURNED...journey.PackageReturned
PackageLostIN_TRANSIT to LOST...journey.PackageLost

Subject and Kafka key: trackingNumber. Start and Void raise no journey event: LabelIssued and LabelVoided announce them. A handover or delivery raises two events in one transaction: PackageScanned and the milestone event.

8. Throughput​

Every scan is a write, from four topics keyed by different ids, so two consumers can write the same journey at once. The version column is the optimistic lock and usecases.transact reruns the whole unit up to three times on ErrConcurrentUpdate (maxAttempts in writer.go) before the conflict surfaces. One load event names many tracking numbers and becomes one unit of work per journey. No load figure is measured in this repository.

9. Size​

One package_journeys row plus its append-only journey_scans rows, every scan kept including unapplied ones. Events per journey: one PackageScanned per applied scan, one PackageHandedOver, one terminal event and zero or more PackageExceptionRaised.

Read models​

Read modelSource eventsUsed forWhy it is not an aggregate
catalog_dimensions (ports.CatalogDimensionsView)offer-availability CatalogItemCreated (catalogItemId, title, lengthMm, widthMm, heightMm, weightG, hazmat, fragile)Item dimensions, weight and handling flagsIt enforces no invariant and accepts no command: a local copy of another context's facts, rebuilt by replaying the topic. No use case of this repository reads it back yet

| node_destinations (ports.NodeDestinationView, ADR 0018) | node-topology NodeRegistered, every node type (nodeId, postalCode) | The destination prefix of a return label that names its destination by node (IssueReturnLabel) | It enforces no invariant and accepts no command: per node, the prefix this context derives from another context's fact (shipto.NodePrefix). No state, no delete; rebuilt by replaying the topic under a fresh consumer group |

GET /journeys/{trackingNumber} reads the PackageJourney itself through views.Journey; it is a query, not a separate read model.