<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by ivan willy artdian on Medium]]></title>
        <description><![CDATA[Stories by ivan willy artdian on Medium]]></description>
        <link>https://medium.com/@ivan.willy.artdian?source=rss-e3ef95064fc1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u4VynxJ_8d0POjGmBp0-4g.jpeg</url>
            <title>Stories by ivan willy artdian on Medium</title>
            <link>https://medium.com/@ivan.willy.artdian?source=rss-e3ef95064fc1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:51:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivan.willy.artdian/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Gradle and Maven in the Same Monorepo]]></title>
            <link>https://medium.com/@ivan.willy.artdian/gradle-and-maven-in-the-same-monorepo-74de682e547e?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/74de682e547e</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 08:27:29 GMT</pubDate>
            <atom:updated>2026-07-13T08:27:29.821Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 11 of the Spring Boot Microservices in Production series.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8AJ9fXPfihKMIcmUbXbBA.png" /></figure><p>Ten services. No root build file. You need to share protobuf-generated gRPC stubs and Kafka event records across all of them.</p><p>That’s the actual constraint this monorepo was built around. Not a theoretical question about which build tool is more expressive — a concrete problem: how do you distribute shared artifacts when each service manages its own build in isolation?</p><p>The answer here was to use both tools, each where its strengths are actually needed.</p><h3>How the Monorepo Is Laid Out</h3><p>There is no root settings.gradle or pom.xml. No central build orchestrator. Each service builds independently. Shared code lives in libs/ and gets distributed via Maven Local.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgHIORDVmECf_1u5fzwF4g.png" /></figure><h3>The Shared Libraries</h3><p>common-events holds Kafka event records. common-proto holds protobuf definitions and generates gRPC stubs at build time. Both are Gradle projects.</p><p>The reason is straightforward: the com.google.protobuf Gradle plugin is mature and handles code generation cleanly. The Maven equivalent works, but wiring it to generate sources that downstream services can import requires more configuration and has sharper edges around IDE integration.</p><pre>// libs/common-proto/build.gradle<br>plugins {<br>    id &#39;java-library&#39;<br>    id &#39;maven-publish&#39;<br>    id &#39;com.google.protobuf&#39; version &#39;0.9.4&#39;<br>}<br><br>group = &#39;com.ecommerce&#39;<br>version = &#39;1.0.0&#39;<br><br>java {<br>    toolchain { languageVersion = JavaLanguageVersion.of(21) }<br>}<br><br>def grpcVersion = &#39;1.65.1&#39;<br>def protobufVersion = &#39;3.25.3&#39;<br><br>dependencies {<br>    api &quot;io.grpc:grpc-protobuf:${grpcVersion}&quot;<br>    api &quot;io.grpc:grpc-stub:${grpcVersion}&quot;<br>    api &quot;io.grpc:grpc-netty-shaded:${grpcVersion}&quot;<br>    api &quot;com.google.protobuf:protobuf-java:${protobufVersion}&quot;<br>    compileOnly &quot;javax.annotation:javax.annotation-api:1.3.2&quot;<br>}<br><br>protobuf {<br>    protoc { artifact = &quot;com.google.protobuf:protoc:${protobufVersion}&quot; }<br>    plugins { grpc { artifact = &quot;io.grpc:protoc-gen-grpc-java:${grpcVersion}&quot; } }<br>    generateProtoTasks { all()*.plugins { grpc {} } }<br>}<br><br>publishing {<br>    publications {<br>        mavenJava(MavenPublication) { from components.java }<br>    }<br>    repositories { mavenLocal() }<br>}</pre><pre>// libs/common-events/build.gradle<br>plugins {<br>    id &#39;java-library&#39;<br>    id &#39;maven-publish&#39;<br>}<br><br>group = &#39;com.ecommerce&#39;<br>version = &#39;1.0.0&#39;<br><br>java {<br>    toolchain { languageVersion = JavaLanguageVersion.of(21) }<br>}<br><br>dependencies {<br>    compileOnly &#39;org.projectlombok:lombok:1.18.32&#39;<br>    annotationProcessor &#39;org.projectlombok:lombok:1.18.32&#39;<br>    api &#39;com.fasterxml.jackson.core:jackson-databind:2.17.2&#39;<br>    api &#39;com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.17.2&#39;<br>}<br><br>publishing {<br>    publications {<br>        mavenJava(MavenPublication) { from components.java }<br>    }<br>    repositories { mavenLocal() }<br>}</pre><p>Running ./gradlew publishToMavenLocal in each library directory drops the JAR into ~/.m2/repository. Every service — Gradle or Maven — resolves com.ecommerce:common-proto:1.0.0 from there.</p><p>The cost: this step is manual. A developer who checks out the repo and builds a service without running publishToMavenLocal first gets an unresolved dependency error. There is no incremental cache across the boundary — each publish is a full rebuild of the library. CI must sequence this explicitly.</p><h3>Maven Services — Version Management via BOM</h3><p>Five services (auth, cart, search, payment, notification) plus two infrastructure services are Maven projects. They all inherit from ecommerce-bom.</p><p>The BOM owns every dependency version in the platform:</p><pre>&lt;!-- libs/ecommerce-bom/pom.xml --&gt;<br>&lt;properties&gt;<br>    &lt;java.version&gt;21&lt;/java.version&gt;<br>    &lt;spring-boot.version&gt;3.4.3&lt;/spring-boot.version&gt;<br>    &lt;spring-cloud.version&gt;2024.0.1&lt;/spring-cloud.version&gt;<br>    &lt;jjwt.version&gt;0.12.6&lt;/jjwt.version&gt;<br>    &lt;resilience4j.version&gt;2.2.0&lt;/resilience4j.version&gt;<br>    &lt;springdoc.version&gt;2.6.0&lt;/springdoc.version&gt;<br>    &lt;flyway.version&gt;10.15.0&lt;/flyway.version&gt;<br>    &lt;liquibase.version&gt;4.28.0&lt;/liquibase.version&gt;<br>    &lt;mapstruct.version&gt;1.6.0&lt;/mapstruct.version&gt;<br>    &lt;lombok.version&gt;1.18.32&lt;/lombok.version&gt;<br>    &lt;testcontainers.version&gt;1.19.8&lt;/testcontainers.version&gt;<br>    &lt;common-events.version&gt;1.0.0&lt;/common-events.version&gt;<br>    &lt;common-proto.version&gt;1.0.0&lt;/common-proto.version&gt;<br>&lt;/properties&gt;<br><br>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;${spring-boot.version}&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;${spring-cloud.version}&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.github.resilience4j&lt;/groupId&gt;<br>            &lt;artifactId&gt;resilience4j-bom&lt;/artifactId&gt;<br>            &lt;version&gt;${resilience4j.version}&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;!-- every other version pinned here --&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><p>A service that inherits from this BOM lists dependencies with no version numbers:</p><pre>&lt;!-- services/auth-service/pom.xml --&gt;<br>&lt;parent&gt;<br>    &lt;groupId&gt;com.ecommerce&lt;/groupId&gt;<br>    &lt;artifactId&gt;ecommerce-bom&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>    &lt;relativePath&gt;../../libs/ecommerce-bom/pom.xml&lt;/relativePath&gt;<br>&lt;/parent&gt;<br><br>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>        &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.flywaydb&lt;/groupId&gt;<br>        &lt;artifactId&gt;flyway-core&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;!-- no version numbers anywhere in this file --&gt;<br>&lt;/dependencies&gt;</pre><p>When Spring Boot 3.5 releases, one edit in ecommerce-bom/pom.xml propagates to all 7 Maven services on the next build. No hunting across service directories.</p><p>The cost is structure. The BOM is versioned as an artifact (1.0.0). Bumping a dependency requires updating the BOM, publishing the new BOM version, and updating the &lt;parent&gt; version in every inheriting service — three coordinated steps instead of one. Maven’s lifecycle phases (validate, compile, test, package, install, deploy) are also fixed. Inserting a custom step at a specific point in the build requires writing a plugin or binding an existing one to a non-default phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtFTqFnOEeIBDXII2sbrnQ.png" /></figure><h3>Gradle Services — Per-Service Version Management</h3><p>The five Gradle services (api-gateway, order, product, inventory, review) each carry their own version block in an ext {} closure:</p><pre>// services/order-service/build.gradle<br>plugins {<br>    id &#39;org.springframework.boot&#39; version &#39;3.4.3&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.6&#39;<br>    id &#39;java&#39;<br>    id &#39;com.google.protobuf&#39; version &#39;0.9.4&#39;<br>}<br><br>ext {<br>    set(&#39;springCloudVersion&#39;, &#39;2024.0.1&#39;)<br>    grpcVersion = &#39;1.65.1&#39;<br>    protobufVersion = &#39;3.25.3&#39;<br>    resilience4jVersion = &#39;2.2.0&#39;<br>    springdocVersion = &#39;2.6.0&#39;<br>    mapstructVersion = &#39;1.6.0&#39;<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-data-jpa&#39;<br>    implementation &#39;org.springframework.kafka:spring-kafka&#39;<br>    implementation &#39;org.liquibase:liquibase-core:4.28.0&#39;<br>    implementation &quot;io.grpc:grpc-netty-shaded:${grpcVersion}&quot;<br>    implementation &quot;io.grpc:grpc-protobuf:${grpcVersion}&quot;<br>    implementation &quot;io.grpc:grpc-stub:${grpcVersion}&quot;<br>    implementation &quot;io.github.resilience4j:resilience4j-spring-boot3:${resilience4jVersion}&quot;<br>    implementation &quot;io.github.resilience4j:resilience4j-feign:${resilience4jVersion}&quot;<br>    implementation &#39;com.ecommerce:common-proto:1.0.0&#39;<br>    implementation &#39;com.ecommerce:common-events:1.0.0&#39;<br>    // ...<br>}<br><br>dependencyManagement {<br>    imports {<br>        mavenBom &quot;org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}&quot;<br>    }<br>}<br><br>protobuf {<br>    protoc { artifact = &quot;com.google.protobuf:protoc:${protobufVersion}&quot; }<br>    plugins { grpc { artifact = &quot;io.grpc:protoc-gen-grpc-java:${grpcVersion}&quot; } }<br>    generateProtoTasks { all()*.plugins { grpc {} } }<br>}</pre><p>Two things here that aren’t obvious. First, Gradle services still use a Maven BOM — spring-cloud-dependencies is imported via the io.spring.dependency-management plugin. The line between tools is not “Gradle manages its own versions.” Gradle services delegate Spring Cloud version management to the Maven BOM convention.</p><p>Second, order-service runs the Protobuf plugin directly to process any .proto files it owns locally, in addition to depending on the pre-built common-proto artifact. That is not feasible in the Maven services without significant plugin configuration.</p><p>ext {} is per-project. Changing grpcVersion in order-service does not touch product-service. That flexibility is the direct inverse of the BOM: there is no enforcement mechanism. If five Gradle services each pin resilience4jVersion independently, they can drift. When a library releases a breaking change, there is no single file to update — each ext {} block gets updated separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwPpCNoinbfKAY0m34jHKg.png" /></figure><h3>The Cross-Tool Seam</h3><p>Maven Local connects Gradle libraries to Maven services. The operation is simple:</p><pre>cd libs/common-events &amp;&amp; ./gradlew publishToMavenLocal<br>cd libs/common-proto  &amp;&amp; ./gradlew publishToMavenLocal<br># now any service resolves com.ecommerce:common-events:1.0.0 and com.ecommerce:common-proto:1.0.0</pre><p>In practice, this creates a build ordering constraint that neither tool enforces. A fresh clone of the repo will fail to build any service until both publish commands have run. There is no transitive resolution across the boundary — if common-proto bumps to 1.0.1, services continue to build against the 1.0.0 JAR in Maven Local until both the BOM property (&lt;common-proto.version&gt;) and the Gradle service declarations are updated and publishToMavenLocal runs again.</p><p>CI handles this by running both publish steps before any service build. The constraint is documented, not automated by the build graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7KE020li3TI5RMW-6EZpQ.png" /></figure><p>Pick the tool that matches your hardest constraint. Gradle when the build needs to do something a fixed lifecycle can’t express; Maven when the team needs a single file to enforce versions across every service that builds independently.</p><p><em>Part 11 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · Gradle · Maven · Monorepo · Build Tools · Microservices</p><h3>Full Source Code</h3><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7">Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</a></li><li><a href="https://medium.com/p/ad88995e10a7">The Transactional Outbox Pattern — Never Lose a Kafka Message Again</a></li><li><a href="https://medium.com/p/c612830da237">Saga Choreography with Kafka — Distributed Transactions Without 2PC</a></li><li><a href="https://medium.com/p/82977eab91b8">Sync vs Async — When to Use gRPC and When to Use Kafka</a></li><li><a href="https://medium.com/p/c99f936b80d7">CQRS in Practice — Two Services, Two Approaches</a></li><li><a href="https://medium.com/p/ead0f970ac58">Idempotency in Payment Services — Exactly-Once Semantics on a Budget</a></li><li><a href="https://medium.com/p/fee1a51a5768">Polyglot Persistence — Choosing the Right Database for Each Service</a></li><li><a href="https://medium.com/p/6221a82e57db">Security Architecture — JWT at the Gateway, Trust Headers Downstream</a></li><li><a href="https://medium.com/p/cc9042e94901">Observability Stack — Tracing, Metrics, and Logs Across 10 Services</a></li><li><a href="https://medium.com/p/74de682e547e"><strong>Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</strong></a> ← <em>you are here</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74de682e547e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Four Services All Look Fine But the Request Is Failing]]></title>
            <link>https://medium.com/@ivan.willy.artdian/when-four-services-all-look-fine-but-the-request-is-failing-cc9042e94901?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc9042e94901</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 04:39:31 GMT</pubDate>
            <atom:updated>2026-07-11T04:39:31.416Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 10 of the Spring Boot Microservices in Production series.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RkqIdFiJrUsvZz0RU8-DQ.png" /></figure><p>The stack trace lands in order-service. You check order-service — no errors in the logs. The failure must be upstream. You SSH into inventory-service. Nothing obvious. Check api-gateway. Still nothing. By the time you’ve correlated timestamps across four containers and figured out that a two-second gRPC timeout in order-service is triggering because inventory-service is responding slowly because api-gateway has a misconfigured route — 45 minutes have passed.</p><p>The fix takes 30 seconds. Finding it took 45 minutes.</p><p>That’s the problem observability solves. Not by adding more logging. By giving every request a single ID that flows through every service and appears in every log line, every metric label, and every trace span. When something breaks, you start with that ID.</p><h3>The Thread That Connects Everything</h3><p>A traceId is assigned when a request enters api-gateway. From that point it travels everywhere: HTTP response headers carry it to downstream services, Kafka message headers carry it through the saga, and MDC makes it available to every log statement on every thread that handles the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SENG59bvQRCJvh2TVtaGA.png" /></figure><p>Each tool answers a different question. They’re connected by the traceId. That’s what makes them useful together instead of three separate dashboards you have to manually correlate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2GNBebBFD78vUnH-vkjMQ.png" /></figure><h3>Distributed Tracing</h3><p>Every service in this system participates in distributed tracing via OpenTelemetry. The dependency set is the same regardless of whether the service uses Maven or Gradle.</p><p><strong>Gradle services (order, product, inventory, review):</strong></p><pre>implementation &#39;io.micrometer:micrometer-tracing-bridge-otel&#39;<br>implementation &#39;io.opentelemetry:opentelemetry-exporter-zipkin&#39;<br>runtimeOnly &#39;io.micrometer:micrometer-registry-prometheus&#39;</pre><p><strong>Maven services (auth, cart, payment, notification, search):</strong></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>    &lt;artifactId&gt;micrometer-tracing-bridge-otel&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.opentelemetry&lt;/groupId&gt;<br>    &lt;artifactId&gt;opentelemetry-exporter-zipkin&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>    &lt;artifactId&gt;micrometer-registry-prometheus&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>micrometer-tracing-bridge-otel is the adapter between Spring’s Micrometer tracing API and OpenTelemetry’s implementation. opentelemetry-exporter-zipkin handles shipping spans to Zipkin. You don’t configure either — they wire themselves up via Spring Boot autoconfiguration.</p><p>The only configuration needed per service is where to send spans and how many to send:</p><pre># order-service application.yml<br>management:<br>  tracing:<br>    sampling:<br>      probability: 1.0<br>  zipkin:<br>    tracing:<br>      endpoint: http://${ZIPKIN_HOST:localhost}:9411/api/v2/spans</pre><p>probability: 1.0 captures every request. At production scale that’s expensive — a service handling 1,000 req/s generates 1,000 spans/s that all need to be shipped to Zipkin and stored. You’d drop this to 0.1 (10%) or lower. For a portfolio project where you want full visibility during debugging, 100% sampling makes sense.</p><h3>What a Trace Looks Like</h3><p>One order placement touches six services across three transports. Spring Boot’s Micrometer instrumentation propagates a single traceId across every hop automatically — no manual work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBLY63cInJI6MTCqqlz23Q.png" /></figure><p>Each transport carries the traceId differently: HTTP uses the W3C traceparent header, gRPC uses metadata headers, and Kafka embeds it in record headers. The consumer on the other end picks it up and creates a child span, so the trace continues across async boundaries without any application code.</p><p>Open Zipkin, search by traceId, and you see the full picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifu-UacoTF_O9k2DVKYX9A.png" /></figure><p>The duration breakdown makes the bottleneck obvious. If order-service shows 238ms while every child span is under 20ms, the time is spent inside order-service itself — not in any downstream call. That’s the case the 45-minute log-grep session would never have surfaced.</p><h3>Metrics</h3><p>Spring Boot Actuator exposes a /actuator/prometheus endpoint. Every service enables it with the same configuration:</p><pre>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: health,info,metrics,prometheus,refresh<br>  metrics:<br>    export:<br>      prometheus:<br>        enabled: true</pre><p>Prometheus scrapes this endpoint on a schedule. The full scrape config covers all 10 services:</p><pre>global:<br>  scrape_interval: 15s<br>  scrape_timeout: 10s<br>  evaluation_interval: 15s<br>scrape_configs:<br>  - job_name: &#39;api-gateway&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;api-gateway:8080&#39;]<br>  - job_name: &#39;auth-service&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;auth-service:8081&#39;]<br>  - job_name: &#39;product-service&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;product-service:8082&#39;]<br>  - job_name: &#39;search-service&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;search-service:8083&#39;]<br>  - job_name: &#39;inventory-service&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;inventory-service:8084&#39;]<br>  - job_name: &#39;cart-service&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;cart-service:8085&#39;]<br>  - job_name: &#39;order-service&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;order-service:8086&#39;]<br>  - job_name: &#39;payment-service&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;payment-service:8087&#39;]<br>  - job_name: &#39;notification-service&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;notification-service:8088&#39;]<br>  - job_name: &#39;review-service&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;review-service:8089&#39;]</pre><p>Grafana is provisioned with Prometheus and Zipkin as data sources via datasources.yml — no manual setup after container start:</p><pre>apiVersion: 1<br><br>datasources:<br>  - name: Prometheus<br>    type: prometheus<br>    access: proxy<br>    url: http://prometheus:9090<br>    isDefault: true<br>  - name: Zipkin<br>    type: zipkin<br>    access: proxy<br>    url: http://zipkin:9411</pre><p>The Zipkin datasource in Grafana is what lets you navigate from a slow request in a Grafana panel directly into the Zipkin trace view.</p><h3>Queries That Matter</h3><pre># Request rate per service (requests/sec over the last minute)<br>rate(http_server_requests_seconds_count{job=&quot;order-service&quot;}[1m])<br><br># 5xx error rate<br>rate(http_server_requests_seconds_count{status=~&quot;5..&quot;}[1m])<br><br># 99th percentile latency<br>histogram_quantile(0.99,<br>  rate(http_server_requests_seconds_bucket[5m]))<br><br># Kafka consumer lag - how far behind is the consumer?<br>kafka_consumer_fetch_manager_records_lag_max</pre><p>Kafka consumer lag is the one that bites you in async architectures. If payment-service is processing stock.reserved events but falling behind, that lag metric tells you before users start complaining about delayed order confirmations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e39mv1GNV7p1itXzaFfHLQ.png" /></figure><h3>Structured Logging</h3><p>Every service emits JSON to stdout. The format is configured in application.yml:</p><pre>logging:<br>  pattern:<br>    console: |-<br>      {&quot;timestamp&quot;:&quot;%d{yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ}&quot;,&quot;level&quot;:&quot;%level&quot;,<br>      &quot;service&quot;:&quot;${spring.application.name}&quot;,&quot;traceId&quot;:&quot;%X{traceId}&quot;,<br>      &quot;spanId&quot;:&quot;%X{spanId}&quot;,&quot;thread&quot;:&quot;%thread&quot;,&quot;logger&quot;:&quot;%logger{36}&quot;,<br>      &quot;message&quot;:&quot;%msg&quot;}%n<br>  level:<br>    com.ecommerce: INFO</pre><p>%X{traceId} and %X{spanId} pull from MDC. The Micrometer tracing bridge populates MDC automatically on every request — you don’t call MDC.put anywhere in application code. The traceId in the log is the same traceId Zipkin uses.</p><p>A log line from order-service during an order placement:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2025-06-06T10:23:45.123+0800&quot;,<br>  &quot;level&quot;: &quot;INFO&quot;,<br>  &quot;service&quot;: &quot;order-service&quot;,<br>  &quot;traceId&quot;: &quot;abc123def456&quot;,<br>  &quot;spanId&quot;: &quot;789xyz&quot;,<br>  &quot;thread&quot;: &quot;kafka-consumer-1&quot;,<br>  &quot;logger&quot;: &quot;c.e.order.application.service.PlaceOrderService&quot;,<br>  &quot;message&quot;: &quot;Order placed orderId=order-xyz status=PENDING&quot;<br>}</pre><h3>Getting Logs Into Elasticsearch</h3><p>The Logstash pipeline uses a TCP JSON lines input — services write structured JSON to stdout, Docker captures it, and something upstream is responsible for forwarding to Logstash on port 5044. The pipeline itself:</p><pre>input {<br>  tcp {<br>    port =&gt; 5044<br>    codec =&gt; json_lines<br>  }<br>}<br><br>filter {<br>  if [traceId] {<br>    mutate {<br>      add_field =&gt; { &quot;[@metadata][traceId]&quot; =&gt; &quot;%{traceId}&quot; }<br>    }<br>  }<br>  date {<br>    match =&gt; [ &quot;@timestamp&quot;, &quot;ISO8601&quot; ]<br>    target =&gt; &quot;@timestamp&quot;<br>  }<br>}<br><br>output {<br>  elasticsearch {<br>    hosts =&gt; [&quot;elasticsearch:9200&quot;]<br>    index =&gt; &quot;ecommerce-logs-%{+YYYY.MM.dd}&quot;<br>    template_name =&gt; &quot;ecommerce-logs&quot;<br>  }<br>  stdout { codec =&gt; rubydebug }<br>}</pre><p>The filter extracts traceId into Logstash metadata and parses the @timestamp field. Logs land in daily indices: ecommerce-logs-2025.06.06. In Kibana’s Discover view you can filter by any JSON field — service, level, traceId, or free text in message.</p><h3>The Infrastructure</h3><p>docker-compose.monitoring.yml runs the full observability stack:</p><pre>services:<br>  prometheus:<br>    image: prom/prometheus:v2.53.0<br>    ports:<br>      - &quot;9394:9090&quot;<br>    volumes:<br>      - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml:ro<br>      - prometheus_data:/prometheus<br>    command:<br>      - &#39;--config.file=/etc/prometheus/prometheus.yml&#39;<br>      - &#39;--storage.tsdb.path=/prometheus&#39;<br>      - &#39;--storage.tsdb.retention.time=15d&#39;<br>      - &#39;--web.enable-lifecycle&#39;<br><br>  grafana:<br>    image: grafana/grafana:11.1.0<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      GF_SECURITY_ADMIN_USER: admin<br>      GF_SECURITY_ADMIN_PASSWORD: admin_pass<br>    volumes:<br>      - grafana_data:/var/lib/grafana<br>      - ./monitoring/grafana/provisioning:/etc/grafana/provisioning:ro<br>    depends_on:<br>      prometheus:<br>        condition: service_healthy<br><br>  zipkin:<br>    image: openzipkin/zipkin:3.4<br>    ports:<br>      - &quot;9411:9411&quot;<br><br>  elasticsearch-logs:<br>    image: docker.elastic.co/elasticsearch/elasticsearch:8.14.0<br>    ports:<br>      - &quot;9201:9200&quot;<br>    environment:<br>      - discovery.type=single-node<br>      - xpack.security.enabled=false<br>      - ES_JAVA_OPTS=-Xms512m -Xmx512m<br><br>  logstash:<br>    image: docker.elastic.co/logstash/logstash:8.14.0<br>    ports:<br>      - &quot;5044:5044&quot;<br>    volumes:<br>      - ./monitoring/logstash/pipeline:/usr/share/logstash/pipeline:ro<br>    depends_on:<br>      elasticsearch-logs:<br>        condition: service_healthy<br><br>  kibana:<br>    image: docker.elastic.co/kibana/kibana:8.14.0<br>    ports:<br>      - &quot;5601:5601&quot;<br>    environment:<br>      ELASTICSEARCH_HOSTS: http://elasticsearch-logs:9200<br>    depends_on:<br>      elasticsearch-logs:<br>        condition: service_healthy</pre><p>Port 9201 for the logging Elasticsearch avoids collision with 9200, which the search-service Elasticsearch already occupies. Two Elasticsearch instances, two purposes — one for product search queries, one for log storage. Kibana connects to elasticsearch-logs by container name; Logstash connects to elasticsearch (the search instance container name) in the default config, which is a naming mismatch worth watching if you reorganize the stack.</p><p>Prometheus retention is set to 15 days. That’s enough to see weekly patterns without the data directory growing unbounded.</p><h3>Three Tools, One Failure</h3><p>This is how the three pillars work together in practice. An order fails. Here’s the investigation:</p><p><strong>Step 1 — Grafana.</strong> The order-service error rate panel shows a spike starting at 10:23. The latency p99 for /api/orders jumped from 200ms to 2,400ms. That’s the signal.</p><p><strong>Step 2 — Zipkin.</strong> Filter traces for order-service between 10:20 and 10:30, status ERROR. The trace for traceId=abc123def456 shows six spans. The inventory-service gRPC span took 1,980ms. The time limiter is configured at 2s. It timed out.</p><p><strong>Step 3 — Kibana.</strong> Filter by traceId: abc123def456. Logs from inventory-service show database connection pool exhaustion starting at 10:22. The root cause is in inventory-service, but the failure surface was order-service. Without the shared traceId connecting all three tools, you’d be guessing.</p><h3>Starting the Stack</h3><pre># Infrastructure (Kafka, databases, Redis, search Elasticsearch)<br>docker compose -f docker/docker-compose.infra.yml up -d<br><br># All 10 services<br>docker compose -f docker/docker-compose.services.yml up -d<br><br># Observability stack<br>docker compose -f docker/docker-compose.monitoring.yml up -d</pre><ul><li>Zipkin: <a href="http://localhost:9411/">http://localhost:9411</a></li><li>Grafana: <a href="http://localhost:3000/">http://localhost:3000</a> (admin / admin_pass)</li><li>Kibana: <a href="http://localhost:5601/">http://localhost:5601</a></li><li>Prometheus: <a href="http://localhost:9394/">http://localhost:9394</a></li></ul><p>Metrics show you that something is wrong. Traces show you where it is. Logs show you what it is. The tools answer different questions, and none of them answers all three on its own — which is why skipping any one of the three leaves a gap you’ll eventually need to fill manually.</p><p><em>Next in this series: </em><a href="https://medium.com/p/74de682e547e"><em>Part 11 — Gradle vs Maven in a Monorepo: Why I Use Both and Which Won</em></a><em>, closing the series with the build-tool decision behind the whole platform.</em></p><p><em>Part 10 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · Microservices · Observability · Zipkin · Prometheus · Grafana · ELK · Distributed Tracing · OpenTelemetry</p><h3>Full Source Code</h3><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7">Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</a></li><li><a href="https://medium.com/p/ad88995e10a7">The Transactional Outbox Pattern — Never Lose a Kafka Message Again</a></li><li><a href="https://medium.com/p/c612830da237">Saga Choreography with Kafka — Distributed Transactions Without 2PC</a></li><li><a href="https://medium.com/p/82977eab91b8">Sync vs Async — When to Use gRPC and When to Use Kafka</a></li><li><a href="https://medium.com/p/c99f936b80d7">CQRS in Practice — Two Services, Two Approaches</a></li><li><a href="https://medium.com/p/ead0f970ac58">Idempotency in Payment Services — Exactly-Once Semantics on a Budget</a></li><li><a href="https://medium.com/p/fee1a51a5768">Polyglot Persistence — Choosing the Right Database for Each Service</a></li><li><a href="https://medium.com/p/6221a82e57db">Security Architecture — JWT at the Gateway, Trust Headers Downstream</a></li><li><a href="https://medium.com/p/cc9042e94901"><strong>Observability Stack — Tracing, Metrics, and Logs Across 10 Services</strong></a> ← <em>you are here</em></li><li><a href="https://medium.com/p/74de682e547e">Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc9042e94901" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security Architecture — JWT at the Gateway, Trust Headers Downstream]]></title>
            <link>https://medium.com/@ivan.willy.artdian/security-architecture-jwt-at-the-gateway-trust-headers-downstream-6221a82e57db?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6221a82e57db</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 04:39:20 GMT</pubDate>
            <atom:updated>2026-07-11T04:39:20.572Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 9 of the Spring Boot Microservices in Production series.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEa8JgfOOX8n8xRij8Dqpw.png" /></figure><p>You’re writing service number three. The order service needs to know who placed the order. The cart service needs to know whose cart it’s reading. Payment needs a user ID to attach the transaction to an account.</p><p>So where does authentication live?</p><p>The naive answer: in every service. Each one validates the JWT, checks the signature, verifies expiry, extracts the claims. You need the JWT library on every classpath. You need the shared secret distributed to every deployment. You need to update that logic in eight places when your token format changes. And after all that work, service four does the exact same cryptographic operation that service three just finished — on the same token, from the same request.</p><p>There’s a simpler model: validate once at the gateway, then propagate user context as trusted headers. Downstream services read the headers, build a SecurityContext, and never touch a JWT at all.</p><p>This is how this project works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZM6av8zWLOWKJyXK4vkqA.png" /></figure><h3>JWT Validation at the Gateway</h3><p>JwtAuthenticationFilter is a Spring Cloud Gateway AbstractGatewayFilterFactory. It intercepts routed requests before they reach any downstream service:</p><pre>@Component<br>@Slf4j<br>public class JwtAuthenticationFilter<br>        extends AbstractGatewayFilterFactory&lt;JwtAuthenticationFilter.Config&gt; {<br>    private final JwtProperties jwtProperties;<br>    public JwtAuthenticationFilter(JwtProperties jwtProperties) {<br>        super(Config.class);<br>        this.jwtProperties = jwtProperties;<br>    }<br>    @Override<br>    public GatewayFilter apply(Config config) {<br>        return (exchange, chain) -&gt; {<br>            String authHeader = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);<br>            if (authHeader == null || !authHeader.startsWith(&quot;Bearer &quot;)) {<br>                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);<br>                return exchange.getResponse().setComplete();<br>            }<br>            String token = authHeader.substring(7);<br>            try {<br>                Claims claims = parseToken(token);<br>                var mutatedRequest = exchange.getRequest().mutate()<br>                        .header(&quot;X-User-Id&quot;, claims.getSubject())<br>                        .header(&quot;X-User-Email&quot;, claims.get(&quot;email&quot;, String.class))<br>                        .header(&quot;X-User-Roles&quot;, String.join(&quot;,&quot;, getRoles(claims)))<br>                        .build();<br>                return chain.filter(exchange.mutate().request(mutatedRequest).build());<br>            } catch (Exception e) {<br>                log.warn(&quot;JWT validation failed: {}&quot;, e.getMessage());<br>                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);<br>                return exchange.getResponse().setComplete();<br>            }<br>        };<br>    }<br>    private Claims parseToken(String token) {<br>        SecretKey key = Keys.hmacShaKeyFor(<br>                jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8));<br>        Claims claims = Jwts.parser()<br>                .verifyWith(key)<br>                .build()<br>                .parseSignedClaims(token)<br>                .getPayload();<br>        if (claims.getExpiration().before(new Date())) {<br>            throw new IllegalStateException(&quot;Token expired&quot;);<br>        }<br>        return claims;<br>    }<br>    @SuppressWarnings(&quot;unchecked&quot;)<br>    private List&lt;String&gt; getRoles(Claims claims) {<br>        Object roles = claims.get(&quot;roles&quot;);<br>        if (roles instanceof List&lt;?&gt; list) {<br>            return list.stream().map(Object::toString).toList();<br>        }<br>        return List.of();<br>    }<br>    public static class Config {}<br>}</pre><p>The gateway runs on WebFlux, not the servlet stack — exchange is a ServerWebExchange, not an HttpServletRequest. Requests are immutable in WebFlux, so you can’t add headers in place. exchange.getRequest().mutate() creates a new request builder, adds the headers, builds a new request, then wraps it back into the exchange with exchange.mutate().request(...). The original request is unchanged; the downstream chain sees the mutated copy.</p><p>Three headers get injected: X-User-Id (the sub claim, which is the user’s UUID), X-User-Email, and X-User-Roles as a comma-separated string. The JWT also carries firstName and lastName — those are in the token, they just aren’t forwarded. The gateway defines the downstream interface. What it chooses to propagate is what downstream services get; the JWT payload has more than the headers expose.</p><p>Not every route is protected. The auth-service and search-service routes have no JwtAuthenticationFilter:</p><pre>routes:<br>  # Public — no JWT filter<br>  - id: auth-service<br>    uri: lb://auth-service<br>    predicates:<br>      - Path=/api/v1/auth/**<br>    filters:<br>      - name: CircuitBreaker<br>        args:<br>          name: auth-cb<br>          fallbackUri: forward:/fallback/auth<br>  - id: search-service<br>    uri: lb://search-service<br>    predicates:<br>      - Path=/api/v1/search/**<br>    filters:<br>      - name: CircuitBreaker<br>        args:<br>          name: search-cb<br>          fallbackUri: forward:/fallback/search<br>  # Protected - JWT required<br>  - id: order-service<br>    uri: lb://order-service<br>    predicates:<br>      - Path=/api/v1/orders/**<br>    filters:<br>      - name: JwtAuthenticationFilter<br>      - name: CircuitBreaker<br>        args:<br>          name: order-cb<br>          fallbackUri: forward:/fallback/order</pre><p>Search is readable without authentication. Cart, order, payment, inventory, product, and review routes all require a valid JWT before the request is forwarded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lV_70i45513a_1o-tsuNNw.png" /></figure><h3>Rate Limiting — Keyed by User, Not Just IP</h3><p>Rate limiting happens before JWT validation, via Spring Cloud Gateway’s RequestRateLimiter filter applied globally:</p><pre>spring:<br>  cloud:<br>    gateway:<br>      default-filters:<br>        - name: RequestRateLimiter<br>          args:<br>            redis-rate-limiter:<br>              replenishRate: 20<br>              burstCapacity: 40<br>              requestedTokens: 1<br>            key-resolver: &quot;#{@userOrIpKeyResolver}&quot;</pre><p>20 requests/second sustained, 40 burst. The userOrIpKeyResolver bean decides what the counter is keyed on:</p><pre>@Configuration<br>public class UserKeyResolver {<br>    @Bean<br>    public KeyResolver userOrIpKeyResolver() {<br>        return (ServerWebExchange exchange) -&gt; {<br>            String userId = exchange.getRequest().getHeaders().getFirst(&quot;X-User-Id&quot;);<br>            if (userId != null) {<br>                return Mono.just(userId);<br>            }<br>            String ip = exchange.getRequest().getRemoteAddress() != null<br>                    ? exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()<br>                    : &quot;unknown&quot;;<br>            return Mono.just(ip);<br>        };<br>    }<br>}</pre><p>For authenticated requests, the counter is per-user. For unauthenticated requests — including /auth/** login and register calls — the counter falls back to client IP. This means a single IP can’t hammer the login endpoint to enumerate credentials, and a legitimate user’s burst can’t bleed into another user’s quota.</p><p>The cost: Redis counters are not durable. A Redis restart resets every counter. Someone who has already consumed their burst capacity gets a clean window after a restart. That’s acceptable — rate limiting is abuse protection, not a business rule. Losing a counter state is not a data integrity event.</p><h3>Token Issuance — auth-service</h3><p>auth-service is the only service that talks to the signing key directly. JwtService builds the access token:</p><pre>@Service<br>@RequiredArgsConstructor<br>public class JwtService {<br>    private final JwtProperties jwtProperties;<br>    public String generateAccessToken(User user) {<br>        Set&lt;String&gt; roles = user.getRoles().stream()<br>                .map(Enum::name)<br>                .collect(Collectors.toSet());<br>        return Jwts.builder()<br>                .subject(user.getId().toString())<br>                .claims(Map.of(<br>                        &quot;email&quot;, user.getEmail(),<br>                        &quot;roles&quot;, roles,<br>                        &quot;firstName&quot;, user.getFirstName(),<br>                        &quot;lastName&quot;, user.getLastName()<br>                ))<br>                .issuedAt(new Date())<br>                .expiration(new Date(System.currentTimeMillis() + jwtProperties.getExpirationMs()))<br>                .signWith(getSigningKey())<br>                .compact();<br>    }<br>    private SecretKey getSigningKey() {<br>        byte[] keyBytes = jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8);<br>        return Keys.hmacShaKeyFor(keyBytes);<br>    }<br>}</pre><p>The configuration behind this:</p><pre>jwt:<br>  secret: ${JWT_SECRET:dev-secret-key-must-be-at-least-32-characters-long}<br>  expiration-ms: 900000       # 15 minutes<br>  refresh-expiration-ms: 604800000  # 7 days</pre><p>Access tokens live 15 minutes. Refresh tokens live 7 days and are persisted to PostgreSQL — a Flyway migration creates the refresh tokens table with a partial index on WHERE revoked = FALSE so active-token lookups stay fast. When a user logs out, refresh tokens for that email are revoked in the database. The access token they already have remains valid until expiry — there’s no revocation mechanism for access tokens.</p><p>That’s a known gap in this design. A user who logs out can still make authenticated requests for up to 15 minutes. For this project, that’s acceptable. For systems with stronger logout guarantees, you’d need a token blocklist — typically a Redis set checked on every gateway request.</p><h3>Downstream Trust — Reading Headers Instead of Tokens</h3><p>Every downstream service contains the same GatewayHeaderAuthFilter:</p><pre>public class GatewayHeaderAuthFilter extends OncePerRequestFilter {<br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request,<br>                                    HttpServletResponse response,<br>                                    FilterChain filterChain) throws ServletException, IOException {<br>        String userId = request.getHeader(&quot;X-User-Id&quot;);<br>        String roles  = request.getHeader(&quot;X-User-Roles&quot;);<br>        if (userId != null &amp;&amp; !userId.isBlank()) {<br>            List&lt;SimpleGrantedAuthority&gt; authorities = roles != null<br>                    ? Arrays.stream(roles.split(&quot;,&quot;))<br>                            .map(String::trim)<br>                            .map(SimpleGrantedAuthority::new)<br>                            .toList()<br>                    : List.of();<br>            UsernamePasswordAuthenticationToken auth =<br>                    new UsernamePasswordAuthenticationToken(userId, null, authorities);<br>            SecurityContextHolder.getContext().setAuthentication(auth);<br>        }<br>        filterChain.doFilter(request, response);<br>    }<br>}</pre><p>UsernamePasswordAuthenticationToken(userId, null, authorities) — principal is the user ID string, credentials are null (there’s no password to verify), authorities come from the role header. Spring Security sees a fully authenticated principal.</p><p>The filter is wired in SecurityConfig:</p><pre>@Configuration<br>@EnableWebSecurity<br>@EnableMethodSecurity<br>public class SecurityConfig {<br>    @Bean<br>    public GatewayHeaderAuthFilter gatewayHeaderAuthFilter() {<br>        return new GatewayHeaderAuthFilter();<br>    }<br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>            .csrf(csrf -&gt; csrf.disable())<br>            .sessionManagement(sm -&gt; sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/actuator/**&quot;, &quot;/v3/api-docs/**&quot;, &quot;/swagger-ui/**&quot;).permitAll()<br>                .anyRequest().authenticated())<br>            .addFilterBefore(gatewayHeaderAuthFilter(), UsernamePasswordAuthenticationFilter.class);<br>        return http.build();<br>    }<br>}</pre><p>@EnableMethodSecurity enables @PreAuthorize on controller methods. A controller reads the user identity through the standard Spring Security API:</p><pre>@GetMapping(&quot;/orders&quot;)<br>public List&lt;OrderResponse&gt; getMyOrders(Authentication auth) {<br>    String userId = (String) auth.getPrincipal();<br>    return orderService.getOrdersByUser(userId);<br>}</pre><p>No JWT dependency. No secret key in the service config. No jjwt on the classpath. The downstream service doesn’t know or care that authentication happened via JWT — it just sees a populated SecurityContext.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_4VyhBqo9_ZwU1LNi5_Gw.png" /></figure><p>The cost is structural: GatewayHeaderAuthFilter trusts X-User-Id unconditionally. If a request carries that header, the service treats it as authenticated. The only thing preventing header forgery is network isolation — downstream services must not be reachable from outside the internal network. In Docker Compose, that means no ports: mapping on downstream services. In Kubernetes, that means NetworkPolicy restricting ingress to traffic from the gateway pod only.</p><p>This assumption is never enforced in the application code itself. It’s a deployment contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_AdYflaKPkxnBtMKIq0kg.png" /></figure><p>JWT validation runs once at the gateway. User context travels downstream as headers. Each service reads those headers into a SecurityContext and operates as if authentication had always been its own concern.</p><p>The model holds exactly as long as the network boundary holds. Centralized validation buys operational simplicity — one secret, one validation path, one place to change. What it gives up is resilience to a broken perimeter. Know which you’re operating before you choose.</p><p><em>Next in this series: </em><a href="https://medium.com/p/cc9042e94901"><em>Part 10 — Observability Stack: Tracing, Metrics, and Logs Across 10 Services</em></a><em>, where Zipkin traces, Prometheus metrics, and ELK logs come together across the platform.</em></p><p><em>Part 9 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · Microservices · Security · JWT · Spring Security · API Gateway · Software Architecture</p><h3>Full Source Code</h3><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7">Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</a></li><li><a href="https://medium.com/p/ad88995e10a7">The Transactional Outbox Pattern — Never Lose a Kafka Message Again</a></li><li><a href="https://medium.com/p/c612830da237">Saga Choreography with Kafka — Distributed Transactions Without 2PC</a></li><li><a href="https://medium.com/p/82977eab91b8">Sync vs Async — When to Use gRPC and When to Use Kafka</a></li><li><a href="https://medium.com/p/c99f936b80d7">CQRS in Practice — Two Services, Two Approaches</a></li><li><a href="https://medium.com/p/ead0f970ac58">Idempotency in Payment Services — Exactly-Once Semantics on a Budget</a></li><li><a href="https://medium.com/p/fee1a51a5768">Polyglot Persistence — Choosing the Right Database for Each Service</a></li><li><a href="https://medium.com/p/6221a82e57db"><strong>Security Architecture — JWT at the Gateway, Trust Headers Downstream</strong></a> ← <em>you are here</em></li><li><a href="https://medium.com/p/cc9042e94901">Observability Stack — Tracing, Metrics, and Logs Across 10 Services</a></li><li><a href="https://medium.com/p/74de682e547e">Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6221a82e57db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polyglot Persistence — Choosing the Right Database for Each Service]]></title>
            <link>https://medium.com/@ivan.willy.artdian/polyglot-persistence-choosing-the-right-database-for-each-service-fee1a51a5768?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fee1a51a5768</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 02:05:22 GMT</pubDate>
            <atom:updated>2026-07-10T02:05:22.353Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 8 of the Spring Boot Microservices in Production series.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11l-8jCOCxTt-8nij_OYZQ.png" /></figure><p>Picture a single database handling every operation in this system: a user logs in, searches for wireless headphones, adds three to their cart, and checks out. The login needs a transactional write with a foreign key to a refresh token table. The search needs full-text matching with relevance scoring across 500,000 product names and descriptions. The cart needs to expire after 24 hours of inactivity without a cleanup job. The checkout needs to atomically record a payment and decrement stock.</p><p>No single database does all four of these well. A relational database running LIKE &#39;%wireless headphones%&#39; on half a million rows does a sequential scan — no B-tree index helps a leading wildcard. A Redis cache storing payment records loses them on restart unless you configure persistence, and then you’ve rebuilt a worse database. A document store running financial transactions across collections has no ACID guarantee to stand on.</p><p>The four PostgreSQL instances are isolated. They do not share schemas or connection pools. This is the microservices boundary applied to storage — each service owns its data exclusively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_sB-P9wjkn5BVkOd3pQwQ.png" /></figure><h3>PostgreSQL — Where Correctness Is Non-Negotiable</h3><p>Four services use PostgreSQL, and the reason is the same for all of them: losing or corrupting their data has consequences that can’t be retried or compensated.</p><p>auth-service stores user accounts and refresh tokens. A lost refresh token silently logs out a user. A corrupted password hash makes their account permanently inaccessible until support intervenes. order-service drives the entire order saga — if the database loses an order between PENDING and CONFIRMED, there is no recovery path in the saga coordinator. payment-service stores financial records; regulatory requirements alone mandate durable, consistent storage. inventory-service tracks stock counts; two concurrent transactions reading the same count and both decrementing it without serialization is a real overselling scenario.</p><p>ACID means you don’t have to build compensating logic for the database layer. That is what these services need.</p><h3>Flyway in auth-service</h3><p>Flyway uses plain SQL files with a naming convention: V1__description.sql, V2__description.sql. The history table (flyway_schema_history) tracks which files have run and refuses to re-apply them.</p><p>V1__create_users_table.sql:</p><pre>CREATE TABLE users (<br>    id            UUID PRIMARY KEY DEFAULT gen_random_uuid(),<br>    email         VARCHAR(100) NOT NULL UNIQUE,<br>    password_hash VARCHAR(255) NOT NULL,<br>    first_name    VARCHAR(100) NOT NULL,<br>    last_name     VARCHAR(100) NOT NULL,<br>    enabled       BOOLEAN NOT NULL DEFAULT TRUE,<br>    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),<br>    updated_at    TIMESTAMPTZ NOT NULL DEFAULT NOW()<br>);</pre><pre>CREATE INDEX idx_users_email ON users (email);</pre><p>V2__create_refresh_tokens_table.sql:</p><pre>CREATE TABLE refresh_tokens (<br>    id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),<br>    token      VARCHAR(512) NOT NULL UNIQUE,<br>    user_id    UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,<br>    expires_at TIMESTAMPTZ NOT NULL,<br>    revoked    BOOLEAN NOT NULL DEFAULT FALSE,<br>    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()<br>);<br><br>CREATE INDEX idx_refresh_tokens_token ON refresh_tokens (token) WHERE revoked = FALSE;<br>CREATE INDEX idx_refresh_tokens_user_id ON refresh_tokens (user_id);</pre><p>The partial index on refresh_tokens (WHERE revoked = FALSE) is the non-obvious part. Every authentication check queries by token value against non-revoked tokens. Revoked tokens are never queried on the authentication path — they exist for audit purposes only. The partial index is smaller than a full index and faster to scan because it excludes all the rows the authentication query will never touch.</p><h3>Liquibase in order-service</h3><p>order-service uses Liquibase with XML changesets. Liquibase is more verbose than Flyway SQL, but it generates database-agnostic DDL and supports declarative rollback per changeset — useful if you need to roll back a migration without writing reverse SQL by hand.</p><p>001-create-orders.xml:</p><pre>&lt;changeSet id=&quot;001-create-orders&quot; author=&quot;order-service&quot;&gt;<br>    &lt;createTable tableName=&quot;orders&quot;&gt;<br>        &lt;column name=&quot;id&quot; type=&quot;VARCHAR(50)&quot;&gt;<br>            &lt;constraints primaryKey=&quot;true&quot; nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;user_id&quot; type=&quot;VARCHAR(100)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;status&quot; type=&quot;VARCHAR(30)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;shipping_address&quot; type=&quot;TEXT&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;total_amount&quot; type=&quot;DECIMAL(19,2)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;created_at&quot; type=&quot;TIMESTAMP WITH TIME ZONE&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;updated_at&quot; type=&quot;TIMESTAMP WITH TIME ZONE&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>    &lt;/createTable&gt;<br>    &lt;createIndex tableName=&quot;orders&quot; indexName=&quot;idx_orders_user_id&quot;&gt;<br>        &lt;column name=&quot;user_id&quot;/&gt;<br>    &lt;/createIndex&gt;<br>    &lt;createIndex tableName=&quot;orders&quot; indexName=&quot;idx_orders_status&quot;&gt;<br>        &lt;column name=&quot;status&quot;/&gt;<br>    &lt;/createIndex&gt;<br>    &lt;createTable tableName=&quot;order_items&quot;&gt;<br>        &lt;column name=&quot;id&quot; type=&quot;BIGSERIAL&quot;&gt;<br>            &lt;constraints primaryKey=&quot;true&quot; nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;order_id&quot; type=&quot;VARCHAR(50)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;<br>                foreignKeyName=&quot;fk_order_items_order&quot;<br>                references=&quot;orders(id)&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;product_id&quot; type=&quot;VARCHAR(100)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;product_name&quot; type=&quot;VARCHAR(255)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;quantity&quot; type=&quot;INT&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;unit_price&quot; type=&quot;DECIMAL(19,2)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>    &lt;/createTable&gt;<br>&lt;/changeSet&gt;</pre><p>order_items has a foreign key to orders. In a microservices system that avoids cross-service joins, intra-service foreign keys remain correct and valuable — they enforce a relationship that actually exists within a single database boundary. Avoiding foreign keys entirely because microservices avoid cross-service joins conflates two different things.</p><h3>The cost</h3><p>Running four PostgreSQL instances means four independent backup schedules, four connection pool configurations, four sets of operational runbooks. When something goes wrong at 2am, you debug four databases instead of one. That operational burden is real, and it scales linearly with the number of services that need ACID guarantees.</p><h3>MongoDB — When Schema Variance Is the Feature</h3><p>product-service is the reason this project has MongoDB at all. Product catalogs are structurally heterogeneous. A laptop needs RAM, CPU, and storage specs. A t-shirt needs size variants and colour options. A book needs ISBN, author, and page count. None of these attribute sets overlap cleanly.</p><p>In PostgreSQL, you have three options: a table with hundreds of nullable columns (most of them empty for any given row), a JSONB column (which sacrifices type safety and makes querying painful), or an EAV table — one row per attribute, with a string key and a string value — which turns a simple product query into five-way join. MongoDB’s document model sidesteps this entirely. Each product document carries exactly the attributes relevant to its category.</p><p>ProductDocument.java:</p><pre>@Document(collection = &quot;products&quot;)<br>@Getter<br>@Setter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Builder<br>public class ProductDocument {<br>    @Id<br>    private String id;<br>    private String name;<br>    private String description;<br>    private BigDecimal price;<br>    private String category;<br>    private List&lt;String&gt; tags;<br>    private boolean active;<br>    private Instant createdAt;<br>    private Instant updatedAt;<br>}</pre><p>This is the base structure. Category-specific attributes — the laptop specs, the t-shirt variants — live in the same document as additional fields without schema changes. Spring Data MongoDB maps them transparently.</p><h3>Mongock migrations</h3><p>Flyway and Liquibase work against SQL databases. MongoDB needs a different tool. Mongock uses Java @ChangeUnit classes — the migration logic is code, not SQL or XML.</p><p>ProductMigrationV001.java:</p><pre>@ChangeUnit(id = &quot;product-migration-v001&quot;, order = &quot;001&quot;, author = &quot;ecommerce&quot;)<br>public class ProductMigrationV001 {<br><br>    @Execution<br>    public void createProductCollection(MongoDatabase database) {<br>        database.createCollection(&quot;products&quot;);<br>        MongoCollection&lt;Document&gt; products = database.getCollection(&quot;products&quot;);<br>        products.createIndex(<br>                new Document(&quot;category&quot;, 1),<br>                new IndexOptions().name(&quot;idx_products_category&quot;)<br>        );<br>        products.createIndex(<br>                new Document(&quot;active&quot;, 1),<br>                new IndexOptions().name(&quot;idx_products_active&quot;)<br>        );<br>        products.createIndex(<br>                new Document(&quot;category&quot;, 1).append(&quot;active&quot;, 1),<br>                new IndexOptions().name(&quot;idx_products_category_active&quot;)<br>        );<br>        products.createIndex(<br>                new Document(&quot;name&quot;, &quot;text&quot;).append(&quot;description&quot;, &quot;text&quot;),<br>                new IndexOptions().name(&quot;idx_products_text&quot;)<br>        );<br>    }<br><br>    @RollbackExecution<br>    public void rollback(MongoDatabase database) {<br>        database.getCollection(&quot;products&quot;).drop();<br>    }<br>}</pre><p>@Execution runs the migration forward. @RollbackExecution handles reversal. Mongock tracks executed changesets in a mongockChangeLog collection — same bookkeeping concept as Flyway’s history table, just stored in MongoDB itself.</p><p>The compound index on (category, active) covers the most common query: fetch active products in a given category. The text index on name and description enables MongoDB’s own $text search for direct catalog queries. It co-exists with Elasticsearch, but the two serve different purposes — the MongoDB text index handles simple in-collection lookups; relevance-scored search across the full catalog is delegated to search-service.</p><h3>The cost</h3><p>The document model gives up enforced schema and cross-document ACID transactions. If product-service and review-service need a consistent view of the same data, there is no transaction boundary that spans both collections. Reviews referencing a product that was deleted have no foreign key to enforce integrity — the application is responsible for that constraint. Schema validation rules exist in MongoDB 3.6+, but they are opt-in and weaker than relational constraints. Flexible schema means the flexibility for inconsistency is also there.</p><h3>Redis — When Expiry Is a Feature, Not a Bug</h3><p>Two services use Redis. Neither stores data that needs to survive indefinitely.</p><p>cart-service stores shopping carts. A cart that hasn’t been touched in 24 hours should disappear on its own. In a relational database, that requires a cleanup job, a soft-delete column, and an archival strategy. In Redis, it is a TTL.</p><p>Cart.java:</p><pre>@RedisHash(&quot;cart&quot;)<br>@Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder<br>public class Cart implements Serializable {<br>    @Id<br>    private String userId;<br>    <br>    @Builder.Default<br>    private Map&lt;String, CartItem&gt; items = new HashMap&lt;&gt;();<br><br>    @TimeToLive<br>    private Long ttlSeconds = 86400L; // 24 hours<br><br>    public void addItem(String productId, String productName, int quantity, BigDecimal unitPrice) {<br>        items.compute(productId, (k, existing) -&gt; {<br>            if (existing == null) {<br>                return new CartItem(productId, productName, quantity, unitPrice);<br>            }<br>            existing.setQuantity(existing.getQuantity() + quantity);<br>            return existing;<br>        });<br>    }<br><br>    public void removeItem(String productId) {<br>        items.remove(productId);<br>    }<br><br>    public void updateQuantity(String productId, int quantity) {<br>        CartItem item = items.get(productId);<br>        if (item == null) throw new com.ecommerce.cart.exception.CartItemNotFoundException(&quot;Item not in cart: &quot; + productId);<br>        if (quantity &lt;= 0) {<br>            items.remove(productId);<br>        } else {<br>            item.setQuantity(quantity);<br>        }<br>    }<br><br>    public void clear() {<br>        items.clear();<br>    }<br><br>    public BigDecimal getTotalPrice() {<br>        return items.values().stream()<br>                .map(i -&gt; i.getUnitPrice().multiply(BigDecimal.valueOf(i.getQuantity())))<br>                .reduce(BigDecimal.ZERO, BigDecimal::add);<br>    }<br>}</pre><p>@RedisHash(&quot;cart&quot;) maps the object to a Redis hash keyed as cart:{userId}. @TimeToLive sets the expiry at the entity level — Spring Data Redis handles the TTL command. items.compute() handles both the new-item and quantity-accumulation cases in one atomic operation on the map.</p><p>api-gateway uses the same Redis instance for rate limiting. Spring Cloud Gateway’s RequestRateLimiter filter requires a KeyResolver bean to identify each client:</p><pre>@Configuration<br>public class UserKeyResolver {<br>    @Bean<br>    public KeyResolver userOrIpKeyResolver() {<br>        return (ServerWebExchange exchange) -&gt; {<br>            String userId = exchange.getRequest().getHeaders().getFirst(&quot;X-User-Id&quot;);<br>            if (userId != null) {<br>                return Mono.just(userId);<br>            }<br>            String ip = exchange.getRequest().getRemoteAddress() != null<br>                    ? exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()<br>                    : &quot;unknown&quot;;<br>            return Mono.just(ip);<br>        };<br>    }<br>}</pre><p>Authenticated requests are rate-limited per user ID. Unauthenticated requests fall back to client IP. The rate limit counters are Redis keys with short TTLs. Restarting Redis resets the counters — acceptable because rate limiting is a protection mechanism, not a business record. A reset counter means a brief window of unenforced limits, not data loss with financial or operational consequences.</p><h3>The cost</h3><p>Redis, by default, is not durable. AOF (append-only file) and RDB snapshots are opt-in and add I/O overhead. If the Redis instance dies before flushing, cart data is gone. For cart-service, that trade is acceptable — a lost cart is an inconvenience, not a crisis. For api-gateway rate limiting, counter loss is by design. Neither of these services should be reconsidered as candidates for Redis if the data they hold were to become critical. Redis also has no join capability and no aggregation pipeline comparable to SQL or MongoDB. Queries are limited to key lookup, range scans, and set operations. If cart-service ever needed to query all carts above a certain value across all users, Redis would not be the right tool for that query.</p><h3>Elasticsearch — Relevance Scoring That SQL Can’t Fake</h3><p>search-service is the only service using Elasticsearch, and the problem it solves is specific.</p><p>LIKE &#39;%wireless headphones%&#39; against a PostgreSQL table with 500,000 products requires a full sequential scan. B-tree indexes don’t help leading wildcards. PostgreSQL’s tsvector/tsquery full-text search is a real option, but it doesn’t support field boosting — ranking results where the query term appears in name higher than where it appears in description, or combining match scores across multiple fields with per-field weights.</p><p>Elasticsearch’s inverted index makes a multi_match query across name, description, and tags — with name boosted by a factor of 3 — a millisecond operation regardless of catalog size.</p><p>ProductIndex.java:</p><pre>@Document(indexName = &quot;products&quot;, createIndex = false)<br>@Getter<br>@Setter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Builder<br>public class ProductIndex {<br>    @Id<br>    private String id;<br>    @Field(type = FieldType.Text, analyzer = &quot;standard&quot;)<br>    private String name;<br>    @Field(type = FieldType.Text, analyzer = &quot;standard&quot;)<br>    private String description;<br>    @Field(type = FieldType.Scaled_Float, scalingFactor = 100)<br>    private BigDecimal price;<br>    @Field(type = FieldType.Keyword)<br>    private String category;<br>    @Field(type = FieldType.Keyword)<br>    private List&lt;String&gt; tags;<br>    @Field(type = FieldType.Boolean)<br>    private boolean active;<br>    @Field(type = FieldType.Date)<br>    private Instant updatedAt;<br>}</pre><p>createIndex = false means Spring Data Elasticsearch will not attempt to create the index on startup. The index and its mapping are managed externally — created once with explicit settings (shard count, replica count, analyzer configuration). When the product mapping changes substantially, the index is rebuilt by replaying product.created and product.updated events through search-service’s Kafka consumer from the beginning. The annotation-based mapping on ProductIndex still drives how documents are indexed; it just doesn’t control index lifecycle.</p><p>Scaled_Float with a scaling factor of 100 stores prices as integers internally (19.99 → 1999). This avoids floating-point representation issues for a field that needs exact numeric filtering and range queries.</p><p>name and description are Text with standard analyzer — tokenized, lowercased, analyzed for stemming. category and tags are Keyword — not analyzed, matched exactly. You’d use Keyword for faceted filtering (“show me all products in ‘Electronics’”), and Text for full-text search.</p><h3>The cost</h3><p>search-service reads from Elasticsearch, but products originate in product-service’s MongoDB. Every product change in MongoDB generates a Kafka event that search-service consumes and indexes. There is a window — typically under a second, but not zero — where a product update is visible in MongoDB but not yet reflected in search results. That eventual consistency is the price of the read model. Index rebuilds during mapping changes take time proportional to catalog size and require the Kafka consumer to replay from offset zero. Elasticsearch also demands cluster sizing care — running it on undersized nodes causes GC pressure and degraded query latency. Unlike PostgreSQL or MongoDB, which can be provisioned conservatively and scaled up, Elasticsearch performs poorly when heap is constrained.</p><h3>Three Migration Tools, One Principle</h3><p>All three track which migrations have run and refuse to re-apply them. The concept is identical across all three tools; only the format changes to match the database type.</p><p>Redis and Elasticsearch have no migration tools because there is nothing to migrate. Redis is schema-less — keys are created at runtime and expire by TTL or eviction policy. Elasticsearch index mappings are defined via @Field annotations on the entity class and applied when the index is created; subsequent mapping changes that aren’t backwards-compatible require an index rebuild, not a migration script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZYRN52QAQq64PlXre1CoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFXVdzyzY8awY7QlBsMu_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8Fsa4qisPDyMFVKy604Fw.png" /></figure><p>The query pattern determines the storage type. The storage type determines the migration tool. Start there, and the rest follows.</p><p><em>Next in this series: </em><a href="https://medium.com/p/6221a82e57db"><em>Part 9 — Security Architecture: JWT at the Gateway, Trust Headers Downstream</em></a><em>, where the gateway validates tokens once and downstream services trust headers instead.</em></p><p><em>Part 8 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · Microservices · PostgreSQL · MongoDB · Redis · Elasticsearch · Database Design · Software Architecture</p><h3>Full Source Code</h3><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7">Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</a></li><li><a href="https://medium.com/p/ad88995e10a7">The Transactional Outbox Pattern — Never Lose a Kafka Message Again</a></li><li><a href="https://medium.com/p/c612830da237">Saga Choreography with Kafka — Distributed Transactions Without 2PC</a></li><li><a href="https://medium.com/p/82977eab91b8">Sync vs Async — When to Use gRPC and When to Use Kafka</a></li><li><a href="https://medium.com/p/c99f936b80d7">CQRS in Practice — Two Services, Two Approaches</a></li><li><a href="https://medium.com/p/ead0f970ac58">Idempotency in Payment Services — Exactly-Once Semantics on a Budget</a></li><li><a href="https://medium.com/p/fee1a51a5768"><strong>Polyglot Persistence — Choosing the Right Database for Each Service</strong></a> ← <em>you are here</em></li><li><a href="https://medium.com/p/6221a82e57db">Security Architecture — JWT at the Gateway, Trust Headers Downstream</a></li><li><a href="https://medium.com/p/cc9042e94901">Observability Stack — Tracing, Metrics, and Logs Across 10 Services</a></li><li><a href="https://medium.com/p/74de682e547e">Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fee1a51a5768" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idempotency in Payment Services — Exactly-Once Semantics on a Budget]]></title>
            <link>https://medium.com/@ivan.willy.artdian/idempotency-in-payment-services-exactly-once-semantics-on-a-budget-ead0f970ac58?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ead0f970ac58</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[payment-systems]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 02:04:45 GMT</pubDate>
            <atom:updated>2026-07-10T02:04:45.928Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 7 of Spring Boot Microservices in Production</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPy2ry1A6DBmEx9eD3vJ2g.png" /></figure><p>The request timed out. The client doesn’t know if the payment went through. It retries.</p><p>Now you have two authorization attempts hitting your payment gateway with the same card, the same amount, the same order. One of them is going to charge the customer twice — unless your service is built to handle this.</p><p>Network timeouts are the obvious case. But in a distributed system running Kafka, there are two more sources of duplicate requests that are easier to miss: at-least-once event delivery from the broker, and compensating transactions replayed during saga failure recovery. By the time you’ve seen all three in production, you stop treating idempotency as a nice-to-have.</p><h3>Three Places Duplicates Enter</h3><p><strong>REST retries.</strong> HTTP clients retry on timeout, connection reset, or 5xx. The client has no way to know whether the first request completed server-side. Without a guard, a retry creates a second payment.</p><p><strong>Kafka redelivery.</strong> Kafka guarantees at-least-once delivery. If a consumer crashes after processing but before committing the offset, the same message arrives again. For most events this is harmless — updating a search index twice produces the same result. For a payment refund, it does not.</p><p><strong>Saga compensation replay.</strong> When a saga fails and recovers, compensating steps re-execute. An OrderCancelled event might arrive a second time hours after the first. The OrderEventConsumer in payment-service handles this case directly:</p><pre>@KafkaListener(topics = &quot;order.events&quot;, groupId = &quot;payment-service&quot;,<br>        containerFactory = &quot;kafkaListenerContainerFactory&quot;)<br>public void onOrderCancelled(OrderCancelled event) {<br>    log.info(&quot;Received OrderCancelled for orderId={}&quot;, event.getOrderId());<br>    paymentRepository.findByOrderId(event.getOrderId().toString())<br>            .filter(payment -&gt; payment.getStatus() == PaymentStatus.CAPTURED)<br>            .flatMap(payment -&gt; refundPaymentUseCase.refund(payment.getId()))<br>            .doOnError(e -&gt; log.error(&quot;Failed to process order cancellation refund&quot;, e))<br>            .onErrorResume(e -&gt; {<br>                log.warn(&quot;Skipping refund for orderId={}: {}&quot;, event.getOrderId(), e.getMessage());<br>                return Mono.empty();<br>            })<br>            .subscribe();<br>}</pre><p>The .filter(payment -&gt; payment.getStatus() == PaymentStatus.CAPTURED) is doing the idempotency work here. A duplicate OrderCancelled event finds a REFUNDED payment, the filter excludes it, nothing happens. The domain state itself is the guard — no separate record needed.</p><p>This works because the state transition is the answer to “was this already processed?” A payment can only be refunded once; its status says so. The problem with REST payment initiation is that no state transition answers that question. A PENDING payment doesn’t tell you whether this specific HTTP request already created it or a second one is about to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njINXx8h5rv4AXOUHhTGPA.png" /></figure><h3>The Record That Survives Retries</h3><p>For REST requests, the guard is an IdempotencyRecord stored in its own table.</p><pre>@Table(&quot;idempotency_records&quot;)<br>public class IdempotencyRecord {<br>    @Id<br>    private UUID id;<br>    private String idempotencyKey;<br>    private String responsePayload;<br>    private LocalDateTime createdAt;<br>    public IdempotencyRecord(String idempotencyKey, String responsePayload) {<br>        this.id = UUID.randomUUID();<br>        this.idempotencyKey = idempotencyKey;<br>        this.responsePayload = responsePayload;<br>        this.createdAt = LocalDateTime.now();<br>    }<br>    public boolean isExpired() {<br>        return createdAt != null &amp;&amp; createdAt.plusHours(24).isBefore(LocalDateTime.now());<br>    }<br>    // getters/setters omitted<br>}</pre><p>The responsePayload stores the full serialized PaymentResponse. When a duplicate request hits within the 24-hour window, the service deserializes and returns the original response — identical HTTP body, identical status. The caller can’t tell it didn’t process again.</p><p>The schema has two separate tables:</p><pre>CREATE TABLE payments (<br>    id UUID PRIMARY KEY,<br>    order_id VARCHAR(255) NOT NULL,<br>    customer_id VARCHAR(255) NOT NULL,<br>    amount NUMERIC(12,2) NOT NULL,<br>    currency VARCHAR(3) NOT NULL,<br>    idempotency_key VARCHAR(255) NOT NULL UNIQUE,<br>    status VARCHAR(50) NOT NULL,<br>    gateway_reference VARCHAR(255),<br>    failure_code VARCHAR(100),<br>    created_at TIMESTAMP NOT NULL,<br>    updated_at TIMESTAMP NOT NULL<br>);<br><br>CREATE TABLE idempotency_records (<br>    id UUID PRIMARY KEY,<br>    idempotency_key VARCHAR(255) NOT NULL UNIQUE,<br>    response_payload TEXT NOT NULL,<br>    created_at TIMESTAMP NOT NULL<br>);</pre><p>Two tables because they serve different lifetimes. A Payment row is a financial record — it never expires. An IdempotencyRecord is a retry cache — after 24 hours, a repeated request is a new payment attempt, not a duplicate. Keeping expiry logic in the record table avoids touching the payments table.</p><p>The UNIQUE on payments.idempotency_key is not redundant with idempotency_records.idempotency_key. They catch different things. The record table catches application-layer duplicates before they hit the gateway. The payments table constraint catches database-layer races — two concurrent requests that both pass the findByKey check before either has committed. More on that below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBwnjkY5aFQs0GUoOT0IfQ.png" /></figure><h3>The Reactive Guard</h3><p>PaymentDomainService.initiate() is where both paths — cache hit and cache miss — live. The service uses R2DBC and Project Reactor throughout, so the guard is a reactive chain:</p><pre>@Override<br>public Mono&lt;PaymentResponse&gt; initiate(InitiatePaymentCommand cmd) {<br>    return idempotencyRepository.findByKey(cmd.idempotencyKey())<br>            .filter(record -&gt; !record.isExpired())<br>            .flatMap(existing -&gt; {<br>                try {<br>                    return Mono.just(objectMapper.readValue(existing.getResponsePayload(), PaymentResponse.class));<br>                } catch (JsonProcessingException e) {<br>                    return Mono.error(new DomainException(&quot;DESERIALIZATION_ERROR&quot;, &quot;Failed to deserialize cached response&quot;));<br>                }<br>            })<br>            .switchIfEmpty(Mono.defer(() -&gt; {<br>                Payment payment = Payment.authorize(<br>                        UUID.randomUUID(),<br>                        cmd.orderId(),<br>                        cmd.customerId(),<br>                        cmd.amount(),<br>                        cmd.currency(),<br>                        cmd.idempotencyKey()<br>                );<br>                return paymentRepository.save(payment)<br>                        .flatMap(saved -&gt; paymentGatewayPort.authorize(saved)<br>                                .flatMap(result -&gt; {<br>                                    if (result.success()) {<br>                                        saved.markAuthorized(result.gatewayRef());<br>                                    } else {<br>                                        saved.fail(result.failureCode());<br>                                    }<br>                                    return paymentRepository.save(saved);<br>                                }))<br>                        .flatMap(updated -&gt; publishPaymentEvent(updated).thenReturn(updated))<br>                        .map(PaymentResponse::from)<br>                        .flatMap(response -&gt; saveIdempotencyRecord(cmd.idempotencyKey(), response).thenReturn(response));<br>            }));<br>}</pre><p>Three non-obvious things in this chain:</p><p><strong>The expiry filter makes </strong><strong>switchIfEmpty fire.</strong> .filter(record -&gt; !record.isExpired()) converts an expired record to an empty Mono. switchIfEmpty then fires the full payment creation path — a new payment is created with the same idempotency key. The UNIQUE constraint on payments.idempotency_key would reject this if the original payment row still exists. This means a re-attempt after the 24-hour window against an existing order will fail at the DB level rather than silently charge again.</p><p><strong>Deserialization failure returns a 500, not a retry.</strong> If the stored JSON in response_payload is malformed, the catch block returns Mono.error(new DomainException(&quot;DESERIALIZATION_ERROR&quot;, ...)). The service does not fall through to the payment creation path. A corrupted record is not treated as a cache miss. This is the conservative choice — a 500 response prompts investigation rather than a silent double-charge. The cost is that a corrupted record blocks all retries for that key until it’s manually cleared.</p><p><strong>The idempotency record saves after the event publish.</strong> saveIdempotencyRecord is the last step in the miss path — after paymentRepository.save, after publishPaymentEvent. The publishPaymentEvent method has an onErrorResume that swallows publish failures:</p><pre>return eventPublisher.publish(json, PAYMENT_EVENTS_TOPIC)<br>        .onErrorResume(e -&gt; {<br>            log.error(&quot;Failed to publish payment event for paymentId={}&quot;, payment.getId(), e);<br>            return Mono.empty();<br>        });</pre><p>If Kafka is unavailable, the payment is authorized, the publish is swallowed, and the idempotency record still saves. A retry of the original request will return the cached response. The payment happened; downstream services just didn’t hear about it yet. That’s a separate problem — event delivery failure — not a duplicate charge problem. But the idempotency record saving doesn’t mean the event was delivered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vD35PY0f3hdRvRFVn3ZF0g.png" /></figure><h3>What the Database Constraint Catches</h3><p>The application-layer guard has a race window. Two concurrent requests with the same idempotency key can both call idempotencyRepository.findByKey() and both get an empty result before either has saved a record. Without the database constraint, both would proceed to the gateway.</p><p>Reactive non-blocking code makes this more likely, not less. There’s no thread-level serialization. Both requests run concurrently on the event loop, hit the database, and both see “no record.”</p><p>The UNIQUE constraint on payments.idempotency_key is the hard stop. When both requests try to insert into payments, one succeeds and one gets a constraint violation. The violation propagates as an error in the reactive chain. The client gets a 500 on the losing request — not ideal, but no double-charge.</p><p>The cost is paid on every insert: the database writes and maintains a unique index on payments.idempotency_key for the lifetime of the table. For a high-volume payments table, that index adds measurable write overhead. The alternative — relying on the application-layer check alone — trades write performance for a race window that will eventually be hit.</p><h3>Why Only Payment-Service</h3><p>Most services in this codebase don’t have idempotency record tables. inventory-service updates stock quantities. order-service manages order state. Both consume events from Kafka with at-least-once delivery. Neither has an idempotency_records table.</p><p>They don’t need one because their operations are naturally guarded by domain state. The domain model rejects impossible transitions — you can’t ship an already-shipped order, you can’t cancel an already-cancelled one. A duplicate event hits a state guard and stops.</p><p>Payment initiation has no such natural guard. PENDING is a valid starting state for both a first attempt and a retry. The domain model can’t distinguish them. That’s the condition that requires an external record: when the domain state doesn’t answer “have I seen this exact request before?”</p><p>The flip side: an idempotency record table is only useful when you control the idempotency key. For Kafka-sourced events where you don’t control message deduplication, domain state checks are more reliable because they don’t depend on key derivation being consistent across producers. OrderEventConsumer doesn’t try to derive an idempotency key from the event — it checks payment status, which is always authoritative regardless of how the event arrived.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7wrJa-o8-c5EL8XHIz6tA.png" /></figure><p>Use an idempotency record table when the domain state can’t distinguish a retry from a first attempt and you control the key. Use domain state as the guard when the state transition itself is the answer. Which one fits depends on what your domain model already knows about the operation.</p><p><em>Next in this series: </em><a href="https://medium.com/p/fee1a51a5768"><em>Part 8 — Polyglot Persistence: Choosing the Right Database for Each Service</em></a><em>, where PostgreSQL, MongoDB, Redis, and Elasticsearch each earn their place in the platform.</em></p><p><em>Part 7 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · Microservices · Idempotency · Payments · Kafka · Distributed Systems</p><h3>Full Source Code</h3><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7">Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</a></li><li><a href="https://medium.com/p/ad88995e10a7">The Transactional Outbox Pattern — Never Lose a Kafka Message Again</a></li><li><a href="https://medium.com/p/c612830da237">Saga Choreography with Kafka — Distributed Transactions Without 2PC</a></li><li><a href="https://medium.com/p/82977eab91b8">Sync vs Async — When to Use gRPC and When to Use Kafka</a></li><li><a href="https://medium.com/p/c99f936b80d7">CQRS in Practice — Two Services, Two Approaches</a></li><li><a href="https://medium.com/p/ead0f970ac58"><strong>Idempotency in Payment Services — Exactly-Once Semantics on a Budget</strong></a> ← <em>you are here</em></li><li><a href="https://medium.com/p/fee1a51a5768">Polyglot Persistence — Choosing the Right Database for Each Service</a></li><li><a href="https://medium.com/p/6221a82e57db">Security Architecture — JWT at the Gateway, Trust Headers Downstream</a></li><li><a href="https://medium.com/p/cc9042e94901">Observability Stack — Tracing, Metrics, and Logs Across 10 Services</a></li><li><a href="https://medium.com/p/74de682e547e">Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ead0f970ac58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CQRS in Practice — Two Services, Two Approaches]]></title>
            <link>https://medium.com/@ivan.willy.artdian/cqrs-in-practice-two-services-two-approaches-c99f936b80d7?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c99f936b80d7</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 01:19:19 GMT</pubDate>
            <atom:updated>2026-07-09T01:19:19.358Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 6 of the Spring Boot Microservices in Production series.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBQdP16n3JUTRviMjP1uUA.png" /></figure><p>Picture a product page. It needs the product name, price, description — standard stuff, all in your write model. It also needs the average rating across every review ever submitted for that product, the total review count, and a relevance-ranked position in search results.</p><p>Now ask your products table for all of that.</p><p>The problem isn’t that it’s impossible. You can write the GROUP BY and the AVG() and the full-text search query. But you’ve just made every product read as expensive as your most expensive query — and you’ve coupled your read performance to your write volume. Ten reviews or ten million, the query shape is the same.</p><p>Command Query Responsibility Segregation (CQRS) says to stop doing that. Separate the read model from the write model. Shape each one for what it actually has to do. Use an event to bridge them.</p><p>That’s the full pattern. No event sourcing, no distributed sagas, no prescribed framework. Just two models instead of one.</p><p>In this project, two services apply CQRS differently. review-service uses Spring Cloud Stream’s functional style to maintain a pre-aggregated rating summary. search-service uses raw @KafkaListener to maintain an Elasticsearch index. Same principle underneath. Different tool choices, for different reasons.</p><h3>The Two Services</h3><p>review-servicesearch-serviceArchitectureHexagonalLayeredWrite side ownerReviewCommandServiceproduct-serviceEventReviewCreatedEvent → review.createdProductUpdatedEvent → product.updatedConsumer styleSpring Cloud Stream Consumer&lt;T&gt;@KafkaListenerRead modelProductRatingSummary in MongoDBProductIndex in ElasticsearchRead query servedAverage rating by productIdFull-text search with relevance ranking</p><h3>review-service: Spring Cloud Stream</h3><h3>The Write Side</h3><p>ReviewCommandService handles review creation. It validates the rating, saves the review, then fires an event through a port interface:</p><pre>@Service<br>@RequiredArgsConstructor<br>@Slf4j<br>public class ReviewCommandService implements CreateReviewUseCase {</pre><pre>    private final ReviewRepository reviewRepository;<br>    private final ReviewEventPublisher eventPublisher;</pre><pre>    @Override<br>    public Review createReview(Command command) {<br>        Review review = new Review(<br>                UUID.randomUUID().toString(),<br>                command.productId(),<br>                command.userId(),<br>                command.userName(),<br>                command.rating(),<br>                command.comment(),<br>                Instant.now(),<br>                Instant.now());</pre><pre>        Review saved = reviewRepository.save(review);</pre><pre>        eventPublisher.publishReviewCreated(saved);</pre><pre>        log.info(&quot;Review created reviewId={} productId={}&quot;, saved.getId(), saved.getProductId());<br>        return saved;<br>    }<br>}</pre><p>ReviewEventPublisher is an interface defined in the application layer. The service doesn’t know Kafka exists — it calls a port, and the infrastructure layer handles the rest. This is the hexagonal contract.</p><p>The port implementation uses Spring Cloud Stream’s StreamBridge:</p><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class StreamBridgeReviewEventPublisher implements ReviewEventPublisher {</pre><pre>    private final StreamBridge streamBridge;<br>    private final ReviewEventMapper mapper;</pre><pre>    @Override<br>    public void publishReviewCreated(Review review) {<br>        boolean sent = streamBridge.send(&quot;reviewCreated-out-0&quot;, mapper.toEvent(review));<br>        log.info(&quot;Published ReviewCreatedEvent reviewId={} sent={}&quot;, review.getId(), sent);<br>    }<br>}</pre><p>&quot;reviewCreated-out-0&quot; is a binding name, not a Kafka topic. The mapping to topic review.created lives in application.yml. Swap the broker, update the config, the publisher class stays the same.</p><p>The binding configuration ties everything together:</p><pre>spring:<br>  cloud:<br>    stream:<br>      bindings:<br>        reviewCreated-out-0:<br>          destination: review.created<br>          content-type: application/json<br>        reviewCreated-in-0:<br>          destination: review.created<br>          group: review-service-read-model<br>          content-type: application/json<br>      function:<br>        definition: reviewCreated</pre><p>Two bindings, one topic. The producer (reviewCreated-out-0) and consumer (reviewCreated-in-0) both point to review.created. The function.definition tells Spring Cloud Stream which beans to wire as functional consumers.</p><h3>The Read Side</h3><p>The consumer is a plain Java Consumer&lt;T&gt; registered as a Spring bean:</p><pre>@Configuration<br>@RequiredArgsConstructor<br>@Slf4j<br>public class ReviewReadModelUpdater {</pre><pre>    private final RatingSummaryRepository ratingSummaryRepository;</pre><pre>    @Bean<br>    public Consumer&lt;ReviewCreatedEvent&gt; reviewCreated() {<br>        return event -&gt; {<br>            log.info(&quot;Updating read model for productId={} reviewId={}&quot;,<br>                    event.productId(), event.reviewId());</pre><pre>            ProductRatingSummary summary = ratingSummaryRepository<br>                    .findByProductId(event.productId())<br>                    .orElseGet(() -&gt; new ProductRatingSummary(event.productId(), 0, 0));</pre><pre>            summary.addRating(event.rating());<br>            ratingSummaryRepository.save(summary);</pre><pre>            log.info(&quot;Rating summary updated productId={} count={} avg={}&quot;,<br>                    event.productId(), summary.getReviewCount(), summary.getAverageRating());<br>        };<br>    }<br>}</pre><p>No @KafkaListener. No topic annotation. Spring Cloud Stream wires the binding reviewCreated-in-0 to this bean automatically — the bean is named reviewCreated, which matches reviewCreated-in-0 by convention.</p><p>The consumer is a standard Java function. You can unit test it by instantiating the bean directly and calling it with a test event, no Kafka infrastructure required.</p><p>The read model that gets updated is ProductRatingSummary:</p><pre>public class ProductRatingSummary {</pre><pre>    private final String productId;<br>    private long reviewCount;<br>    private long ratingSum;</pre><pre>    public ProductRatingSummary(String productId, long reviewCount, long ratingSum) {<br>        this.productId = productId;<br>        this.reviewCount = reviewCount;<br>        this.ratingSum = ratingSum;<br>    }</pre><pre>    public void addRating(int rating) {<br>        reviewCount++;<br>        ratingSum += rating;<br>    }</pre><pre>    public BigDecimal getAverageRating() {<br>        if (reviewCount == 0) return BigDecimal.ZERO;<br>        return BigDecimal.valueOf(ratingSum)<br>                .divide(BigDecimal.valueOf(reviewCount), 2, RoundingMode.HALF_UP);<br>    }<br>}</pre><p>No annotations. No Spring imports. Two longs and a method that takes one millisecond to run. When a product’s average rating is requested, the query service fetches this document by productId. That’s a single key lookup in MongoDB — O(1) regardless of how many reviews exist.</p><p>This works because reviews are immutable after creation. A rating never changes once submitted. Each new review increments reviewCount by 1 and adds to ratingSum. The update is append-only, which makes pre-aggregation safe. If ratings could be edited, the math breaks and you’d need a different read model strategy.</p><h3>What Spring Cloud Stream Costs You</h3><p>The broker abstraction is real and it earns its keep in a hexagonal service. But it has specific failure modes worth knowing.</p><p>The binding name convention is implicit. The bean named reviewCreated wires to reviewCreated-in-0 automatically — but only if function.definition in application.yml includes reviewCreated. Miss that config key and the consumer simply doesn’t start. No exception. No log warning. Messages accumulate in the topic and nothing processes them.</p><p>The same applies to binding names in streamBridge.send(). Pass a string that doesn’t match a configured binding and StreamBridge returns false. The message is dropped. The log line says sent=false, but only if you’re logging the return value — which is easy to miss.</p><p>Getting partition and offset metadata in the consumer requires extra work. You’d need to configure header mapping in the binding and add a Message&lt;T&gt; parameter to extract Kafka headers. It’s possible but not the default — you’re working against the abstraction rather than with it.</p><p>Debugging a broken Spring Cloud Stream consumer usually means reading actuator endpoints (/actuator/bindings) and checking binder logs, not the application logs. That’s a different mental model from reading a @KafkaListener annotation.</p><h3>search-service: @KafkaListener</h3><h3>Where the Event Comes From</h3><p>search-service doesn’t own a write side. It’s a read-only projection service. The data it indexes comes from product-service, which publishes events using a plain KafkaTemplate:</p><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class KafkaProductEventPublisher implements ProductEventPublisher {</pre><pre>    private static final String TOPIC = &quot;product.updated&quot;;</pre><pre>    private final KafkaTemplate&lt;String, Object&gt; kafkaTemplate;</pre><pre>    @Override<br>    public void publish(ProductDomainEvent event) {<br>        ProductUpdatedEvent kafkaEvent = switch (event) {<br>            case ProductCreatedDomainEvent e -&gt; new ProductUpdatedEvent(<br>                    UUID.randomUUID().toString(), e.productId(), e.name(),<br>                    e.description(), e.price(), e.category(), e.tags(), true, e.occurredAt()<br>            );<br>            case ProductUpdatedDomainEvent e -&gt; new ProductUpdatedEvent(<br>                    UUID.randomUUID().toString(), e.productId(), e.name(),<br>                    e.description(), e.price(), e.category(), e.tags(), e.active(), e.occurredAt()<br>            );<br>        };</pre><pre>        kafkaTemplate.send(TOPIC, kafkaEvent.productId(), kafkaEvent)<br>                .whenComplete((result, ex) -&gt; {<br>                    if (ex != null) {<br>                        log.error(&quot;Failed to publish product event for productId={}&quot;,<br>                                kafkaEvent.productId(), ex);<br>                    } else {<br>                        log.debug(&quot;Published product event: productId={}&quot;, kafkaEvent.productId());<br>                    }<br>                });<br>    }<br>}</pre><p>Both create and update domain events map to a single ProductUpdatedEvent on the Kafka side. The active field handles deactivation. search-service doesn’t need to know about the product domain model — it just needs enough data to build a search index.</p><h3>The Consumer</h3><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class ProductEventConsumer {</pre><pre>    private final ProductSearchService productSearchService;</pre><pre>    @KafkaListener(<br>            topics = &quot;product.updated&quot;,<br>            groupId = &quot;${spring.kafka.consumer.group-id}&quot;,<br>            containerFactory = &quot;kafkaListenerContainerFactory&quot;<br>    )<br>    public void onProductUpdated(@Payload ProductUpdatedEvent event,<br>                                  @Header(KafkaHeaders.RECEIVED_PARTITION) int partition,<br>                                  @Header(KafkaHeaders.OFFSET) long offset) {<br>        log.info(&quot;Received ProductUpdatedEvent productId={} partition={} offset={}&quot;,<br>                event.productId(), partition, offset);</pre><pre>        if (!event.active()) {<br>            productSearchService.removeProduct(event.productId());<br>            return;<br>        }</pre><pre>        ProductIndex index = ProductIndex.builder()<br>                .id(event.productId())<br>                .name(event.name())<br>                .description(event.description())<br>                .price(event.price())<br>                .category(event.category())<br>                .tags(event.tags())<br>                .active(event.active())<br>                .updatedAt(event.occurredAt())<br>                .build();</pre><pre>        productSearchService.indexProduct(index);<br>    }<br>}</pre><p>Read the class — everything is declared. The topic. The consumer group. The container factory. You don’t need to cross-reference a binding config to understand what this consumer is listening to.</p><p>The @Header parameters give you partition and offset directly from Kafka metadata. Every log line from this consumer includes both. When a product update doesn’t appear in search results, you grep the logs for the productId. You see partition=2 offset=14837. You can check the Kafka topic at that exact position, confirm the event was received and processed, and narrow the problem to indexing rather than consumption. That kind of per-message observability is a log line away.</p><h3>The Read Model</h3><p>ProductIndex is the Elasticsearch document:</p><pre>@Document(indexName = &quot;products&quot;, createIndex = false)<br>@Getter<br>@Setter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Builder<br>public class ProductIndex {</pre><pre>    @Id<br>    private String id;</pre><pre>    @Field(type = FieldType.Text, analyzer = &quot;standard&quot;)<br>    private String name;</pre><pre>    @Field(type = FieldType.Text, analyzer = &quot;standard&quot;)<br>    private String description;</pre><pre>    @Field(type = FieldType.Scaled_Float, scalingFactor = 100)<br>    private BigDecimal price;</pre><pre>    @Field(type = FieldType.Keyword)<br>    private String category;</pre><pre>    @Field(type = FieldType.Keyword)<br>    private List&lt;String&gt; tags;</pre><pre>    @Field(type = FieldType.Boolean)<br>    private boolean active;</pre><pre>    @Field(type = FieldType.Date)<br>    private Instant updatedAt;<br>}</pre><p>name and description use the standard analyzer — tokenized, lowercased, stop words removed. category and tags are Keyword — exact match, no analysis. This lets a search request filter on category: &quot;Electronics&quot; exactly while running a scored text search across name and description.</p><p>A search query runs a multi_match across those fields:</p><pre>{<br>  &quot;bool&quot;: {<br>    &quot;must&quot;: [<br>      {<br>        &quot;multi_match&quot;: {<br>          &quot;query&quot;: &quot;wireless headphones&quot;,<br>          &quot;fields&quot;: [&quot;name^3&quot;, &quot;description&quot;, &quot;tags&quot;],<br>          &quot;type&quot;: &quot;best_fields&quot;<br>        }<br>      }<br>    ],<br>    &quot;filter&quot;: [<br>      { &quot;term&quot;: { &quot;active&quot;: true } },<br>      { &quot;term&quot;: { &quot;category&quot;: &quot;Electronics&quot; } }<br>    ]<br>  }<br>}</pre><p>name^3 — the name field contributes three times more to the relevance score than description or tags. A product whose name matches “wireless headphones” ranks above one where only the description mentions it. That scoring behavior is a single character in the query. Replicating it in MongoDB’s text index — which uses fixed weights set at index creation time — is far more constrained.</p><p>The Elasticsearch index is both the data store and the query engine for this service. There’s no secondary database. search-service holds exactly one source of truth: what the product catalog looks like for search purposes.</p><h3>What @KafkaListener Costs You</h3><p>The consumer is tightly coupled to Kafka. The topic name is in the annotation. The consumer group is a Kafka concept. The container factory is configured against Kafka-specific deserialization settings. If this service ever needed to switch message brokers, this class and its config would need to be rewritten.</p><p>For a service whose only job is to consume from Kafka and write to Elasticsearch, that coupling is an acceptable tradeoff. Both Kafka and Elasticsearch are infrastructure commitments that get made at a system level, not a service level. But the coupling is still real — it accumulates as the number of listeners in a service grows.</p><p>The consumer factory configuration is also verbose. You need a ConcurrentKafkaListenerContainerFactory bean, a ConsumerFactory bean, and deserializer config spread across application.yml. None of it is hard, but it’s more setup than Spring Cloud Stream’s binder-based config, and it’s easy to misconfigure the trusted packages list and end up with deserialization errors that only show up at runtime.</p><h3>Choosing Between Them</h3><p>The decision isn’t a judgment about which library is better. It’s three questions about the service you’re building.</p><p><strong>Does your architecture have a broker boundary to protect?</strong></p><p>review-service is hexagonal. ReviewEventPublisher is an outbound port in the application layer. The domain model has no broker imports. Spring Cloud Stream’s abstraction fits naturally as the adapter behind that port — the broker is config, not code. Replacing Kafka with a different broker is a dependency swap and a config update.</p><p>search-service is layered. There’s no port interface wrapping the consumer. The consumer class is infrastructure by nature — it exists to receive Kafka events and write to Elasticsearch. Adding a broker abstraction here wouldn’t protect anything, it would just add a layer with no purpose.</p><p><strong>Do you need per-message broker metadata?</strong></p><p>For search-service, partition and offset per message is operationally useful. Index failures need to be traceable to specific positions in the log. @KafkaListener exposes those directly through @Header — no additional config needed.</p><p>For review-service, partition and offset metadata isn’t needed. The consumer logic is deterministic: a ReviewCreatedEvent arrives, a rating summary updates. Tracing a specific event to a partition is not part of the debugging story here.</p><p><strong>Is Kafka a permanent infrastructure choice for this service?</strong></p><p>If yes, @KafkaListener’s coupling is a non-issue — you’re not going to swap the broker. If there’s any chance the messaging infrastructure changes, Spring Cloud Stream preserves the option to reconfigure rather than rewrite.</p><p>Spring Cloud Stream@KafkaListenerBroker couplingConfig onlyCode + configTopic declarationBinding config in application.ymlAnnotation on the methodPartition/offset accessNeeds extra header mapping configDirect via @HeaderConsumer unit testingNo Kafka neededNeeds Kafka container or mockSilent consumer failure riskHigh — naming mismatch = no errorLow — misconfigured factory throws at startupBroker swap costUpdate config + binder depRewrite consumer classesDebugging broken wiringActuator /actuator/bindingsStacktrace at startup</p><p>Neither column wins. They’re different positions on the abstraction curve, appropriate for different service structures.</p><h3>The Read Model Is the Query</h3><p>Both services maintain CQRS read models, but they look nothing alike — because the queries they serve look nothing alike.</p><p>ProductRatingSummary has two fields: reviewCount and ratingSum. The average is computed from those two numbers at read time. The document is fetched by productId — a single key lookup. The read model is optimized for one thing: returning a pre-computed aggregate as fast as possible. It works because the update operation is append-only: a new review increments a counter and adds to a sum. The entire state of ten thousand reviews compresses to two longs.</p><p>ProductIndex has eight fields with type annotations that control how Elasticsearch analyzes and stores each one. The document is a projection of the current product state, shaped for a query that needs tokenization, stop word removal, field boosting, exact-match category filtering, and price range filtering — all in a single scored result set. The read model is optimized for one thing: relevance-ranked full-text search.</p><p>You can’t serve the rating query from ProductIndex. You can’t serve the search query from ProductRatingSummary. Neither is a general-purpose model — they’re both narrow by design. That narrowness is the point. CQRS gives you the freedom to build a read model that fits the query exactly, instead of compromising to fit a model that has to serve everything.</p><h3>Wrapping Up</h3><p>CQRS shows up in this project twice: once in review-service with Spring Cloud Stream, once in search-service with @KafkaListener. The pattern is the same. The tools are different.</p><p>review-service needed a broker-agnostic boundary that respects its hexagonal structure — Spring Cloud Stream delivers that, with the tradeoff of implicit binding conventions that can fail silently. search-service needed direct access to partition and offset metadata, explicit topic configuration, and no abstraction overhead over a service that’s infrastructure by nature — @KafkaListener delivers that, with the tradeoff of hard Kafka coupling.</p><p>The read models are different because the queries are different. A pre-aggregated MongoDB document for rating lookups, an Elasticsearch index for relevance-ranked search. Each model is shaped for the query it serves, not for consistency with the other.</p><p>In a microservices system, variety across services is expected. Different services have different structures, different query requirements, and different infrastructure commitments. Using the same messaging abstraction everywhere wouldn’t be consistency — it would be uniformity at the cost of fit.</p><p>The work is knowing what each service actually needs, then choosing accordingly.</p><p><em>Next in this series: </em><a href="https://medium.com/p/ead0f970ac58"><em>Part 7 — Idempotency in Payment Services: Exactly-Once Semantics on a Budget</em></a><em>, where duplicate Kafka deliveries and client retries meet two different idempotency guards.</em></p><p><em>Part 6 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · Microservices · CQRS · Kafka · Elasticsearch · Spring Cloud Stream · Software Architecture</p><h3>Full Source Code</h3><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7">Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</a></li><li><a href="https://medium.com/p/ad88995e10a7">The Transactional Outbox Pattern — Never Lose a Kafka Message Again</a></li><li><a href="https://medium.com/p/c612830da237">Saga Choreography with Kafka — Distributed Transactions Without 2PC</a></li><li><a href="https://medium.com/p/82977eab91b8">Sync vs Async — When to Use gRPC and When to Use Kafka</a></li><li><a href="https://medium.com/p/c99f936b80d7"><strong>CQRS in Practice — Two Services, Two Approaches</strong></a> ← <em>you are here</em></li><li><a href="https://medium.com/p/ead0f970ac58">Idempotency in Payment Services — Exactly-Once Semantics on a Budget</a></li><li><a href="https://medium.com/p/fee1a51a5768">Polyglot Persistence — Choosing the Right Database for Each Service</a></li><li><a href="https://medium.com/p/6221a82e57db">Security Architecture — JWT at the Gateway, Trust Headers Downstream</a></li><li><a href="https://medium.com/p/cc9042e94901">Observability Stack — Tracing, Metrics, and Logs Across 10 Services</a></li><li><a href="https://medium.com/p/74de682e547e">Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c99f936b80d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sync vs Async: When to Use gRPC and When to Use Kafka]]></title>
            <link>https://medium.com/@ivan.willy.artdian/sync-vs-async-when-to-use-grpc-and-when-to-use-kafka-82977eab91b8?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/82977eab91b8</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 01:19:09 GMT</pubDate>
            <atom:updated>2026-07-09T01:19:09.040Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 5 of the Spring Boot Microservices in Production series.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAAygMM0yKQk94VAgc4U5g.png" /></figure><p>Imagine a customer submits an order for five items. Three of them are out of stock. If you used Kafka for the stock check, here’s what happens: you commit the order to the database as PENDING, publish an OrderCreatedEvent, and return HTTP 201. Then inventory-service consumes the event, finds the shortfall, and fires a StockReservationFailedEvent. Order-service receives it — maybe 300ms later, maybe 3 seconds later — and runs a compensating transaction to cancel. The customer gets a 201 followed by a failure notification. The order existed in a broken state for a non-zero amount of time.</p><p>That’s not wrong, exactly. Saga choreography handles it. But you’ve made the order’s validity uncertain by design. You’ve written a permanent record to the database before knowing whether the order could be fulfilled. Every downstream step — payment, notification, analytics — now has to tolerate orders that might be cancelled before they begin.</p><p>gRPC exists in this system to stop that from happening.</p><h3>The Order Placement Flow</h3><p>Everything starts in PlaceOrderService.placeOrder(). The structure makes the strategy explicit:</p><pre>@Service<br>@RequiredArgsConstructor<br>@Slf4j<br>public class PlaceOrderService implements PlaceOrderUseCase {<br>    private final OrderRepository orderRepository;<br>    private final OutboxRepository outboxRepository;<br>    private final ProductPriceGateway productPriceGateway;<br>    private final StockCheckGateway stockCheckGateway;<br>    private final CartGateway cartGateway;<br>    private final ObjectMapper objectMapper;<br>    @Override<br>    @Transactional<br>    public Order placeOrder(Command command) {<br>        List&lt;CartGateway.CartItem&gt; cartItems = cartGateway.getCartItems(command.userId());<br>        if (cartItems.isEmpty()) {<br>            throw new EmptyCartException(&quot;Cart is empty&quot;);<br>        }<br>        List&lt;String&gt; productIds = cartItems.stream()<br>                .map(CartGateway.CartItem::productId).toList();<br>        // Step 1 - sync gRPC: check stock availability (fast-fail)<br>        List&lt;StockCheckGateway.StockItem&gt; stockItems = cartItems.stream()<br>                .map(i -&gt; new StockCheckGateway.StockItem(i.productId(), i.quantity()))<br>                .toList();<br>        StockCheckGateway.StockCheckResult stockCheck = stockCheckGateway.checkStock(stockItems);<br>        if (!stockCheck.allAvailable()) {<br>            throw new OutOfStockException(&quot;One or more items out of stock&quot;);<br>        }<br>        // Step 2 - sync gRPC: fetch current prices for order snapshot<br>        Map&lt;String, ProductPriceGateway.ProductPrice&gt; prices = productPriceGateway.getPrices(productIds);<br>        List&lt;OrderItem&gt; orderItems = cartItems.stream()<br>                .map(i -&gt; {<br>                    ProductPriceGateway.ProductPrice price = prices.get(i.productId());<br>                    if (price == null || !price.active()) {<br>                        throw new ProductUnavailableException(&quot;Product unavailable: &quot; + i.productId());<br>                    }<br>                    return new OrderItem(i.productId(), price.name(), i.quantity(), price.price());<br>                })<br>                .toList();<br>        BigDecimal total = orderItems.stream()<br>                .map(OrderItem::subtotal)<br>                .reduce(BigDecimal.ZERO, BigDecimal::add);<br>        // Step 3 - save Order (PENDING)<br>        Order order = new Order(<br>                UUID.randomUUID().toString(), command.userId(), command.userEmail(), orderItems,<br>                OrderStatus.PENDING, command.shippingAddress(), total,<br>                Instant.now(), Instant.now()<br>        );<br>        Order saved = orderRepository.save(order);<br>        // Step 4 - save OutboxMessage in same transaction (Outbox pattern)<br>        saveOutboxMessage(saved);<br>        return saved;<br>    }<br>    // ...<br>}</pre><p>Two gRPC calls happen before a single row is written to the database. Stock check — if it fails, throw and return 4xx. Price fetch — if a product is unavailable, throw and return 4xx. The order only gets persisted after both pass. Once it’s persisted, the outbox message fires the saga via Kafka.</p><p>That’s the boundary: synchronous for gates, asynchronous for progression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyZogXnEOtWnYUV7FaQBww.png" /></figure><h3>gRPC: The Client Side</h3><p>GrpcStockCheckGateway implements the StockCheckGateway port:</p><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class GrpcStockCheckGateway implements StockCheckGateway {<br>    private final InventoryGrpcServiceGrpc.InventoryGrpcServiceBlockingStub inventoryStub;<br>    <br>    @Value(&quot;${resilience4j.timelimiter.instances.inventory-grpc.timeout-duration:2s}&quot;)<br>    private String timeoutDuration;<br>    <br>    @Override<br>    public StockCheckResult checkStock(List&lt;StockItem&gt; items) {<br>        List&lt;com.ecommerce.grpc.inventory.StockItem&gt; grpcItems = items.stream()<br>                .map(i -&gt; com.ecommerce.grpc.inventory.StockItem.newBuilder()<br>                        .setProductId(i.productId())<br>                        .setQuantity(i.quantity())<br>                        .build())<br>                .toList();<br>        CheckStockResponse response = inventoryStub<br>                .withDeadlineAfter(parseSeconds(timeoutDuration), TimeUnit.SECONDS)<br>                .checkStock(CheckStockRequest.newBuilder().addAllItems(grpcItems).build());<br>        return new StockCheckResult(response.getAvailable());<br>    }<br>    <br>    private long parseSeconds(String duration) {<br>        return Long.parseLong(duration.replace(&quot;s&quot;, &quot;&quot;));<br>    }<br>}</pre><p>The deadline comes from config, not hardcoded. That means the timeout is tunable per environment without a rebuild. Without withDeadlineAfter, a slow inventory-service holds the HTTP thread for as long as the TCP connection lives. With it, gRPC sends a cancellation signal after 2 seconds and the caller gets DEADLINE_EXCEEDED — a distinct status the caller can handle differently from UNAVAILABLE.</p><p>GrpcProductPriceGateway follows the same pattern:</p><pre>@Component<br>@RequiredArgsConstructor<br>public class GrpcProductPriceGateway implements ProductPriceGateway {<br>    private final ProductGrpcServiceGrpc.ProductGrpcServiceBlockingStub productStub;<br>    <br>    @Value(&quot;${resilience4j.timelimiter.instances.product-grpc.timeout-duration:2s}&quot;)<br>    private String timeoutDuration;<br>    <br>    @Override<br>    public Map&lt;String, ProductPrice&gt; getPrices(List&lt;String&gt; productIds) {<br>        GetProductPricesResponse response = productStub<br>                .withDeadlineAfter(parseSeconds(timeoutDuration), TimeUnit.SECONDS)<br>                .getProductPrices(GetProductPricesRequest.newBuilder().addAllProductIds(productIds).build());<br>        return response.getPricesList().stream()<br>                .collect(Collectors.toMap(<br>                        com.ecommerce.grpc.product.ProductPrice::getProductId,<br>                        p -&gt; new ProductPrice(<br>                                p.getProductId(), p.getName(),<br>                                BigDecimal.valueOf(p.getPriceCents(), 2),<br>                                p.getActive())<br>                ));<br>    }<br>    <br>    private long parseSeconds(String duration) {<br>        return Long.parseLong(duration.replace(&quot;s&quot;, &quot;&quot;));<br>    }<br>}</pre><p>The price is stored as cents (int64) in the proto message and converted to BigDecimal in the adapter with BigDecimal.valueOf(p.getPriceCents(), 2). Proto doesn’t have a decimal type. Floating-point types exist but introduce rounding errors on financial values. Cents as a long, converted at the boundary, keeps the wire format exact.</p><p>Both gateways use BlockingStub. The calling code is synchronous — blocking at the gRPC layer matches the calling context. gRPC also offers AsyncStub (callback-based) and FutureStub (ListenableFuture), but introducing async here just to avoid blocking a thread that’s already waiting adds complexity without benefit.</p><h3>gRPC: The Server Side</h3><p>inventory-service serves both CheckStock and ReserveStock from a single gRPC adapter:</p><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class InventoryGrpcServiceImpl extends InventoryGrpcServiceGrpc.InventoryGrpcServiceImplBase {<br>    private final CheckStockUseCase checkStockUseCase;<br>    private final ReserveStockUseCase reserveStockUseCase;<br>    <br>    @Override<br>    public void checkStock(CheckStockRequest request, StreamObserver&lt;CheckStockResponse&gt; responseObserver) {<br>        try {<br>            List&lt;CheckStockUseCase.StockCheckItem&gt; items = request.getItemsList().stream()<br>                    .map(i -&gt; new CheckStockUseCase.StockCheckItem(i.getProductId(), i.getQuantity()))<br>                    .toList();<br>            CheckStockUseCase.StockCheckResult result = checkStockUseCase.checkStock(items);<br>            List&lt;StockAvailability&gt; availability = result.items().stream()<br>                    .map(a -&gt; StockAvailability.newBuilder()<br>                            .setProductId(a.productId())<br>                            .setRequested(a.requested())<br>                            .setAvailable(a.available())<br>                            .setSufficient(a.sufficient())<br>                            .build())<br>                    .toList();<br>            responseObserver.onNext(CheckStockResponse.newBuilder()<br>                    .setAvailable(result.allAvailable())<br>                    .addAllAvailability(availability)<br>                    .build());<br>            responseObserver.onCompleted();<br>        } catch (InvalidQuantityException e) {<br>            responseObserver.onError(Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException());<br>        } catch (Exception e) {<br>            log.error(&quot;gRPC checkStock failed&quot;, e);<br>            responseObserver.onError(Status.INTERNAL.withDescription(e.getMessage()).asRuntimeException());<br>        }<br>    }<br>    <br>    @Override<br>    public void reserveStock(ReserveStockRequest request, StreamObserver&lt;ReserveStockResponse&gt; responseObserver) {<br>        try {<br>            List&lt;ReserveStockUseCase.ReservationItem&gt; items = request.getItemsList().stream()<br>                    .map(i -&gt; new ReserveStockUseCase.ReservationItem(i.getProductId(), i.getQuantity()))<br>                    .toList();<br>            ReserveStockUseCase.ReservationResult result =<br>                    reserveStockUseCase.reserve(request.getOrderId(), &quot;&quot;, java.math.BigDecimal.ZERO, items);<br>            responseObserver.onNext(ReserveStockResponse.newBuilder()<br>                    .setSuccess(result.success())<br>                    .setReservationId(result.reservationId() != null ? result.reservationId() : &quot;&quot;)<br>                    .setErrorMessage(result.errorMessage() != null ? result.errorMessage() : &quot;&quot;)<br>                    .build());<br>            responseObserver.onCompleted();<br>        } catch (InsufficientStockException | InvalidStockOperationException e) {<br>            responseObserver.onError(Status.FAILED_PRECONDITION.withDescription(e.getMessage()).asRuntimeException());<br>        } catch (InvalidQuantityException e) {<br>            responseObserver.onError(Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException());<br>        } catch (Exception e) {<br>            log.error(&quot;gRPC reserveStock failed&quot;, e);<br>            responseObserver.onError(Status.INTERNAL.withDescription(e.getMessage()).asRuntimeException());<br>        }<br>    }<br>}</pre><p>The adapter extends InventoryGrpcServiceImplBase — generated from the proto. The domain (CheckStockUseCase, ReserveStockUseCase) has no knowledge of gRPC. This is the hexagonal inbound adapter: it translates proto types to domain types, calls the use case, translates back. Error mapping is the adapter’s job — domain exceptions become gRPC Status codes.</p><p>The proto contract sits in libs/common-proto, a shared module both services depend on:</p><pre>service InventoryGrpcService {<br>  rpc CheckStock(CheckStockRequest) returns (CheckStockResponse);<br>  rpc ReserveStock(ReserveStockRequest) returns (ReserveStockResponse);<br>}<br><br>message CheckStockResponse {<br>  bool available = 1;<br>  repeated StockAvailability availability = 2;<br>}<br>message StockAvailability {<br>  string product_id = 1;<br>  int32 requested = 2;<br>  int32 available = 3;<br>  bool sufficient = 4;<br>}</pre><p>The cost: any proto change requires rebuilding and republishing the shared lib before either service can use the new definition. It’s a compile-time contract, which means the compiler catches mismatches — but it also means schema changes are a coordinated deployment, not just a code push.</p><p>The stubs are Spring beans wired in GrpcClientConfig:</p><pre>@Configuration<br>public class GrpcClientConfig {<br>    @Bean<br>    public InventoryGrpcServiceGrpc.InventoryGrpcServiceBlockingStub inventoryGrpcStub(<br>            @Value(&quot;${grpc.client.inventory-service.host:localhost}&quot;) String host,<br>            @Value(&quot;${grpc.client.inventory-service.port:9091}&quot;) int port) {<br>        ManagedChannel channel = ManagedChannelBuilder.forAddress(host, port)<br>                .usePlaintext()<br>                .build();<br>        return InventoryGrpcServiceGrpc.newBlockingStub(channel);<br>    }<br>    <br>    @Bean<br>    public ProductGrpcServiceGrpc.ProductGrpcServiceBlockingStub productGrpcStub(<br>            @Value(&quot;${grpc.client.product-service.host:localhost}&quot;) String host,<br>            @Value(&quot;${grpc.client.product-service.port:9090}&quot;) int port) {<br>        ManagedChannel channel = ManagedChannelBuilder.forAddress(host, port)<br>                .usePlaintext()<br>                .build();<br>        return ProductGrpcServiceGrpc.newBlockingStub(channel);<br>    }<br>}</pre><p>usePlaintext() disables TLS. In production, TLS is terminated at the ingress/service mesh layer — Envoy or Istio handles mTLS between services, so service-to-service communication is plaintext on the internal network. TLS in the ManagedChannel would double-encrypt without adding trust.</p><h3>Kafka: The Saga Side</h3><p>Once the order is persisted, the saga launches via Kafka. The outbox message is saved in the same database transaction as the order, then published asynchronously by OutboxPoller:</p><pre>@Scheduled(fixedDelay = 500)<br>@Transactional<br>public void poll() {<br>    List&lt;OutboxMessage&gt; messages = outboxRepository.findUnprocessedBatch(BATCH_SIZE);<br>    if (messages.isEmpty()) return;<br>    <br>    for (OutboxMessage msg : messages) {<br>        if (msg.getRetryCount() &gt;= MAX_RETRIES) {<br>            log.error(&quot;Outbox message exceeded max retries, skipping: id={} aggregateId={}&quot;,<br>                    msg.getId(), msg.getAggregateId());<br>            outboxRepository.markProcessed(msg.getId());<br>            continue;<br>        }<br>        try {<br>            kafkaTemplate.send(msg.getTopic(), msg.getAggregateId(), msg.getPayload())<br>                    .get(); // blocking for reliability<br>            outboxRepository.markProcessed(msg.getId());<br>        } catch (Exception e) {<br>            log.warn(&quot;Outbox publish failed, incrementing retry: id={} error={}&quot;,<br>                    msg.getId(), e.getMessage());<br>            outboxRepository.incrementRetry(msg.getId());<br>        }<br>    }<br>}</pre><p>The Kafka publish is not in the HTTP transaction. If Kafka is down when the order is placed, the order is still committed. The poller retries until the broker is available. This is the difference in reliability model: gRPC failures are the caller’s problem immediately; Kafka failures are hidden from the HTTP layer and retried in the background.</p><p>SagaEventConsumer in order-service handles the outcomes:</p><pre>@KafkaListener(topics = &quot;payment.processed&quot;, groupId = &quot;order-service&quot;,<br>        properties = {&quot;spring.json.value.default.type=com.ecommerce.events.payment.PaymentProcessedEvent&quot;})<br>@Transactional<br>public void onPaymentProcessed(PaymentProcessedEvent event) {<br>    orderRepository.findById(event.orderId()).ifPresent(order -&gt; {<br>        order.confirm();<br>        orderRepository.save(order);<br>        notificationPort.sendOrderConfirmed(order.getUserEmail(), order.getId(), order.getTotalAmount().toPlainString());<br>    });<br>}<br><br>@KafkaListener(topics = &quot;payment.failed&quot;, groupId = &quot;order-service&quot;,<br>        properties = {&quot;spring.json.value.default.type=com.ecommerce.events.payment.PaymentFailedEvent&quot;})<br>@Transactional<br>public void onPaymentFailed(PaymentFailedEvent event) {<br>    orderRepository.findById(event.orderId()).ifPresent(order -&gt; {<br>        order.markPaymentFailed();<br>        orderRepository.save(order);<br>        notificationPort.sendPaymentFailed(order.getUserEmail(), order.getId(), event.reason());<br>    });<br>}<br><br>@KafkaListener(topics = &quot;stock.reservation.failed&quot;, groupId = &quot;order-service&quot;,<br>        properties = {&quot;spring.json.value.default.type=com.ecommerce.events.inventory.StockReservationFailedEvent&quot;})<br>@Transactional<br>public void onStockReservationFailed(StockReservationFailedEvent event) {<br>    orderRepository.findById(event.orderId()).ifPresent(order -&gt; {<br>        order.cancel(&quot;Stock unavailable: &quot; + event.reason());<br>        orderRepository.save(order);<br>        notificationPort.sendOrderCancelled(order.getUserEmail(), order.getId(), &quot;Stock unavailable: &quot; + event.reason());<br>    });<br>}</pre><p>These are reactions to things that happened, not requests for things to happen now. order-service doesn’t call payment-service and wait. It emits OrderCreatedEvent and moves on. payment-service consumes when it’s ready. If payment-service is down for 30 seconds, the message waits in the topic. When it recovers, processing continues from where it left off. The producer — order-service — is unaffected.</p><p>The cost is visible here too: onPaymentProcessed and onPaymentFailed must be idempotent. Kafka’s at-least-once delivery means these handlers can fire more than once for the same event. If order.confirm() isn’t safe to call twice on an already-confirmed order, you’ll corrupt state.</p><h3>Failure Modes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kpGuSdgTzDHrILObJWUtg.png" /></figure><p>gRPC failures are synchronous and caller-visible. Two cases matter:</p><p><strong>UNAVAILABLE</strong> — inventory-service is down. The gRPC channel fails to connect. The stub throws immediately. PlaceOrderService propagates the exception, the HTTP layer returns 503. The caller knows within milliseconds.</p><p><strong>DEADLINE_EXCEEDED</strong> — inventory-service is up but slow. The 2-second deadline fires. gRPC sends a cancellation signal to the server and the stub throws. This prevents one slow downstream from holding HTTP threads until the connection times out at the TCP level, which under load would exhaust the thread pool.</p><p>Kafka failures are invisible to the producer. Two cases matter:</p><p><strong>Consumer down</strong> — the message sits in the topic. Consumer lag builds. When the consumer recovers, it processes from its last committed offset. order-service (producer) never knew anything was wrong.</p><p><strong>Consumer crash mid-processing</strong> — offset not committed, message redelivered. The consumer must be idempotent. Every @KafkaListener in this system has to handle duplicate delivery as a first-class case.</p><h3>gRPC vs REST</h3><p>Both gRPC and REST are synchronous. The stock check and price fetch could use REST instead. Three reasons they don’t:</p><p><strong>Compile-time contracts.</strong> The proto is the contract. Both client and server compile against the same generated stubs. Rename a field in the proto and the code that uses it fails to compile. With REST and OpenAPI, the contract is YAML. You can generate clients from it, but the compiler doesn’t enforce it — field renames and missing fields show up at runtime.</p><p>The cost: proto changes require rebuilding and republishing common-proto. It’s coordinated deployment, not just a code change. REST lets you evolve endpoints more independently.</p><p><strong>HTTP/2 multiplexing.</strong> gRPC runs over HTTP/2. Multiple concurrent in-flight calls share one TCP connection with flow control. The stock check and price fetch in PlaceOrderService could run in parallel over the same connection. REST over HTTP/1.1 requires a separate TCP connection per concurrent request.</p><p>The cost: HTTP/2 debugging is harder. curl works with gRPC only via grpc_cli or dedicated tooling. Inspecting traffic requires understanding binary framing, not just reading JSON in Wireshark.</p><p><strong>Binary serialization.</strong> Protobuf is more compact than JSON. For services exchanging large structured payloads — price lists for a large cart, full inventory snapshots — the wire size difference matters.</p><p>The cost: proto messages are not human-readable. The stock check request is a handful of product IDs and quantities. JSON would be trivially small and trivially debuggable. Protobuf buys nothing on small payloads except consistency with the rest of the gRPC pattern.</p><p>The rule in this system: gRPC when the caller needs the answer before it can proceed; Kafka when the caller is announcing that something happened. The pre-saga checks use gRPC because PlaceOrderService cannot build a valid Order without stock availability and current prices. The saga events use Kafka because order-service has nothing to wait for once the order is saved.</p><p><em>Next in this series: </em><a href="https://medium.com/p/c99f936b80d7"><em>Part 6 — CQRS in Practice: Two Services, Two Approaches</em></a><em>, where </em><em>review-service and </em><em>search-service both implement CQRS — with completely different mechanisms.</em></p><p><em>Part 5 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · gRPC · Kafka · Microservices · Distributed Systems</p><h3>Full Source Code</h3><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7">Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</a></li><li><a href="https://medium.com/p/ad88995e10a7">The Transactional Outbox Pattern — Never Lose a Kafka Message Again</a></li><li><a href="https://medium.com/p/c612830da237">Saga Choreography with Kafka — Distributed Transactions Without 2PC</a></li><li><a href="https://medium.com/p/82977eab91b8"><strong>Sync vs Async — When to Use gRPC and When to Use Kafka</strong></a> ← <em>you are here</em></li><li><a href="https://medium.com/p/c99f936b80d7">CQRS in Practice — Two Services, Two Approaches</a></li><li><a href="https://medium.com/p/ead0f970ac58">Idempotency in Payment Services — Exactly-Once Semantics on a Budget</a></li><li><a href="https://medium.com/p/fee1a51a5768">Polyglot Persistence — Choosing the Right Database for Each Service</a></li><li><a href="https://medium.com/p/6221a82e57db">Security Architecture — JWT at the Gateway, Trust Headers Downstream</a></li><li><a href="https://medium.com/p/cc9042e94901">Observability Stack — Tracing, Metrics, and Logs Across 10 Services</a></li><li><a href="https://medium.com/p/74de682e547e">Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82977eab91b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saga Choreography with Kafka: Distributed Transactions Without 2PC]]></title>
            <link>https://medium.com/@ivan.willy.artdian/saga-choreography-with-kafka-distributed-transactions-without-2pc-c612830da237?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c612830da237</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 00:50:57 GMT</pubDate>
            <atom:updated>2026-07-08T00:50:57.858Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 4 of the Spring Boot Microservices in Production series.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3z-8y7e5GKj3hbByH1YX7A.png" /></figure><p>Placing an order touches three services: inventory needs to reserve stock, payment needs to charge the customer, the order needs to be confirmed. All three must succeed together — or none of them should.</p><p>In a monolith, you wrap this in a database transaction and let the database handle the rollback. In microservices, each service has its own database. order-service talks to order_db. inventory-service talks to inventory_db. payment-service talks to payment_db. There is no transaction manager that spans all three. If payment fails after stock was reserved, you can’t call rollback(). You have to undo the reservation manually — by publishing another event and hoping inventory-service processes it.</p><p>This is the saga pattern. Each service executes a local transaction and publishes the result. If something fails downstream, compensating events unwind whatever succeeded. It’s not a rollback. It’s a correction.</p><p>There are two ways to implement sagas: <strong>orchestration</strong> (a central coordinator drives each step) and <strong>choreography</strong> (each service reacts to events and drives the next step). This system uses choreography. No central coordinator. Services react to what happened rather than being told what to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05rYzJWiHHnIT0CawGhR8A.png" /></figure><h3>Starting the Saga</h3><p>The saga begins when a user places an order. Before the async chain starts, PlaceOrderService makes two synchronous gRPC calls: a stock availability check against inventory-service and a price fetch from product-service. These are fast-fail checks — if stock is obviously unavailable right now, fail before creating anything.</p><p>If both checks pass, the service saves the order and the outbox message in a single database transaction:</p><pre>@Override<br>@Transactional<br>public Order placeOrder(Command command) {<br>    List&lt;CartGateway.CartItem&gt; cartItems = cartGateway.getCartItems(command.userId());<br>    if (cartItems.isEmpty()) {<br>        throw new EmptyCartException(&quot;Cart is empty&quot;);<br>    }<br><br>List&lt;String&gt; productIds = cartItems.stream()<br>            .map(CartGateway.CartItem::productId).toList();<br>    <br>    // Sync gRPC: fast-fail if stock clearly unavailable<br>    List&lt;StockCheckGateway.StockItem&gt; stockItems = cartItems.stream()<br>            .map(i -&gt; new StockCheckGateway.StockItem(i.productId(), i.quantity()))<br>            .toList();<br>    StockCheckGateway.StockCheckResult stockCheck = stockCheckGateway.checkStock(stockItems);<br>    if (!stockCheck.allAvailable()) {<br>        throw new OutOfStockException(&quot;One or more items out of stock&quot;);<br>    }<br>    <br>    // Sync gRPC: price snapshot at order time<br>    Map&lt;String, ProductPriceGateway.ProductPrice&gt; prices = productPriceGateway.getPrices(productIds);<br>    List&lt;OrderItem&gt; orderItems = cartItems.stream()<br>            .map(i -&gt; {<br>                ProductPriceGateway.ProductPrice price = prices.get(i.productId());<br>                if (price == null || !price.active()) {<br>                    throw new ProductUnavailableException(&quot;Product unavailable: &quot; + i.productId());<br>                }<br>                return new OrderItem(i.productId(), price.name(), i.quantity(), price.price());<br>            })<br>            .toList();<br>    BigDecimal total = orderItems.stream()<br>            .map(OrderItem::subtotal)<br>            .reduce(BigDecimal.ZERO, BigDecimal::add);<br>    Order order = new Order(<br>            UUID.randomUUID().toString(), command.userId(), command.userEmail(), orderItems,<br>            OrderStatus.PENDING, command.shippingAddress(), total,<br>            Instant.now(), Instant.now()<br>    );<br>    Order saved = orderRepository.save(order);<br>    <br>    // Outbox message saved in same transaction as the order<br>    saveOutboxMessage(saved);<br>    return saved;<br>}</pre><p>The outbox exists because Kafka publish cannot participate in a database transaction. If you save the order and then publish to Kafka, the service can crash between the two operations — the order exists in the database but the order.created event never fires. The outbox solves this: save a message row alongside the order in the same transaction, then a poller picks it up and publishes to Kafka. If the poller crashes, it retries. The order and the outbox row are atomically consistent.</p><p>The event payload carries everything downstream services need:</p><pre>public record OrderCreatedEvent(<br>        String eventId,<br>        String orderId,<br>        String userId,<br>        List&lt;OrderItem&gt; items,<br>        BigDecimal totalAmount,<br>        String shippingAddress,<br>        @JsonFormat(shape = JsonFormat.Shape.STRING) Instant occurredAt<br>) {<br>    public record OrderItem(<br>            String productId,<br>            String productName,<br>            int quantity,<br>            BigDecimal unitPrice<br>    ) {}<br>}</pre><p>No downstream service needs to call back to order-service to get item details. The event is self-contained.</p><h3>Step 1: Stock Reservation</h3><p>inventory-service listens on order.created:</p><pre>@KafkaListener(topics = &quot;order.created&quot;, groupId = &quot;inventory-service&quot;,<br>        properties = {&quot;spring.json.value.default.type=com.ecommerce.events.order.OrderCreatedEvent&quot;})<br>public void onOrderCreated(OrderCreatedEvent event) {<br>    log.info(&quot;Processing OrderCreatedEvent orderId={}&quot;, event.orderId());<br>    List&lt;ReserveStockUseCase.ReservationItem&gt; items = event.items().stream()<br>            .map(i -&gt; new ReserveStockUseCase.ReservationItem(i.productId(), i.quantity()))<br>            .toList();<br>    reserveStockUseCase.reserve(event.orderId(), event.userId(), event.totalAmount(), items);<br>}</pre><p>The reservation logic uses a two-pass approach:</p><pre>@Override<br>@Transactional<br>public ReservationResult reserve(String orderId, String userId, BigDecimal totalAmount,<br>                                  List&lt;ReservationItem&gt; items) {<br>    List&lt;String&gt; productIds = items.stream().map(ReservationItem::productId).toList();<br>    Map&lt;String, StockItem&gt; stockMap = stockRepository.findAllByProductIds(productIds)<br>            .stream().collect(Collectors.toMap(StockItem::getProductId, s -&gt; s));<br>    <br>    // First pass: validate all items before touching any<br>    for (ReservationItem item : items) {<br>        StockItem stock = stockMap.get(item.productId());<br>        if (stock == null || !stock.canReserve(item.quantity())) {<br>            String reason = stock == null ? &quot;Product not found in inventory&quot;<br>                    : &quot;Insufficient stock: available=%d, requested=%d&quot;<br>                        .formatted(stock.getAvailableQuantity(), item.quantity());<br>            log.warn(&quot;Stock reservation failed orderId={} productId={} reason={}&quot;,<br>                    orderId, item.productId(), reason);<br>            eventPublisher.publishStockReservationFailed(orderId, item.productId(), reason);<br>            return new ReservationResult(false, null, reason);<br>        }<br>    }<br>    <br>    // Second pass: decrement stock<br>    for (ReservationItem item : items) {<br>        StockItem stock = stockMap.get(item.productId());<br>        stock.reserve(item.quantity());<br>        stockRepository.save(stock);<br>    }<br>    <br>    String reservationId = UUID.randomUUID().toString();<br>    List&lt;InventoryEventPublisher.ReservedItem&gt; reservedItems = items.stream()<br>            .map(i -&gt; new InventoryEventPublisher.ReservedItem(i.productId(), i.quantity()))<br>            .toList();<br>    eventPublisher.publishStockReserved(orderId, userId, totalAmount, reservedItems);<br>    return new ReservationResult(true, reservationId, null);<br>}</pre><p>The first pass checks every item before modifying anything. If item 3 of 5 has insufficient stock, the method publishes stock.reservation.failed and returns — items 1 and 2 are untouched, nothing needs to be undone. Without this design, a partial reservation would require additional compensation logic to reverse the items that did succeed.</p><p>On the first failing item the method returns early. A single stock.reservation.failed event fires per failed reservation, not one per failing item.</p><p><strong>Failure path:</strong> publishes stock.reservation.failed → order-service cancels the order.</p><p><strong>Success path:</strong> publishes stock.reserved → payment-service processes payment.</p><h3>Step 2: Payment Processing</h3><p>payment-service listens on stock.reserved:</p><pre>@KafkaListener(<br>        topics = &quot;stock.reserved&quot;,<br>        groupId = &quot;${spring.kafka.consumer.group-id}&quot;,<br>        containerFactory = &quot;kafkaListenerContainerFactory&quot;<br>)<br>public void onStockReserved(@Payload StockReservedEvent event,<br>                             @Header(KafkaHeaders.RECEIVED_PARTITION) int partition,<br>                             @Header(KafkaHeaders.OFFSET) long offset) {<br>    log.info(&quot;Received StockReservedEvent orderId={} partition={} offset={}&quot;,<br>            event.orderId(), partition, offset);<br>    ProcessPaymentUseCase.Command command = new ProcessPaymentUseCase.Command(<br>            &quot;saga-&quot; + event.orderId(),  // idempotency key from saga correlation<br>            event.orderId(),<br>            event.userId(),<br>            event.totalAmount());<br>    processPaymentUseCase.processPayment(command);<br>}</pre><p>The idempotency key is &quot;saga-&quot; + orderId. Kafka’s at-least-once delivery means this consumer can receive the same stock.reserved event more than once — on consumer restart, on rebalance, on retry after a transient failure. Without the idempotency key, the customer gets charged twice.</p><pre>@Override<br>@Transactional<br>public Payment processPayment(Command command) {<br>    return idempotencyRepository.findByKey(command.idempotencyKey())<br>            .map(record -&gt; {<br>                log.info(&quot;Duplicate payment request idempotencyKey={}&quot;, command.idempotencyKey());<br>                return paymentRepository.findById(record.paymentId()).orElseThrow();<br>            })<br>            .orElseGet(() -&gt; doProcessPayment(command));<br>}<br><br>private Payment doProcessPayment(Command command) {<br>    Payment payment = Payment.create(<br>            UUID.randomUUID().toString(),<br>            command.orderId(),<br>            command.userId(),<br>            command.amount());<br>    <br>    boolean success = simulatePaymentGateway(payment);<br>    if (success) {<br>        payment.process();<br>        eventPublisher.publishPaymentProcessed(payment);<br>    } else {<br>        payment.fail(&quot;Payment gateway declined&quot;);<br>        eventPublisher.publishPaymentFailed(payment);<br>    }<br>    <br>    Payment saved = paymentRepository.save(payment);<br>    try {<br>        String responseBody = objectMapper.writeValueAsString(saved.getId());<br>        idempotencyRepository.save(new IdempotencyRecord(<br>                command.idempotencyKey(), saved.getId(), responseBody, Instant.now()));<br>    } catch (JsonProcessingException e) {<br>        log.warn(&quot;Failed to serialize idempotency response for paymentId={}&quot;, saved.getId());<br>    }<br>    return saved;<br>}<br>private boolean simulatePaymentGateway(Payment payment) {<br>    // Amounts ending in .99 simulate failure for testing compensating transactions<br>    return !payment.getAmount().toPlainString().endsWith(&quot;.99&quot;);<br>}</pre><p>The idempotency check happens before any payment logic. If the same key arrives again, the service returns the stored result without re-processing. The record is saved after processing — so a crash between payment and record save means the second attempt re-processes, not the first.</p><p>To trigger the compensation path in this system: place an order where the total ends in .99.</p><p><strong>Success path:</strong> publishes payment.processed → order-service confirms the order.</p><p><strong>Failure path:</strong> publishes payment.failed → order-service marks the order PAYMENT_FAILED.</p><h3>Closing the Loop</h3><p>order-service listens on three topics to complete the saga:</p><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class SagaEventConsumer {<br>    private final OrderRepository orderRepository;<br>    private final NotificationPort notificationPort;<br>    <br>    @KafkaListener(topics = &quot;payment.processed&quot;, groupId = &quot;order-service&quot;,<br>            properties = {&quot;spring.json.value.default.type=com.ecommerce.events.payment.PaymentProcessedEvent&quot;})<br>    @Transactional<br>    public void onPaymentProcessed(PaymentProcessedEvent event) {<br>        log.info(&quot;Saga: PaymentProcessed orderId={}&quot;, event.orderId());<br>        orderRepository.findById(event.orderId()).ifPresent(order -&gt; {<br>            order.confirm();<br>            orderRepository.save(order);<br>            notificationPort.sendOrderConfirmed(<br>                    order.getUserEmail(), order.getId(), order.getTotalAmount().toPlainString());<br>        });<br>    }<br>    <br>    @KafkaListener(topics = &quot;payment.failed&quot;, groupId = &quot;order-service&quot;,<br>            properties = {&quot;spring.json.value.default.type=com.ecommerce.events.payment.PaymentFailedEvent&quot;})<br>    @Transactional<br>    public void onPaymentFailed(PaymentFailedEvent event) {<br>        log.warn(&quot;Saga: PaymentFailed orderId={} reason={}&quot;, event.orderId(), event.reason());<br>        orderRepository.findById(event.orderId()).ifPresent(order -&gt; {<br>            order.markPaymentFailed();<br>            orderRepository.save(order);<br>            notificationPort.sendPaymentFailed(order.getUserEmail(), order.getId(), event.reason());<br>        });<br>    }<br>    <br>    @KafkaListener(topics = &quot;stock.reservation.failed&quot;, groupId = &quot;order-service&quot;,<br>            properties = {&quot;spring.json.value.default.type=com.ecommerce.events.inventory.StockReservationFailedEvent&quot;})<br>    @Transactional<br>    public void onStockReservationFailed(StockReservationFailedEvent event) {<br>        log.warn(&quot;Saga: StockReservationFailed orderId={} reason={}&quot;, event.orderId(), event.reason());<br>        orderRepository.findById(event.orderId()).ifPresent(order -&gt; {<br>            order.cancel(&quot;Stock unavailable: &quot; + event.reason());<br>            orderRepository.save(order);<br>            notificationPort.sendOrderCancelled(<br>                    order.getUserEmail(), order.getId(), &quot;Stock unavailable: &quot; + event.reason());<br>        });<br>    }<br>}</pre><p>Every state change goes through a domain method on Order. Each method enforces its own guard:</p><pre>public void confirm() {<br>    if (status != OrderStatus.PENDING) {<br>        throw new InvalidOrderStateException(&quot;Can only confirm PENDING orders, current: &quot; + status);<br>    }<br>    status = OrderStatus.CONFIRMED;<br>    updatedAt = Instant.now();<br>}<br><br>public void markPaymentFailed() {<br>    if (status != OrderStatus.PENDING) {<br>        throw new InvalidOrderStateException(&quot;Can only fail payment for PENDING orders&quot;);<br>    }<br>    status = OrderStatus.PAYMENT_FAILED;<br>    updatedAt = Instant.now();<br>}<br>public void cancel(String reason) {<br>    if (status == OrderStatus.SHIPPED || status == OrderStatus.DELIVERED) {<br>        throw new InvalidOrderStateException(&quot;Cannot cancel order in status: &quot; + status);<br>    }<br>    status = OrderStatus.CANCELLED;<br>    updatedAt = Instant.now();<br>}</pre><p>confirm() and markPaymentFailed() only accept PENDING. cancel() accepts anything except SHIPPED or DELIVERED. If a duplicate payment.processed event arrives after an order is already CONFIRMED, confirm() throws InvalidOrderStateException. That exception propagates out of the Kafka listener and routes the message to a dead-letter topic in a hardened deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stfcCIFijZd7B2JSSZonpg.png" /></figure><h3>The Compensation Gap</h3><p>When payment fails, reserved stock should be released. The flow looks complete from the outside:</p><ol><li>payment-service publishes payment.failed</li><li>order-service marks order PAYMENT_FAILED and publishes order.cancelled</li><li>inventory-service listens to order.cancelled and releases the stock</li></ol><p>Step 3 is not wired up. The actual onOrderCancelled handler in inventory-service:</p><pre>@KafkaListener(topics = &quot;order.cancelled&quot;, groupId = &quot;inventory-service&quot;,<br>        properties = {&quot;spring.json.value.default.type=com.ecommerce.events.order.OrderCancelledEvent&quot;})<br>public void onOrderCancelled(OrderCancelledEvent event) {<br>    log.info(&quot;Processing OrderCancelledEvent orderId={}&quot;, event.orderId());<br>    log.warn(&quot;Stock release for orderId={} requires order items — lookup needed in production&quot;, event.orderId());<br>}</pre><p>The OrderCancelledEvent carries only the orderId, not the items. Releasing stock requires knowing which products and quantities to release. In a real system, inventory-service would look up the reservation by orderId. That lookup is not implemented here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1J6iLY_c3gHP9VEyXNx01g.png" /></figure><p>This is the recurring cost of choreography: failure paths require the same engineering rigor as happy paths, and they’re easier to skip. With orchestration, a central coordinator explicitly invokes each compensation step — the incomplete step is immediately visible in the orchestrator’s code. With choreography, the gap hides in a Kafka listener that compiles and runs without error, just without effect.</p><h3>Operational Reality</h3><p><strong>Duplicate events.</strong> Kafka’s at-least-once delivery means any handler can receive the same event more than once. payment-service handles this with the idempotency key table. inventory-service does not — a duplicate order.created event would trigger a second reservation attempt, which would fail only because stock was already decremented. The failure path handles it accidentally rather than intentionally. Production hardening means checking whether a reservation for this orderId already exists before touching any stock.</p><p><strong>Message ordering.</strong> Kafka guarantees ordering within a partition. Using orderId as the Kafka message key routes all events for that order to the same partition, preserving the sequence order.created → stock.reserved → payment.processed (or failure variants). Without this, payment.processed could arrive before stock.reserved on a different partition.</p><p><strong>Visibility.</strong> With orchestration, you look at one place to see saga state. With choreography, you correlate events across six Kafka topics by orderId. Distributed tracing (this system uses Zipkin) ties them together — a single trace ID spans all three services, making a full saga traceable in one query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZjyqKE8n4rwJAXRxamh0Q.png" /></figure><p>Saga choreography trades a distributed transaction for a chain of local transactions and compensating events. Each service owns its own state changes and publishes what happened — no service tells another what to do.</p><h3>Choreography vs Orchestration: When to Use Which</h3><p><strong>Use choreography when:</strong></p><ul><li>Services are truly independent — adding a new step (loyalty points reacting to payment.processed) requires zero changes to existing services</li><li>You want each service deployable and scalable in isolation</li><li>Failure paths are few and simple</li></ul><p><strong>Use orchestration when:</strong></p><ul><li>The saga has many steps with complex branching</li><li>You need saga state visible in one place for debugging and support</li><li>Compensation logic is non-trivial — an incomplete handler like the onOrderCancelled stub above becomes a production incident; an orchestrator makes that gap impossible to miss</li><li>Multiple teams own different services — a central coordinator makes the contract explicit and auditable</li></ul><p>Choreography scales better. Orchestration debugs better. The choice is which pain you’d rather have.</p><p><em>Next in this series: </em><a href="https://medium.com/p/82977eab91b8"><em>Part 5 — Sync vs Async: When to Use gRPC and When to Use Kafka</em></a><em>, where the specific decision points that drove gRPC for stock checks and Kafka for the saga are examined head-to-head.</em></p><p><em>Part 4 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · Kafka · Microservices · Distributed Systems · Saga Pattern</p><h3>Full Source Code</h3><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7">Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</a></li><li><a href="https://medium.com/p/ad88995e10a7">The Transactional Outbox Pattern — Never Lose a Kafka Message Again</a></li><li><a href="https://medium.com/p/c612830da237"><strong>Saga Choreography with Kafka — Distributed Transactions Without 2PC</strong></a> ← <em>you are here</em></li><li><a href="https://medium.com/p/82977eab91b8">Sync vs Async — When to Use gRPC and When to Use Kafka</a></li><li><a href="https://medium.com/p/c99f936b80d7">CQRS in Practice — Two Services, Two Approaches</a></li><li><a href="https://medium.com/p/ead0f970ac58">Idempotency in Payment Services — Exactly-Once Semantics on a Budget</a></li><li><a href="https://medium.com/p/fee1a51a5768">Polyglot Persistence — Choosing the Right Database for Each Service</a></li><li><a href="https://medium.com/p/6221a82e57db">Security Architecture — JWT at the Gateway, Trust Headers Downstream</a></li><li><a href="https://medium.com/p/cc9042e94901">Observability Stack — Tracing, Metrics, and Logs Across 10 Services</a></li><li><a href="https://medium.com/p/74de682e547e">Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c612830da237" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Transactional Outbox Pattern: Never Lose a Kafka Message Again]]></title>
            <link>https://medium.com/@ivan.willy.artdian/the-transactional-outbox-pattern-never-lose-a-kafka-message-again-ad88995e10a7?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad88995e10a7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 00:50:42 GMT</pubDate>
            <atom:updated>2026-07-08T00:50:42.206Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3 of the Spring Boot Microservices in Production series.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ny2uMZ3ybO-jXJJ35SmDpQ.png" /></figure><p>Here’s a bug that’s invisible in development and catastrophic in production.</p><p>My order service places an order. It saves the order to PostgreSQL. Then it publishes an OrderCreatedEvent to Kafka so the inventory service can reserve stock.</p><p>Between those two operations — the database commit and the Kafka publish — the service crashes. Power outage, OOM kill, network timeout. Doesn’t matter.</p><p>The order is in the database. The Kafka message was never sent. The saga never starts. The customer sees “Order Confirmed” but inventory never decreases. Payment never processes. The order sits in PENDING forever.</p><p>This is the dual-write problem. Any system that writes to two different resources without coordination can lose messages. The only way to fix it properly is to make the message part of the same transaction as the business data.</p><p>That’s the Transactional Outbox Pattern.</p><h3>The Problem in Code</h3><p>The naive approach — the one everyone writes first:</p><pre>// WRONG — dual-write, message can be lost<br>@Transactional<br>public Order placeOrder(Command command) {<br>    Order order = buildOrder(command);<br>    orderRepository.save(order);           // write 1: PostgreSQL<br>    kafkaTemplate.send(&quot;order.created&quot;,    // write 2: Kafka<br>        new OrderCreatedEvent(order));     // ← crash here = lost message<br>    return order;<br>}</pre><p>If the service dies after orderRepository.save() but before kafkaTemplate.send() completes, the order exists but no event fires. Because Kafka isn’t part of the PostgreSQL transaction, you can’t roll back the Kafka send if the database write fails either — the problem cuts both ways.</p><h3>The Solution: Write to the Database Twice, Publish Once</h3><p>The pattern replaces the direct Kafka publish with a second database write — an outbox_messages table that lives in the same database as the business data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JuqIsJRkjvyV7LDQSzi7Sw.png" /></figure><p>The flow:</p><ol><li>Begin database transaction</li><li>Save the Order to orders table</li><li>Save the serialized event to outbox_messages table</li><li>Commit transaction — both writes are atomic</li><li>A background poller reads unprocessed outbox messages and publishes to Kafka</li><li>On successful publish, mark the outbox row as processed</li></ol><p>Steps 2–4 are atomic. Either both the order and the outbox message are written, or neither is. The Kafka publish is now decoupled from the business transaction and can be retried safely.</p><h3>The Outbox Table</h3><p>The schema is managed by Liquibase:</p><pre>&lt;!-- db/changelog/changes/002-create-outbox.xml --&gt;<br>&lt;changeSet id=&quot;002-create-outbox&quot; author=&quot;order-service&quot;&gt;<br>    &lt;createTable tableName=&quot;outbox_messages&quot;&gt;<br>        &lt;column name=&quot;id&quot; type=&quot;VARCHAR(50)&quot;&gt;<br>            &lt;constraints primaryKey=&quot;true&quot; nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;aggregate_id&quot; type=&quot;VARCHAR(100)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;aggregate_type&quot; type=&quot;VARCHAR(50)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;event_type&quot; type=&quot;VARCHAR(100)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;payload&quot; type=&quot;TEXT&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;topic&quot; type=&quot;VARCHAR(200)&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;processed&quot; type=&quot;BOOLEAN&quot; defaultValueBoolean=&quot;false&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;retry_count&quot; type=&quot;INT&quot; defaultValueNumeric=&quot;0&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;created_at&quot; type=&quot;TIMESTAMP WITH TIME ZONE&quot;&gt;<br>            &lt;constraints nullable=&quot;false&quot;/&gt;<br>        &lt;/column&gt;<br>        &lt;column name=&quot;processed_at&quot; type=&quot;TIMESTAMP WITH TIME ZONE&quot;/&gt;<br>    &lt;/createTable&gt;<br>    &lt;createIndex tableName=&quot;outbox_messages&quot; indexName=&quot;idx_outbox_processed_created&quot;&gt;<br>        &lt;column name=&quot;processed&quot;/&gt;<br>        &lt;column name=&quot;created_at&quot;/&gt;<br>    &lt;/createIndex&gt;<br>&lt;/changeSet&gt;</pre><p>The composite index on (processed, created_at) is non-negotiable. Without it, the poller does a full table scan on every tick. Unprocessed rows are always the minority — this index makes the poller query fast regardless of how many processed rows accumulate.</p><h3>The Domain Model</h3><p>OutboxMessage is a pure domain class with no framework imports:</p><pre>public class OutboxMessage {<br>    private final String id;<br>    private final String aggregateId;<br>    private final String aggregateType;<br>    private final String eventType;<br>    private final String payload;<br>    private final String topic;<br>    private boolean processed;<br>    private int retryCount;<br>    private final Instant createdAt;<br>    private Instant processedAt;<br>    public OutboxMessage(String id, String aggregateId, String aggregateType,<br>                         String eventType, String payload, String topic,<br>                         boolean processed, int retryCount,<br>                         Instant createdAt, Instant processedAt) {<br>        this.id = id;<br>        this.aggregateId = aggregateId;<br>        this.aggregateType = aggregateType;<br>        this.eventType = eventType;<br>        this.payload = payload;<br>        this.topic = topic;<br>        this.processed = processed;<br>        this.retryCount = retryCount;<br>        this.createdAt = createdAt;<br>        this.processedAt = processedAt;<br>    }<br>    public void markProcessed() {<br>        this.processed = true;<br>        this.processedAt = Instant.now();<br>    }<br>    public void incrementRetry() { retryCount++; }<br>    public String getId() { return id; }<br>    public String getAggregateId() { return aggregateId; }<br>    public String getAggregateType() { return aggregateType; }<br>    public String getEventType() { return eventType; }<br>    public String getPayload() { return payload; }<br>    public String getTopic() { return topic; }<br>    public boolean isProcessed() { return processed; }<br>    public int getRetryCount() { return retryCount; }<br>    public Instant getCreatedAt() { return createdAt; }<br>    public Instant getProcessedAt() { return processedAt; }<br>}</pre><h3>The Atomic Write</h3><p>PlaceOrderService saves both the Order and the OutboxMessage inside a single @Transactional:</p><pre>@Service<br>@RequiredArgsConstructor<br>@Slf4j<br>public class PlaceOrderService implements PlaceOrderUseCase {<br>    private final OrderRepository orderRepository;<br>    private final OutboxRepository outboxRepository;<br>    private final ProductPriceGateway productPriceGateway;<br>    private final StockCheckGateway stockCheckGateway;<br>    private final CartGateway cartGateway;<br>    private final ObjectMapper objectMapper;<br>    @Override<br>    @Transactional<br>    public Order placeOrder(Command command) {<br>        List&lt;CartGateway.CartItem&gt; cartItems = cartGateway.getCartItems(command.userId());<br>        if (cartItems.isEmpty()) {<br>            throw new EmptyCartException(&quot;Cart is empty&quot;);<br>        }<br>        List&lt;String&gt; productIds = cartItems.stream()<br>                .map(CartGateway.CartItem::productId).toList();<br>        // sync gRPC: fast-fail before touching the DB<br>        List&lt;StockCheckGateway.StockItem&gt; stockItems = cartItems.stream()<br>                .map(i -&gt; new StockCheckGateway.StockItem(i.productId(), i.quantity()))<br>                .toList();<br>        StockCheckGateway.StockCheckResult stockCheck = stockCheckGateway.checkStock(stockItems);<br>        if (!stockCheck.allAvailable()) {<br>            throw new OutOfStockException(&quot;One or more items out of stock&quot;);<br>        }<br>        Map&lt;String, ProductPriceGateway.ProductPrice&gt; prices = productPriceGateway.getPrices(productIds);<br>        List&lt;OrderItem&gt; orderItems = cartItems.stream()<br>                .map(i -&gt; {<br>                    ProductPriceGateway.ProductPrice price = prices.get(i.productId());<br>                    if (price == null || !price.active()) {<br>                        throw new ProductUnavailableException(&quot;Product unavailable: &quot; + i.productId());<br>                    }<br>                    return new OrderItem(i.productId(), price.name(), i.quantity(), price.price());<br>                })<br>                .toList();<br>        BigDecimal total = orderItems.stream()<br>                .map(OrderItem::subtotal)<br>                .reduce(BigDecimal.ZERO, BigDecimal::add);<br>        Order order = new Order(<br>                UUID.randomUUID().toString(), command.userId(), command.userEmail(), orderItems,<br>                OrderStatus.PENDING, command.shippingAddress(), total,<br>                Instant.now(), Instant.now());<br>        Order saved = orderRepository.save(order);   // write 1: orders table<br>        saveOutboxMessage(saved);                    // write 2: outbox_messages - same transaction<br>        log.info(&quot;Order placed orderId={} userId={} total={}&quot;, saved.getId(), saved.getUserId(), total);<br>        return saved;<br>    }<br>    private void saveOutboxMessage(Order order) {<br>        OrderCreatedEvent event = new OrderCreatedEvent(<br>                UUID.randomUUID().toString(),<br>                order.getId(), order.getUserId(),<br>                order.getItems().stream()<br>                        .map(i -&gt; new OrderCreatedEvent.OrderItem(<br>                                i.productId(), i.productName(), i.quantity(), i.unitPrice()))<br>                        .toList(),<br>                order.getTotalAmount(), order.getShippingAddress(), Instant.now());<br>        try {<br>            String payload = objectMapper.writeValueAsString(event);<br>            OutboxMessage outbox = new OutboxMessage(<br>                    UUID.randomUUID().toString(), order.getId(), &quot;Order&quot;,<br>                    &quot;OrderCreatedEvent&quot;, payload, &quot;order.created&quot;,<br>                    false, 0, Instant.now(), null);<br>            outboxRepository.save(outbox);<br>        } catch (JsonProcessingException e) {<br>            throw new RuntimeException(&quot;Failed to serialize outbox message&quot;, e);<br>        }<br>    }<br>}</pre><p>If anything throws between orderRepository.save() and outboxRepository.save(), @Transactional rolls back both. Either the order and the outbox message both exist, or neither does. The JsonProcessingException wrapping matters here — serialization failure is a programming error, not a recoverable runtime condition. Wrapping it as RuntimeException causes the transaction to roll back rather than silently committing an order with no outbox row.</p><h3>The Poller</h3><p>A @Scheduled component reads unprocessed outbox rows and publishes them to Kafka:</p><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class OutboxPoller {<br>    private static final int BATCH_SIZE = 50;<br>    private static final int MAX_RETRIES = 3;<br>    private final OutboxRepository outboxRepository;<br>    private final KafkaTemplate&lt;String, String&gt; kafkaTemplate;<br>    @Scheduled(fixedDelay = 500)<br>    @Transactional<br>    public void poll() {<br>        List&lt;OutboxMessage&gt; messages = outboxRepository.findUnprocessedBatch(BATCH_SIZE);<br>        if (messages.isEmpty()) return;<br>        for (OutboxMessage msg : messages) {<br>            if (msg.getRetryCount() &gt;= MAX_RETRIES) {<br>                log.error(&quot;Outbox message exceeded max retries, skipping: id={} aggregateId={}&quot;,<br>                        msg.getId(), msg.getAggregateId());<br>                outboxRepository.markProcessed(msg.getId());<br>                continue;<br>            }<br>            try {<br>                kafkaTemplate.send(msg.getTopic(), msg.getAggregateId(), msg.getPayload())<br>                        .get();<br>                outboxRepository.markProcessed(msg.getId());<br>                log.debug(&quot;Outbox published: topic={} aggregateId={}&quot;, msg.getTopic(), msg.getAggregateId());<br>            } catch (Exception e) {<br>                log.warn(&quot;Outbox publish failed, incrementing retry: id={} error={}&quot;,<br>                        msg.getId(), e.getMessage());<br>                outboxRepository.incrementRetry(msg.getId());<br>            }<br>        }<br>    }<br>}</pre><p>.get() is blocking. kafkaTemplate.send(...).get() waits for the broker to acknowledge receipt before marking the message processed. An async callback would require more complex state management — you’d need to handle the case where the callback fires after the poller’s transaction commits. The blocking call keeps state transitions synchronous within each tick.</p><p>After 3 Kafka publish failures, the message gets marked processed and logged as an error. In production you’d want a dead-letter table here. The current behavior prevents a permanently broken message from blocking the queue, but it does silently drop the event after three failures. That trade-off is worth naming explicitly when you adopt this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOrMAilwjH8GtbVB2S96nQ.png" /></figure><h3>The Port and Adapter</h3><p>The application service depends on OutboxRepository — an interface, not a JPA class:</p><pre>public interface OutboxRepository {<br>    void save(OutboxMessage message);<br>    List&lt;OutboxMessage&gt; findUnprocessedBatch(int limit);<br>    void markProcessed(String messageId);<br>    void incrementRetry(String messageId);<br>}</pre><p>The JPA repository uses @Modifying @Query for the update operations rather than load-and-save:</p><pre>interface JpaOutboxRepository extends JpaRepository&lt;OutboxEntity, String&gt; {<br>    @Query(&quot;SELECT o FROM OutboxEntity o WHERE o.processed = false ORDER BY o.createdAt ASC&quot;)<br>    List&lt;OutboxEntity&gt; findUnprocessed(Pageable pageable);<br>    <br>    @Modifying<br>    @Query(&quot;UPDATE OutboxEntity o SET o.processed = true, o.processedAt = :now WHERE o.id = :id&quot;)<br>    void markProcessed(@Param(&quot;id&quot;) String id, @Param(&quot;now&quot;) Instant now);<br>    <br>    @Modifying<br>    @Query(&quot;UPDATE OutboxEntity o SET o.retryCount = o.retryCount + 1 WHERE o.id = :id&quot;)<br>    void incrementRetry(@Param(&quot;id&quot;) String id);<br>}</pre><p>The adapter wires these together:</p><pre>@Component<br>@RequiredArgsConstructor<br>class OutboxPersistenceAdapter implements OutboxRepository {<br>    private final JpaOutboxRepository jpaOutboxRepository;<br>    <br>    @Override<br>    public void save(OutboxMessage message) {<br>        OutboxEntity entity = new OutboxEntity();<br>        entity.setId(message.getId());<br>        entity.setAggregateId(message.getAggregateId());<br>        entity.setAggregateType(message.getAggregateType());<br>        entity.setEventType(message.getEventType());<br>        entity.setPayload(message.getPayload());<br>        entity.setTopic(message.getTopic());<br>        entity.setProcessed(false);<br>        entity.setRetryCount(0);<br>        entity.setCreatedAt(message.getCreatedAt());<br>        jpaOutboxRepository.save(entity);<br>    }<br>    <br>    @Override<br>    public List&lt;OutboxMessage&gt; findUnprocessedBatch(int limit) {<br>        return jpaOutboxRepository.findUnprocessed(PageRequest.of(0, limit)).stream()<br>                .map(e -&gt; new OutboxMessage(<br>                        e.getId(), e.getAggregateId(), e.getAggregateType(),<br>                        e.getEventType(), e.getPayload(), e.getTopic(),<br>                        e.isProcessed(), e.getRetryCount(),<br>                        e.getCreatedAt(), e.getProcessedAt()))<br>                .toList();<br>    }<br>    <br>    @Override<br>    public void markProcessed(String messageId) {<br>        jpaOutboxRepository.markProcessed(messageId, Instant.now());<br>    }<br>    <br>    @Override<br>    public void incrementRetry(String messageId) {<br>        jpaOutboxRepository.incrementRetry(messageId);<br>    }<br>}</pre><p>The @Modifying @Query approach for markProcessed and incrementRetry issues a single UPDATE statement rather than a SELECT + dirty check + UPDATE. Under concurrent pollers or high message volume, the load-and-save approach also risks stale reads — the row may have been modified between the findById and the save. The direct UPDATE is both faster and safer.</p><h3>Failure Scenarios</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nR_lzodqqUZYX0ygXz0bQ.png" /></figure><p><strong>Crash before commit:</strong> @Transactional rolls back. No order, no outbox row. The client gets an error and retries. A fresh request creates a new order correctly.</p><p><strong>Crash after commit, before poller runs:</strong> Order and outbox row both exist with processed=false. On restart, the poller picks up the unprocessed row and publishes. The saga continues.</p><p><strong>Kafka broker down during publish:</strong> kafkaTemplate.send().get() throws. The poller increments retry_count and moves on. The row stays processed=false. On the next tick, the poller retries. After 3 failures, the message is dropped (see dead-letter note above).</p><p><strong>Duplicate publish:</strong> If the poller publishes successfully but crashes before markProcessed() runs, the row stays processed=false and the next tick publishes again. Downstream consumers must be idempotent. In this system, inventory-service and payment-service both check whether a reservation for that order ID already exists before acting.</p><h3>At-Least-Once Delivery</h3><p>The Transactional Outbox pattern gives you at-least-once delivery. The message will eventually be delivered, and it may be delivered more than once in failure scenarios.</p><p>At-least-once is workable here because OrderCreatedEvent is a notification of something that already happened — the order exists in the database before the event fires. Downstream services receiving it twice don’t create a second order; they check the order ID before acting. The idempotency contract is a real cost: every consumer of this event must implement the check or accept the consequences of double-processing.</p><p>For exactly-once semantics, Kafka transactions with transactional producers exist. The complexity is significant — distributed transaction coordination, producer fencing, consumer group coordination — and the latency hit is measurable. Whether the operational burden is worth eliminating the idempotency requirement depends on what the consumers actually do with the event.</p><h3>The Latency Floor</h3><p>The outbox introduces a fixed latency floor between order placement and saga start. The OrderCreatedEvent reaches inventory-service after: poller fires (up to 500ms wait) + Kafka publish acknowledgement (typically under 10ms).</p><p>At the current 500ms polling interval, the saga starts within roughly 510ms of the HTTP response returning. For an async background flow, that’s acceptable. Whether it’s acceptable for your system depends on whether any SLA is measured end-to-end from order placement to stock reservation confirmation.</p><p>Two options exist for reducing this. Polling interval can be dropped to 100ms — straightforward but increases database query frequency by 5×. Alternatively, the service can emit a Spring ApplicationEvent inside the @Transactional block and trigger the poller immediately after commit via @TransactionalEventListener(phase = AFTER_COMMIT). This achieves near-zero additional latency but adds a transactional listener dependency between the business write and the Kafka relay. Neither option is obviously better — one trades database load for simplicity, the other trades simplicity for lower latency.</p><p>The Transactional Outbox pattern converts a dual-write race condition into a single atomic write plus a background relay. The database holds both the business state and the pending messages; nothing is lost if the service dies between steps.</p><p>The cost is real: two database writes per order instead of one, a polling thread consuming connections every 500ms, retry logic that silently drops messages after three failures, and an idempotency contract that every downstream consumer must honor. Whether that cost is worth it depends entirely on what happens to your business when a Kafka message is lost.</p><p><em>Next in this series: </em><a href="https://medium.com/p/c612830da237"><em>Part 4 — Saga Choreography with Kafka: Distributed Transactions Without 2PC</em></a><em>, tracing the full order flow from </em><em>OrderCreatedEvent through stock reservation, payment processing, and final confirmation.</em></p><p><em>Part 3 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · Kafka · Microservices · Distributed Systems</p><h3>Full Source Code</h3><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7">Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</a></li><li><a href="https://medium.com/p/ad88995e10a7"><strong>The Transactional Outbox Pattern — Never Lose a Kafka Message Again</strong></a> ← <em>you are here</em></li><li><a href="https://medium.com/p/c612830da237">Saga Choreography with Kafka — Distributed Transactions Without 2PC</a></li><li><a href="https://medium.com/p/82977eab91b8">Sync vs Async — When to Use gRPC and When to Use Kafka</a></li><li><a href="https://medium.com/p/c99f936b80d7">CQRS in Practice — Two Services, Two Approaches</a></li><li><a href="https://medium.com/p/ead0f970ac58">Idempotency in Payment Services — Exactly-Once Semantics on a Budget</a></li><li><a href="https://medium.com/p/fee1a51a5768">Polyglot Persistence — Choosing the Right Database for Each Service</a></li><li><a href="https://medium.com/p/6221a82e57db">Security Architecture — JWT at the Gateway, Trust Headers Downstream</a></li><li><a href="https://medium.com/p/cc9042e94901">Observability Stack — Tracing, Metrics, and Logs Across 10 Services</a></li><li><a href="https://medium.com/p/74de682e547e">Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad88995e10a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hexagonal Architecture in Spring Boot 3: What It Costs and What It Buys]]></title>
            <link>https://medium.com/@ivan.willy.artdian/hexagonal-architecture-in-spring-boot-3-what-it-costs-and-what-it-buys-ce19512e8ce7?source=rss-e3ef95064fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce19512e8ce7</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[ivan willy artdian]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 00:40:09 GMT</pubDate>
            <atom:updated>2026-07-07T00:40:09.193Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of Building a Production Spring Boot Microservices Platform</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NIGM4VQ68sQCM09WI9o_w.png" /></figure><p>You’re six months into a microservice. The product team wants cart calls cached in Redis. You open the service class — OrderService — and find it calls CartHttpClient directly. The HTTP client is injected by type. To add caching, you need to: wrap CartHttpClient in a decorator, inject the decorator instead, update the bean wiring, and adjust two tests that mock the concrete type. Four files for a one-line conceptual change.</p><p>That’s the wall hexagonal architecture is designed to prevent. The idea: isolate your business logic from the frameworks and external systems it depends on. Not by adding more layers, but by inverting where dependencies point.</p><h3>The Structure</h3><p>The order-service in this codebase has 44 Java files. They split into three packages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_tpqPStF1SrD0gV_Ibkvg.png" /></figure><p>The dependency rule is strict: adapter depends on application, application depends on domain. Nothing points outward. domain has no imports from Spring, JPA, or any adapter package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ros1eIuMA8u6gtYOyk0kzg.png" /></figure><h3>The Domain Layer</h3><p>Order.java has no @Entity, no Spring annotations, no JPA imports. It’s plain Java.</p><pre>package com.ecommerce.order.domain.model;<br><br>import com.ecommerce.order.domain.exception.InvalidOrderStateException;<br>import java.math.BigDecimal;<br>import java.time.Instant;<br>import java.util.List;<br><br>public class Order {<br>    private final String id;<br>    private final String userId;<br>    private final String userEmail;<br>    private final List&lt;OrderItem&gt; items;<br>    private OrderStatus status;<br>    private final String shippingAddress;<br>    private final BigDecimal totalAmount;<br>    private final Instant createdAt;<br>    private Instant updatedAt;<br>    public Order(String id, String userId, String userEmail, List&lt;OrderItem&gt; items, OrderStatus status,<br>                 String shippingAddress, BigDecimal totalAmount,<br>                 Instant createdAt, Instant updatedAt) {<br>        this.id = id;<br>        this.userId = userId;<br>        this.userEmail = userEmail;<br>        this.items = items;<br>        this.status = status;<br>        this.shippingAddress = shippingAddress;<br>        this.totalAmount = totalAmount;<br>        this.createdAt = createdAt;<br>        this.updatedAt = updatedAt;<br>    }<br><br>    public void confirm() {<br>        if (status != OrderStatus.PENDING) {<br>            throw new InvalidOrderStateException(&quot;Can only confirm PENDING orders, current: &quot; + status);<br>        }<br>        status = OrderStatus.CONFIRMED;<br>        updatedAt = Instant.now();<br>    }<br><br>    public void cancel(String reason) {<br>        if (status == OrderStatus.SHIPPED || status == OrderStatus.DELIVERED) {<br>            throw new InvalidOrderStateException(&quot;Cannot cancel order in status: &quot; + status);<br>        }<br>        status = OrderStatus.CANCELLED;<br>        updatedAt = Instant.now();<br>    }<br><br>    public void ship() {<br>        if (status != OrderStatus.CONFIRMED) {<br>            throw new InvalidOrderStateException(&quot;Can only ship a CONFIRMED order, current: &quot; + status);<br>        }<br>        status = OrderStatus.SHIPPED;<br>        updatedAt = Instant.now();<br>    }<br><br>    public void deliver() {<br>        if (status != OrderStatus.SHIPPED) {<br>            throw new InvalidOrderStateException(&quot;Can only deliver a SHIPPED order, current: &quot; + status);<br>        }<br>        status = OrderStatus.DELIVERED;<br>        updatedAt = Instant.now();<br>    }<br><br>    public void markPaymentFailed() {<br>        if (status != OrderStatus.PENDING) {<br>            throw new InvalidOrderStateException(&quot;Can only fail payment for PENDING orders&quot;);<br>        }<br>        status = OrderStatus.PAYMENT_FAILED;<br>        updatedAt = Instant.now();<br>    }<br><br>    public static Order reconstitute(String id, String userId, String userEmail, OrderStatus status,<br>                                     String shippingAddress, List&lt;OrderItem&gt; items,<br>                                     BigDecimal totalAmount, Instant createdAt, Instant updatedAt) {<br>        return new Order(id, userId, userEmail, items, status, shippingAddress, totalAmount, createdAt, updatedAt);<br>    }<br><br>    public String getId() { return id; }<br>    public String getUserId() { return userId; }<br>    public String getUserEmail() { return userEmail; }<br>    public List&lt;OrderItem&gt; getItems() { return items; }<br>    public OrderStatus getStatus() { return status; }<br>    public String getShippingAddress() { return shippingAddress; }<br>    public BigDecimal getTotalAmount() { return totalAmount; }<br>    public Instant getCreatedAt() { return createdAt; }<br>    public Instant getUpdatedAt() { return updatedAt; }<br>}</pre><p>The state machine lives in the domain, not in a service class. confirm(), ship(), deliver(), and markPaymentFailed() each enforce their own preconditions. The business rule “you can’t ship an order that isn’t confirmed” is one if statement that can be tested with new Order(...) and no Spring context.</p><p>reconstitute() is a separate static factory from the regular constructor. The distinction matters: when you create a new order, you generate a UUID and set createdAt. When you load one from the database, those fields already exist. Two factory methods make that intent explicit.</p><p><strong>Cost.</strong> A rich domain model means two parallel object graphs — Order and OrderEntity. The OrderMapper that translates between them becomes the most-edited class in the persistence package every time the domain model changes. If your domain model and your database schema are structurally identical, that mapper adds lines with no value.</p><h3>The Application Layer — Ports</h3><p>Ports are interfaces. Input ports describe what the application can do. Output ports describe what the application needs from outside.</p><pre>package com.ecommerce.order.application.port.in;<br><br>import com.ecommerce.order.domain.model.Order;<br><br>public interface PlaceOrderUseCase {<br>    record Command(<br>            String userId,<br>            String userEmail,<br>            String shippingAddress<br>    ) {}<br>    Order placeOrder(Command command);<br>}</pre><p>The Command record is embedded in the interface. The calling contract lives next to the behavior it invokes. HTTP controllers, Kafka consumers, and gRPC handlers all construct a Command — they don’t leak their own types into the application layer.</p><p>Output ports follow the same pattern of owning their data shapes:</p><pre>package com.ecommerce.order.application.port.out;<br><br>import java.math.BigDecimal;<br>import java.util.List;<br><br>public interface CartGateway {<br>    record CartItem(String productId, String productName, int quantity, BigDecimal unitPrice) {}<br>    List&lt;CartItem&gt; getCartItems(String userId);<br>}</pre><pre>package com.ecommerce.order.application.port.out;<br><br>import java.util.List;<br><br>public interface StockCheckGateway {<br>    record StockItem(String productId, int quantity) {}<br>    record StockCheckResult(boolean allAvailable) {}<br>    StockCheckResult checkStock(List&lt;StockItem&gt; items);<br>}</pre><p>CartGateway knows nothing about Feign. StockCheckGateway knows nothing about gRPC. Both adapters translate their external types into these records. The application layer is insulated from the protocol.</p><p><strong>Cost.</strong> Writing port interfaces for every operation is overhead with no return on a CRUD service. If your “use case” is save(entity) and your “gateway” is findById(id), you’ve added two interfaces and four classes to implement what Spring Data gives you in one line.</p><h3>The Application Service</h3><p>PlaceOrderService implements PlaceOrderUseCase. All six of its dependencies are port interfaces.</p><pre>package com.ecommerce.order.application.service;<br><br>import com.ecommerce.events.order.OrderCreatedEvent;<br>import com.ecommerce.order.application.port.in.PlaceOrderUseCase;<br>import com.ecommerce.order.application.port.out.*;<br>import com.ecommerce.order.domain.exception.EmptyCartException;<br>import com.ecommerce.order.domain.exception.OutOfStockException;<br>import com.ecommerce.order.domain.exception.ProductUnavailableException;<br>import com.ecommerce.order.domain.model.*;<br>import com.fasterxml.jackson.core.JsonProcessingException;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Transactional;<br>import java.math.BigDecimal;<br>import java.time.Instant;<br>import java.util.List;<br>import java.util.Map;<br>import java.util.UUID;<br><br>@Service<br>@RequiredArgsConstructor<br>@Slf4j<br>public class PlaceOrderService implements PlaceOrderUseCase {<br>    private final OrderRepository orderRepository;<br>    private final OutboxRepository outboxRepository;<br>    private final ProductPriceGateway productPriceGateway;<br>    private final StockCheckGateway stockCheckGateway;<br>    private final CartGateway cartGateway;<br>    private final ObjectMapper objectMapper;<br><br>    @Override<br>    @Transactional<br>    public Order placeOrder(Command command) {<br>        List&lt;CartGateway.CartItem&gt; cartItems = cartGateway.getCartItems(command.userId());<br>        if (cartItems.isEmpty()) {<br>            throw new EmptyCartException(&quot;Cart is empty&quot;);<br>        }<br><br>        List&lt;String&gt; productIds = cartItems.stream()<br>                .map(CartGateway.CartItem::productId).toList();<br>        List&lt;StockCheckGateway.StockItem&gt; stockItems = cartItems.stream()<br>                .map(i -&gt; new StockCheckGateway.StockItem(i.productId(), i.quantity()))<br>                .toList();<br><br>        StockCheckGateway.StockCheckResult stockCheck = stockCheckGateway.checkStock(stockItems);<br>        if (!stockCheck.allAvailable()) {<br>            throw new OutOfStockException(&quot;One or more items out of stock&quot;);<br>        }<br><br>        Map&lt;String, ProductPriceGateway.ProductPrice&gt; prices = productPriceGateway.getPrices(productIds);<br>        List&lt;OrderItem&gt; orderItems = cartItems.stream()<br>                .map(i -&gt; {<br>                    ProductPriceGateway.ProductPrice price = prices.get(i.productId());<br>                    if (price == null || !price.active()) {<br>                        throw new ProductUnavailableException(&quot;Product unavailable: &quot; + i.productId());<br>                    }<br>                    return new OrderItem(i.productId(), price.name(), i.quantity(), price.price());<br>                })<br>                .toList();<br><br>        BigDecimal total = orderItems.stream()<br>                .map(OrderItem::subtotal)<br>                .reduce(BigDecimal.ZERO, BigDecimal::add);<br>        Order order = new Order(<br>                UUID.randomUUID().toString(), command.userId(), command.userEmail(), orderItems,<br>                OrderStatus.PENDING, command.shippingAddress(), total,<br>                Instant.now(), Instant.now()<br>        );<br><br>        Order saved = orderRepository.save(order);<br>        saveOutboxMessage(saved);<br>        log.info(&quot;Order placed orderId={} userId={} total={}&quot;, saved.getId(), saved.getUserId(), total);<br>        return saved;<br>    }<br><br>    private void saveOutboxMessage(Order order) {<br>        OrderCreatedEvent event = new OrderCreatedEvent(<br>                UUID.randomUUID().toString(),<br>                order.getId(), order.getUserId(),<br>                order.getItems().stream()<br>                        .map(i -&gt; new OrderCreatedEvent.OrderItem(<br>                                i.productId(), i.productName(), i.quantity(), i.unitPrice()))<br>                        .toList(),<br>                order.getTotalAmount(), order.getShippingAddress(), Instant.now()<br>        );<br><br>        try {<br>            String payload = objectMapper.writeValueAsString(event);<br>            OutboxMessage outbox = new OutboxMessage(<br>                    UUID.randomUUID().toString(), order.getId(), &quot;Order&quot;,<br>                    &quot;OrderCreatedEvent&quot;, payload, &quot;order.created&quot;,<br>                    false, 0, Instant.now(), null<br>            );<br>            outboxRepository.save(outbox);<br>        } catch (JsonProcessingException e) {<br>            throw new RuntimeException(&quot;Failed to serialize outbox message&quot;, e);<br>        }<br>    }<br>}</pre><p>Three things to notice.</p><p>@Transactional lives here, not in an adapter. The service owns the transaction boundary. orderRepository.save() and outboxRepository.save() both execute inside the same transaction. If the outbox write fails, the order save rolls back. That atomicity is the whole point of saving them together — it’s what prevents OrderCreatedEvent from being lost during a crash between the two writes.</p><p>No Spring Data repository appears directly. No gRPC stub. No Feign client. The service calls cartGateway.getCartItems(), which could be HTTP today and Kafka tomorrow. The service doesn’t know.</p><p><strong>Cost.</strong> PlaceOrderService takes six constructor arguments. When all dependencies are interfaces, there’s no natural size limit. Services grow because every new requirement gets added as “more application logic.” In a layered architecture, the controller or repository might push back. Here, everything belongs until it doesn’t.</p><h3>The Adapter Layer</h3><p>Adapters are where the frameworks live. They translate between the outside world and the port interfaces.</p><h3>Inbound: REST Controller</h3><pre>package com.ecommerce.order.adapter.in.web;<br><br>import com.ecommerce.order.adapter.in.web.dto.OrderResponse;<br>import com.ecommerce.order.adapter.in.web.dto.PlaceOrderRequest;<br>import com.ecommerce.order.adapter.in.web.dto.UpdateOrderStatusRequest;<br>import com.ecommerce.order.application.port.in.PlaceOrderUseCase;<br>import com.ecommerce.order.application.port.in.UpdateOrderStatusUseCase;<br>import com.ecommerce.order.application.port.out.OrderRepository;<br>import io.swagger.v3.oas.annotations.Operation;<br>import io.swagger.v3.oas.annotations.tags.Tag;<br>import jakarta.validation.Valid;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.data.domain.Page;<br>import org.springframework.data.domain.Pageable;<br>import org.springframework.data.web.PageableDefault;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.security.core.annotation.AuthenticationPrincipal;<br>import org.springframework.web.bind.annotation.*;<br>import org.springframework.web.server.ResponseStatusException;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1/orders&quot;)<br>@RequiredArgsConstructor<br>@Tag(name = &quot;Orders&quot;, description = &quot;Order management - Saga Choreography + Transactional Outbox&quot;)<br>public class OrderController {<br>    private final PlaceOrderUseCase placeOrderUseCase;<br>    private final UpdateOrderStatusUseCase updateOrderStatusUseCase;<br>    private final OrderRepository orderRepository;<br>    private final OrderResponseMapper mapper;<br><br>    @PostMapping<br>    @ResponseStatus(HttpStatus.CREATED)<br>    @Operation(summary = &quot;Place a new order - triggers Saga flow via Kafka&quot;)<br>    public OrderResponse placeOrder(@Valid @RequestBody PlaceOrderRequest request,<br>                                    @AuthenticationPrincipal String userId,<br>                                    @RequestHeader(&quot;X-User-Email&quot;) String userEmail) {<br>        return mapper.toResponse(placeOrderUseCase.placeOrder(<br>                new PlaceOrderUseCase.Command(userId, userEmail, request.shippingAddress())));<br>    }<br><br>    @GetMapping(&quot;/{orderId}&quot;)<br>    @Operation(summary = &quot;Get order by ID&quot;)<br>    public OrderResponse getOrder(@PathVariable String orderId,<br>                                  @AuthenticationPrincipal String userId) {<br>        return orderRepository.findById(orderId)<br>                .filter(o -&gt; o.getUserId().equals(userId))<br>                .map(mapper::toResponse)<br>                .orElseThrow(() -&gt; new ResponseStatusException(HttpStatus.NOT_FOUND, &quot;Order not found&quot;));<br>    }<br><br>    @GetMapping<br>    @Operation(summary = &quot;List all orders for authenticated user&quot;)<br>    public Page&lt;OrderResponse&gt; listOrders(@AuthenticationPrincipal String userId,<br>                                          @PageableDefault(size = 20) Pageable pageable) {<br>        return orderRepository.findByUserId(userId, pageable).map(mapper::toResponse);<br>    }<br><br>    @GetMapping(&quot;/all&quot;)<br>    @Operation(summary = &quot;List all orders - admin only&quot;)<br>    public Page&lt;OrderResponse&gt; listAllOrders(@RequestHeader(&quot;X-User-Roles&quot;) String roles,<br>                                              @PageableDefault(size = 50) Pageable pageable) {<br>        if (!roles.contains(&quot;ROLE_ADMIN&quot;)) {<br>            throw new ResponseStatusException(HttpStatus.FORBIDDEN, &quot;Admin only&quot;);<br>        }<br>        return orderRepository.findAll(pageable).map(mapper::toResponse);<br>    }<br><br>    @PatchMapping(&quot;/{orderId}/status&quot;)<br>    @Operation(summary = &quot;Update order status - admin only (CONFIRMED→SHIPPED, SHIPPED→DELIVERED)&quot;)<br>    public OrderResponse updateOrderStatus(@PathVariable String orderId,<br>                                           @RequestHeader(&quot;X-User-Roles&quot;) String roles,<br>                                           @Valid @RequestBody UpdateOrderStatusRequest request) {<br>        if (!roles.contains(&quot;ROLE_ADMIN&quot;)) {<br>            throw new ResponseStatusException(HttpStatus.FORBIDDEN, &quot;Admin only&quot;);<br>        }<br>        return mapper.toResponse(updateOrderStatusUseCase.updateStatus(<br>                new UpdateOrderStatusUseCase.Command(orderId, request.status())));<br>    }<br>}</pre><p>The controller depends on PlaceOrderUseCase and UpdateOrderStatusUseCase — interfaces. Replacing PlaceOrderService with a different implementation requires zero changes here.</p><h3>Outbound: Persistence Adapter</h3><pre>package com.ecommerce.order.adapter.out.persistence;<br><br>import com.ecommerce.order.application.port.out.OrderRepository;<br>import com.ecommerce.order.domain.model.Order;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.data.domain.Page;<br>import org.springframework.data.domain.Pageable;<br>import org.springframework.stereotype.Component;<br>import java.util.Optional;<br><br>@Component<br>@RequiredArgsConstructor<br>class OrderPersistenceAdapter implements OrderRepository {<br>    private final JpaOrderRepository jpaOrderRepository;<br>    private final OrderMapper mapper;<br><br>    @Override<br>    public Order save(Order order) {<br>        return mapper.toDomain(jpaOrderRepository.save(mapper.toEntity(order)));<br>    }<br><br>    @Override<br>    public Optional&lt;Order&gt; findById(String orderId) {<br>        return jpaOrderRepository.findById(orderId).map(mapper::toDomain);<br>    }<br><br>    @Override<br>    public Page&lt;Order&gt; findByUserId(String userId, Pageable pageable) {<br>        return jpaOrderRepository.findByUserId(userId, pageable).map(mapper::toDomain);<br>    }<br><br>    @Override<br>    public Page&lt;Order&gt; findAll(Pageable pageable) {<br>        return jpaOrderRepository.findAll(pageable).map(mapper::toDomain);<br>    }<br>}</pre><p>JPA is an implementation detail that never crosses the adapter boundary. PlaceOrderService calls orderRepository.save(order) — it receives a domain Order back. It has no idea that OrderEntity exists.</p><h3>Outbound: gRPC Adapter</h3><pre>package com.ecommerce.order.adapter.out.grpc;<br><br>import com.ecommerce.grpc.inventory.*;<br>import com.ecommerce.order.application.port.out.StockCheckGateway;<br>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Component;<br>import java.util.List;<br>import java.util.concurrent.TimeUnit;<br><br>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class GrpcStockCheckGateway implements StockCheckGateway {<br>    private final InventoryGrpcServiceGrpc.InventoryGrpcServiceBlockingStub inventoryStub;<br><br>    @Value(&quot;${resilience4j.timelimiter.instances.inventory-grpc.timeout-duration:2s}&quot;)<br>    private String timeoutDuration;<br><br>    @Override<br>    public StockCheckResult checkStock(List&lt;StockItem&gt; items) {<br>        List&lt;com.ecommerce.grpc.inventory.StockItem&gt; grpcItems = items.stream()<br>                .map(i -&gt; com.ecommerce.grpc.inventory.StockItem.newBuilder()<br>                        .setProductId(i.productId())<br>                        .setQuantity(i.quantity())<br>                        .build())<br>                .toList();<br>        CheckStockResponse response = inventoryStub<br>                .withDeadlineAfter(parseSeconds(timeoutDuration), TimeUnit.SECONDS)<br>                .checkStock(CheckStockRequest.newBuilder().addAllItems(grpcItems).build());<br>        return new StockCheckResult(response.getAvailable());<br>    }<br><br>    private long parseSeconds(String duration) {<br>        return Long.parseLong(duration.replace(&quot;s&quot;, &quot;&quot;));<br>    }<br>}</pre><p>The proto-generated types — InventoryGrpcServiceGrpc, StockItem, CheckStockRequest, CheckStockResponse — never leave this class. The application layer sees only StockCheckGateway.StockItem and StockCheckGateway.StockCheckResult.</p><p><strong>Cost.</strong> Every adapter method in OrderPersistenceAdapter is a one-liner. Four lines of interface for four lines of delegation. If the domain model and persistence model were identical, the mapper would be pure overhead. Adapter classes don’t compress well when the underlying operation is simple.</p><h3>What Infrastructure Changes Actually Cost</h3><p>The real test of hexagonal architecture is how many files change when infrastructure requirements change. These four scenarios use the actual order-service structure.</p><h3>Swap PostgreSQL for MongoDB</h3><p>Change OrderPersistenceAdapter to use a Mongo repository. Replace OrderEntity (with JPA annotations) with OrderDocument (with Mongo annotations). Update OrderMapper. That’s three files, all in adapter/out/persistence/.</p><p>Order.java, PlaceOrderService.java, OrderController.java — untouched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MAbKpBCqLkRhuvtxcmWXw.png" /></figure><h3>Add a trackingNumber Field</h3><p>Add the field to Order.java. Add it to OrderEntity.java. Update OrderMapper to copy it. Add it to OrderResponse.java. Update OrderResponseMapper. Five files across domain, persistence adapter, and web adapter.</p><p>No adapter logic changes. No service changes. The field propagates along the data path, not the business logic path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MW2yG5ewDVPPiyDyizW9lA.png" /></figure><h3>Replace HTTP with Kafka for Cart Fetching</h3><p>Delete FeignCartGateway.java. Add KafkaCartGateway.java that implements CartGateway. CartGateway itself doesn’t change. PlaceOrderService doesn’t change — it calls cartGateway.getCartItems() either way.</p><p>One file deleted, one file added, both in adapter/out/.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHg_0kFFGkbs4PYVoxOHxA.png" /></figure><h3>Add Redis Caching to Cart Gateway</h3><p>Create RedisCachedCartGateway implements CartGateway. It holds a reference to FeignCartGateway and wraps it with cache logic. Mark it @Primary so Spring injects it instead of the Feign adapter.</p><p>PlaceOrderService receives a CartGateway — it doesn’t know which one. One new file, zero changes to existing files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8K1DbeQm5wDWUMfn29spQ.png" /></figure><p>This is the scenario from the opening. Four files vs one. That’s the concrete payoff.</p><h3>Three Object Graphs</h3><p>Order data exists in three forms in this service: domain model (Order), persistence entity (OrderEntity), and API response (OrderResponse). Each one is optimized for its context.</p><p>Order carries behavior — state machine methods, business invariants. OrderEntity carries JPA annotations, column mappings, and a generated ID strategy. OrderResponse is a flat JSON-serializable record with no methods.</p><p>Keeping them separate means changes to one don’t ripple into the others. A new JPA column mapping doesn’t touch the domain model. A new API field doesn’t require a database migration. The mappers are the coupling points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1O1KKHj5u1JDvBS7LMvM7Q.png" /></figure><h3>When It’s Worth It</h3><p>Hexagonal architecture pays when infrastructure adapters change independently of each other and of the business logic. In order-service, the four scenarios above show that the pattern absorbed every infrastructure change in one or two adapter files. That’s the structural guarantee it provides.</p><p>It doesn’t pay when the business logic is thin. A service that translates HTTP requests into database writes has no domain logic to protect. Adding port interfaces for save and findById creates three files where Spring Data needs one. The blast radius of infrastructure changes stays small anyway, because the logic coupling them together is minimal.</p><p>Count how many times your infrastructure has changed independently in the last six months. If the answer is rarely, the pattern adds more overhead than it removes.</p><p><em>Next in this series: </em><a href="https://medium.com/p/ad88995e10a7"><em>Part 3 — The Transactional Outbox Pattern: Never Lose a Kafka Message Again</em></a><em>, where the </em><em>outbox table, the poller, and the delivery guarantees behind </em><em>order.created events get a full walkthrough.</em></p><p><em>Part 2 of the </em><strong><em>Spring Boot Microservices in Production</em></strong><em> series.</em></p><p><strong>Tags:</strong> Java · Spring Boot · Microservices · Hexagonal Architecture · Software Architecture</p><p>The full source is on GitHub:</p><p><strong>GitHub:</strong> <a href="https://github.com/ivan-artdian/ecommerce-microservices">github.com/ivan-artdian/ecommerce-microservices</a></p><h3>Series: Spring Boot Microservices in Production</h3><ol><li><a href="https://medium.com/p/1776405acefa">The Architecture Decision Map</a></li><li><a href="https://medium.com/p/ce19512e8ce7"><strong>Hexagonal Architecture in Spring Boot 3 — A Complete Practical Guide</strong></a> ← <em>you are here</em></li><li><a href="https://medium.com/p/ad88995e10a7">The Transactional Outbox Pattern — Never Lose a Kafka Message Again</a></li><li><a href="https://medium.com/p/c612830da237">Saga Choreography with Kafka — Distributed Transactions Without 2PC</a></li><li><a href="https://medium.com/p/82977eab91b8">Sync vs Async — When to Use gRPC and When to Use Kafka</a></li><li><a href="https://medium.com/p/c99f936b80d7">CQRS in Practice — Two Services, Two Approaches</a></li><li><a href="https://medium.com/p/ead0f970ac58">Idempotency in Payment Services — Exactly-Once Semantics on a Budget</a></li><li><a href="https://medium.com/p/fee1a51a5768">Polyglot Persistence — Choosing the Right Database for Each Service</a></li><li><a href="https://medium.com/p/6221a82e57db">Security Architecture — JWT at the Gateway, Trust Headers Downstream</a></li><li><a href="https://medium.com/p/cc9042e94901">Observability Stack — Tracing, Metrics, and Logs Across 10 Services</a></li><li><a href="https://medium.com/p/74de682e547e">Gradle vs Maven in a Monorepo — Why I Use Both and Which Won</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce19512e8ce7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>