Project 1: Event-Driven Order System with Spring Boot, Kafka and Docker Compose

Apache Kafka 25 min min read Updated: Nov 17, 2026 Intermediate
Project 1: Event-Driven Order System with Spring Boot, Kafka and Docker Compose
Intermediate Topic 1 of 3

What We Build

text client --POST /orders--> [order-service] --OrderCreated--> topic shop.orders.created.v1 | [payment-service] <------+ charges, then publishes | PaymentCompleted / PaymentFailed --> topic shop.payments.result.v1 v [order-service] <---- consumes result, sets CONFIRMED or CANCELLED --> publishes OrderConfirmed / OrderCancelled [notification-service] <---- consumes shop.orders.status.v1 and sends emails (logged in this demo)
ServicePortProducesConsumes
order-service8081shop.orders.created.v1, shop.orders.status.v1shop.payments.result.v1
payment-service8082shop.payments.result.v1shop.orders.created.v1
notification-service8083-shop.orders.status.v1

Step 1: Kafka with Docker Compose (KRaft)

yaml # docker-compose.yml services: kafka: image: apache/kafka:latest container_name: kafka ports: ["9092:9092"] environment: KAFKA_NODE_ID: 1 KAFKA_PROCESS_ROLES: broker,controller KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093 KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092 KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 KAFKA_AUTO_CREATE_TOPICS_ENABLE: "false" kafka-ui: image: provectuslabs/kafka-ui:latest ports: ["8080:8080"] environment: KAFKA_CLUSTERS_0_NAME: local KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:9092 depends_on: [kafka]
bash docker compose up -d for t in shop.orders.created.v1 shop.payments.result.v1 shop.orders.status.v1 ; do docker exec kafka /opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic $t --partitions 3 done docker exec kafka /opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --list

Step 2: Shared Event Classes

Keep events in a small shared library (or copy the records into each service). Use records with a type and eventId for idempotency.

java public record OrderCreated(String eventId, String orderId, String customerId, double total) {} public record PaymentResult(String eventId, String orderId, boolean success, String reason) {} public record OrderStatus(String eventId, String orderId, String status, String customerId) {}

Step 3: order-service

yaml # application.yml server: { port: 8081 } spring: datasource: { url: "jdbc:h2:mem:orders", driver-class-name: org.h2.Driver } jpa: { hibernate: { ddl-auto: update } } kafka: bootstrap-servers: localhost:9092 producer: key-serializer: org.apache.kafka.common.serialization.StringSerializer value-serializer: org.springframework.kafka.support.serializer.JsonSerializer acks: all properties: { enable.idempotence: true, spring.json.add.type.headers: false } consumer: group-id: order-service auto-offset-reset: earliest key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer properties: spring.deserializer.value.delegate.class: org.springframework.kafka.support.serializer.JsonDeserializer spring.json.value.default.type: com.example.shop.events.PaymentResult spring.json.trusted.packages: com.example.shop.events
java @Entity @Table(name = "orders") public class OrderEntity { @Id private String id; private String customerId; private double total; private String status; // NEW, CONFIRMED, CANCELLED // constructors, getters, setters } @RestController @RequestMapping("/orders") public class OrderController { private final OrderService service; OrderController(OrderService service) { this.service = service; } @PostMapping public ResponseEntity<Map<String, String>> create(@RequestBody CreateOrderRequest req) { String id = service.createOrder(req.customerId(), req.total()); return ResponseEntity.accepted().body(Map.of("orderId", id, "status", "NEW")); // 202: processing continues asynchronously } @GetMapping("/{id}") public OrderEntity get(@PathVariable String id) { return service.find(id); } } @Service public class OrderService { private final OrderRepository repo; private final KafkaTemplate<String, Object> kafka; public String createOrder(String customerId, double total) { String id = UUID.randomUUID().toString(); repo.save(new OrderEntity(id, customerId, total, "NEW")); kafka.send("shop.orders.created.v1", id, new OrderCreated(UUID.randomUUID().toString(), id, customerId, total)); return id; // note: dual write, see the improvement list at the end } @KafkaListener(topics = "shop.payments.result.v1") @Transactional public void onPayment(PaymentResult result) { OrderEntity order = repo.findById(result.orderId()).orElseThrow(); if (!"NEW".equals(order.getStatus())) return; // idempotent: already handled order.setStatus(result.success() ? "CONFIRMED" : "CANCELLED"); repo.save(order); kafka.send("shop.orders.status.v1", order.getId(), new OrderStatus(UUID.randomUUID().toString(), order.getId(), order.getStatus(), order.getCustomerId())); } }

Step 4: payment-service

java @Component public class PaymentListener { private static final Logger log = LoggerFactory.getLogger(PaymentListener.class); private final KafkaTemplate<String, Object> kafka; private final Set<String> processed = ConcurrentHashMap.newKeySet(); // demo only: use a database table in real systems PaymentListener(KafkaTemplate<String, Object> kafka) { this.kafka = kafka; } @KafkaListener(topics = "shop.orders.created.v1", groupId = "payment-service") public void onOrder(OrderCreated order) { if (!processed.add(order.eventId())) return; // idempotent consumer boolean ok = order.total() <= 1000; // fake rule: big orders are declined log.info("Payment for {} -> {}", order.orderId(), ok ? "OK" : "DECLINED"); kafka.send("shop.payments.result.v1", order.orderId(), new PaymentResult(UUID.randomUUID().toString(), order.orderId(), ok, ok ? null : "limit exceeded")); } }

Step 5: notification-service with Retry and DLT

java @Component public class NotificationListener { @RetryableTopic(attempts = "3", backoff = @Backoff(delay = 2000, multiplier = 2.0)) @KafkaListener(topics = "shop.orders.status.v1", groupId = "notification-service") public void onStatus(OrderStatus status) { if ("CONFIRMED".equals(status.status())) { sendEmail(status.customerId(), "Order " + status.orderId() + " confirmed"); // call an email provider here } else { sendEmail(status.customerId(), "Order " + status.orderId() + " was cancelled"); } } @DltHandler public void dead(OrderStatus status) { log.error("Giving up on notification for {}", status.orderId()); } private void sendEmail(String customer, String text) { log.info("EMAIL to {}: {}", customer, text); } }

Step 6: Run and Test the Flow

bash # start the three services (separate terminals) cd order-service && ./mvnw spring-boot:run cd payment-service && ./mvnw spring-boot:run cd notification-service && ./mvnw spring-boot:run # create a normal order and a big order curl -s -X POST localhost:8081/orders -H 'Content-Type: application/json' -d '{"customerId":"c-7","total":59.9}' curl -s -X POST localhost:8081/orders -H 'Content-Type: application/json' -d '{"customerId":"c-8","total":2500}' # expected logs # payment-service: Payment for <id1> -> OK ; Payment for <id2> -> DECLINED # notification-service: EMAIL to c-7: Order <id1> confirmed ; EMAIL to c-8: Order <id2> was cancelled curl -s localhost:8081/orders/<id1> # status CONFIRMED # watch the topics docker exec kafka /opt/kafka/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic shop.orders.status.v1 --from-beginning --property print.key=true

Step 7: Check Failure Behaviour

  1. Stop payment-service, create three orders, start it again. It reads the backlog from its committed offset, so nothing is lost
  2. Check lag while it is stopped: kafka-consumer-groups.sh --describe --group payment-service
  3. Make sendEmail throw an exception and watch retry topics (shop.orders.status.v1-retry-0, ...) and finally the DLT
  4. Run two instances of payment-service and see partitions split between them (rebalance log lines)
  5. Send the same OrderCreated message twice with the console producer and confirm only one payment result appears

Improvements to Practice

Weakness in the demoBetter design
Order is saved and event is sent as two stepsUse the outbox pattern (Debezium) or Kafka transactions plus idempotent handling
In-memory processed setDatabase table with unique event_id, in the same transaction as the business change
JSON without schemaAvro and Schema Registry with a compatibility mode
No securitySASL_SSL and ACLs per service
No metricsActuator, Micrometer, Prometheus, a lag dashboard
No timeout for missing payment resultsScheduled job that cancels orders still NEW after 15 minutes (saga timeout)
Single broker3 brokers, replication factor 3, min.insync.replicas=2

Conclusion

You built a working event-driven system: three Spring Boot services connected by Kafka topics, keyed by order id, with idempotent consumers, retry topics and a dead letter topic, and you tested failure and replay behaviour.

Quick Summary: order -> payment -> status -> notification; key=orderId; idempotent handlers; retry + DLT; test by stopping a service.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators