A checkout usually starts as one service calling the next: sales calls inventory, inventory calls orders, orders calls payments. It works until one of them is slow, down, or needs a second consumer. Then every caller has to know about every callee.

In ventas-kafka-spark I took the opposite route. One sale goes through five services (sales, inventory, order, payment, delivery) and none of them calls another one. Each service listens to one Kafka topic, does its job and publishes the next event. When the sale is done, a separate Apache Spark job reads the payments and prints a summary per product.

The whole thing runs with one command (./start.sh), and the repo includes sequence diagrams in English and español.

The problem with a chain of calls

With synchronous calls, the sales service owns the whole flow. It has to know the address of inventory, wait for it, handle its errors, then do the same for orders, payments and delivery. Adding analytics means touching that chain again.

Event choreography flips the ownership. Each service only knows two things: the topic it reads and the topic it writes. The flow is the sum of those small contracts:

Step Service Consumes Publishes
1 sales — sale.created
2 inventory sale.created inventory.reserved
3 order inventory.reserved order.created
4 payment order.created payment.processed
5 delivery payment.processed delivery.scheduled
6 monitor delivery.scheduled —
6' analytics (Spark) payment.processed console

Notice payment.processed: it has two readers. Delivery reads it during the sale, and Spark reads it later. Neither of them knows the other exists, and the payment service did not change to make that happen.

The sample sale

Said buys, in a single sale:

SKU Product Qty Unit price (before VAT) Subtotal
PLY-AZUL-M Blue t-shirt 2 $50.00 $100.00
LEV-502-AZUL Levi's 502 jeans 1 $600.00 $600.00

With Mexico's 16% VAT that becomes $700.00 + $112.00 = $812.00.

The event contracts

All messages are Java records serialized as JSON. A sale has lines, so every event carries them along:

public final class Eventos { /** One line of the purchase: product, quantity and unit price before VAT. */ public record Linea(String sku, String producto, int cantidad, BigDecimal precioUnitario) {} /** Published by sales when the purchase is registered. */ public record VentaCreada(String ventaId, String cliente, List<Linea> lineas) {} /** Published by inventory when every line is reserved. */ public record InventarioReservado(String ventaId, String cliente, List<Linea> lineas) {} /** Published by orders with the subtotal of all lines. */ public record OrdenCreada(String ordenId, String ventaId, List<Linea> lineas, BigDecimal subtotal) {} /** Published by payments, with VAT per line and in total. */ public record PagoProcesado(String pagoId, String ordenId, String ventaId, List<LineaPagada> lineas, BigDecimal subtotal, BigDecimal iva, BigDecimal total) {} // ... } 

Records keep the contracts small and immutable, and Spring Kafka's JsonSerializer / JsonDeserializer handle them without extra code. The only setting worth calling out is the trusted package for the deserializer, plus earliest so no consumer misses an event published before it subscribed:

spring: kafka: consumer: value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer auto-offset-reset: earliest properties: spring.json.trusted.packages: com.josesaid.simulacion.common 

One service, one listener

Every service has the same shape: a @KafkaListener on its input topic with its own groupId, some work, and a kafka.send to the next topic. Here is the order service:

@Component public class OrdenService { private final KafkaTemplate<String, Object> kafka; public OrdenService(KafkaTemplate<String, Object> kafka) { this.kafka = kafka; } @KafkaListener(topics = Topicos.INVENTARIO_RESERVADO, groupId = "orden") public void alReservar(Eventos.InventarioReservado reserva) { String ordenId = "ORD-" + UUID.randomUUID().toString().substring(0, 8); BigDecimal subtotal = reserva.lineas().stream() .map(l -> l.precioUnitario().multiply(BigDecimal.valueOf(l.cantidad()))) .reduce(BigDecimal.ZERO, BigDecimal::add) .setScale(2, RoundingMode.HALF_UP); var evento = new Eventos.OrdenCreada(ordenId, reserva.ventaId(), reserva.lineas(), subtotal); kafka.send(Topicos.ORDEN_CREADA, ordenId, evento); } } 

The separate groupId per service matters: it is what lets delivery and Spark both read payment.processed in full, instead of splitting the messages between them.

Inventory: all or nothing

Inventory is the only step where a sale can stop. It checks every line first, and only then decrements stock. If one line does not fit, nothing changes:

@KafkaListener(topics = Topicos.VENTA_CREADA, groupId = "inventario") public void alVender(Eventos.VentaCreada venta) { for (Eventos.Linea linea : venta.lineas()) { int disponible = stock.getOrDefault(linea.sku(), 0); if (disponible < linea.cantidad()) { log.warn("[INVENTARIO] Sin stock para {} (disponible {}, pedido {}). Venta {} rechazada", linea.sku(), disponible, linea.cantidad(), venta.ventaId()); return; // nothing was decremented } } venta.lineas().forEach(l -> stock.merge(l.sku(), -l.cantidad(), Integer::sum)); kafka.send(Topicos.INVENTARIO_RESERVADO, venta.ventaId(), new Eventos.InventarioReservado(venta.ventaId(), venta.cliente(), venta.lineas())); } 

A common mistake is to decrement inside the first loop. With two lines, the first one would be reserved and the second rejected, leaving stock out of sync with a sale that never happened.

There is a trade-off here, and the demo leaves it visible on purpose: a rejected sale publishes no event. Order, payment and delivery never hear about it. In a real system you would publish something like inventory.rejected so the sale can be closed and the customer notified. The "out of stock" sequence diagram shows exactly what happens instead: the flow just waits until it times out.

Payment: VAT per line with BigDecimal

The payment service recomputes each line and applies 16% VAT. Money is BigDecimal with an explicit scale and rounding mode, never double:

public final class CalculadoraIva { public static final BigDecimal TASA = new BigDecimal("0.16"); public static BigDecimal iva(BigDecimal subtotal) { return subtotal.multiply(TASA).setScale(2, RoundingMode.HALF_UP); } public static BigDecimal total(BigDecimal subtotal) { return subtotal.add(iva(subtotal)); } } 

Per line that gives $16.00 and $96.00; for the whole sale, $112.00 and a total of $812.00. Keeping the per-line values in the event means analytics can group by product later without redoing any tax math.

Knowing when the flow is done

Since nobody calls anybody, how does main know the sale is finished? A small monitor listens to the last topic and releases a CountDownLatch:

@Component public class MonitorFlujo { private final CountDownLatch fin = new CountDownLatch(1); @KafkaListener(topics = Topicos.ENTREGA_PROGRAMADA, groupId = "monitor-flujo") public void alProgramarEntrega(Eventos.EntregaProgramada entrega) { fin.countDown(); } public boolean esperarFin(Duration tiempoMaximo) throws InterruptedException { return fin.await(tiempoMaximo.toMillis(), TimeUnit.MILLISECONDS); } } 

main registers the sale, waits up to 60 seconds, prints the outcome and closes the Spring context. That is what lets the simulation run as a short-lived container instead of a server.

Analytics with Spark Structured Streaming

Spark runs in its own container, after the simulation has finished. It reads payment.processed from the beginning, flattens the lines and groups by product:

Dataset<Row> pagos = spark.readStream() .format("kafka") .option("kafka.bootstrap.servers", bootstrap) .option("subscribe", "payment.processed") .option("startingOffsets", "earliest") .load() .select(from_json(col("value").cast("string"), esquema).as("p")) .select("p.*"); Dataset<Row> resumen = pagos .select(explode(col("lineas")).as("l")) .select("l.*") .groupBy("producto") .agg(sum("cantidad").as("unidades"), sum("subtotal").as("subtotal"), sum("iva").as("iva_recaudado"), sum("total") /* ...and the total per product */); resumen.writeStream() .outputMode("complete") .format("console") .trigger(Trigger.AvailableNow()) // process what is there, then stop .start() .awaitTermination(); 

Trigger.AvailableNow() is the key piece for a batch-like job: it processes everything currently in the topic and then stops, instead of listening forever. The output is two rows: the t-shirts (2 units, $116.00) and the jeans (1 unit, $696.00).

Two details that bite if you skip them:

  • The schema must match the records. from_json does not fail on a misnamed field; it just returns null, and your totals quietly become empty.
  • Spark 4 on Java 21 needs --add-opens. The Dockerfile passes them to the JVM; without them Spark fails at startup with module access errors.

Running it: order matters

start.sh makes the run reproducible:

  1. docker compose down -v: start clean. Since Spark reads from earliest, an old Kafka volume would add payments from previous runs.
  2. docker compose build.
  3. docker compose up -d --wait kafka: wait until Kafka's healthcheck passes.
  4. docker compose run --rm simulacion: create the topics and run the sale.
  5. docker compose run --rm analitica: run Spark and print the table.

Kafka keeps running afterwards; ./stop.sh removes everything. The startup sequence diagram walks through each step.

Best practices from this demo

  • One topic per business fact, named in the past tense (sale.created, payment.processed). Consumers subscribe to facts, not to commands.
  • One groupId per service, so every service sees every event.
  • Use the business id as the message key (ventaId, ordenId, pagoId) so related events stay in order within a partition.
  • Validate everything before changing state, as inventory does.
  • Publish failures too. The demo does not, and the out-of-stock scenario shows the cost.
  • Keep money in BigDecimal with explicit scale and rounding.

Known limits

This is a simulation, not a production system. The five services live in one Spring Boot app (as separate classes that share nothing but Kafka), stock is in memory, and there are no retries, dead-letter topics or idempotent consumers. Those are the natural next steps, and they are much easier to add when each service already owns a single topic.

Wrapping up

One sale, five services, five topics, and zero REST calls between them. Each service is small enough to read in a minute, the flow is visible in Kafka, and adding analytics was one more consumer instead of one more call in the chain.

Stack: Java 21, Spring Boot 3.4.1 with spring-kafka, Apache Kafka 3.8 (KRaft), Apache Spark 4.0, Maven and Docker Compose.