Arcadia Editions Microservices
Section titled “Arcadia Editions Microservices”The five bounded contexts of the place-order flow as standalone Java + Spring Boot microservices: clean hexagonal layout, PostgreSQL, Kafka with Avro events (Spring Cloud Stream), and synchronous HTTP calls where the flow needs an answer. arcadia-editions-microservices-compose runs them all together.
Each bounded context has two repositories:
- an API repository that owns the domain model (
domain-model.zdl) and the contracts generated from it:openapi.yml,asyncapi.yml(events it publishes),asyncapi-client.yml(events it consumes) and the Avro schemas. - a service repository with the Spring Boot application, generated from the released contracts of its API repository.
| Service | API repository | Service repository | HTTP port |
|---|---|---|---|
| Orders Checkout | orders-checkout-api | orders-checkout-service-java | 8101 |
| Catalog Inventory | catalog-inventory-api | catalog-inventory-service-java | 8102 |
| Payments Processing | payments-processing-api | payments-processing-service-java | 8103 |
| Fulfillment Shipping | fulfillment-shipping-api | fulfillment-shipping-service-java | 8104 |
| Notifications Consumer | notifications-consumer-api | notifications-consumer-service-java | 8105 |
Services
Section titled “Services”Every service has its own REST API; the customer enters the flow through Orders Checkout. Most steps travel as Avro events on Kafka. Three steps call another service over HTTP and wait for the answer. The arrows come from @asyncapi and @calls in the models.
This page walks through Orders Checkout. The other four follow the same structure.
Domain models
Section titled “Domain models”The aggregate
Section titled “The aggregate”The Order aggregate of Orders Checkout, with its lifecycle. It is the same aggregate as in the moduliths:
orders-checkout-api/domain-model.zdl: Order aggregate
@aggregate@lifecycle(field: status, initial: CREATED)entity Order(checkout_order) { orderId String required unique status OrderStatus required /** Customer snapshot taken at checkout (there is no customers bounded context yet). */ customerId String required customerEmail String required maxlength(254) paymentMethodId String required @json items OrderItem[] required minlength(1) { sku String required quantity Integer required min(1) unitPrice BigDecimal required min(0) // client-sent (as designed for now); should come from catalog.products } @json shippingAddress ShippingAddress required { name String required line1 String required line2 String city String required region String postalCode String required country String required } totalAmount BigDecimal required currency String required maxlength(3) createdAt Instant confirmedAt Instant cancelledAt Instant cancellationReason String}Its rules and @invariant
Section titled “Its rules and @invariant”Each microservice ZDL carries the same rules and @invariants as its bounded context in the modulith model. The rules of the whole flow are in place-order-flow.zfl. The same natural-language rules are the spec for the behavior in both architectures:
orders-checkout-api/domain-model.zdl: rules (Order)
rules (Order) { @invariant orderTotal "totalAmount equals the sum of quantity * unitPrice over all items, in the order's currency" @invariant checkoutSnapshotFixed "customerId, customerEmail, paymentMethodId, items, shippingAddress, totalAmount and currency are fixed at checkout and never change" @invariant orderOnlyWithReservedStock "An Order exists only if its stock was reserved: StockUnavailable persists nothing" @invariant cancelledIsFinal "CANCELLED is terminal: no command takes an Order out of it" @invariant cancelledNeverConfirmed "A CANCELLED Order is never confirmed: a late authorization is answered with OrderConfirmationRejected" @invariant confirmationData "confirmedAt is set exactly when the Order reaches CONFIRMED and is never cleared" @invariant cancellationData "cancelledAt and cancellationReason are set if and only if the Order is CANCELLED" singleCancellation "An Order is cancelled at most once: a redelivered cancellation is a no-op with no event"}The service-level rules, which span the Order and the calls to Catalog Inventory:
orders-checkout-api/domain-model.zdl: rules
rules { reserveBeforePersist "startOrderCheckout reserves stock (InventoryService.reserveStock) before persisting the Order; all lines are reserved or none" confirmOnlyWithHeldStock "An Order is confirmed only if InventoryService.confirmStockReservation answers CONFIRMED: every line is still RESERVED" rejectedConfirmationVoids "A confirmation refused because the Order is CANCELLED or its stock is NOT_HELD emits OrderConfirmationRejected, so payments voids the authorization" cancellationOwner "OrdersCheckout is the only owner of OrderCancelled: it cancels only in reaction to StockReleased" cancellationReasonFromRelease "cancellationReason is the StockReleaseReason carried by StockReleased" orderCreatedCarriesAmount "OrderCreated.amount and currency are Order.totalAmount and currency: they are the amount payments authorizes"}The only modulith rule not ported is limitedEdition in Catalog Inventory. It needs Product.editionSize, which the microservice does not hold.
Service and APIs
Section titled “Service and APIs”What changes from the modulith is how contexts talk to each other. In the modulith a command listens to another module with @listener. Here it subscribes to a channel of another service’s AsyncAPI with @asyncapi, and the other services are declared as asyncapi clients:
orders-checkout-api/domain-model.zdl: service
@rest("/orders")service OrdersCheckoutService for (Order) {
/** Persists the Order only on OrderCreated; StockUnavailable answers 409 and persists nothing (P-03 A). */ @post("/start-checkout") @transition(to: CREATED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.reserveStock) startOrderCheckout(StartOrderCheckoutInput) Order withEvents [OrderCreated | StockUnavailable]
/** * No-op on CONFIRMED (redelivery). On CANCELLED, or when the stock is no longer * held (NOT_HELD), the Order is not confirmed and OrderConfirmationRejected asks payments to void. */ @asyncapi(api: PaymentsProcessingApi, channel: "payment-authorized-event-v1") @transition(from: CREATED, to: CONFIRMED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.confirmStockReservation) confirmOrder(ConfirmOrderInput) Order withEvents [OrderConfirmed | OrderConfirmationRejected]
/** No-op, no event, on CANCELLED (redelivered StockReleased). */ @asyncapi(api: CatalogInventoryApi, channel: "stock-released-event-v1") @transition(from: [CREATED, CONFIRMED], to: CANCELLED) cancelOrder(CancelOrderInput) Order withEvents OrderCancelled
@get("/{id}") getOrder(id) Order?}orders-checkout-api/domain-model.zdl: apis
apis { asyncapi client CatalogInventoryApi "https://raw.githubusercontent.com/arcadia-editions/catalog-inventory-api/main/asyncapi.yml" asyncapi client PaymentsProcessingApi "https://raw.githubusercontent.com/arcadia-editions/payments-processing-api/main/asyncapi.yml" zdl client CatalogInventoryZdl "https://raw.githubusercontent.com/arcadia-editions/catalog-inventory-api/main/domain-model.zdl"}All the models
Section titled “All the models”orders-checkout-api/domain-model.zdl
config { id "urn:com.arcadiaeditions:orders:checkout" version "0.2.0" title "Arcadia Editions - Orders Checkout" basePackage "com.arcadiaeditions.orders.checkout" persistence jpa
plugins { /** Generates an AsyncAPI v3 specification from this ZDL model. */ ZDLToAsyncAPIPlugin { id "urn:com.arcadiaeditions:orders:checkout:asyncapi" applicationExtensions """ x-application-bindings: x-principal: orders_checkout x-clientId: orders_checkout x-groupId: orders_checkout """ schemaFormat avro idType integer idTypeFormat int64 avroPackage com.arcadiaeditions.orders.checkout.events.avro includeCloudEventsHeaders true includeKafkaCommonHeaders true asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-overlay.yml" targetFile "./asyncapi.yml" } ZDLToAsyncAPIClientPlugin { id "urn:com.arcadiaeditions:orders:checkout:asyncapi:client" applicationExtensions """ x-application-bindings: x-principal: orders_checkout x-clientId: orders_checkout x-groupId: orders_checkout """ title "Arcadia Editions - Orders Checkout - AsyncAPI Client" asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-client-overlay.yml" targetFile "./asyncapi-client.yml" } /** Generates an OpenAPI 3.0 specification from this ZDL model. */ ZDLToOpenAPIPlugin { openapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/openapi-overlay.yml", "./openapi-overlay.yml" idType integer idTypeFormat int64 targetFile "./openapi.yml" } }}
apis { asyncapi client CatalogInventoryApi "https://raw.githubusercontent.com/arcadia-editions/catalog-inventory-api/main/asyncapi.yml" asyncapi client PaymentsProcessingApi "https://raw.githubusercontent.com/arcadia-editions/payments-processing-api/main/asyncapi.yml" zdl client CatalogInventoryZdl "https://raw.githubusercontent.com/arcadia-editions/catalog-inventory-api/main/domain-model.zdl"}
@aggregate@lifecycle(field: status, initial: CREATED)entity Order(checkout_order) { orderId String required unique status OrderStatus required /** Customer snapshot taken at checkout (there is no customers bounded context yet). */ customerId String required customerEmail String required maxlength(254) paymentMethodId String required @json items OrderItem[] required minlength(1) { sku String required quantity Integer required min(1) unitPrice BigDecimal required min(0) // client-sent (as designed for now); should come from catalog.products } @json shippingAddress ShippingAddress required { name String required line1 String required line2 String city String required region String postalCode String required country String required } totalAmount BigDecimal required currency String required maxlength(3) createdAt Instant confirmedAt Instant cancelledAt Instant cancellationReason String}
rules (Order) { @invariant orderTotal "totalAmount equals the sum of quantity * unitPrice over all items, in the order's currency" @invariant checkoutSnapshotFixed "customerId, customerEmail, paymentMethodId, items, shippingAddress, totalAmount and currency are fixed at checkout and never change" @invariant orderOnlyWithReservedStock "An Order exists only if its stock was reserved: StockUnavailable persists nothing" @invariant cancelledIsFinal "CANCELLED is terminal: no command takes an Order out of it" @invariant cancelledNeverConfirmed "A CANCELLED Order is never confirmed: a late authorization is answered with OrderConfirmationRejected" @invariant confirmationData "confirmedAt is set exactly when the Order reaches CONFIRMED and is never cleared" @invariant cancellationData "cancelledAt and cancellationReason are set if and only if the Order is CANCELLED" singleCancellation "An Order is cancelled at most once: a redelivered cancellation is a no-op with no event"}
enum OrderStatus { CREATED CONFIRMED CANCELLED}
input StartOrderCheckoutInput { customerId String required customerEmail String required maxlength(254) paymentMethodId String required currency String required maxlength(3) items OrderItemInput[] required minlength(1) { sku String required quantity Integer required min(1) unitPrice BigDecimal required min(0) // client-sent (as designed for now); should come from catalog.products } shippingAddress ShippingAddressInput required { name String required line1 String required line2 String city String required region String postalCode String required country String required }}
input ConfirmOrderInput { orderId String required}
input CancelOrderInput { orderId String required /** From StockReleased.reason (StockReleaseReason name). */ reason String required}
@rest("/orders")service OrdersCheckoutService for (Order) {
/** Persists the Order only on OrderCreated; StockUnavailable answers 409 and persists nothing (P-03 A). */ @post("/start-checkout") @transition(to: CREATED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.reserveStock) startOrderCheckout(StartOrderCheckoutInput) Order withEvents [OrderCreated | StockUnavailable]
/** * No-op on CONFIRMED (redelivery). On CANCELLED, or when the stock is no longer * held (NOT_HELD), the Order is not confirmed and OrderConfirmationRejected asks payments to void. */ @asyncapi(api: PaymentsProcessingApi, channel: "payment-authorized-event-v1") @transition(from: CREATED, to: CONFIRMED) @calls(zdl: CatalogInventoryZdl, command: InventoryService.confirmStockReservation) confirmOrder(ConfirmOrderInput) Order withEvents [OrderConfirmed | OrderConfirmationRejected]
/** No-op, no event, on CANCELLED (redelivered StockReleased). */ @asyncapi(api: CatalogInventoryApi, channel: "stock-released-event-v1") @transition(from: [CREATED, CONFIRMED], to: CANCELLED) cancelOrder(CancelOrderInput) Order withEvents OrderCancelled
@get("/{id}") getOrder(id) Order?}
rules { reserveBeforePersist "startOrderCheckout reserves stock (InventoryService.reserveStock) before persisting the Order; all lines are reserved or none" confirmOnlyWithHeldStock "An Order is confirmed only if InventoryService.confirmStockReservation answers CONFIRMED: every line is still RESERVED" rejectedConfirmationVoids "A confirmation refused because the Order is CANCELLED or its stock is NOT_HELD emits OrderConfirmationRejected, so payments voids the authorization" cancellationOwner "OrdersCheckout is the only owner of OrderCancelled: it cancels only in reaction to StockReleased" cancellationReasonFromRelease "cancellationReason is the StockReleaseReason carried by StockReleased" orderCreatedCarriesAmount "OrderCreated.amount and currency are Order.totalAmount and currency: they are the amount payments authorizes"}
@asyncapi({ channel: "order-created-event-v1", topic: "orders-checkout.order-created.event.avro.v1" })event OrderCreated { orderId String version Integer customerId String customerEmail String paymentMethodId String /** Order total (Order.totalAmount), named to match AuthorizePaymentInput. */ amount BigDecimal currency String}
@asyncapi({ channel: "stock-unavailable-event-v1", topic: "orders-checkout.stock-unavailable.event.avro.v1" })event StockUnavailable { orderId String customerId String customerEmail String unavailableItems StockUnavailableItem[] { sku String requestedQuantity Integer availableQuantity Integer }}
@asyncapi({ channel: "order-confirmed-event-v1", topic: "orders-checkout.order-confirmed.event.avro.v1" })event OrderConfirmed { orderId String version Integer customerId String confirmedAt Instant items OrderConfirmedItem[] { sku String quantity Integer } shippingAddress OrderConfirmedShippingAddress { name String line1 String line2 String city String region String postalCode String country String }}
@asyncapi({ channel: "order-cancelled-event-v1", topic: "orders-checkout.order-cancelled.event.avro.v1" })event OrderCancelled { orderId String version Integer customerId String customerEmail String /** Order.cancellationReason */ reason String cancelledAt Instant}
/** The authorization arrived for an order that is cancelled or whose stock is no longer held; payments voids it. */@asyncapi({ channel: "order-confirmation-rejected-event-v1", topic: "orders-checkout.order-confirmation-rejected.event.avro.v1" })event OrderConfirmationRejected { orderId String customerId String /** ORDER_CANCELLED or STOCK_NOT_HELD */ reason String rejectedAt Instant}catalog-inventory-api/domain-model.zdl
config { id "urn:com.arcadiaeditions:catalog:inventory" version "0.2.1" title "Arcadia Editions - Catalog Inventory" basePackage "com.arcadiaeditions.catalog.inventory" persistence jpa
plugins { /** Generates an AsyncAPI v3 specification from this ZDL model. */ ZDLToAsyncAPIPlugin { id "urn:com.arcadiaeditions:catalog:inventory:asyncapi" applicationExtensions """ x-application-bindings: x-principal: catalog_inventory x-clientId: catalog_inventory x-groupId: catalog_inventory """ schemaFormat avro idType integer idTypeFormat int64 avroPackage com.arcadiaeditions.catalog.inventory.events.avro includeCloudEventsHeaders true includeKafkaCommonHeaders true asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-overlay.yml" targetFile "./asyncapi.yml" } ZDLToAsyncAPIClientPlugin { id "urn:com.arcadiaeditions:catalog:inventory:asyncapi:client" applicationExtensions """ x-application-bindings: x-principal: catalog_inventory x-clientId: catalog_inventory x-groupId: catalog_inventory """ title "Arcadia Editions - Catalog Inventory - AsyncAPI Client" asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-client-overlay.yml" targetFile "./asyncapi-client.yml" } /** Generates an OpenAPI 3.0 specification from this ZDL model. */ ZDLToOpenAPIPlugin { openapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/openapi-overlay.yml" idType integer idTypeFormat int64 targetFile "./openapi.yml" } }}
apis { asyncapi client PaymentsProcessingApi "https://raw.githubusercontent.com/arcadia-editions/payments-processing-api/main/asyncapi.yml" zdl client PaymentsProcessingZdl "https://raw.githubusercontent.com/arcadia-editions/payments-processing-api/main/domain-model.zdl"}
@aggregate@lifecycle(field: status, initial: RESERVED)entity StockReservation { reservationId String required unique /** One reservation per order line: an order has as many reservations as items. */ orderId String required sku String required quantity Integer required status ReservationStatus required reservedAt Instant required expiresAt Instant required confirmedAt Instant releasedAt Instant releaseReason StockReleaseReason}
rules (StockReservation) { @invariant oneReservationPerLine "One StockReservation per order line: (orderId, sku) is unique" @invariant positiveQuantity "quantity is at least 1" @invariant reservationWindow "expiresAt is reservedAt + 10 minutes" @invariant releasedIsFinal "RELEASED is terminal: a released line never goes back to RESERVED or CONFIRMED" @invariant confirmationData "confirmedAt is set exactly when the line reaches CONFIRMED" @invariant releaseData "releasedAt and releaseReason are set if and only if the line is RELEASED" expiryReleasesOnlyReserved "The reservation timer releases only RESERVED lines, with reason RESERVATION_EXPIRED; it never touches a CONFIRMED line" expiryOnlyWithoutPayment "The timer releases nothing once a payment exists for the order: payment owns the end" releaseReasonFromEventType "releaseReason comes from the type of the triggering event, never from its free-text reason"}
enum ReservationStatus { RESERVED RELEASED CONFIRMED}
enum StockReleaseReason { PAYMENT_DECLINED PAYMENT_RETRY_EXHAUSTED PAYMENT_VOIDED PAYMENT_VOID_FAILED RESERVATION_EXPIRED}
input ReserveStockInput { orderId String required items ReserveStockItemInput[] required minlength(1) { sku String required quantity Integer required min(1) }}
/** Confirms every reservation of the order. */input ConfirmStockReservationInput { orderId String required}
/** Releases every reservation of the order. */input ReleaseStockInput { orderId String required /** Set by the listener from the triggering event type; never from the event's free-text reason. */ reason StockReleaseReason required}
/** Expires every RESERVED reservation of the order. */input ExpireReservationInput { orderId String required}
enum ConfirmStockReservationOutcome { CONFIRMED NOT_HELD}
/** Exactly one of `confirmed` / `notHeld` is set, according to `outcome`. */output ConfirmStockReservationResult { outcome ConfirmStockReservationOutcome required confirmed StockReservationConfirmedResult notHeld StockReservationNotHeldResult}
output StockReservationConfirmedResult { orderId String confirmedAt Instant}
/** Some line of the order is not RESERVED (released by the timer). Nothing is confirmed. */output StockReservationNotHeldResult { orderId String}
enum ReserveStockOutcome { RESERVED UNAVAILABLE}
/** * Wrapper for the two ZFL responses of reserveStock (ZDL has no union return type). * Exactly one of `reserved` / `unavailable` is set, according to `outcome`. */output ReserveStockResult { outcome ReserveStockOutcome required reserved StockReservedResult unavailable StockUnavailableResult}
output StockReservedResult { orderId String expiresAt Instant reservations StockReservedLine[] { reservationId String sku String quantity Integer reservedAt Instant }}
output StockUnavailableResult { orderId String unavailableItems StockUnavailableLine[] { sku String requestedQuantity Integer availableQuantity Integer }}
@rest("/inventory")service InventoryService for (StockReservation) {
@post("/reservations/reserve") @transition(to: RESERVED) reserveStock(ReserveStockInput) ReserveStockResult
/** The type of the triggering event sets the reason. No-op, no event, when already RELEASED. */ @asyncapi(api: PaymentsProcessingApi, channel: "payment-declined-event-v1") @asyncapi(api: PaymentsProcessingApi, channel: "payment-retry-exhausted-event-v1") @asyncapi(api: PaymentsProcessingApi, channel: "payment-voided-event-v1") @asyncapi(api: PaymentsProcessingApi, channel: "payment-void-failed-event-v1") @transition(from: [RESERVED, CONFIRMED], to: RELEASED) releaseStock(ReleaseStockInput) StockReservation[] withEvents StockReleased
/** * Reservation timer, 10 minutes after OrderCreated. No-op, no event, when no line of the order * is RESERVED. Releases them (RESERVATION_EXPIRED) only when payments answers NO_PAYMENT; * on STARTED, payment owns the end and nothing happens. */ @timer(api: SchedulerApi, channel: "reservation-expired-event-v1") @calls(zdl: PaymentsProcessingZdl, command: PaymentsProcessingService.getPaymentStatus) @transition(from: RESERVED, to: RELEASED) expireReservation(ExpireReservationInput) StockReservation[] withEvents StockReleased
/** Returns CONFIRMED with no change when every line is already CONFIRMED (redelivery). */ @post("/reservations/confirm") @transition(from: RESERVED, to: CONFIRMED) confirmStockReservation(ConfirmStockReservationInput) ConfirmStockReservationResult withEvents StockReservationConfirmed}
rules { @invariant noOversell "A line is reserved only if InventoryPosition.availableQuantity of its sku covers its quantity: stock is never oversold" allOrNothingReservation "reserveStock reserves every line of the order or none: if one sku is short, nothing is reserved and the answer is StockUnavailableResult" allOrNothingConfirmation "confirmStockReservation confirms every line of the order or none: NOT_HELD when any line is not RESERVED" @invariant reservedMatchesPosition "InventoryPosition.reservedQuantity of a sku is the sum of quantity over its RESERVED lines" @invariant soldMatchesPosition "InventoryPosition.soldQuantity of a sku includes the quantity of its CONFIRMED lines" reservationMovesStock "Reserving moves quantity from available to reserved; confirming moves it from reserved to sold; releasing returns it to available"}
@asyncapi({ channel: "stock-released-event-v1", topic: "catalog-inventory.stock-released.event.avro.v1" })event StockReleased { orderId String reason StockReleaseReason releasedAt Instant items StockReleasedItem[] { reservationId String sku String quantity Integer }}
/** Published on purpose (inventory projections); no step of place-order-flow consumes it. */@asyncapi({ channel: "stock-reservation-confirmed-event-v1", topic: "catalog-inventory.stock-reservation-confirmed.event.avro.v1" })event StockReservationConfirmed { orderId String confirmedAt Instant items StockReservationConfirmedItem[] { reservationId String sku String quantity Integer }}
//--- backoffice ----
@aggregateentity InventoryPosition { sku String required unique availableQuantity Integer required reservedQuantity Integer required soldQuantity Integer required}
rules (InventoryPosition) { @invariant oneSkuOnePosition "One InventoryPosition per sku" @invariant nonNegativeQuantities "availableQuantity, reservedQuantity and soldQuantity are never negative" adjustmentKeepsNonNegative "adjustStock is refused when it would make availableQuantity negative" positiveIntake "receiveStock adds a positive quantity to availableQuantity" adjustmentHasReason "Every adjustment carries a StockAdjustmentReason and is published as StockAdjusted"}
input CreateInventoryPositionInput { sku String required initialQuantity Integer required}
input ReceiveStockInput { sku String required quantity Integer required reason String reference String}
input AdjustStockInput { sku String required quantityDelta Integer required reason StockAdjustmentReason required reference String}
enum StockAdjustmentReason { DAMAGED LOST FOUND MANUAL_CORRECTION RETURNED}
@rest("/inventory")service InventoryBackofficeService for (InventoryPosition) {
@post("/positions") createInventoryPosition(CreateInventoryPositionInput) InventoryPosition
@post("/{sku}/stock-intakes") receiveStock(ReceiveStockInput) InventoryPosition withEvents StockReceived
@post("/{sku}/adjustments") adjustStock(AdjustStockInput) InventoryPosition withEvents StockAdjusted}
rules { intakeOnlyThroughBackoffice "Stock enters or leaves the pool outside an order only through receiveStock and adjustStock"}
@asyncapi({ channel: "stock-received-event-v1", topic: "catalog-inventory.stock-received.event.avro.v1" })event StockReceived { sku String quantity Integer availableQuantity Integer reservedQuantity Integer soldQuantity Integer reason String reference String receivedAt Instant}
@asyncapi({ channel: "stock-adjusted-event-v1", topic: "catalog-inventory.stock-adjusted.event.avro.v1" })event StockAdjusted { sku String quantityDelta Integer availableQuantity Integer reservedQuantity Integer soldQuantity Integer reason StockAdjustmentReason reference String adjustedAt Instant}payments-processing-api/domain-model.zdl
config { id "urn:com.arcadiaeditions:payments:processing" version "0.2.2" title "Arcadia Editions - Payments Processing" basePackage "com.arcadiaeditions.payments.processing" persistence jpa
plugins { /** Generates an AsyncAPI v3 specification from this ZDL model. */ ZDLToAsyncAPIPlugin { id "urn:com.arcadiaeditions:payments:processing:asyncapi" applicationExtensions """ x-application-bindings: x-principal: payments_processing x-clientId: payments_processing x-groupId: payments_processing """ schemaFormat avro idType integer idTypeFormat int64 avroPackage com.arcadiaeditions.payments.processing.events.avro includeCloudEventsHeaders true includeKafkaCommonHeaders true asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-overlay.yml" targetFile "./asyncapi.yml" } ZDLToAsyncAPIClientPlugin { id "urn:com.arcadiaeditions:payments:processing:asyncapi:client" applicationExtensions """ x-application-bindings: x-principal: payments_processing x-clientId: payments_processing x-groupId: payments_processing """ title "Arcadia Editions - Payments Processing - AsyncAPI Client" asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-client-overlay.yml" targetFile "./asyncapi-client.yml" } /** Generates an OpenAPI 3.0 specification from this ZDL model. */ ZDLToOpenAPIPlugin { openapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/openapi-overlay.yml" idType integer idTypeFormat int64 targetFile "./openapi.yml" } }}
apis { asyncapi client FulfillmentShippingApi "https://raw.githubusercontent.com/arcadia-editions/fulfillment-shipping-api/main/asyncapi.yml" asyncapi client OrdersCheckoutApi "https://raw.githubusercontent.com/arcadia-editions/orders-checkout-api/main/asyncapi.yml"}
@aggregate@lifecycle(field: status, initial: AUTHORIZATION_REQUESTED)entity Payment { orderId String required unique customerId String required paymentMethodId String required /** Carried so PaymentCaptured can drive the order confirmation e-mail. */ customerEmail String required amount BigDecimal required currency String required status PaymentStatus required providerReference String attemptCount Integer required authorizedAt Instant declinedAt Instant failedAt Instant capturedAt Instant voidedAt Instant voidFailedAt Instant failureReason String}
rules (Payment) { @invariant onePaymentPerOrder "At most one Payment per order: authorizePayment never creates a second one, whatever the state of the first" @invariant amountFixed "amount, currency, paymentMethodId and orderId never change after creation" @invariant attemptBounds "attemptCount is between 1 and 3" @invariant attemptsOnlyGrow "attemptCount only grows, by one, and only on reauthorizePayment" @invariant terminalStates "DECLINED, RETRY_EXHAUSTED, CAPTURED, VOIDED and VOID_FAILED are terminal" @invariant capturedNeverVoided "A CAPTURED Payment is never voided: a void applies only to AUTHORIZED or CAPTURE_FAILED" @invariant captureOnlyAuthorized "Only an AUTHORIZED Payment is captured, for its whole amount" @invariant stateTimestamps "Each of authorizedAt, declinedAt, failedAt, capturedAt, voidedAt and voidFailedAt is set when the Payment enters that state" declineNotRetried "A hard decline is never retried: the customer must act" retryOnlyCurrentAttempt "retryPayment and reauthorizePayment act only when the Payment is FAILED and input.attemptCount equals attemptCount; otherwise no-op, no event" retryBackoff "Backoff before attempt 2 is 5 seconds, before attempt 3 is 15 seconds; the third failure is RETRY_EXHAUSTED" processorTimeout "A processor call that takes more than 30 seconds is a failure (PaymentFailed)" inFlightVisible "AUTHORIZATION_REQUESTED is committed before calling the processor, so an attempt in flight is visible to getPaymentStatus"}
enum PaymentStatus { AUTHORIZATION_REQUESTED AUTHORIZED DECLINED FAILED RETRY_EXHAUSTED CAPTURED CAPTURE_FAILED VOIDED /** The processor refused the void; ops release the hold by hand. Terminal. */ VOID_FAILED}
input AuthorizePaymentInput { orderId String required customerId String required customerEmail String required amount BigDecimal required currency String required paymentMethodId String required}
input RetryPaymentInput { orderId String required /** PaymentFailed.attemptCount: the attempt that failed. */ attemptCount Integer required}
input ReauthorizePaymentInput { orderId String required /** PaymentRetried.attemptCount: equals the failed attempt; reauthorize increments it. */ attemptCount Integer required}
input GetPaymentStatusInput { orderId String required}
enum GetPaymentStatusOutcome { NO_PAYMENT STARTED}
/** Exactly one of `noPayment` / `started` is set, according to `outcome`. */output GetPaymentStatusResult { outcome GetPaymentStatusOutcome required noPayment NoPaymentResult started PaymentStartedResult}
output NoPaymentResult { orderId String}
output PaymentStartedResult { orderId String status PaymentStatus}
/** The payment is resolved by orderId (Payment.orderId is unique); fulfillment events carry no paymentId. */input CapturePaymentInput { orderId String required}
/** The payment is resolved by orderId (Payment.orderId is unique); fulfillment events carry no paymentId. */input VoidPaymentInput { orderId String required reason String required}
@rest("/payments")service PaymentsProcessingService for (Payment) {
/** * Creation only: no-op when a Payment for orderId exists, in any state (supersedes P-01 D). * Saves AUTHORIZATION_REQUESTED (attemptCount = 1) and commits before calling the processor, * so getPaymentStatus sees a call in flight; then saves the outcome. * The processor call times out after 30 seconds and becomes PaymentFailed. */ @asyncapi(api: OrdersCheckoutApi, channel: "order-created-event-v1") @transition(to: AUTHORIZATION_REQUESTED) @transition(from: AUTHORIZATION_REQUESTED, to: [AUTHORIZED, DECLINED, FAILED]) authorizePayment(AuthorizePaymentInput) Payment withEvents [PaymentAuthorized | PaymentDeclined | PaymentFailed]
/** * No-op, no event, when there is no Payment (P-12 A), or unless FAILED and input.attemptCount == attemptCount. Saves AUTHORIZATION_REQUESTED with * attemptCount + 1 and commits before calling the processor, as authorizePayment (P-11 A); then saves the outcome. * The processor call times out after 30 seconds and becomes PaymentFailed. */ @asyncapi(channel: "payment-retried-event-v1") @transition(from: FAILED, to: AUTHORIZATION_REQUESTED) @transition(from: AUTHORIZATION_REQUESTED, to: [AUTHORIZED, DECLINED, FAILED]) reauthorizePayment(ReauthorizePaymentInput) Payment? withEvents [PaymentAuthorized | PaymentDeclined | PaymentFailed]
/** * No-op, no event, when there is no Payment (P-12 A), or unless FAILED and input.attemptCount == attemptCount. * Never increments attemptCount. * At most 3 attempts in all (authorize + reauthorize); backoff before the next attempt: 5 seconds * before attempt 2, 15 seconds before attempt 3. RETRY_EXHAUSTED at the limit. */ @asyncapi(channel: "payment-failed-event-v1") @transition(from: FAILED, to: [FAILED, RETRY_EXHAUSTED]) retryPayment(RetryPaymentInput) Payment? withEvents [PaymentRetried | PaymentRetryExhausted]
/** No-op, no event, when CAPTURED, CAPTURE_FAILED or VOIDED (redelivery). */ @asyncapi(api: FulfillmentShippingApi, channel: "fulfillment-scheduled-event-v1") @transition(from: AUTHORIZED, to: [CAPTURED, CAPTURE_FAILED]) capturePayment(CapturePaymentInput) Payment withEvents [PaymentCaptured | PaymentCaptureFailed]
/** * FulfillmentFailed and PaymentCaptureFailed void after a failure downstream; * OrderConfirmationRejected voids an authorization that arrived after expiry or cancellation. * No-op, no event, when there is no Payment or it is not AUTHORIZED or CAPTURE_FAILED (redelivery). */ @asyncapi(api: OrdersCheckoutApi, channel: "order-confirmation-rejected-event-v1") @asyncapi(api: FulfillmentShippingApi, channel: "fulfillment-failed-event-v1") @asyncapi(channel: "payment-capture-failed-event-v1") @transition(from: [AUTHORIZED, CAPTURE_FAILED], to: [VOIDED, VOID_FAILED]) voidPayment(VoidPaymentInput) Payment? withEvents [PaymentVoided | PaymentVoidFailed]
/** Read only, for the reservation timer. STARTED for any existing Payment. */ @post("/status") getPaymentStatus(GetPaymentStatusInput) GetPaymentStatusResult}
rules { authorizedAmountIsOrderTotal "The authorized amount and currency are those of OrderCreated, that is Order.totalAmount and currency" authorizeBeforeCapture "Funds are held at checkout (authorization) and moved only after fulfillment is scheduled (FulfillmentScheduled)" voidRatherThanRefund "When the order cannot be fulfilled after authorization, the hold is voided, never captured and refunded" voidFailedToOps "A refused void (PaymentVoidFailed) is left to ops, who release the hold by hand; the order is cancelled anyway" paymentByOrder "Every command resolves the Payment by orderId; no event of another context carries a paymentId" paymentStartedOwnsEnd "getPaymentStatus answers STARTED for any existing Payment, whatever its state: from then on the reservation timer does nothing"}
@asyncapi({ channel: "payment-authorized-event-v1", topic: "payments-processing.payment-authorized.event.avro.v1" })event PaymentAuthorized { orderId String customerId String amount BigDecimal currency String providerReference String authorizedAt Instant}
@asyncapi({ channel: "payment-declined-event-v1", topic: "payments-processing.payment-declined.event.avro.v1" })event PaymentDeclined { orderId String customerId String amount BigDecimal currency String reason String declinedAt Instant}
@asyncapi({ channel: "payment-failed-event-v1", topic: "payments-processing.payment-failed.event.avro.v1" })event PaymentFailed { orderId String customerId String attemptCount Integer reason String failedAt Instant}
@asyncapi({ channel: "payment-retried-event-v1", topic: "payments-processing.payment-retried.event.avro.v1" })event PaymentRetried { orderId String customerId String attemptCount Integer retriedAt Instant}
@asyncapi({ channel: "payment-retry-exhausted-event-v1", topic: "payments-processing.payment-retry-exhausted.event.avro.v1" })event PaymentRetryExhausted { orderId String customerId String attemptCount Integer reason String exhaustedAt Instant}
@asyncapi({ channel: "payment-captured-event-v1", topic: "payments-processing.payment-captured.event.avro.v1" })event PaymentCaptured { orderId String customerId String customerEmail String amount BigDecimal currency String providerReference String capturedAt Instant}
@asyncapi({ channel: "payment-capture-failed-event-v1", topic: "payments-processing.payment-capture-failed.event.avro.v1" })event PaymentCaptureFailed { orderId String customerId String reason String failedAt Instant}
@asyncapi({ channel: "payment-voided-event-v1", topic: "payments-processing.payment-voided.event.avro.v1" })event PaymentVoided { orderId String customerId String providerReference String reason String voidedAt Instant}
/** Published for ops (manual follow-up) and consumed by releaseStock. */@asyncapi({ channel: "payment-void-failed-event-v1", topic: "payments-processing.payment-void-failed.event.avro.v1" })event PaymentVoidFailed { orderId String customerId String providerReference String reason String failedAt Instant}fulfillment-shipping-api/domain-model.zdl
config { id "urn:com.arcadiaeditions:fulfillment:shipping" version "0.2.0" title "Arcadia Editions - Fulfillment Shipping" basePackage "com.arcadiaeditions.fulfillment.shipping" persistence jpa
plugins { /** Generates an AsyncAPI v3 specification from this ZDL model. */ ZDLToAsyncAPIPlugin { id "urn:com.arcadiaeditions:fulfillment:shipping:asyncapi" applicationExtensions """ x-application-bindings: x-principal: fulfillment_shipping x-clientId: fulfillment_shipping x-groupId: fulfillment_shipping """ schemaFormat avro idType integer idTypeFormat int64 avroPackage com.arcadiaeditions.fulfillment.shipping.events.avro includeCloudEventsHeaders true includeKafkaCommonHeaders true asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-overlay.yml" targetFile "./asyncapi.yml" } ZDLToAsyncAPIClientPlugin { id "urn:com.arcadiaeditions:fulfillment:shipping:asyncapi:client" applicationExtensions """ x-application-bindings: x-principal: fulfillment_shipping x-clientId: fulfillment_shipping x-groupId: fulfillment_shipping """ title "Arcadia Editions - Fulfillment Shipping - AsyncAPI Client" asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-client-overlay.yml" targetFile "./asyncapi-client.yml" } /** Generates an OpenAPI 3.0 specification from this ZDL model. */ ZDLToOpenAPIPlugin { openapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/openapi-overlay.yml" idType integer idTypeFormat int64 targetFile "./openapi.yml" } }}
apis { asyncapi client OrdersCheckoutApi "https://raw.githubusercontent.com/arcadia-editions/orders-checkout-api/main/asyncapi.yml" asyncapi client PaymentsProcessingApi "https://raw.githubusercontent.com/arcadia-editions/payments-processing-api/main/asyncapi.yml"}
@aggregate@lifecycle(field: status, initial: SCHEDULED)entity Fulfillment { fulfillmentId String required unique orderId String required unique customerId String required status FulfillmentStatus required @json shippingAddress ShippingAddress required { name String required line1 String required line2 String city String required region String postalCode String required country String required } @json items FulfillmentItem[] required minlength(1) { sku String required quantity Integer required } carrierCode String trackingNumber String scheduledAt Instant readyAt Instant failedAt Instant failureReason String /** Set from PaymentCaptured; markReadyToShip requires it. */ paymentCapturedAt Instant cancelledAt Instant cancellationReason String}
rules (Fulfillment) { @invariant oneFulfillmentPerOrder "At most one Fulfillment per order" @invariant readyRequiresCapture "A Fulfillment is READY_TO_SHIP only if paymentCapturedAt is set: nothing ships before money moves" @invariant terminalStates "FAILED and CANCELLED are terminal" @invariant failureData "failedAt and failureReason are set if and only if the Fulfillment is FAILED" @invariant cancellationData "cancelledAt and cancellationReason are set if and only if the Fulfillment is CANCELLED" @invariant readyHasTracking "A READY_TO_SHIP Fulfillment has carrierCode, trackingNumber and readyAt" @invariant contentsFixed "items and shippingAddress never change after scheduling" paymentCapturedRecordedOnce "paymentCapturedAt is set once, only while SCHEDULED, and never cleared"}
enum FulfillmentStatus { SCHEDULED READY_TO_SHIP FAILED CANCELLED}
input ScheduleFulfillmentInput { orderId String required customerId String required shippingAddress ShippingAddressInput required items FulfillmentItemInput[] required}
input RecordPaymentCapturedInput { orderId String required /** PaymentCaptured.capturedAt */ capturedAt Instant required}
input CancelFulfillmentInput { orderId String required /** OrderCancelled.reason */ reason String required}
input ShippingAddressInput { name String required line1 String required line2 String city String required region String postalCode String required country String required}
input FulfillmentItemInput { sku String required quantity Integer required}
@rest("/fulfillments")service FulfillmentShippingService for (Fulfillment) {
/** No-op, no event, when a Fulfillment exists for orderId (redelivery). */ @asyncapi(api: OrdersCheckoutApi, channel: "order-confirmed-event-v1") @transition(to: [SCHEDULED, FAILED]) scheduleFulfillment(ScheduleFulfillmentInput) Fulfillment withEvents [FulfillmentScheduled | FulfillmentFailed]
/** * Money moved: the warehouse may now prepare the parcel. Sets paymentCapturedAt; no state change, * no event. No-op when there is no Fulfillment, it is not SCHEDULED, or paymentCapturedAt is set. */ @asyncapi(api: PaymentsProcessingApi, channel: "payment-captured-event-v1") recordPaymentCaptured(RecordPaymentCapturedInput) Fulfillment?
/** Warehouse action. Refused (no transition, no event) until paymentCapturedAt is set. */ @transition(from: SCHEDULED, to: READY_TO_SHIP) markReadyToShip(id) Fulfillment withEvents FulfillmentReadyToShip
/** No-op, no event, when there is no Fulfillment for orderId or it is FAILED or CANCELLED. */ @asyncapi(api: OrdersCheckoutApi, channel: "order-cancelled-event-v1") @transition(from: [SCHEDULED, READY_TO_SHIP], to: CANCELLED) cancelFulfillment(CancelFulfillmentInput) Fulfillment? withEvents FulfillmentCancelled}
rules { scheduleOnlyConfirmedOrders "A Fulfillment is scheduled only for a CONFIRMED order (OrderConfirmed)" contentsFromOrder "items and shippingAddress are those of the confirmed Order" cancelFollowsOrder "A cancelled order stops its Fulfillment: SCHEDULED or READY_TO_SHIP becomes CANCELLED and the warehouse is told (FulfillmentCancelled)" failureVoidsPayment "A Fulfillment that cannot be scheduled (FulfillmentFailed) makes payments void the authorization"}
@asyncapi({ channel: "fulfillment-scheduled-event-v1", topic: "fulfillment-shipping.fulfillment-scheduled.event.avro.v1" })event FulfillmentScheduled { fulfillmentId String orderId String customerId String scheduledAt Instant}
@asyncapi({ channel: "fulfillment-failed-event-v1", topic: "fulfillment-shipping.fulfillment-failed.event.avro.v1" })event FulfillmentFailed { fulfillmentId String orderId String customerId String reason String failedAt Instant}
@asyncapi({ channel: "fulfillment-ready-to-ship-event-v1", topic: "fulfillment-shipping.fulfillment-ready-to-ship.event.avro.v1" })event FulfillmentReadyToShip { fulfillmentId String orderId String customerId String carrierCode String trackingNumber String readyAt Instant}
/** Published for the warehouse; no step of place-order-flow consumes it. */@asyncapi({ channel: "fulfillment-cancelled-event-v1", topic: "fulfillment-shipping.fulfillment-cancelled.event.avro.v1" })event FulfillmentCancelled { fulfillmentId String orderId String customerId String reason String cancelledAt Instant}notifications-consumer-api/domain-model.zdl
config { id "urn:com.arcadiaeditions:notifications:consumer" version "0.2.0" title "Arcadia Editions - Notifications Consumer" basePackage "com.arcadiaeditions.notifications.consumer" persistence jpa
plugins { /** Generates an AsyncAPI v3 specification from this ZDL model. */ ZDLToAsyncAPIPlugin { id "urn:com.arcadiaeditions:notifications:consumer:asyncapi" applicationExtensions """ x-application-bindings: x-principal: notifications_consumer x-clientId: notifications_consumer x-groupId: notifications_consumer """ schemaFormat avro idType integer idTypeFormat int64 avroPackage com.arcadiaeditions.notifications.consumer.events.avro includeCloudEventsHeaders true includeKafkaCommonHeaders true asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-overlay.yml" targetFile "./asyncapi.yml" } ZDLToAsyncAPIClientPlugin { id "urn:com.arcadiaeditions:notifications:consumer:asyncapi:client" applicationExtensions """ x-application-bindings: x-principal: notifications_consumer x-clientId: notifications_consumer x-groupId: notifications_consumer """ title "Arcadia Editions - Notifications Consumer - AsyncAPI Client" asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-client-overlay.yml" targetFile "./asyncapi-client.yml" } /** Generates an OpenAPI 3.0 specification from this ZDL model. */ ZDLToOpenAPIPlugin { openapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/openapi-overlay.yml" idType integer idTypeFormat int64 targetFile "./openapi.yml" } }}
apis { asyncapi client OrdersCheckoutApi "https://raw.githubusercontent.com/arcadia-editions/orders-checkout-api/main/asyncapi.yml" asyncapi client PaymentsProcessingApi "https://raw.githubusercontent.com/arcadia-editions/payments-processing-api/main/asyncapi.yml"}
@aggregate@lifecycle(field: status, initial: PENDING)entity Notification { notificationId String required unique customerId String required orderId String skus String[] type NotificationType required channel NotificationChannel required status NotificationStatus required subject String required body String required recipient String required createdAt Instant required sentAt Instant failedAt Instant failureReason String}
rules (Notification) { @invariant terminalStates "SENT and FAILED are terminal: a Notification is never sent again" @invariant sentData "sentAt is set if and only if the Notification is SENT" @invariant failureData "failedAt and failureReason are set if and only if the Notification is FAILED" @invariant contentFixed "recipient, subject and body never change after creation" @invariant orderBound "ORDER_CONFIRMATION and ORDER_CANCELLED notifications always carry orderId" @invariant unavailableSkus "A STOCK_UNAVAILABLE notification lists at least one sku" onePerOrderAndType "At most one Notification per (orderId, type): a redelivered event does not notify twice"}
enum NotificationType { ORDER_CONFIRMATION STOCK_UNAVAILABLE ORDER_CANCELLED}
enum NotificationChannel { EMAIL SMS PUSH}
enum NotificationStatus { PENDING SENT FAILED}
input SendOrderConfirmationInput { orderId String required customerId String required customerEmail String required}
input SendStockUnavailableNotificationInput { orderId String required customerId String required customerEmail String required unavailableItems StockUnavailableItemInput[] required minlength(1) { sku String required requestedQuantity Integer availableQuantity Integer }}
input SendOrderCancelledNotificationInput { orderId String required customerId String required reason String required customerEmail String required}
@rest("/notifications")service NotificationsConsumerService for (Notification) {
@asyncapi(api: PaymentsProcessingApi, channel: "payment-captured-event-v1") @transition(to: [SENT, FAILED]) sendOrderConfirmation(SendOrderConfirmationInput) Notification withEvents [OrderConfirmationSent | NotificationDeliveryFailed]
@asyncapi(api: OrdersCheckoutApi, channel: "stock-unavailable-event-v1") @transition(to: [SENT, FAILED]) sendStockUnavailableNotification(SendStockUnavailableNotificationInput) Notification withEvents [StockUnavailableNotificationSent | NotificationDeliveryFailed]
@asyncapi(api: OrdersCheckoutApi, channel: "order-cancelled-event-v1") @transition(to: [SENT, FAILED]) sendOrderCancelledNotification(SendOrderCancelledNotificationInput) Notification withEvents [OrderCancelledNotificationSent | NotificationDeliveryFailed]}
rules { confirmationOnlyAfterCapture "The order confirmation is sent only after the payment is captured (PaymentCaptured), never at authorization" recipientIsCustomer "The recipient of every notification is the customerEmail given at checkout" cancellationTellsWhy "An order cancelled notification says why the order was cancelled" voidFailedWarnsHold "When the reason is PAYMENT_VOID_FAILED, the cancellation message says the hold may still show until it is released" failureNamesOutcome "NotificationDeliveryFailed.type says which business outcome the customer was not told"}
@asyncapi({ channel: "order-confirmation-sent-event-v1", topic: "notifications-consumer.order-confirmation-sent.event.avro.v1" })event OrderConfirmationSent { notificationId String orderId String customerId String channel NotificationChannel recipient String sentAt Instant}
@asyncapi({ channel: "stock-unavailable-notification-sent-event-v1", topic: "notifications-consumer.stock-unavailable-notification-sent.event.avro.v1" })event StockUnavailableNotificationSent { notificationId String orderId String customerId String skus String[] channel NotificationChannel recipient String sentAt Instant}
@asyncapi({ channel: "order-cancelled-notification-sent-event-v1", topic: "notifications-consumer.order-cancelled-notification-sent.event.avro.v1" })event OrderCancelledNotificationSent { notificationId String orderId String customerId String reason String channel NotificationChannel recipient String sentAt Instant}
/** Ends place-order-flow as notificationFailed; `type` tells which business outcome the customer was not told. */@asyncapi({ channel: "notification-delivery-failed-event-v1", topic: "notifications-consumer.notification-delivery-failed.event.avro.v1" })event NotificationDeliveryFailed { notificationId String orderId String customerId String skus String[] type NotificationType channel NotificationChannel recipient String reason String failedAt Instant}Contracts generated from the model
Section titled “Contracts generated from the model”The API repository runs ZDLToAsyncAPIPlugin, ZDLToAsyncAPIClientPlugin and ZDLToOpenAPIPlugin from the config block of the ZDL. Shared servers, traits and bindings come from overlays in api-contract-commons:
orders-checkout-api/domain-model.zdl: config
config { id "urn:com.arcadiaeditions:orders:checkout" version "0.2.0" title "Arcadia Editions - Orders Checkout" basePackage "com.arcadiaeditions.orders.checkout" persistence jpa
plugins { /** Generates an AsyncAPI v3 specification from this ZDL model. */ ZDLToAsyncAPIPlugin { id "urn:com.arcadiaeditions:orders:checkout:asyncapi" applicationExtensions """ x-application-bindings: x-principal: orders_checkout x-clientId: orders_checkout x-groupId: orders_checkout """ schemaFormat avro idType integer idTypeFormat int64 avroPackage com.arcadiaeditions.orders.checkout.events.avro includeCloudEventsHeaders true includeKafkaCommonHeaders true asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-overlay.yml" targetFile "./asyncapi.yml" } ZDLToAsyncAPIClientPlugin { id "urn:com.arcadiaeditions:orders:checkout:asyncapi:client" applicationExtensions """ x-application-bindings: x-principal: orders_checkout x-clientId: orders_checkout x-groupId: orders_checkout """ title "Arcadia Editions - Orders Checkout - AsyncAPI Client" asyncapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-client-overlay.yml" targetFile "./asyncapi-client.yml" } /** Generates an OpenAPI 3.0 specification from this ZDL model. */ ZDLToOpenAPIPlugin { openapiOverlayFiles "https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/openapi-overlay.yml", "./openapi-overlay.yml" idType integer idTypeFormat int64 targetFile "./openapi.yml" } }}An event annotated with @asyncapi:
orders-checkout-api/domain-model.zdl
@asyncapi({ channel: "order-created-event-v1", topic: "orders-checkout.order-created.event.avro.v1" })event OrderCreated { orderId String version Integer customerId String customerEmail String paymentMethodId String /** Order total (Order.totalAmount), named to match AuthorizePaymentInput. */ amount BigDecimal currency String}becomes a channel bound to a Kafka topic, with an Avro payload, in asyncapi.yml:
orders-checkout-api/asyncapi.yml
channels: order-created-event-v1: address: orders-checkout.order-created.event.avro.v1 messages: OrderCreatedEvent: $ref: "#/components/messages/OrderCreatedEvent" x-traits: - $ref: https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-channel-traits.yml#/components/channelTraits/kafkaTopicS - $ref: https://raw.githubusercontent.com/arcadia-editions/api-contract-commons/refs/heads/main/asyncapi-channel-traits.yml#/components/channelTraits/kafkaTopicRetained x-visibility: globalThe contracts are released as a Maven artifact (service-all) that the service repository imports.
ZenWave scripts
Section titled “ZenWave scripts”The service repository generates nothing into src/main/resources/public/apis: it reads the model and the contracts from the released package.
orders-checkout-service-java/zenwave-scripts.zw
@import("com.arcadiaeditions.orders.checkout.orders-checkout:service-all:0.2.0")// ZenWave Scripts File (.zw): plugins and configuration for ZenWave SDK code generation.//// The models and API contracts are owned by the orders-checkout-api repository and read from// its released service-all package (keep the version in sync with pom.xml orders-checkout-api.version). Nothing is generated into src/main/resources/public/apis:// the OpenAPI/AsyncAPI contracts are produced in that repository from its domain-model.zdl.//// Usage: Play button in the ZenWave IDE plugin, or copy the command line shown on hover.config {
zdlFile "classpath:/com/arcadiaeditions/orders/checkout/orders-checkout/domain-model.zdl" databaseType postgresql
layout CleanHexagonalProjectLayout // Package properties (openApi*, entities, core, adapters...) are derived from basePackage and the layout. // The generated AsyncAPI SDK lives outside the hexagon (asyncapi.provider / asyncapi.client), so the // asyncApi* layout values are overridden below. Keep the pom.xml properties openApiApiPackage, // openApiModelPackage, asyncApiModelPackage and asyncApiProducerApiPackage in sync with the layout values. openApiModelNameSuffix DTO
plugins { /** Generates a Backend Application from the ZDL model. (Headless Core) */ BackendApplicationDefaultPlugin { useLombok false useJSpecify true includeEmitEventsImplementation true layout.asyncApiModelPackage "{{basePackage}}.events.avro" layout.asyncApiProducerApiPackage "{{basePackage}}.asyncapi.provider" layout.asyncApiConsumerApiPackage "{{basePackage}}.asyncapi.provider" // --force // overwite all files } /** Generates Spring MVC controllers from the OpenAPI specification (Web Adapters). */ OpenAPIControllersPlugin { openapiFile "classpath:/com/arcadiaeditions/orders/checkout/orders-checkout/openapi.yml" } /** Generates API tests from the OpenAPI specification. */ SpringWebTestClientPlugin { openapiFile "classpath:/com/arcadiaeditions/orders/checkout/orders-checkout/openapi.yml" } }}On every build, zenwave-sdk-maven-plugin with the AsyncAPI generator generates the Kafka producers and consumer interfaces into target/generated-sources/zenwave: asyncapi.yml into asyncapi.provider and asyncapi-client.yml into asyncapi.client.
orders-checkout-service-java/pom.xml: AsyncAPI generator
<plugin> <groupId>io.zenwave360.sdk</groupId> <artifactId>zenwave-sdk-maven-plugin</artifactId> <version>${zenwave.version}</version> <configuration> <inputSpec>${asyncapi.inputSpec}</inputSpec> <skip>false</skip> <addCompileSourceRoot>true</addCompileSourceRoot> <addTestCompileSourceRoot>true</addTestCompileSourceRoot> <!-- <authentication> --> <!-- <authentication><key>API_KEY</key><value>XXX</value></authentication> --> <!-- </authentication> --> </configuration> <executions> <execution> <id>generate-asyncapi</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <generatorName>AsyncAPIGenerator</generatorName> <configOptions> <role>provider</role> <!-- payloads are avro: <modelPackage> (${asyncApiModelPackage}) is only needed for json-schema payloads --> <producerApiPackage>${asyncApiProducerApiPackage}</producerApiPackage> <consumerApiPackage>${asyncApiConsumerApiPackage}</consumerApiPackage> <avroCompilerProperties.imports>${asyncapi.avro.imports}</avroCompilerProperties.imports> </configOptions> </configuration> </execution> <execution> <id>generate-asyncapi-client</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${asyncapi.client.inputSpec}</inputSpec> <generatorName>AsyncAPIGenerator</generatorName> <configOptions> <!-- asyncapi-client.yml is written from this service's point of view (action: receive), so it is generated as provider --> <role>provider</role> <producerApiPackage>${asyncApiClientApiPackage}</producerApiPackage> <consumerApiPackage>${asyncApiClientApiPackage}</consumerApiPackage> <avroCompilerProperties.imports>${asyncapi.client.avro.imports}</avroCompilerProperties.imports> </configOptions> </configuration> </execution> </executions>Generated code
Section titled “Generated code”A consumer of payment-authorized-event-v1 implements the interface generated from asyncapi-client.yml and calls the inbound port:
PaymentAuthorizedConsumerService.java
/** * Inbound adapter: payment-authorized-event-v1 -> OrdersCheckoutService.confirmOrder. */@Componentpublic class PaymentAuthorizedConsumerService implements IPaymentAuthorizedEventV1ConsumerService {
private final OrdersCheckoutService ordersCheckoutService;
public PaymentAuthorizedConsumerService(OrdersCheckoutService ordersCheckoutService) { this.ordersCheckoutService = ordersCheckoutService; }
@Override public void onPaymentAuthorizedEventV1(PaymentAuthorized payload, PaymentAuthorizedHeaders headers) { ordersCheckoutService.confirmOrder( new ConfirmOrderInput().setOrderId(payload.getOrderId().toString())); }}The service implementation publishes events through the producer generated from asyncapi.yml, and reserves stock with a synchronous call to Catalog Inventory behind an outbound port:
OrdersCheckoutServiceImpl.java: startOrderCheckout
public Order startOrderCheckout(StartOrderCheckoutInput input) {
log.debug("Request startOrderCheckout: {}", input);
var orderId = orderIdGenerator.nextOrderId(); var reservation = inventoryClient.reserveStock( orderId, input.getItems().stream() .map(item -> new ReserveStockItem(item.getSku(), item.getQuantity())) .toList()); if (reservation instanceof StockUnavailableResult unavailable) { // nothing persisted: only the event, and the exception the web adapter answers 409 from eventsProducer.onStockUnavailable( eventsMapper.asStockUnavailable(input, orderId, unavailable.unavailableItems())); throw new StockUnavailableException( orderId, unavailable.unavailableItems().stream() .map(line -> new StockUnavailableException.Line( line.sku(), line.requestedQuantity(), line.availableQuantity())) .toList()); }
var order = ordersCheckoutServiceMapper.update(new Order(), input); order.setOrderId(orderId); order.setStatus(OrderStatus.CREATED); order.setCreatedAt(Instant.now(clock)); order.setTotalAmount(input.getItems().stream() .map(item -> item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity()))) .reduce(BigDecimal.ZERO, BigDecimal::add)); order = orderRepository.saveAndFlush(order); // emit events var orderCreated = eventsMapper.asOrderCreated(order); eventsProducer.onOrderCreated(orderCreated); return order; }Most of the flow goes through Kafka events. Two steps call another service over HTTP and wait for the result:
| Caller | Step (ZFL) | Calls |
|---|---|---|
| Orders Checkout | startOrderCheckout, confirmOrder | Catalog Inventory reserveStock, confirmStockReservation |
| Catalog Inventory | expireReservation | Payments Processing getPaymentStatus |
Each client is a Spring @HttpExchange interface generated from the callee’s openapi.yml, behind an outbound-port adapter.
How to run
Section titled “How to run”Requirements: Git Bash, Java 25, Maven, Docker.
git clone https://github.com/arcadia-editions/arcadia-editions-microservices-compose.git
cd arcadia-editions-microservices-compose
./checkout.sh # clones every service next to this repo (or pulls if already there)
./build-images.sh # mvn -DskipTests spring-boot:build-image in each one
docker compose up -d
The compose file starts PostgreSQL (one database per service), Kafka, Zookeeper, Schema Registry and the five services. Swagger UI is at http://localhost:<port>/swagger-ui/index.html for each service port in the table above. HTTP basic auth: admin / password.
Follow the events in one terminal:
./log-events.sh # all <service>.<event>.event.avro.v1 topics, from the beginning
Put a product in stock and place an order in another:
# 1. stock (Catalog Inventory)
curl -s -u admin:password -X POST http://localhost:8102/api/inventory/positions \
-H 'Content-Type: application/json' \
-d '{"sku": "BOOK-001", "initialQuantity": 10}'
# 2. checkout (Orders Checkout): 201 with the Order (status CREATED), or 409 if stock is short
curl -s -u admin:password -X POST http://localhost:8101/api/orders/start-checkout \
-H 'Content-Type: application/json' \
-d '{
"customerId": "customer-1",
"customerEmail": "customer@example.com",
"paymentMethodId": "pm-visa-1",
"currency": "EUR",
"items": [{"sku": "BOOK-001", "quantity": 2, "unitPrice": 19.95}],
"shippingAddress": {"name": "Jane Doe", "line1": "Calle Mayor 1", "city": "Madrid", "postalCode": "28013", "country": "ES"}
}'
# 3. the order is CONFIRMED once the flow ends ({id} is the numeric "id" of the response, not orderId)
curl -s -u admin:password http://localhost:8101/api/orders/1
Expected events:
[orders-checkout.order-created.event.avro.v1] ...
[payments-processing.payment-authorized.event.avro.v1] ...
[catalog-inventory.stock-reservation-confirmed.event.avro.v1] ...
[orders-checkout.order-confirmed.event.avro.v1] ...
[fulfillment-shipping.fulfillment-scheduled.event.avro.v1] ...
[payments-processing.payment-captured.event.avro.v1] ...
See the compose README for ports, environment variables and useful commands.