Skip to content

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.
ServiceAPI repositoryService repositoryHTTP port
Orders Checkoutorders-checkout-apiorders-checkout-service-java8101
Catalog Inventorycatalog-inventory-apicatalog-inventory-service-java8102
Payments Processingpayments-processing-apipayments-processing-service-java8103
Fulfillment Shippingfulfillment-shipping-apifulfillment-shipping-service-java8104
Notifications Consumernotifications-consumer-apinotifications-consumer-service-java8105

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.

Arcadia Editions microservices: services, aggregates and how they talk

This page walks through Orders Checkout. The other four follow the same structure.

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
}

Navigate to source

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"
}

Navigate to source

The service-level rules, which span the Order and the calls to Catalog Inventory:

orders-checkout-api/domain-model.zdl: rules

Navigate to source

The only modulith rule not ported is limitedEdition in Catalog Inventory. It needs Product.editionSize, which the microservice does not hold.

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?
}

Navigate to source

orders-checkout-api/domain-model.zdl: apis

Navigate to source

orders-checkout-api/domain-model.zdl

Navigate to source

catalog-inventory-api/domain-model.zdl

Navigate to source

payments-processing-api/domain-model.zdl

Navigate to source

fulfillment-shipping-api/domain-model.zdl

Navigate to source

notifications-consumer-api/domain-model.zdl

Navigate to source

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

Navigate to source

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
}

Navigate to source

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: global

Navigate to source

orders-checkout-api/asyncapi.yml: send operation

Navigate to source

The contracts are released as a Maven artifact (service-all) that the service repository imports.

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"
}
}
}

Navigate to source

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

Navigate to source

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.
*/
@Component
public 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()));
}
}

Navigate to source

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;
}

Navigate to source

Most of the flow goes through Kafka events. Two steps call another service over HTTP and wait for the result:

CallerStep (ZFL)Calls
Orders CheckoutstartOrderCheckout, confirmOrderCatalog Inventory reserveStock, confirmStockReservation
Catalog InventoryexpireReservationPayments Processing getPaymentStatus

Each client is a Spring @HttpExchange interface generated from the callee’s openapi.yml, behind an outbound-port adapter.

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.