<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6581802047354010081</id><updated>2026-11-16T21:28:19.784+08:00</updated><category term="Java"/><category term="Troubleshooting"/><category term="C#"/><category term="Database"/><category term="Spring"/><category term="Java EE"/><category term="Web Development"/><category term="REST API"/><category term="Security"/><category term="Frontend"/><category term="Source Control"/><category term="Maven"/><category term="Xcode"/><category term="Identity &amp; Access Management"/><category term="Persistence"/><category term="Microservices"/><category term="Operating Systems"/><category term="Spring Boot"/><category term="Architecture"/><category term="Cloud"/><category term="Keycloak"/><category term="Application Server"/><category term="WildFly"/><category term="PHP"/><category term="Ubuntu"/><category term="Git"/><category term="Remote Work"/><category term="Distributed Systems"/><category term="Containers"/><category term="NERV"/><category term="PostgreSQL"/><category term="Docker"/><category term="Eclipse RCP"/><category term="Software Engineering"/><category term="Event-Driven Architecture"/><category term="React"/><category term="Observability"/><category term="WordPress"/><category term="AWS"/><category term="JSF"/><category term="Testing"/><category term="Hibernate"/><category term="Angular"/><category term="JPA"/><category term="CI/CD"/><category term="Quarkus"/><category term="Windows"/><category term="Android"/><category term="CzetsuyaTech"/><category term="DevOps"/><category term="Software Architecture"/><category term="device"/><category term="Algorithms"/><category term="Featured"/><category term="Jenkins"/><category term="Mobile Development"/><category term="NERV Event"/><category term="Serverless"/><category term="computer-science"/><category term="Amazon Cognito"/><category term="Computer Science"/><category term="Next.js"/><category term="Algorithmic Trading"/><category term="Blogger"/><category term="Concurrency"/><category term="Database Version Control"/><category term="Eclipse"/><category term="Education"/><category term="Integration"/><category term="Kafka"/><category term="Machine Learning"/><category term="NERV Audit"/><category term="NERV Persistence"/><category term="NERV Trade"/><category term="Programming Exercise"/><category term="Subversion"/><category term="Auditing"/><category term="Careers"/><category term="Hibernate Envers"/><category term="Inbox Pattern"/><category term="Kubernetes"/><category term="NERV Exception"/><category term="Networking"/><category term="Outbox Pattern"/><category term="Production Support"/><category term="SEO"/><category term="Spring Data JPA"/><category term="Trading"/><category term="Trading Engine"/><category term="Trading Systems"/><category term="API Design"/><category term="Amazon SQS"/><category term="Archive"/><category term="Automation"/><category term="Big Data"/><category term="Binance"/><category term="Cassandra"/><category term="DataFrame"/><category term="Deterministic Systems"/><category term="ELK"/><category term="Exception Handling"/><category term="GitHub Actions"/><category term="Grafana"/><category term="JPA Specifications"/><category term="JasperReports"/><category term="Magento"/><category term="MySQL"/><category term="NERV Actions"/><category term="OAuth"/><category term="Open Source"/><category term="Payment Systems"/><category term="Prometheus"/><category term="Transactional Outbox"/><category term="Transactions"/><category term="YouTube"/><category term="iOS"/><category term="jobs"/><category term="macOS"/><category term="review"/><category term="startup"/><title type='text'>czetsuyatech</title><subtitle type='html'> This blog contains tutorials, how-to&#39;s, and tips for programmers, engineers, and anyone else who would like to learn programming and tools/plugins used by professional programmers.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default?start-index=26&amp;max-results=25'/><author><name>avcarreon</name><uri>http://www.blogger.com/profile/07645787568344634224</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>745</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-108808428168770390</id><published>2026-11-16T21:19:47.602+08:00</published><updated>2026-11-16T21:28:19.784+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="JPA Specifications"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Persistence"/><category scheme="http://www.blogger.com/atom/ns#" term="Persistence"/><category scheme="http://www.blogger.com/atom/ns#" term="Software Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Data JPA"/><title type='text'>The Specification Pattern in Spring Data JPA: Building Composable Queries That Scale</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzdqLjkNjJkyX-dVgfC4OkPvIINDWyOcEJ2IxNtzXRQH1qtaX9ZFFI1V9-asD7lVX7QD1032lVFrGe9zwoIMwgETm1JkTUX5XUz0rFVtGx-P-fcJyNd0-GWfHWO7Vk08YX1mYfBWHMZgQHtHzDXaA-YgemPSdvLTDdAXyVSN56-Igav5rFNl2UHZN2zig1/s1600/nerv-persistence-specification-pattern-composable-queries.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;NERV Persistence architecture illustrating the Specification pattern in Spring Data JPA, with reusable predicates, AND/OR/NOT composition, Hibernate, and database query execution.&quot; border=&quot;0&quot; data-original-height=&quot;941&quot; data-original-width=&quot;1672&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzdqLjkNjJkyX-dVgfC4OkPvIINDWyOcEJ2IxNtzXRQH1qtaX9ZFFI1V9-asD7lVX7QD1032lVFrGe9zwoIMwgETm1JkTUX5XUz0rFVtGx-P-fcJyNd0-GWfHWO7Vk08YX1mYfBWHMZgQHtHzDXaA-YgemPSdvLTDdAXyVSN56-Igav5rFNl2UHZN2zig1/s1600/nerv-persistence-specification-pattern-composable-queries.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;

&lt;article&gt;
  &lt;p&gt;
    In the previous article,
    &lt;em&gt;Dynamic Queries in Spring Data JPA Without Repository Method Explosion&lt;/em&gt;,
    we explored how optional search filters can turn a clean repository
    into a growing collection of derived query methods.
  &lt;/p&gt;

  &lt;p&gt;
    Spring Data JPA Specifications offer a practical solution:
    represent individual query conditions as predicates and compose
    them according to the requirements of a search operation.
  &lt;/p&gt;

  &lt;p&gt;
    But eliminating repository method explosion is only the beginning.
  &lt;/p&gt;

  &lt;p&gt;
    As applications become more complex, we encounter another
    challenge: &lt;strong&gt;how do we organize Specifications so they remain
    reusable, understandable, testable, and efficient?&lt;/strong&gt;
  &lt;/p&gt;

  &lt;p&gt;
    A poorly designed Specification layer can become just as difficult
    to maintain as the repository methods it replaced.
  &lt;/p&gt;

  &lt;p&gt;
    In this article, we&#39;ll explore the Specification pattern beyond
    simple optional filters. We&#39;ll build composable business predicates,
    combine logical conditions, query relationships, and examine the
    architectural decisions that make Specifications sustainable
    in enterprise applications.
  &lt;/p&gt;

  &lt;h2&gt;1. Specifications Are More Than Dynamic Filters&lt;/h2&gt;

  &lt;p&gt;
    When developers first encounter Spring Data JPA Specifications,
    they often think of them as a convenient way to build dynamic
    WHERE clauses.
  &lt;/p&gt;

  &lt;p&gt;That&#39;s certainly one application, but the underlying idea is broader.&lt;/p&gt;

  &lt;p&gt;
    The Specification pattern, as described in domain-driven design,
    provides a way to represent business rules as reusable,
    composable conditions.
  &lt;/p&gt;

  &lt;p&gt;
    In the persistence layer, Spring Data JPA expresses these
    conditions through the JPA Criteria API.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@FunctionalInterface
public interface Specification&amp;lt;T&amp;gt; {

    Predicate toPredicate(
        Root&amp;lt;T&amp;gt; root,
        CriteriaQuery&amp;lt;?&amp;gt; query,
        CriteriaBuilder criteriaBuilder
    );
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This simplified representation illustrates the traditional
    Specification contract. Exact signatures and nullability
    annotations vary by Spring Data JPA version.
  &lt;/p&gt;

  &lt;p&gt;
    A Specification describes a condition without directly executing
    the query.
  &lt;/p&gt;

  &lt;p&gt;
    Query execution remains the responsibility of Spring Data JPA.
  &lt;/p&gt;

  &lt;p&gt;
    This separation gives us an important architectural property:
    &lt;strong&gt;the definition of a query condition is independent of
    the repository operation that uses it.&lt;/strong&gt;
  &lt;/p&gt;

  &lt;h2&gt;2. Start With a Real Domain&lt;/h2&gt;

  &lt;p&gt;
    Consider an order management system where operators need to
    search orders using different business conditions.
  &lt;/p&gt;

  &lt;p&gt;Our simplified order entity might look like this:&lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Entity
@Table(name = &quot;orders&quot;)
@Getter
@Setter
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private OrderStatus status;

    @Column(nullable = false, precision = 19, scale = 2)
    private BigDecimal totalAmount;

    @Column(nullable = false)
    private String currency;

    @Column(nullable = false)
    private Instant createdAt;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = &quot;customer_id&quot;, nullable = false)
    private Customer customer;
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Suppose the business introduces the following requirements:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Find orders awaiting payment.&lt;/li&gt;
    &lt;li&gt;Find high-value orders.&lt;/li&gt;
    &lt;li&gt;Find orders created within a particular period.&lt;/li&gt;
    &lt;li&gt;Find orders belonging to customers in a particular country.&lt;/li&gt;
    &lt;li&gt;Combine these conditions for operational dashboards.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    These aren&#39;t necessarily separate repository operations.
    They&#39;re business conditions that can participate in different
    queries.
  &lt;/p&gt;

  &lt;p&gt;
    Instead of creating one large search method, let&#39;s represent
    these conditions independently.
  &lt;/p&gt;

  &lt;h2&gt;3. Build Small, Meaningful Specifications&lt;/h2&gt;

  &lt;p&gt;
    A good Specification should express one meaningful condition.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public final class OrderSpecifications {

    private OrderSpecifications() {
    }

    public static Specification&amp;lt;Order&amp;gt; hasStatus(
            OrderStatus status) {

        return (root, query, cb) -&amp;gt;
            cb.equal(root.get(&quot;status&quot;), status);
    }

    public static Specification&amp;lt;Order&amp;gt; hasCurrency(
            String currency) {

        return (root, query, cb) -&amp;gt;
            cb.equal(root.get(&quot;currency&quot;), currency);
    }

    public static Specification&amp;lt;Order&amp;gt; amountAtLeast(
            BigDecimal amount) {

        return (root, query, cb) -&amp;gt;
            cb.greaterThanOrEqualTo(
                root.get(&quot;totalAmount&quot;),
                amount
            );
    }
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Each method describes a condition that can be understood
    independently.
  &lt;/p&gt;

  &lt;p&gt;
    Notice that the method names communicate intent.
    We don&#39;t need to know how the Criteria API works to understand
    what &lt;code&gt;amountAtLeast()&lt;/code&gt; means.
  &lt;/p&gt;

  &lt;p&gt;
    However, the meaning of an amount threshold must remain explicit.
    Comparing monetary amounts without also accounting for currency
    can produce misleading business results.
  &lt;/p&gt;

  &lt;p&gt;
    For example, a high-value order query might require a specific
    currency:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public static Specification&amp;lt;Order&amp;gt; highValueInCurrency(
        BigDecimal threshold,
        String currency) {

    return Specification.allOf(
        amountAtLeast(threshold),
        hasCurrency(currency)
    );
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This is already more expressive than a generic field comparison.
    It encodes the business assumption that the threshold and order
    amounts use the same currency.
  &lt;/p&gt;

  &lt;h2&gt;4. Compose Business Rules With AND, OR, and NOT&lt;/h2&gt;

  &lt;p&gt;
    The real value of Specifications appears when we combine them.
  &lt;/p&gt;

  &lt;p&gt;
    Suppose we need orders that are awaiting payment and have a
    total amount of at least 10,000 PHP.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Specification&amp;lt;Order&amp;gt; specification =
    Specification.allOf(
        OrderSpecifications.hasStatus(
            OrderStatus.PENDING_PAYMENT
        ),
        OrderSpecifications.highValueInCurrency(
            new BigDecimal(&quot;10000.00&quot;),
            &quot;PHP&quot;
        )
    );&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Conceptually, the resulting SQL resembles:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT o.*
FROM orders o
WHERE o.status = &#39;PENDING_PAYMENT&#39;
  AND o.total_amount &amp;gt;= 10000.00
  AND o.currency = &#39;PHP&#39;;&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    We can also express alternatives using OR.
  &lt;/p&gt;

  &lt;p&gt;
    For example, suppose an operational dashboard should display
    orders awaiting payment or requiring manual review.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Specification&amp;lt;Order&amp;gt; needsAttention =
    Specification.anyOf(
        OrderSpecifications.hasStatus(
            OrderStatus.PENDING_PAYMENT
        ),
        OrderSpecifications.hasStatus(
            OrderStatus.MANUAL_REVIEW
        )
    );&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    And we can negate a condition using &lt;code&gt;Specification.not()&lt;/code&gt;.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Specification&amp;lt;Order&amp;gt; notCancelled =
    Specification.not(
        OrderSpecifications.hasStatus(
            OrderStatus.CANCELLED
        )
    );&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This is where Specifications become more than a mechanism for
    handling nullable search parameters.
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;
      We can construct larger query rules from smaller,
      independently understandable business conditions.
    &lt;/strong&gt;
  &lt;/p&gt;

  &lt;h2&gt;5. Group Logical Conditions Explicitly&lt;/h2&gt;

  &lt;p&gt;
    Once queries combine AND and OR, logical grouping becomes
    important.
  &lt;/p&gt;

  &lt;p&gt;Consider the requirement:&lt;/p&gt;

  &lt;blockquote&gt;
    Find PHP orders that are either awaiting payment or
    under manual review.
  &lt;/blockquote&gt;

  &lt;p&gt;
    The intended expression is:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;currency = PHP
AND
(
    status = PENDING_PAYMENT
    OR
    status = MANUAL_REVIEW
)&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    We can express this directly:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Specification&amp;lt;Order&amp;gt; specification =
    Specification.allOf(
        OrderSpecifications.hasCurrency(&quot;PHP&quot;),
        Specification.anyOf(
            OrderSpecifications.hasStatus(
                OrderStatus.PENDING_PAYMENT
            ),
            OrderSpecifications.hasStatus(
                OrderStatus.MANUAL_REVIEW
            )
        )
    );&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Explicit grouping matters because:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;A AND (B OR C)&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;is not equivalent to:&lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;(A AND B) OR C&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The second expression could include manual-review orders
    regardless of currency.
  &lt;/p&gt;

  &lt;p&gt;
    A Specification implementation can compile successfully,
    return results, and still violate the intended business rule.
  &lt;/p&gt;

  &lt;p&gt;
    That&#39;s why complex predicate composition deserves
    behavioral tests rather than relying on code inspection alone.
  &lt;/p&gt;

  &lt;h2&gt;6. Build Higher-Level Business Specifications&lt;/h2&gt;

  &lt;p&gt;
    Once primitive Specifications exist, we can compose them into
    higher-level rules.
  &lt;/p&gt;

  &lt;p&gt;
    For example, an operations dashboard might repeatedly need
    orders that require attention.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public static Specification&amp;lt;Order&amp;gt; requiresAttention() {

    return Specification.anyOf(
        hasStatus(OrderStatus.PENDING_PAYMENT),
        hasStatus(OrderStatus.MANUAL_REVIEW)
    );
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Other application components no longer need to know which
    statuses constitute an attention-required order.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Specification&amp;lt;Order&amp;gt; specification =
    Specification.allOf(
        OrderSpecifications.requiresAttention(),
        OrderSpecifications.hasCurrency(&quot;PHP&quot;)
    );&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    If the business definition changes, we update the higher-level
    Specification rather than searching through multiple services
    for duplicated status combinations.
  &lt;/p&gt;

  &lt;p&gt;
    There is an important distinction here.
  &lt;/p&gt;

  &lt;p&gt;
    Specifications are useful for expressing query-time rules,
    but they should not automatically become the authoritative
    implementation of every domain invariant.
  &lt;/p&gt;

  &lt;p&gt;
    Rules that govern whether a state transition is permitted
    still belong in the appropriate domain or application logic.
    A database query predicate alone cannot enforce every business
    invariant.
  &lt;/p&gt;

  &lt;h2&gt;7. Querying Relationships With Specifications&lt;/h2&gt;

  &lt;p&gt;
    Real applications rarely filter only scalar fields.
    Queries frequently involve relationships.
  &lt;/p&gt;

  &lt;p&gt;
    Suppose we need orders belonging to customers in a
    particular country.
  &lt;/p&gt;

  &lt;p&gt;
    Assuming &lt;code&gt;Customer&lt;/code&gt; has a
    &lt;code&gt;country&lt;/code&gt; property, we can write:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public static Specification&amp;lt;Order&amp;gt; customerInCountry(
        String country) {

    return (root, query, cb) -&amp;gt; {

        Join&amp;lt;Order, Customer&amp;gt; customer =
            root.join(&quot;customer&quot;, JoinType.INNER);

        return cb.equal(
            customer.get(&quot;country&quot;),
            country
        );
    };
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This condition can be combined with the others:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Specification&amp;lt;Order&amp;gt; specification =
    Specification.allOf(
        OrderSpecifications.customerInCountry(&quot;PH&quot;),
        OrderSpecifications.requiresAttention()
    );&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Notice that the calling service does not need to know
    how the relationship is joined.
  &lt;/p&gt;

  &lt;p&gt;
    The Specification encapsulates the persistence mechanics
    necessary to express the condition.
  &lt;/p&gt;

  &lt;h3&gt;Be Careful With Collection Joins&lt;/h3&gt;

  &lt;p&gt;
    Joining a many-to-one relationship generally does not multiply
    rows for each order, assuming the relationship is valid.
  &lt;/p&gt;

  &lt;p&gt;
    Joining a one-to-many collection is different.
    A root entity may appear in multiple SQL rows when several
    related records match.
  &lt;/p&gt;

  &lt;p&gt;
    That can affect result cardinality, pagination, and count queries.
  &lt;/p&gt;

  &lt;p&gt;
    For existence checks against collections, an
    &lt;code&gt;EXISTS&lt;/code&gt; subquery is often preferable.
  &lt;/p&gt;

  &lt;p&gt;
    Avoid treating &lt;code&gt;DISTINCT&lt;/code&gt; as a universal fix.
    It can introduce additional query costs and may not solve
    every pagination or fetch-join problem.
  &lt;/p&gt;

  &lt;h2&gt;8. Type Safety: Prefer the Static Metamodel When Appropriate&lt;/h2&gt;

  &lt;p&gt;
    The previous examples use string-based property names:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;root.get(&quot;status&quot;)&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This is concise, but property names are checked at runtime
    rather than through ordinary Java member references.
  &lt;/p&gt;

  &lt;p&gt;
    Renaming an entity property may leave a string-based Criteria
    expression unchanged.
  &lt;/p&gt;

  &lt;p&gt;
    For projects using the generated JPA static metamodel,
    we can write:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public static Specification&amp;lt;Order&amp;gt; hasStatus(
        OrderStatus status) {

    return (root, query, cb) -&amp;gt;
        cb.equal(root.get(Order_.status), status);
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Here, &lt;code&gt;Order_&lt;/code&gt; is a generated metamodel class,
    typically produced by the Hibernate JPA metamodel annotation
    processor during compilation.
  &lt;/p&gt;

  &lt;p&gt;
    This provides stronger compile-time checking of property
    references, at the cost of additional build configuration.
  &lt;/p&gt;

  &lt;p&gt;
    The choice depends on the project&#39;s complexity and
    conventions, but type safety becomes increasingly valuable
    as the number of Specifications grows.
  &lt;/p&gt;

  &lt;h2&gt;9. Keep Query Execution Separate From Query Definition&lt;/h2&gt;

  &lt;p&gt;
    One useful architectural boundary is separating the definition
    of query conditions from their execution.
  &lt;/p&gt;

  &lt;p&gt;
    A repository should remain responsible for persistence access:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public interface OrderRepository
        extends JpaRepository&amp;lt;Order, Long&amp;gt;,
                JpaSpecificationExecutor&amp;lt;Order&amp;gt; {
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The application service can compose the relevant business rules
    and execute them:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class OrderSearchService {

    private final OrderRepository orderRepository;

    public Page&amp;lt;Order&amp;gt; findOrdersRequiringAttention(
            String currency,
            Pageable pageable) {

        Specification&amp;lt;Order&amp;gt; specification =
            Specification.allOf(
                OrderSpecifications.requiresAttention(),
                OrderSpecifications.hasCurrency(currency)
            );

        return orderRepository.findAll(
            specification,
            pageable
        );
    }
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The service knows which business conditions are required.
    The Specification knows how to express those conditions.
    The repository executes the resulting query.
  &lt;/p&gt;

  &lt;p&gt;
    These responsibilities are related, but they do not need
    to be collapsed into a single class.
  &lt;/p&gt;

  &lt;h2&gt;10. Reusable Specifications Across Services&lt;/h2&gt;

  &lt;p&gt;
    In a microservice architecture, similar query patterns
    often appear across multiple bounded contexts.
  &lt;/p&gt;

  &lt;p&gt;
    It can be tempting to create a shared library containing
    Specifications for every entity.
  &lt;/p&gt;

  &lt;p&gt;
    However, sharing domain-specific Specifications between
    services can introduce unwanted coupling.
  &lt;/p&gt;

  &lt;p&gt;
    For example, a billing service and an order management service
    may both have a concept of an order, but their persistence models
    and business responsibilities may be different.
  &lt;/p&gt;

  &lt;p&gt;
    Sharing their entity-specific query rules would tie the services
    to a common model that may not belong to either boundary.
  &lt;/p&gt;

  &lt;p&gt;
    A better approach is to distinguish between two categories.
  &lt;/p&gt;

  &lt;h3&gt;Domain-Specific Specifications&lt;/h3&gt;

  &lt;p&gt;These belong with the application that owns the domain:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;code&gt;requiresAttention()&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;hasUnsettledBalance()&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;eligibleForFulfillment()&lt;/code&gt;&lt;/li&gt;
  &lt;/ul&gt;

  &lt;h3&gt;Reusable Persistence Mechanics&lt;/h3&gt;

  &lt;p&gt;These may be appropriate for shared infrastructure:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Common comparison and range operations&lt;/li&gt;
    &lt;li&gt;Optional-filter assembly&lt;/li&gt;
    &lt;li&gt;Pagination and sorting conventions&lt;/li&gt;
    &lt;li&gt;Validated query-field handling&lt;/li&gt;
    &lt;li&gt;Reusable Criteria API helpers&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    &lt;strong&gt;
      Share the mechanics of querying, not the ownership
      of business meaning.
    &lt;/strong&gt;
  &lt;/p&gt;

  &lt;h2&gt;11. Where NERV Persistence Fits&lt;/h2&gt;

  &lt;p&gt;
    This separation is closely related to the architectural goals
    behind &lt;strong&gt;NERV Persistence&lt;/strong&gt;.
  &lt;/p&gt;

  &lt;p&gt;
    Spring Data JPA already provides the foundational abstractions
    needed for composable queries.
  &lt;/p&gt;

  &lt;p&gt;
    NERV Persistence builds on the broader idea that common
    persistence conventions and technical infrastructure should
    be reusable without replacing Spring Data JPA or forcing
    unrelated services to share domain models.
  &lt;/p&gt;

  &lt;p&gt;
    Conceptually, the responsibilities look like this:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;Application Service
        |
        v
Domain Specifications
        |
        v
Reusable Query Mechanics
        |
        v
Spring Data JPA
        |
        v
Hibernate
        |
        v
Database&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This diagram illustrates architectural responsibilities,
    not a claim that every layer maps to a particular
    NERV Persistence class.
  &lt;/p&gt;

  &lt;p&gt;
    The library should complement the framework, not hide it.
    Developers should still be able to use native Specifications,
    JPQL, Criteria API, and SQL when those are the right tools.
  &lt;/p&gt;

  &lt;p&gt;
    Explore the project:
    &lt;a href=&quot;https://github.com/czetsuyatech/nerv-persistence&quot;
       target=&quot;_blank&quot;
       rel=&quot;noopener noreferrer&quot;&gt;
      NERV Persistence on GitHub
    &lt;/a&gt;.
  &lt;/p&gt;

  &lt;h2&gt;12. Production Considerations&lt;/h2&gt;

  &lt;p&gt;
    Composable query design improves maintainability, but it does
    not automatically guarantee efficient database access.
  &lt;/p&gt;

  &lt;h3&gt;12.1 Understand the Generated SQL&lt;/h3&gt;

  &lt;p&gt;
    A small Specification may produce a complex SQL query,
    particularly when relationships, subqueries, or sorting
    are involved.
  &lt;/p&gt;

  &lt;p&gt;
    Use SQL logging and database execution plans to understand
    important queries.
  &lt;/p&gt;

  &lt;p&gt;
    For PostgreSQL, &lt;code&gt;EXPLAIN (ANALYZE, BUFFERS)&lt;/code&gt;
    can provide valuable information about actual execution,
    although its execution cost and side effects should be
    considered before running it against production workloads.
  &lt;/p&gt;

  &lt;h3&gt;12.2 Keep Fetching Separate From Filtering&lt;/h3&gt;

  &lt;p&gt;
    Specifications are best treated primarily as query predicates.
  &lt;/p&gt;

  &lt;p&gt;
    Mixing fetch joins, query ordering, and other mutations into
    reusable Specifications can create surprising interactions
    when those Specifications are composed or reused for counts.
  &lt;/p&gt;

  &lt;p&gt;
    Consider entity graphs, projections, or dedicated query
    implementations when fetching requirements become complex.
  &lt;/p&gt;

  &lt;h3&gt;12.3 Be Careful With Count Queries&lt;/h3&gt;

  &lt;p&gt;
    Paginated queries may require a count of all matching records.
    Complex joins and subqueries can make counts expensive.
  &lt;/p&gt;

  &lt;p&gt;
    Depending on the Spring Data JPA version, separate count
    Specifications can help optimize some scenarios.
  &lt;/p&gt;

  &lt;p&gt;
    When total counts are not required, consider retrieval
    strategies that avoid them.
  &lt;/p&gt;

  &lt;h3&gt;12.4 Apply Mandatory Restrictions Explicitly&lt;/h3&gt;

  &lt;p&gt;
    In multi-tenant or security-sensitive applications,
    user-supplied filters must not be allowed to remove
    mandatory visibility restrictions.
  &lt;/p&gt;

  &lt;p&gt;
    Tenant boundaries and authorization should be enforced
    through appropriate security and persistence controls,
    not merely treated as optional search filters.
  &lt;/p&gt;

  &lt;h3&gt;12.5 Avoid Over-Generalizing the Query Layer&lt;/h3&gt;

  &lt;p&gt;
    A generic query engine that accepts arbitrary property paths,
    operators, and nested expressions can become difficult to
    validate, secure, and optimize.
  &lt;/p&gt;

  &lt;p&gt;
    Flexibility is useful, but public query capabilities should
    remain intentionally constrained.
  &lt;/p&gt;

  &lt;h2&gt;13. Testing Composable Specifications&lt;/h2&gt;

  &lt;p&gt;
    Specifications should be tested as business query behavior,
    not merely as Java methods returning non-null objects.
  &lt;/p&gt;

  &lt;p&gt;
    A useful integration test verifies that the composed query
    returns the expected records.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@DataJpaTest
class OrderSpecificationsTest {

    @Autowired
    private OrderRepository orderRepository;

    @Test
    void shouldFindPendingOrManualReviewOrdersInPhp() {

        Specification&amp;lt;Order&amp;gt; specification =
            Specification.allOf(
                OrderSpecifications.hasCurrency(&quot;PHP&quot;),
                OrderSpecifications.requiresAttention()
            );

        List&amp;lt;Order&amp;gt; results =
            orderRepository.findAll(specification);

        assertThat(results)
            .allSatisfy(order -&amp;gt; {
                assertThat(order.getCurrency())
                    .isEqualTo(&quot;PHP&quot;);

                assertThat(order.getStatus())
                    .isIn(
                        OrderStatus.PENDING_PAYMENT,
                        OrderStatus.MANUAL_REVIEW
                    );
            });
    }
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This illustrates the assertion structure, but a complete
    test must also seed representative records and verify the
    expected result IDs or counts.
  &lt;/p&gt;

  &lt;p&gt;
    Otherwise, an empty result could satisfy the assertions
    without proving that the query is correct.
  &lt;/p&gt;

  &lt;p&gt;
    Test fixtures should include both matching and nonmatching
    records, especially cases that distinguish:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;A AND (B OR C)&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;from:&lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;(A AND B) OR C&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Also test relationship cardinality, date boundaries,
    pagination, and count behavior.
  &lt;/p&gt;

  &lt;p&gt;
    When PostgreSQL is the production database, integration tests
    using PostgreSQL and Testcontainers can catch differences
    that in-memory database tests may miss.
  &lt;/p&gt;

  &lt;h2&gt;14. When Not to Use Specifications&lt;/h2&gt;

  &lt;p&gt;
    Not every query benefits from a Specification abstraction.
  &lt;/p&gt;

  &lt;p&gt;
    For simple fixed lookups, derived repository methods are often
    more readable:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Optional&amp;lt;Order&amp;gt; findByExternalReference(
    String externalReference
);&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    For specialized reporting, aggregation, window functions,
    or database-specific operations, explicit JPQL or SQL may
    be more appropriate.
  &lt;/p&gt;

  &lt;p&gt;
    For highly optimized read models, dedicated projections
    and query implementations may provide better control.
  &lt;/p&gt;

  &lt;p&gt;
    The goal is not to force every query through Specifications.
    It is to use composition where composition genuinely
    improves the design.
  &lt;/p&gt;

  &lt;h2&gt;15. The Real Measure of a Good Specification Design&lt;/h2&gt;

  &lt;p&gt;
    A well-designed Specification layer should make it easier to:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Express query conditions in meaningful business terms&lt;/li&gt;
    &lt;li&gt;Reuse predicates without duplicating logic&lt;/li&gt;
    &lt;li&gt;Combine conditions without ambiguous grouping&lt;/li&gt;
    &lt;li&gt;Add new requirements without modifying unrelated queries&lt;/li&gt;
    &lt;li&gt;Test query behavior independently&lt;/li&gt;
    &lt;li&gt;Inspect and optimize generated SQL&lt;/li&gt;
    &lt;li&gt;Preserve domain boundaries between services&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    The most important benefit is not that we write fewer
    repository methods.
  &lt;/p&gt;

  &lt;p&gt;
    It&#39;s that we can evolve query behavior without making the
    persistence layer increasingly difficult to understand.
  &lt;/p&gt;

  &lt;h2&gt;Final Thoughts&lt;/h2&gt;

  &lt;p&gt;
    Spring Data JPA Specifications are often introduced as a
    solution to dynamic filtering.
  &lt;/p&gt;

  &lt;p&gt;
    But their architectural value goes further.
  &lt;/p&gt;

  &lt;p&gt;
    They allow us to represent query conditions as independent,
    meaningful components that can be combined into larger rules.
  &lt;/p&gt;

  &lt;p&gt;
    Used carefully, this improves readability, reuse,
    testability, and maintainability.
  &lt;/p&gt;

  &lt;p&gt;
    Used carelessly, Specifications can become another layer
    of abstraction that hides query behavior and complicates
    performance analysis.
  &lt;/p&gt;

  &lt;p&gt;
    The distinction comes down to design discipline:
    keep predicates focused, compose business rules explicitly,
    preserve domain ownership, and understand the SQL
    ultimately executed by the database.
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;
      A scalable Specification design isn&#39;t about making every
      query generic. It&#39;s about making query behavior composable
      without losing its meaning.
    &lt;/strong&gt;
  &lt;/p&gt;

  &lt;hr /&gt;

  &lt;p&gt;
    &lt;em&gt;
      This is Article #3 in the NERV Persistence series,
      exploring reusable persistence architecture and
      production-oriented Spring Data JPA design.
    &lt;/em&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;Explore NERV Persistence:&lt;/strong&gt;
    &lt;a href=&quot;https://github.com/czetsuyatech/nerv-persistence&quot;
       target=&quot;_blank&quot;
       rel=&quot;noopener noreferrer&quot;&gt;
      github.com/czetsuyatech/nerv-persistence
    &lt;/a&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;More engineering articles:&lt;/strong&gt;
    &lt;a href=&quot;https://www.czetsuyatech.com/&quot;&gt;
      CzetsuyaTech
    &lt;/a&gt;
  &lt;/p&gt;
&lt;/article&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/10/dynamic-queries-spring-data-jpa.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Dynamic Queries in Spring Data JPA Without Repository Method Explosion
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Persistence
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Persistence&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/108808428168770390/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/11/specification-pattern-spring-data-jpa-composable-queries.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/108808428168770390'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/108808428168770390'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/11/specification-pattern-spring-data-jpa-composable-queries.html' title='The Specification Pattern in Spring Data JPA: Building Composable Queries That Scale'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzdqLjkNjJkyX-dVgfC4OkPvIINDWyOcEJ2IxNtzXRQH1qtaX9ZFFI1V9-asD7lVX7QD1032lVFrGe9zwoIMwgETm1JkTUX5XUz0rFVtGx-P-fcJyNd0-GWfHWO7Vk08YX1mYfBWHMZgQHtHzDXaA-YgemPSdvLTDdAXyVSN56-Igav5rFNl2UHZN2zig1/s72-c/nerv-persistence-specification-pattern-composable-queries.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-4374165966437319243</id><published>2026-10-29T17:44:01.988+08:00</published><updated>2026-10-29T17:44:01.988+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Auditing"/><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate"/><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate Envers"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Audit"/><category scheme="http://www.blogger.com/atom/ns#" term="Observability"/><category scheme="http://www.blogger.com/atom/ns#" term="Production Support"/><category scheme="http://www.blogger.com/atom/ns#" term="Software Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>Logs Aren&#39;t an Audit Trail: Debugging Business Data in Production</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYoSo5IvY3bAAduVShROXqlnS_5DW_3buSR5rQrb27Xb1LR7OHV6nPsDkl2BXLbIvcXx0R25LGtMccsurZccsoCm-4W55DNQYNTAtq96wKjup-SitAgVfM1myfcuazuas5bLm8CvTfcSAj2Mwc33YuJZVkqduQstYzvOXHzNhy11bd9fYgwfdoNkmrEJAD/s1600/nerv-audit-logs-vs-audit-trail.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;Application logs compared with a structured audit history showing changes to business data in a production system.&quot; border=&quot;0&quot; data-original-height=&quot;887&quot; data-original-width=&quot;1774&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYoSo5IvY3bAAduVShROXqlnS_5DW_3buSR5rQrb27Xb1LR7OHV6nPsDkl2BXLbIvcXx0R25LGtMccsurZccsoCm-4W55DNQYNTAtq96wKjup-SitAgVfM1myfcuazuas5bLm8CvTfcSAj2Mwc33YuJZVkqduQstYzvOXHzNhy11bd9fYgwfdoNkmrEJAD/s1600/nerv-audit-logs-vs-audit-trail.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;

&lt;h2&gt;Logs Aren&#39;t an Audit Trail: Debugging Business Data in Production&lt;/h2&gt;

&lt;p&gt;Something went wrong in production.&lt;/p&gt;

&lt;p&gt;A customer reports that an account was unexpectedly deactivated. Support checks the application and confirms that the account is indeed inactive.&lt;/p&gt;

&lt;p&gt;Now comes the question every backend developer eventually encounters:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;&quot;Why did this happen?&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You open your observability platform and search the application logs.&lt;/p&gt;

&lt;p&gt;You find a message:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;2026-10-12T09:42:18Z INFO
AccountService - Account 1042 updated successfully&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&#39;s useful. The application processed an update.&lt;/p&gt;

&lt;p&gt;But what exactly changed?&lt;/p&gt;

&lt;p&gt;Was the account previously active? Who initiated the operation? Was the change performed by an administrator, a scheduled job, or another service?&lt;/p&gt;

&lt;p&gt;And perhaps most importantly, what sequence of changes led to the account&#39;s current state?&lt;/p&gt;

&lt;p&gt;The log message doesn&#39;t tell us.&lt;/p&gt;

&lt;p&gt;We could add more logging, of course. But that raises a more fundamental question:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Should application logs be responsible for preserving the history of our business data?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I don&#39;t think they should.&lt;/p&gt;

&lt;p&gt;Logs and audit trails serve different purposes. Understanding that distinction is an important part of designing systems that are easier to investigate, support, and operate in production.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;1. Logs Describe Execution, Not Necessarily Business History&lt;/h2&gt;

&lt;p&gt;Application logging is primarily concerned with what happens while software executes.&lt;/p&gt;

&lt;p&gt;Consider a typical Spring Boot service:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public void deactivateAccount(Long accountId) {
    Account account = accountRepository.findById(accountId)
        .orElseThrow(() -&gt; new AccountNotFoundException(accountId));

    account.setStatus(AccountStatus.DEACTIVATED);

    accountRepository.save(account);

    log.info(&quot;Account {} deactivated&quot;, accountId);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At first glance, the log message looks sufficient.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Account 1042 deactivated&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But the message describes an application operation. It doesn&#39;t necessarily provide a complete, durable history of the entity.&lt;/p&gt;

&lt;p&gt;For example, it doesn&#39;t establish:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;What the previous status was.&lt;/li&gt;
  &lt;li&gt;Whether other fields changed in the same transaction.&lt;/li&gt;
  &lt;li&gt;Which authenticated user or background process initiated the operation.&lt;/li&gt;
  &lt;li&gt;Whether the operation eventually committed successfully.&lt;/li&gt;
  &lt;li&gt;What other revisions occurred before or after this change.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We could enrich the log statement with additional information.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Account 1042 changed:
status=ACTIVE -&amp;gt; DEACTIVATED
actor=admin-17&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&#39;s better for diagnostics.&lt;/p&gt;

&lt;p&gt;But adding more information to a log message doesn&#39;t automatically turn the logging system into a reliable audit system.&lt;/p&gt;

&lt;p&gt;The difference becomes clearer when we examine how these records are created and stored.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;2. A Successful Log Message Doesn&#39;t Prove a Successful Database Change&lt;/h2&gt;

&lt;p&gt;One of the most important differences between logs and audit records concerns transaction boundaries.&lt;/p&gt;

&lt;p&gt;Consider this example:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Transactional
public void deactivateAccount(Long accountId) {
    Account account = accountRepository.findById(accountId)
        .orElseThrow(() -&gt; new AccountNotFoundException(accountId));

    account.setStatus(AccountStatus.DEACTIVATED);

    log.info(&quot;Account {} deactivated&quot;, accountId);

    performAdditionalValidation(account);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Suppose &lt;code&gt;performAdditionalValidation()&lt;/code&gt; throws an unchecked exception.&lt;/p&gt;

&lt;p&gt;Spring&#39;s transaction management normally rolls back the database transaction.&lt;/p&gt;

&lt;p&gt;However, the log message may already have been written to the logging system.&lt;/p&gt;

&lt;p&gt;Now we have a potentially misleading situation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;APPLICATION LOG

09:42:18 Account 1042 deactivated

DATABASE

Account 1042
status = ACTIVE&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The log message describes an operation that was attempted, but the business-data change was never committed.&lt;/p&gt;

&lt;p&gt;This is not a defect in the logging framework.&lt;/p&gt;

&lt;p&gt;Logging systems generally do not participate in the application&#39;s database transaction.&lt;/p&gt;

&lt;p&gt;They are designed to capture execution information, including operations that subsequently fail.&lt;/p&gt;

&lt;p&gt;That behavior is valuable for debugging.&lt;/p&gt;

&lt;p&gt;But it also demonstrates why logs should not be treated as authoritative evidence that a particular database transition was committed.&lt;/p&gt;

&lt;h3&gt;What changes with transactional auditing?&lt;/h3&gt;

&lt;p&gt;When audit revisions are persisted as part of the same database transaction as the entity change, they can share the transaction&#39;s commit and rollback outcome.&lt;/p&gt;

&lt;p&gt;If the transaction rolls back, the associated audit revision is rolled back as well.&lt;/p&gt;

&lt;p&gt;This is one of the important properties of Hibernate Envers when used with normal transactional entity persistence.&lt;/p&gt;

&lt;p&gt;It provides a stronger relationship between the committed entity state and its recorded revision history.&lt;/p&gt;

&lt;p&gt;That doesn&#39;t make an audit trail infallible. Direct database modifications, untracked write paths, incorrect mappings, and operational failures can still undermine completeness.&lt;/p&gt;

&lt;p&gt;But transactionally persisted revisions provide a different guarantee from ordinary application logging.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;3. Logs and Audit Records Have Different Lifecycles&lt;/h2&gt;

&lt;p&gt;Another difference appears when we look at retention.&lt;/p&gt;

&lt;p&gt;Application logs are often stored in centralized observability platforms.&lt;/p&gt;

&lt;p&gt;Depending on operational requirements, logs may be retained for days, weeks, or months.&lt;/p&gt;

&lt;p&gt;Retention policies are commonly influenced by storage cost, indexing volume, operational usefulness, and security requirements.&lt;/p&gt;

&lt;p&gt;That&#39;s reasonable.&lt;/p&gt;

&lt;p&gt;A high-traffic application might generate millions of log entries per day. Keeping every diagnostic message indefinitely would be expensive and often unnecessary.&lt;/p&gt;

&lt;p&gt;Business audit history has a different purpose.&lt;/p&gt;

&lt;p&gt;Imagine a customer asks:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&quot;Who changed my account settings three months ago?&quot;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The application logs may no longer exist.&lt;/p&gt;

&lt;p&gt;But the business may still need to reconstruct the relevant changes.&lt;/p&gt;

&lt;p&gt;An audit trail can have a retention policy designed around business, operational, and regulatory requirements rather than general log retention.&lt;/p&gt;

&lt;p&gt;This doesn&#39;t mean audit records should always be kept forever.&lt;/p&gt;

&lt;p&gt;Retention, archival, privacy, and deletion requirements must still be considered carefully.&lt;/p&gt;

&lt;p&gt;The important point is that &lt;strong&gt;the lifecycle of diagnostic telemetry should not automatically determine the lifecycle of business history.&lt;/strong&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;4. Structured Business Changes Are Different From Log Messages&lt;/h2&gt;

&lt;p&gt;Logs are usually optimized for searching and diagnosing execution events.&lt;/p&gt;

&lt;p&gt;Even structured JSON logs are generally organized around individual log events.&lt;/p&gt;

&lt;p&gt;An audit trail is organized around changes to business entities.&lt;/p&gt;

&lt;p&gt;Consider the following logs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;09:41:12 Account update requested
09:41:12 Validating account 1042
09:41:12 Account validation successful
09:41:13 Updating account 1042
09:41:13 Account 1042 updated successfully&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These messages may help us follow the execution.&lt;/p&gt;

&lt;p&gt;But imagine the account actually changed as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Account #1042

Revision 18
2026-10-12T09:41:13Z

status:
ACTIVE -&amp;gt; SUSPENDED

reasonCode:
null -&amp;gt; CUSTOMER_REQUEST

changedBy:
admin-17&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The audit representation gives us something different:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The identity of the business entity.&lt;/li&gt;
  &lt;li&gt;The revision associated with the change.&lt;/li&gt;
  &lt;li&gt;The previous and new values.&lt;/li&gt;
  &lt;li&gt;The fields modified in that revision.&lt;/li&gt;
  &lt;li&gt;The recorded timestamp.&lt;/li&gt;
  &lt;li&gt;The available actor or process metadata.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This information can be queried and presented as a business-data timeline.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ACCOUNT #1042

Oct 12, 09:41
ACTIVE -&amp;gt; SUSPENDED

Oct 15, 14:20
SUSPENDED -&amp;gt; ACTIVE

Oct 21, 08:10
ACTIVE -&amp;gt; DEACTIVATED&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can see how the account evolved over time.&lt;/p&gt;

&lt;p&gt;We don&#39;t need to infer its entire history from scattered execution messages.&lt;/p&gt;

&lt;p&gt;And if we need to understand why one of those transitions occurred, we can use the recorded context to guide a more focused investigation.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;5. Why Not Just Log Every Entity Change?&lt;/h2&gt;

&lt;p&gt;This is a reasonable question.&lt;/p&gt;

&lt;p&gt;Why introduce a separate auditing mechanism when we could simply log the previous and new values?&lt;/p&gt;

&lt;p&gt;For a small application with limited requirements, structured change logs might be sufficient.&lt;/p&gt;

&lt;p&gt;But as an application grows, several problems emerge.&lt;/p&gt;

&lt;h3&gt;Consistency across write paths&lt;/h3&gt;

&lt;p&gt;Changes can originate from REST endpoints, scheduled jobs, asynchronous consumers, internal services, and administrative operations.&lt;/p&gt;

&lt;p&gt;If every developer is responsible for writing audit-style log statements manually, it becomes easy to miss a write path.&lt;/p&gt;

&lt;h3&gt;Transactional correctness&lt;/h3&gt;

&lt;p&gt;A log emitted before a transaction commits may describe a change that ultimately rolls back.&lt;/p&gt;

&lt;p&gt;Logging after commit can reduce that particular problem, but it introduces other concerns, such as failures between commit and log delivery.&lt;/p&gt;

&lt;h3&gt;Queryability&lt;/h3&gt;

&lt;p&gt;Searching for a text message is not the same as querying a structured revision history by entity, property, revision, actor, or time range.&lt;/p&gt;

&lt;h3&gt;Schema evolution&lt;/h3&gt;

&lt;p&gt;As entities change, manually maintained logging conventions can become inconsistent across application versions.&lt;/p&gt;

&lt;h3&gt;Security and privacy&lt;/h3&gt;

&lt;p&gt;Blindly logging old and new values can expose passwords, tokens, personal information, or other sensitive fields.&lt;/p&gt;

&lt;p&gt;Auditing requires deliberate decisions about what information should be captured and who should be allowed to access it.&lt;/p&gt;

&lt;p&gt;These concerns don&#39;t mean manual audit logging is always wrong.&lt;/p&gt;

&lt;p&gt;They mean that once business history becomes an important application requirement, it deserves an explicit design rather than an informal collection of log statements.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;6. Where Hibernate Envers Fits&lt;/h2&gt;

&lt;p&gt;For Spring Boot applications using Hibernate ORM, Hibernate Envers provides a useful foundation for entity revision history.&lt;/p&gt;

&lt;p&gt;With Envers enabled and an entity configured for auditing, Hibernate can maintain historical revisions of that entity&#39;s persistent state.&lt;/p&gt;

&lt;p&gt;A simplified example looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Entity
@Audited
public class Account {

    @Id
    private Long id;

    @Enumerated(EnumType.STRING)
    private AccountStatus status;

    private String reasonCode;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When an audited entity changes through Hibernate&#39;s managed persistence lifecycle, Envers can record the corresponding revision information.&lt;/p&gt;

&lt;p&gt;Rather than manually placing audit log statements throughout the business layer, the persistence integration captures revision history.&lt;/p&gt;

&lt;p&gt;This is particularly useful because the audit records are normally written within the same transaction as the entity modifications.&lt;/p&gt;

&lt;p&gt;But Envers is not a universal solution to every auditing requirement.&lt;/p&gt;

&lt;p&gt;It does not automatically explain the business reason behind a change.&lt;/p&gt;

&lt;p&gt;It does not automatically know which authenticated user initiated an operation unless the relevant context is captured.&lt;/p&gt;

&lt;p&gt;It also does not automatically audit changes performed outside the Hibernate-managed write path, such as arbitrary direct SQL updates.&lt;/p&gt;

&lt;p&gt;And while it provides APIs for querying historical revisions, building a practical audit history experience still requires additional application design.&lt;/p&gt;

&lt;p&gt;That&#39;s where the distinction between &lt;strong&gt;capturing revisions&lt;/strong&gt; and &lt;strong&gt;consuming audit history&lt;/strong&gt; becomes important.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;7. An Audit Trail Can Tell Us What Changed, But Not Always Why&lt;/h2&gt;

&lt;p&gt;There&#39;s another distinction worth making.&lt;/p&gt;

&lt;p&gt;Suppose our audit history shows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Account #1042

status:
ACTIVE -&amp;gt; SUSPENDED

changedBy:
account-service

changedAt:
2026-10-12T09:41:13Z&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We now know what changed, when it changed, and which recorded actor was associated with the revision.&lt;/p&gt;

&lt;p&gt;But do we know why?&lt;/p&gt;

&lt;p&gt;Not necessarily.&lt;/p&gt;

&lt;p&gt;The audit trail alone may not tell us whether the transition was caused by a customer request, an administrative decision, a business rule, or an external event.&lt;/p&gt;

&lt;p&gt;That information requires additional context.&lt;/p&gt;

&lt;p&gt;For example, a system might deliberately record:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;reasonCode:
CUSTOMER_REQUEST

correlationId:
c5d8f1e2-7a40-4d9c-8b1e-9f1c02d5a611&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With a correlation identifier, investigators may be able to connect the revision to related logs and traces, provided that the same identifier is propagated and recorded consistently.&lt;/p&gt;

&lt;p&gt;With a business reason code, they may also understand why the application was instructed to make the transition.&lt;/p&gt;

&lt;p&gt;But neither field should be invented after the fact.&lt;/p&gt;

&lt;p&gt;An audit system should preserve the context it actually knows, not pretend to understand business intent that was never captured.&lt;/p&gt;

&lt;p&gt;This is an important architectural principle:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Audit history provides evidence of recorded changes. Explaining business intent requires trustworthy context.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2&gt;8. Distributed Systems Need More Than One Kind of History&lt;/h2&gt;

&lt;p&gt;Now consider an asynchronous business workflow:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Account API
    |
    v
Account Service
    |
    v
Database
    |
    v
Transactional Outbox
    |
    v
Kafka
    |
    v
Notification Service&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Suppose an account is suspended and an event is published to notify another service.&lt;/p&gt;

&lt;p&gt;Several different questions may arise during production support.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Did the API request fail?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Application logs, exception information, and tracing can help answer that.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Was the event successfully published?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Event-delivery records, outbox state, retry history, and broker diagnostics can help answer that.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Did the consumer process the event?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consumer processing records, inbox state, idempotency controls, and logs may help.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Did the account actually change from ACTIVE to SUSPENDED?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The committed business state and its audit history can help answer that.&lt;/p&gt;

&lt;p&gt;These questions are related, but they are not interchangeable.&lt;/p&gt;

&lt;p&gt;An event being published doesn&#39;t necessarily prove that a downstream business operation completed.&lt;/p&gt;

&lt;p&gt;A successful HTTP response doesn&#39;t necessarily explain every subsequent asynchronous state transition.&lt;/p&gt;

&lt;p&gt;And a database audit revision doesn&#39;t necessarily tell us whether a notification was delivered.&lt;/p&gt;

&lt;p&gt;Reliable production investigations require us to examine the right evidence for the right question.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;9. Connecting NERV Event and NERV Audit&lt;/h2&gt;

&lt;p&gt;This distinction is particularly relevant to the problems I&#39;ve been exploring through the NERV open-source libraries.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NERV Event&lt;/strong&gt; focuses on reliable event-driven processing, including patterns such as transactional outbox, inbox processing, retries, and idempotency.&lt;/p&gt;

&lt;p&gt;These mechanisms help applications reason about message delivery and processing, including what happens when operations fail or are retried.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NERV Audit&lt;/strong&gt; addresses a different concern: making historical changes to business data easier to inspect and understand.&lt;/p&gt;

&lt;p&gt;The two capabilities complement each other.&lt;/p&gt;

&lt;p&gt;Consider a fictional account suspension workflow:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;1. Account suspension requested

2. Account state updated
   ACTIVE -&amp;gt; SUSPENDED

3. Audit revision persisted

4. Outbox event persisted

5. Database transaction committed

6. Event published asynchronously

7. Downstream consumer processed event&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In a correctly configured transactional design, steps 2 through 4 can participate in the same database transaction.&lt;/p&gt;

&lt;p&gt;The audit revision records the entity change.&lt;/p&gt;

&lt;p&gt;The outbox record represents an event awaiting publication.&lt;/p&gt;

&lt;p&gt;After commit, the event infrastructure can handle asynchronous publication and subsequent processing according to its configured guarantees.&lt;/p&gt;

&lt;p&gt;Notice that these mechanisms answer different questions.&lt;/p&gt;

&lt;p&gt;The audit trail helps establish what happened to the account&#39;s persistent state.&lt;/p&gt;

&lt;p&gt;The event infrastructure helps establish what happened to the asynchronous workflow.&lt;/p&gt;

&lt;p&gt;Neither replaces the other.&lt;/p&gt;

&lt;p&gt;And together with logs, metrics, and tracing, they can make production investigations much more precise.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;10. Building Systems That Are Easier to Investigate&lt;/h2&gt;

&lt;p&gt;After years of building and supporting enterprise applications, I&#39;ve come to appreciate a simple principle:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;A production system should make important business changes explainable through evidence, not guesswork.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That doesn&#39;t mean logging everything.&lt;/p&gt;

&lt;p&gt;It doesn&#39;t mean auditing every column in every table.&lt;/p&gt;

&lt;p&gt;And it certainly doesn&#39;t mean storing sensitive information without considering security and retention requirements.&lt;/p&gt;

&lt;p&gt;It means deliberately designing the mechanisms that help us answer operational questions.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Question&lt;/th&gt;
      &lt;th&gt;Primary source of evidence&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Why did this request fail?&lt;/td&gt;
      &lt;td&gt;Logs, exceptions, and traces&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Was this message delivered or retried?&lt;/td&gt;
      &lt;td&gt;Messaging and event-processing records&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;How was the system performing?&lt;/td&gt;
      &lt;td&gt;Metrics and telemetry&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Who changed this entity?&lt;/td&gt;
      &lt;td&gt;Audit history with actor metadata&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;What was the previous value?&lt;/td&gt;
      &lt;td&gt;Audit revision history&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Why was this business decision made?&lt;/td&gt;
      &lt;td&gt;Recorded business context and supporting evidence&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Each mechanism has a responsibility.&lt;/p&gt;

&lt;p&gt;When those responsibilities are clear, the system becomes easier to operate and its behavior becomes easier to investigate.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;11. Why This Matters for NERV Audit&lt;/h2&gt;

&lt;p&gt;NERV Audit grew out of a recurring problem: applications may already capture entity revisions, yet developers and support teams still struggle to consume that history effectively.&lt;/p&gt;

&lt;p&gt;Hibernate Envers provides the underlying persistence mechanism.&lt;/p&gt;

&lt;p&gt;But applications still need a usable layer for working with revision history, understanding changed fields, and exposing the appropriate information through application interfaces.&lt;/p&gt;

&lt;p&gt;That&#39;s the problem NERV Audit is intended to address.&lt;/p&gt;

&lt;p&gt;It builds on Hibernate Envers rather than replacing it.&lt;/p&gt;

&lt;p&gt;And its purpose is not to replace logs, tracing, or event-processing records either.&lt;/p&gt;

&lt;p&gt;Instead, it helps make business-data history a first-class application capability.&lt;/p&gt;

&lt;p&gt;Because when someone asks why an account was deactivated, why a configuration changed, or how an entity reached an unexpected state, we should have better tools than searching through thousands of unrelated log messages.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Final Thoughts&lt;/h2&gt;

&lt;p&gt;Logs are essential.&lt;/p&gt;

&lt;p&gt;Without them, diagnosing application failures would be considerably harder.&lt;/p&gt;

&lt;p&gt;But logs are not a substitute for a structured, reliable audit trail.&lt;/p&gt;

&lt;p&gt;They have different purposes, different storage lifecycles, different transactional characteristics, and different ways of being queried.&lt;/p&gt;

&lt;p&gt;Application logs help us reconstruct execution.&lt;/p&gt;

&lt;p&gt;Audit history helps us reconstruct changes to business data.&lt;/p&gt;

&lt;p&gt;Event-processing records help us reconstruct asynchronous workflow progress.&lt;/p&gt;

&lt;p&gt;Distributed tracing helps connect execution across service boundaries.&lt;/p&gt;

&lt;p&gt;And recorded business context can help explain why a particular decision was made.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Good production engineering is not about choosing one of these mechanisms.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It&#39;s about understanding where each belongs.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Logs tell us what the application was doing. An audit trail tells us what happened to the data.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When a production incident involves unexpected business state, knowing the difference can save hours of investigation.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;About NERV Audit&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;NERV Audit&lt;/strong&gt; is an open-source Java and Spring Boot auditing library built on Hibernate Envers, designed to make historical business-data changes easier to query, inspect, and consume.&lt;/p&gt;

&lt;p&gt;It is part of the NERV family of open-source libraries focused on practical production engineering challenges.&lt;/p&gt;

&lt;p&gt;Explore the NERV projects on &lt;a href=&quot;https://github.com/czetsuyatech&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For more articles on Java, Spring Boot, persistence, and production-ready system design, visit &lt;a href=&quot;https://www.czetsuyatech.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;CzetsuyaTech&lt;/a&gt;.&lt;/p&gt;


&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/database-tells-you-what-is-audit-trail-tells-you-what-happened.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        The Database Tells You What Is. An Audit Trail Tells You What Happened
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Audit&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;



  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/4374165966437319243/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/10/logs-arent-an-audit-trail-debugging-business-data.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/4374165966437319243'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/4374165966437319243'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/10/logs-arent-an-audit-trail-debugging-business-data.html' title='Logs Aren&#39;t an Audit Trail: Debugging Business Data in Production'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYoSo5IvY3bAAduVShROXqlnS_5DW_3buSR5rQrb27Xb1LR7OHV6nPsDkl2BXLbIvcXx0R25LGtMccsurZccsoCm-4W55DNQYNTAtq96wKjup-SitAgVfM1myfcuazuas5bLm8CvTfcSAj2Mwc33YuJZVkqduQstYzvOXHzNhy11bd9fYgwfdoNkmrEJAD/s72-c/nerv-audit-logs-vs-audit-trail.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-6580409714448064926</id><published>2026-10-27T12:33:42.075+08:00</published><updated>2026-11-16T21:23:17.510+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Persistence"/><category scheme="http://www.blogger.com/atom/ns#" term="Persistence"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Data JPA"/><title type='text'>Dynamic Queries in Spring Data JPA Without Repository Method Explosion</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgIybiz7gMEN0XlZMbH5IVA7erc7poWJbFuY0aeu7C0Tqaupnj61DYreLtNcHZLcPYOykUEFUjdbRAmIQ48fosiVAei7QDnPkG_OIcIS6s_fGUlxHhGYgDQpWfC6RsCIWIJApPhsNhWepngBs-Zia2vtthlbRAqJ0eYpfJ9ys2h_3-XLFU_E4GjxJ9Daptj/s1600/nerv-persistence-dynamic-queries-spring-data-jpa.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;NERV Persistence article cover illustrating dynamic queries in Spring Data JPA using composable Specifications, optional search filters, pagination, and SQL query generation&quot; border=&quot;0&quot; data-original-height=&quot;941&quot; data-original-width=&quot;1672&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgIybiz7gMEN0XlZMbH5IVA7erc7poWJbFuY0aeu7C0Tqaupnj61DYreLtNcHZLcPYOykUEFUjdbRAmIQ48fosiVAei7QDnPkG_OIcIS6s_fGUlxHhGYgDQpWfC6RsCIWIJApPhsNhWepngBs-Zia2vtthlbRAqJ0eYpfJ9ys2h_3-XLFU_E4GjxJ9Daptj/s1600/nerv-persistence-dynamic-queries-spring-data-jpa.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;article&gt;
  &lt;p&gt;
    Spring Data JPA makes database access remarkably straightforward.
    Define an entity, extend &lt;code&gt;JpaRepository&lt;/code&gt;, declare a few
    query methods, and you have a working persistence layer with very
    little code.
  &lt;/p&gt;

  &lt;p&gt;
    For straightforward applications, this is often enough.
    But as an application grows, the number of repository methods can
    begin growing faster than the number of business operations.
  &lt;/p&gt;

  &lt;p&gt;
    What started as a simple customer search becomes a collection
    of increasingly specific methods:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;List&amp;lt;Customer&amp;gt; findByStatus(CustomerStatus status);

List&amp;lt;Customer&amp;gt; findByCountry(String country);

List&amp;lt;Customer&amp;gt; findByStatusAndCountry(
    CustomerStatus status,
    String country
);

List&amp;lt;Customer&amp;gt; findByStatusAndCountryAndType(
    CustomerStatus status,
    String country,
    CustomerType type
);&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Eventually, you discover that you are not implementing different
    business operations. You are implementing different combinations
    of the same search criteria.
  &lt;/p&gt;

  &lt;p&gt;
    This is where derived repository methods stop being a convenient
    abstraction and start becoming a maintenance problem.
  &lt;/p&gt;

  &lt;p&gt;
    In this article, we&#39;ll explore how to design dynamic queries in
    Spring Data JPA without accumulating repository methods for every
    possible filter combination. We&#39;ll also examine how this approach
    fits into the reusable persistence infrastructure behind
    &lt;strong&gt;NERV Persistence&lt;/strong&gt;.
  &lt;/p&gt;

  &lt;h2&gt;1. The Repository Method Explosion&lt;/h2&gt;

  &lt;p&gt;
    Consider a customer management application. Initially, the
    requirements are simple: find customers by status, country,
    or customer type.
  &lt;/p&gt;

  &lt;p&gt;
    Spring Data JPA&#39;s derived query methods are a natural fit:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public interface CustomerRepository
        extends JpaRepository&amp;lt;Customer, Long&amp;gt; {

    List&amp;lt;Customer&amp;gt; findByStatus(CustomerStatus status);

    List&amp;lt;Customer&amp;gt; findByCountry(String country);

    List&amp;lt;Customer&amp;gt; findByType(CustomerType type);
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Everything looks reasonable until the product team introduces
    a search page where users can combine optional filters:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Status&lt;/li&gt;
    &lt;li&gt;Country&lt;/li&gt;
    &lt;li&gt;Customer type&lt;/li&gt;
    &lt;li&gt;Registration date&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    With four independent optional filters, there are already
    &lt;strong&gt;2&lt;sup&gt;4&lt;/sup&gt; = 16 possible combinations&lt;/strong&gt;.
    With eight filters, there are 256.
  &lt;/p&gt;

  &lt;p&gt;
    Not every combination necessarily requires a separate repository
    method. However, the underlying problem is clear:
    &lt;strong&gt;query requirements are combinatorial, while derived
    repository methods describe fixed queries.&lt;/strong&gt;
  &lt;/p&gt;

  &lt;p&gt;We need a different abstraction.&lt;/p&gt;

  &lt;h2&gt;2. The Problem Is Query Composition&lt;/h2&gt;

  &lt;p&gt;
    One common solution is a single JPQL query with nullable
    parameters:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Query(&quot;&quot;&quot;
    SELECT c
    FROM Customer c
    WHERE (:status IS NULL OR c.status = :status)
      AND (:country IS NULL OR c.country = :country)
      AND (:type IS NULL OR c.type = :type)
    &quot;&quot;&quot;)
List&amp;lt;Customer&amp;gt; search(
    @Param(&quot;status&quot;) CustomerStatus status,
    @Param(&quot;country&quot;) String country,
    @Param(&quot;type&quot;) CustomerType type
);&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This reduces the number of repository methods, but it introduces
    other concerns:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Queries become harder to maintain as conditions accumulate.&lt;/li&gt;
    &lt;li&gt;Optional-filter behavior is embedded directly into JPQL.&lt;/li&gt;
    &lt;li&gt;
      OR conditions may complicate query optimization, depending on
      the database and execution plan.
    &lt;/li&gt;
    &lt;li&gt;
      The query remains tightly coupled to a particular set of
      search requirements.
    &lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    We have reduced method proliferation, but we have not necessarily
    improved query composition.
  &lt;/p&gt;

  &lt;p&gt;
    A better approach is to represent conditions independently and
    combine only those required by the current request.
  &lt;/p&gt;

  &lt;h2&gt;3. Enter Spring Data JPA Specifications&lt;/h2&gt;

  &lt;p&gt;
    Spring Data JPA provides the
    &lt;code&gt;Specification&amp;lt;T&amp;gt;&lt;/code&gt; abstraction for building
    composable predicates using the JPA Criteria API.
  &lt;/p&gt;

  &lt;p&gt;
    A Specification represents a condition that can be applied to
    a query.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public final class CustomerSpecifications {

    private CustomerSpecifications() {
    }

    public static Specification&amp;lt;Customer&amp;gt; hasStatus(
            CustomerStatus status) {

        return (root, query, cb) -&amp;gt;
            cb.equal(root.get(&quot;status&quot;), status);
    }

    public static Specification&amp;lt;Customer&amp;gt; hasCountry(
            String country) {

        return (root, query, cb) -&amp;gt;
            cb.equal(root.get(&quot;country&quot;), country);
    }

    public static Specification&amp;lt;Customer&amp;gt; hasType(
            CustomerType type) {

        return (root, query, cb) -&amp;gt;
            cb.equal(root.get(&quot;type&quot;), type);
    }
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Each Specification describes one condition. It does not need
    to know which other conditions will be used.
  &lt;/p&gt;

  &lt;p&gt;
    Instead of implementing every possible search combination,
    we implement reusable predicates and compose them:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Specification&amp;lt;Customer&amp;gt; specification =
    Specification.allOf(
        CustomerSpecifications.hasStatus(status),
        CustomerSpecifications.hasCountry(country)
    );&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The repository only needs to support Specification execution:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public interface CustomerRepository
        extends JpaRepository&amp;lt;Customer, Long&amp;gt;,
                JpaSpecificationExecutor&amp;lt;Customer&amp;gt; {
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;Now we can execute the composed query:&lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;List&amp;lt;Customer&amp;gt; customers =
    customerRepository.findAll(specification);&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The same repository supports different combinations of criteria
    without requiring a dedicated method for each variation.
  &lt;/p&gt;

  &lt;h2&gt;4. Handling Optional Filters Properly&lt;/h2&gt;

  &lt;p&gt;
    Real search requests rarely provide every field. Suppose our
    application accepts the following criteria:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public record CustomerSearchCriteria(
    CustomerStatus status,
    String country,
    CustomerType type,
    LocalDate registeredFrom,
    LocalDate registeredTo
) {
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    We can build a query using only the supplied filters:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public static Specification&amp;lt;Customer&amp;gt; from(
        CustomerSearchCriteria criteria) {

    List&amp;lt;Specification&amp;lt;Customer&amp;gt;&amp;gt; filters =
        new ArrayList&amp;lt;&amp;gt;();

    if (criteria.status() != null) {
        filters.add(hasStatus(criteria.status()));
    }

    if (criteria.country() != null
            &amp;amp;&amp;amp; !criteria.country().isBlank()) {

        filters.add(hasCountry(criteria.country()));
    }

    if (criteria.type() != null) {
        filters.add(hasType(criteria.type()));
    }

    if (criteria.registeredFrom() != null) {
        filters.add(registeredOnOrAfter(
            criteria.registeredFrom()
        ));
    }

    if (criteria.registeredTo() != null) {
        filters.add(registeredBefore(
            criteria.registeredTo().plusDays(1)
        ));
    }

    return Specification.allOf(filters);
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This example assumes the helper methods belong to
    &lt;code&gt;CustomerSpecifications&lt;/code&gt;.
    An empty collection produces an unrestricted Specification,
    so an empty search matches all customers unless the application
    imposes additional restrictions.
  &lt;/p&gt;

  &lt;p&gt;
    Date filters deserve particular attention. Suppose registration
    timestamps are stored as &lt;code&gt;Instant&lt;/code&gt;.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public static Specification&amp;lt;Customer&amp;gt; registeredOnOrAfter(
        LocalDate date) {

    Instant start = date
        .atStartOfDay(ZoneOffset.UTC)
        .toInstant();

    return (root, query, cb) -&amp;gt;
        cb.greaterThanOrEqualTo(
            root.get(&quot;registeredAt&quot;),
            start
        );
}

public static Specification&amp;lt;Customer&amp;gt; registeredBefore(
        LocalDate exclusiveDate) {

    Instant end = exclusiveDate
        .atStartOfDay(ZoneOffset.UTC)
        .toInstant();

    return (root, query, cb) -&amp;gt;
        cb.lessThan(
            root.get(&quot;registeredAt&quot;),
            end
        );
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Notice that the upper boundary is exclusive.
    Instead of manufacturing an end-of-day timestamp, we use the
    beginning of the following day.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;registeredAt &amp;gt;= 2026-10-01T00:00:00Z
registeredAt &amp;lt;  2026-10-06T00:00:00Z&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This represents October 1 through October 5 inclusive,
    using UTC calendar boundaries.
  &lt;/p&gt;

  &lt;p&gt;
    If business dates are interpreted in a particular local timezone,
    that timezone must be used instead.
  &lt;/p&gt;

  &lt;p&gt;
    The important architectural benefit is that each predicate
    remains independently reusable.
  &lt;/p&gt;

  &lt;h2&gt;5. Pagination and Sorting Without Additional Repository Methods&lt;/h2&gt;

  &lt;p&gt;
    Dynamic filtering is only part of a production search API.
    Most applications also require pagination and sorting.
  &lt;/p&gt;

  &lt;p&gt;
    Spring Data JPA Specifications integrate naturally with
    &lt;code&gt;Pageable&lt;/code&gt;.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public Page&amp;lt;Customer&amp;gt; search(
        CustomerSearchCriteria criteria,
        Pageable pageable) {

    Specification&amp;lt;Customer&amp;gt; specification =
        CustomerSpecifications.from(criteria);

    return customerRepository.findAll(
        specification,
        pageable
    );
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    A controller can expose the functionality through a conventional
    REST endpoint:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@GetMapping(&quot;/customers&quot;)
public Page&amp;lt;CustomerResponse&amp;gt; search(
        @ModelAttribute CustomerSearchCriteria criteria,
        Pageable pageable) {

    return customerService
        .search(criteria, pageable)
        .map(customerMapper::toResponse);
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    For public APIs, avoid exposing JPA entities directly.
    The response should represent the API contract rather than
    the persistence model.
  &lt;/p&gt;

  &lt;p&gt;
    Production implementations should also enforce maximum page
    sizes, validate sortable properties, and consider deterministic
    ordering to prevent unstable pagination.
  &lt;/p&gt;

  &lt;h2&gt;6. The Hidden Duplication in Dynamic Query Infrastructure&lt;/h2&gt;

  &lt;p&gt;
    Specifications solve an important problem, but they do not
    eliminate every form of duplication.
  &lt;/p&gt;

  &lt;p&gt;
    Imagine implementing dynamic search across customers, payments,
    invoices, orders, and subscriptions.
  &lt;/p&gt;

  &lt;p&gt;
    Each domain should own its business-specific predicates.
    However, developers may repeatedly implement the same technical
    mechanics:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Checking whether optional filters are present&lt;/li&gt;
    &lt;li&gt;Mapping operators to Criteria API expressions&lt;/li&gt;
    &lt;li&gt;Applying consistent sorting conventions&lt;/li&gt;
    &lt;li&gt;Translating search requests into predicates&lt;/li&gt;
    &lt;li&gt;Handling pagination consistently&lt;/li&gt;
    &lt;li&gt;Validating permitted query fields&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    These are persistence infrastructure concerns rather than
    necessarily domain-specific business rules.
  &lt;/p&gt;

  &lt;p&gt;
    The goal is not to create a universal repository that understands
    every domain. It is to centralize genuinely common mechanics
    while preserving meaningful business predicates.
  &lt;/p&gt;

  &lt;p&gt;For example, customer search might express:&lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;hasActiveSubscription()&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;Payment search might express:&lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;hasUnsettledBalance()&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    These are illustrative domain predicate names, not built-in
    Spring Data JPA or NERV Persistence methods.
  &lt;/p&gt;

  &lt;p&gt;
    Such business concepts should not disappear into an unrestricted
    string-based query language merely because both ultimately
    produce SQL predicates.
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;
      Good reuse removes repetition without removing meaning.
    &lt;/strong&gt;
  &lt;/p&gt;

  &lt;h2&gt;7. Where NERV Persistence Fits&lt;/h2&gt;

  &lt;p&gt;
    This is one of the motivations behind
    &lt;strong&gt;NERV Persistence&lt;/strong&gt;.
  &lt;/p&gt;

  &lt;p&gt;
    Spring Data JPA already provides excellent building blocks:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;&lt;code&gt;JpaRepository&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;JpaSpecificationExecutor&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;Specification&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;Pageable&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;JPA projections&lt;/li&gt;
    &lt;li&gt;The JPA Criteria API&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    NERV Persistence builds on the idea of reusable persistence
    conventions and infrastructure rather than replacing
    Spring Data JPA.
  &lt;/p&gt;

  &lt;p&gt;
    The distinction matters. Spring Data JPA remains responsible
    for integrating query execution with JPA.
    The application domain remains responsible for defining
    meaningful search conditions.
  &lt;/p&gt;

  &lt;p&gt;
    Reusable infrastructure can help standardize technical mechanics
    between those layers.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;REST API
   |
   v
Search Criteria
   |
   v
Domain Query Rules
   |
   v
Reusable Query Infrastructure
   |
   v
Spring Data JPA
   |
   v
Hibernate / Database&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    This is a conceptual architectural diagram, not a mapping
    of specific NERV Persistence classes.
  &lt;/p&gt;

  &lt;p&gt;
    A reusable library should make common operations easier
    without preventing developers from using Specifications,
    JPQL, the Criteria API, or native SQL when necessary.
  &lt;/p&gt;

  &lt;p&gt;
    Explore the project:
    &lt;a href=&quot;https://github.com/czetsuyatech/nerv-persistence&quot;
       target=&quot;_blank&quot;
       rel=&quot;noopener noreferrer&quot;&gt;
      NERV Persistence on GitHub
    &lt;/a&gt;.
  &lt;/p&gt;

  &lt;h2&gt;8. Dynamic Queries Still Need Production Discipline&lt;/h2&gt;

  &lt;p&gt;
    Removing repository method explosion does not automatically
    produce efficient queries.
  &lt;/p&gt;

  &lt;p&gt;
    Specifications are a composition mechanism.
    &lt;strong&gt;They are not a query optimizer.&lt;/strong&gt;
  &lt;/p&gt;

  &lt;h3&gt;8.1 Indexes Still Matter&lt;/h3&gt;

  &lt;p&gt;Consider the following SQL:&lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT *
FROM customer
WHERE status = &#39;ACTIVE&#39;
  AND country = &#39;PH&#39;
ORDER BY registered_at DESC;&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Whether this performs well depends on table size, data
    distribution, indexes, and the database execution plan.
  &lt;/p&gt;

  &lt;p&gt;
    The Java abstraction does not eliminate the need to inspect
    generated SQL and evaluate important queries using realistic data.
  &lt;/p&gt;

  &lt;h3&gt;8.2 Joins Can Change Result Cardinality&lt;/h3&gt;

  &lt;p&gt;
    Filtering across relationships introduces additional complexity.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;return (root, query, cb) -&amp;gt; {
    Join&amp;lt;Customer, Order&amp;gt; orders =
        root.join(&quot;orders&quot;);

    return cb.equal(
        orders.get(&quot;status&quot;),
        OrderStatus.COMPLETED
    );
};&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    If a customer has multiple matching orders, the SQL join
    may produce multiple rows for the same customer.
  &lt;/p&gt;

  &lt;p&gt;
    This can affect result duplication, pagination, and count
    behavior. Depending on the requirement, an
    &lt;code&gt;EXISTS&lt;/code&gt; subquery may be more appropriate.
  &lt;/p&gt;

  &lt;h3&gt;8.3 Pagination Can Trigger Expensive Count Queries&lt;/h3&gt;

  &lt;p&gt;
    A &lt;code&gt;Page&amp;lt;T&amp;gt;&lt;/code&gt; generally requires the total
    number of matching records.
  &lt;/p&gt;

  &lt;p&gt;
    For complex joins and large datasets, the count query
    can contribute significantly to request latency.
  &lt;/p&gt;

  &lt;p&gt;
    When total counts are unnecessary, a slice-oriented or
    otherwise specialized retrieval strategy may be more efficient.
    Spring Data JPA also supports separate content and count
    Specifications in applicable versions.
  &lt;/p&gt;

  &lt;h3&gt;8.4 Not Every Field Should Be Searchable&lt;/h3&gt;

  &lt;p&gt;
    A generic filter API that accepts arbitrary entity property
    names can expose implementation details or generate expensive
    queries.
  &lt;/p&gt;

  &lt;p&gt;
    Public search APIs should validate supported fields, operators,
    sorting options, and pagination limits.
  &lt;/p&gt;

  &lt;h3&gt;8.5 Test Against the Actual Database&lt;/h3&gt;

  &lt;p&gt;
    Unit tests are useful for checking how Specifications are
    assembled, but integration tests should verify:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Null and empty-filter handling&lt;/li&gt;
    &lt;li&gt;Date boundaries&lt;/li&gt;
    &lt;li&gt;Join behavior&lt;/li&gt;
    &lt;li&gt;Pagination and count accuracy&lt;/li&gt;
    &lt;li&gt;Case sensitivity and collation&lt;/li&gt;
    &lt;li&gt;Database-specific query behavior&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    For critical persistence behavior, PostgreSQL integration tests
    provide stronger confidence when PostgreSQL is the production
    database than relying exclusively on an in-memory substitute.
  &lt;/p&gt;

  &lt;h2&gt;9. When Specifications Are Not the Right Tool&lt;/h2&gt;

  &lt;p&gt;
    Specifications are useful, but they should not become the
    default answer to every database problem.
  &lt;/p&gt;

  &lt;p&gt;
    For a simple fixed query, a derived repository method is
    often clearer:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Optional&amp;lt;Customer&amp;gt; findByExternalId(
    String externalId
);&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    For complex reporting involving aggregation, window functions,
    or database-specific features, explicit SQL may be easier
    to reason about and optimize.
  &lt;/p&gt;

  &lt;p&gt;
    For high-volume read models, projections or specialized query
    implementations may be more appropriate.
  &lt;/p&gt;

  &lt;p&gt;
    And when a query has highly specific business semantics,
    a descriptive repository method can communicate intent
    better than a generic filter object.
  &lt;/p&gt;

  &lt;p&gt;
    The goal is not to eliminate repository methods.
    It is to stop using fixed repository methods to represent
    an expanding number of optional search combinations.
  &lt;/p&gt;

  &lt;h2&gt;10. Design for Change, Not Just Less Code&lt;/h2&gt;

  &lt;p&gt;
    One recurring mistake in persistence design is measuring
    abstraction quality by how many lines of code it removes.
  &lt;/p&gt;

  &lt;p&gt;
    Less code is useful, but fewer lines do not necessarily
    mean better architecture.
  &lt;/p&gt;

  &lt;p&gt;A well-designed dynamic query system should make it easier to:&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Add search conditions without modifying unrelated queries&lt;/li&gt;
    &lt;li&gt;Understand which business rules are applied&lt;/li&gt;
    &lt;li&gt;Test predicates independently&lt;/li&gt;
    &lt;li&gt;Control query complexity&lt;/li&gt;
    &lt;li&gt;Inspect generated SQL&lt;/li&gt;
    &lt;li&gt;Maintain stable API contracts&lt;/li&gt;
    &lt;li&gt;Reuse common infrastructure across services&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    The real benefit of composable Specifications is not merely
    that they replace dozens of repository methods.
  &lt;/p&gt;

  &lt;p&gt;
    It is that search behavior can evolve without turning
    the persistence layer into a fragile collection of
    increasingly specific combinations.
  &lt;/p&gt;

  &lt;h2&gt;Final Thoughts&lt;/h2&gt;

  &lt;p&gt;
    Spring Data JPA&#39;s derived query methods are one of its
    most convenient features.
  &lt;/p&gt;

  &lt;p&gt;
    They work extremely well when a query is fixed and
    its intent is clear.
  &lt;/p&gt;

  &lt;p&gt;
    But optional search filters introduce a different problem.
    Instead of asking how many repository methods we need,
    we should ask how to represent and compose query conditions.
  &lt;/p&gt;

  &lt;p&gt;
    Specifications provide a useful answer. They let us keep
    domain predicates independent, combine only the conditions
    required by a request, and integrate naturally with
    Spring Data JPA&#39;s repository and pagination infrastructure.
  &lt;/p&gt;

  &lt;p&gt;
    NERV Persistence builds on the broader idea that common
    persistence mechanics should be reusable while
    domain-specific query behavior remains explicit.
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;
      The best persistence abstraction is not the one that hides
      the most SQL or produces the fewest methods.
      It is the one that makes the next requirement easier
      to implement without making the existing system
      harder to understand.
    &lt;/strong&gt;
  &lt;/p&gt;

  &lt;hr /&gt;

  &lt;p&gt;
    &lt;em&gt;
      This is Article #2 in the NERV Persistence series,
      exploring practical persistence architecture for
      Java and Spring Boot applications.
    &lt;/em&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;Explore NERV Persistence:&lt;/strong&gt;
    &lt;a href=&quot;https://github.com/czetsuyatech/nerv-persistence&quot;
       target=&quot;_blank&quot;
       rel=&quot;noopener noreferrer&quot;&gt;
      github.com/czetsuyatech/nerv-persistence
    &lt;/a&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;More engineering articles:&lt;/strong&gt;
    &lt;a href=&quot;https://www.czetsuyatech.com/&quot;&gt;
      CzetsuyaTech
    &lt;/a&gt;
  &lt;/p&gt;
&lt;/article&gt;


&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/building-production-ready-persistence-layer-spring-boot.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Building a Production-Ready Persistence Layer in Spring Boot
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Persistence&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;

    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/11/specification-pattern-spring-data-jpa-composable-queries.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        The Specification Pattern in Spring Data JPA: Building Composable Queries That Scale
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/6580409714448064926/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/10/dynamic-queries-spring-data-jpa.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/6580409714448064926'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/6580409714448064926'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/10/dynamic-queries-spring-data-jpa.html' title='Dynamic Queries in Spring Data JPA Without Repository Method Explosion'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgIybiz7gMEN0XlZMbH5IVA7erc7poWJbFuY0aeu7C0Tqaupnj61DYreLtNcHZLcPYOykUEFUjdbRAmIQ48fosiVAei7QDnPkG_OIcIS6s_fGUlxHhGYgDQpWfC6RsCIWIJApPhsNhWepngBs-Zia2vtthlbRAqJ0eYpfJ9ys2h_3-XLFU_E4GjxJ9Daptj/s72-c/nerv-persistence-dynamic-queries-spring-data-jpa.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-7348948419470692653</id><published>2026-10-18T22:26:57.633+08:00</published><updated>2026-10-18T22:36:42.624+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="API Design"/><category scheme="http://www.blogger.com/atom/ns#" term="Exception Handling"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Exception"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>Designing a Consistent Error Contract for Spring Boot APIs</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGeZA1kO17WM1a8Eo6cU1N5p8x09uNWfa65JI893aAcksxo3dmwxmUgzHXjP3WxfMPBpCiis8kgUwG6xb40YdJMJqOp_jjgg9xzjkS0JUBh3cGANAqe_UMyo3qaVVEeUgK2iMl2TP5coUZ35ZA5Rk2Z84XptQWIGiSajCLFHfP-wsHhL0lcVoMZFIsBJyq/s1600/spring-boot-consistent-error-contract.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;Architecture of a consistent Spring Boot API error contract across microservices&quot; border=&quot;0&quot; data-original-height=&quot;1024&quot; data-original-width=&quot;1536&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGeZA1kO17WM1a8Eo6cU1N5p8x09uNWfa65JI893aAcksxo3dmwxmUgzHXjP3WxfMPBpCiis8kgUwG6xb40YdJMJqOp_jjgg9xzjkS0JUBh3cGANAqe_UMyo3qaVVEeUgK2iMl2TP5coUZ35ZA5Rk2Z84XptQWIGiSajCLFHfP-wsHhL0lcVoMZFIsBJyq/s1600/spring-boot-consistent-error-contract.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;

&lt;h2&gt;Introduction&lt;/h2&gt;

&lt;p&gt;
Exception handling is easy to overlook when building an application.
&lt;/p&gt;

&lt;p&gt;
A controller throws an exception. A global exception handler catches
it. The application returns an HTTP status and an error message.
&lt;/p&gt;

&lt;p&gt;
For a small application, that may be sufficient.
&lt;/p&gt;

&lt;p&gt;
But when the application becomes part of a distributed system,
exception handling becomes an API design problem.
&lt;/p&gt;

&lt;p&gt;
Consider three Spring Boot services returning errors.
&lt;/p&gt;

&lt;p&gt;Customer Service:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;message&quot;: &quot;Customer not found&quot;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Payment Service:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;error&quot;: &quot;PAYMENT_ALREADY_PROCESSED&quot;,
  &quot;status&quot;: 409
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Inventory Service:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;timestamp&quot;: &quot;2026-10-18T10:30:00Z&quot;,
  &quot;status&quot;: 404,
  &quot;error&quot;: &quot;Not Found&quot;,
  &quot;path&quot;: &quot;/inventory/123&quot;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
All three services report failures, but each exposes a different
response structure.
&lt;/p&gt;

&lt;p&gt;
Now imagine an API gateway, frontend application, or another
microservice attempting to interpret these responses.
&lt;/p&gt;

&lt;p&gt;
Every integration requires additional error-handling logic.
&lt;/p&gt;

&lt;p&gt;
The problem is not necessarily that exceptions are handled
incorrectly.
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;
The problem is that exception handling has not been designed
as a consistent API contract.
&lt;/strong&gt;
&lt;/p&gt;

&lt;h2&gt;1. An Exception Is Not an API Error Contract&lt;/h2&gt;

&lt;p&gt;
Java exceptions and API error responses serve different purposes.
&lt;/p&gt;

&lt;p&gt;
An exception represents a failure inside an application.
An API error response communicates that failure across an
application boundary.
&lt;/p&gt;

&lt;p&gt;
Consider:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;throw new IllegalStateException(
    &quot;Customer account is disabled&quot;
);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This exception is meaningful to the developer.
&lt;/p&gt;

&lt;p&gt;
However, an API consumer needs more than a Java exception message.
&lt;/p&gt;

&lt;p&gt;
It may need to understand:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;What failure occurred?&lt;/li&gt;
  &lt;li&gt;Which application error code identifies it?&lt;/li&gt;
  &lt;li&gt;What HTTP status represents the failure?&lt;/li&gt;
  &lt;li&gt;Is the failure potentially retryable?&lt;/li&gt;
  &lt;li&gt;Which service originated the error?&lt;/li&gt;
  &lt;li&gt;What additional information is available for troubleshooting?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
These concerns should not depend on Java exception class names
or arbitrary exception messages.
&lt;/p&gt;

&lt;p&gt;
An API error contract provides a stable representation
independent of the internal exception hierarchy.
&lt;/p&gt;

&lt;h2&gt;2. Designing the Error Contract&lt;/h2&gt;

&lt;p&gt;
A consistent error contract should provide enough information
for applications and operational systems to understand a failure.
&lt;/p&gt;

&lt;p&gt;
In NERV Exception, the HTTP error response is represented
by &lt;code&gt;NervErrorResponse&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
The following example illustrates a business-related conflict
using the native &lt;code&gt;CONFLICT&lt;/code&gt; error definition.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;code&quot;: &quot;CONFLICT&quot;,
  &quot;message&quot;: &quot;Duplicate resource&quot;,
  &quot;status&quot;: 409,
  &quot;retryable&quot;: false,
  &quot;category&quot;: &quot;CLIENT&quot;,
  &quot;traceId&quot;: null,
  &quot;spanId&quot;: null,
  &quot;path&quot;: &quot;/nerv&quot;,
  &quot;timestamp&quot;: &quot;2026-10-18T00:00:00Z&quot;,
  &quot;origin&quot;: {
    &quot;service&quot;: &quot;unknown-service&quot;,
    &quot;instance&quot;: &quot;unknown-instance&quot;,
    &quot;version&quot;: &quot;unknown-version&quot;,
    &quot;environment&quot;: &quot;default&quot;
  },
  &quot;details&quot;: {}
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This example reflects the structure supported by the
NERV Exception implementation.
&lt;/p&gt;

&lt;p&gt;
The timestamp is illustrative. The null tracing fields assume
no active tracing context and null-inclusive JSON serialization.
Applications may configure Jackson to omit null fields.
&lt;/p&gt;

&lt;p&gt;
Notice that the native &lt;code&gt;CONFLICT&lt;/code&gt; definition uses
the category &lt;code&gt;CLIENT&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
Although the example represents a business conflict,
the category is determined by the error definition,
not automatically inferred from the use case.
&lt;/p&gt;

&lt;p&gt;
Let&#39;s examine the responsibilities of each field.
&lt;/p&gt;

&lt;h3&gt;Application Error Code&lt;/h3&gt;

&lt;p&gt;
The &lt;code&gt;code&lt;/code&gt; field provides a stable,
machine-readable identifier.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;code&quot;: &quot;CONFLICT&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Application consumers can use error codes to implement
predictable behavior without parsing human-readable messages.
&lt;/p&gt;

&lt;p&gt;
For example, an application might define its own
domain-specific codes:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CUSTOMER_NOT_FOUND
CUSTOMER_DISABLED
PAYMENT_ALREADY_PROCESSED&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
These are illustrative application codes, not built-in
NERV Exception definitions.
&lt;/p&gt;

&lt;p&gt;
The important principle is that error codes should remain
stable once external consumers depend on them.
&lt;/p&gt;

&lt;h3&gt;Human-Readable Message&lt;/h3&gt;

&lt;p&gt;
The &lt;code&gt;message&lt;/code&gt; field explains the failure.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;message&quot;: &quot;Duplicate resource&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Messages should be understandable, but they should not
be treated as stable application identifiers.
&lt;/p&gt;

&lt;p&gt;
Messages may evolve for clarity or localization.
&lt;/p&gt;

&lt;p&gt;
They should also avoid exposing sensitive information,
including internal stack traces, credentials,
and database implementation details.
&lt;/p&gt;

&lt;h3&gt;HTTP Status&lt;/h3&gt;

&lt;p&gt;
The &lt;code&gt;status&lt;/code&gt; field represents the HTTP status
associated with the selected error definition.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;status&quot;: 409&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
NERV Exception&#39;s Spring Web handler uses the mapped response
status as the actual HTTP response status.
&lt;/p&gt;

&lt;p&gt;
This allows the response body and HTTP transport to communicate
the same selected application failure.
&lt;/p&gt;

&lt;p&gt;
However, when errors are decoded from downstream services,
the selected status may come from a local error definition
rather than the original downstream transport status.
&lt;/p&gt;

&lt;p&gt;
This distinction matters when designing error propagation.
&lt;/p&gt;

&lt;h3&gt;Error Category&lt;/h3&gt;

&lt;p&gt;
The &lt;code&gt;category&lt;/code&gt; field classifies the nature
of the failure.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;category&quot;: &quot;CLIENT&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
NERV Exception supports categories through error definitions.
&lt;/p&gt;

&lt;p&gt;
Its API declares several category constants, including
VALIDATION, BUSINESS, SECURITY, DEPENDENCY, and SYSTEM.
&lt;/p&gt;

&lt;p&gt;
However, the serialized category is a string.
&lt;/p&gt;

&lt;p&gt;
The implementation also uses additional category values
such as CLIENT, DOWNSTREAM, and DATA.
&lt;/p&gt;

&lt;p&gt;
Therefore, applications should not assume that every
error category belongs to one closed enumeration.
&lt;/p&gt;

&lt;p&gt;
Importantly, the category does not automatically determine
the HTTP status or retryability.
&lt;/p&gt;

&lt;p&gt;
Those properties are independently defined by the
selected error definition.
&lt;/p&gt;

&lt;h3&gt;Retryability&lt;/h3&gt;

&lt;p&gt;
The &lt;code&gt;retryable&lt;/code&gt; field communicates whether
a failure is considered potentially retryable.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;retryable&quot;: false&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This information becomes especially important
when services communicate over unreliable networks.
&lt;/p&gt;

&lt;p&gt;
For example, a validation failure generally should not
be retried without correcting the request.
&lt;/p&gt;

&lt;p&gt;
A temporary dependency failure may be eligible for retry.
&lt;/p&gt;

&lt;p&gt;
But retryability is not determined solely by HTTP status.
&lt;/p&gt;

&lt;p&gt;
In NERV Exception, retryability comes from the selected
error definition.
&lt;/p&gt;

&lt;p&gt;
For example, the native INTERNAL_SERVER_ERROR definition
is non-retryable, while TOO_MANY_REQUESTS and
OPTIMISTIC_LOCK_CONFLICT are retryable.
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;
A retryable error is a signal for retry policy,
not a guarantee that a retry will occur.
&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;
The caller must still consider idempotency,
retry limits, backoff, and operation safety.
&lt;/p&gt;

&lt;h3&gt;Tracing Information&lt;/h3&gt;

&lt;p&gt;
The response includes:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;traceId&quot;: null,
  &quot;spanId&quot;: null
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
When Micrometer tracing is available and an active
trace context exists, NERV Exception can obtain
the corresponding trace and span identifiers.
&lt;/p&gt;

&lt;p&gt;
Otherwise, those values may be null.
&lt;/p&gt;

&lt;p&gt;
NERV Exception reads the existing tracing context.
It does not automatically create a new tracing span
for every exception.
&lt;/p&gt;

&lt;h3&gt;Error Origin&lt;/h3&gt;

&lt;p&gt;
The &lt;code&gt;origin&lt;/code&gt; object identifies the service
associated with the failure.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;origin&quot;: {
    &quot;service&quot;: &quot;customer-service&quot;,
    &quot;instance&quot;: &quot;customer-service-01&quot;,
    &quot;version&quot;: &quot;1.0.0&quot;,
    &quot;environment&quot;: &quot;production&quot;
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This is an illustrative origin object.
&lt;/p&gt;

&lt;p&gt;
In Spring Boot, NERV Exception can resolve origin information
from application configuration and runtime information.
&lt;/p&gt;

&lt;p&gt;
When an exception already contains an explicit origin,
that origin takes precedence.
&lt;/p&gt;

&lt;p&gt;
This is useful when a failure originates in a downstream
service and is later exposed by another application.
&lt;/p&gt;

&lt;p&gt;
However, origin is not a complete service-hop history.
&lt;/p&gt;

&lt;p&gt;
For full distributed request tracing, applications should
use an appropriate tracing system.
&lt;/p&gt;

&lt;h3&gt;Structured Details&lt;/h3&gt;

&lt;p&gt;
The &lt;code&gt;details&lt;/code&gt; field contains structured
additional information.
&lt;/p&gt;

&lt;p&gt;
For example:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;details&quot;: {
    &quot;requestedQuantity&quot;: 150,
    &quot;maximumQuantity&quot;: 100
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This allows API consumers to process useful context
without parsing exception messages.
&lt;/p&gt;

&lt;p&gt;
NERV Exception uses &lt;code&gt;details&lt;/code&gt;,
not a top-level field named &lt;code&gt;metadata&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
Applications should carefully control what information
is included.
&lt;/p&gt;

&lt;p&gt;
Structured details should not expose credentials,
personal information, or internal implementation details
that are inappropriate for the API consumer.
&lt;/p&gt;

&lt;h2&gt;3. HTTP Status Codes Are Necessary but Not Sufficient&lt;/h2&gt;

&lt;p&gt;
HTTP status codes describe the outcome of an HTTP request
at the protocol level.
&lt;/p&gt;

&lt;p&gt;
For example:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;400 — Bad Request&lt;/li&gt;
  &lt;li&gt;401 — Unauthorized&lt;/li&gt;
  &lt;li&gt;403 — Forbidden&lt;/li&gt;
  &lt;li&gt;404 — Not Found&lt;/li&gt;
  &lt;li&gt;409 — Conflict&lt;/li&gt;
  &lt;li&gt;429 — Too Many Requests&lt;/li&gt;
  &lt;li&gt;500 — Internal Server Error&lt;/li&gt;
  &lt;li&gt;503 — Service Unavailable&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
However, HTTP status codes rarely describe the complete
application-level failure.
&lt;/p&gt;

&lt;p&gt;
Consider two errors:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PAYMENT_ALREADY_PROCESSED
ORDER_ALREADY_CANCELLED&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Both could reasonably map to HTTP 409.
&lt;/p&gt;

&lt;p&gt;
But they represent different business conditions.
&lt;/p&gt;

&lt;p&gt;
A consumer may need to respond differently to each.
&lt;/p&gt;

&lt;p&gt;
This leads to an important distinction:
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;
HTTP status describes the protocol outcome.
Application error codes describe the application failure.
&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;
A consistent error contract preserves both.
&lt;/p&gt;

&lt;h2&gt;4. Consistency Across Microservices&lt;/h2&gt;

&lt;p&gt;
Within a monolithic application, a global exception handler
can provide a consistent error response.
&lt;/p&gt;

&lt;p&gt;
In a distributed architecture, every service may act
as both an API provider and an API consumer.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;API Gateway
    |
    v
Order Service
    |
    +---- Customer Service
    |
    +---- Inventory Service
    |
    +---- Payment Service&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Suppose Payment Service rejects an operation because
the payment has already been processed.
&lt;/p&gt;

&lt;p&gt;
The response travels back through Order Service
and eventually reaches the API gateway.
&lt;/p&gt;

&lt;p&gt;
Without a shared contract, the original application error
may be replaced by a generic HTTP client exception.
&lt;/p&gt;

&lt;p&gt;
That can cause several problems:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Loss of meaningful application error codes&lt;/li&gt;
  &lt;li&gt;Incorrect error classification&lt;/li&gt;
  &lt;li&gt;Incorrect retry decisions&lt;/li&gt;
  &lt;li&gt;Additional service-specific parsing logic&lt;/li&gt;
  &lt;li&gt;Increased coupling between applications&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
A common error contract reduces these inconsistencies.
&lt;/p&gt;

&lt;p&gt;
However, sharing a contract does not mean every service
must share the same business error definitions.
&lt;/p&gt;

&lt;h2&gt;5. Handling Unknown Downstream Error Codes&lt;/h2&gt;

&lt;p&gt;
Consider a downstream service returning the following
NERV-compatible error response:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;code&quot;: &quot;REMOTE_FAILURE&quot;,
  &quot;message&quot;: &quot;Downstream explanation&quot;,
  &quot;status&quot;: 422,
  &quot;retryable&quot;: false,
  &quot;category&quot;: &quot;REMOTE_CATEGORY&quot;,
  &quot;origin&quot;: {
    &quot;service&quot;: &quot;remote-service&quot;
  },
  &quot;details&quot;: {
    &quot;reason&quot;: &quot;remote detail&quot;
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Suppose the calling service does not recognize
REMOTE_FAILURE in its local error registry.
&lt;/p&gt;

&lt;p&gt;
Should the original code be discarded?
&lt;/p&gt;

&lt;p&gt;
Should the failure become a generic integration error?
&lt;/p&gt;

&lt;p&gt;
Should the caller assume the operation is retryable?
&lt;/p&gt;

&lt;p&gt;
NERV Exception provides a mechanism for preserving
the semantics of unknown downstream error codes.
&lt;/p&gt;

&lt;p&gt;
Its Feign decoder can create a
&lt;code&gt;RemoteNervErrorCode&lt;/code&gt;
using the information supplied by the downstream response.
&lt;/p&gt;

&lt;p&gt;
For a recognized NERV error envelope, the decoder requires
a nonblank code, a nonnull message, and a body status
between 400 and 599.
&lt;/p&gt;

&lt;p&gt;
When the code is unknown locally, the remote definition
retains the downstream code, message, body status,
retryability, and category.
&lt;/p&gt;

&lt;p&gt;
The resulting downstream exception also carries
supported origin and details information.
&lt;/p&gt;

&lt;p&gt;
This allows services to preserve meaningful failures
without importing every downstream business error catalog.
&lt;/p&gt;

&lt;h3&gt;Known Error Codes Behave Differently&lt;/h3&gt;

&lt;p&gt;
There is an important distinction when the downstream
error code is already registered locally.
&lt;/p&gt;

&lt;p&gt;
In that case, NERV Exception uses the local error definition
as the authority for:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;HTTP status&lt;/li&gt;
  &lt;li&gt;Error category&lt;/li&gt;
  &lt;li&gt;Retryability&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The remote message, origin, and supported details
can still be carried by the downstream exception.
&lt;/p&gt;

&lt;p&gt;
This means propagation is not always a byte-for-byte
preservation of the original response.
&lt;/p&gt;

&lt;p&gt;
For example, the receiving service may generate
a new timestamp, path, and tracing information
when rendering its own HTTP response.
&lt;/p&gt;

&lt;p&gt;
The original downstream traceId, spanId, path, and timestamp
are not retained by the downstream exception.
&lt;/p&gt;

&lt;p&gt;
This distinction is intentional to understand
when designing service boundaries.
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;
A shared error contract supports controlled propagation,
not necessarily lossless forwarding.
&lt;/strong&gt;
&lt;/p&gt;

&lt;h3&gt;What About Invalid Downstream Responses?&lt;/h3&gt;

&lt;p&gt;
Not every downstream response follows the NERV contract.
&lt;/p&gt;

&lt;p&gt;
A service may return malformed JSON, an HTML error page,
or an unrelated error structure.
&lt;/p&gt;

&lt;p&gt;
When NERV Exception cannot recognize the response
as a valid NERV error envelope, its Feign decoder
delegates to the configured fallback decoder.
&lt;/p&gt;

&lt;p&gt;
The default fallback is Feign&#39;s standard error decoder.
&lt;/p&gt;

&lt;p&gt;
Connection failures that occur before an HTTP response
is received are outside the response decoder&#39;s responsibility.
&lt;/p&gt;

&lt;p&gt;
These failures must be handled through the HTTP client&#39;s
transport and resilience configuration.
&lt;/p&gt;

&lt;h2&gt;6. Retryability Is Not the Same as Retry Execution&lt;/h2&gt;

&lt;p&gt;
Retryability is often misunderstood in distributed systems.
&lt;/p&gt;

&lt;p&gt;
A response containing:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;retryable&quot;: true
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
does not mean the operation will automatically be retried.
&lt;/p&gt;

&lt;p&gt;
In NERV Exception, the Feign decoder can wrap a retryable
downstream error in a Feign &lt;code&gt;RetryableException&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
The underlying &lt;code&gt;NervDownstreamException&lt;/code&gt;
is retained as the cause.
&lt;/p&gt;

&lt;p&gt;
However, whether a retry actually occurs depends
on the configured Feign retry policy.
&lt;/p&gt;

&lt;p&gt;
NERV Exception does not install a retry policy
through this decoder.
&lt;/p&gt;

&lt;p&gt;
There is another important limitation.
&lt;/p&gt;

&lt;p&gt;
If the retryable wrapper reaches the default generic
Spring Web exception handler, it may be mapped
to an internal server error rather than being
unwrapped into the original downstream NERV error.
&lt;/p&gt;

&lt;p&gt;
Therefore, applications should not assume that retryable
downstream errors will always be transparently propagated
after retries are exhausted.
&lt;/p&gt;

&lt;p&gt;
Reliable retry handling requires coordination between:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Error classification&lt;/li&gt;
  &lt;li&gt;HTTP client retry configuration&lt;/li&gt;
  &lt;li&gt;Operation idempotency&lt;/li&gt;
  &lt;li&gt;Backoff and retry limits&lt;/li&gt;
  &lt;li&gt;Exception handling after retry exhaustion&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The error contract provides information.
The application architecture determines how to use it.
&lt;/p&gt;

&lt;h2&gt;7. Validation Errors Need Structured Information&lt;/h2&gt;

&lt;p&gt;
Validation failures are another reason to use
a consistent error contract.
&lt;/p&gt;

&lt;p&gt;
Consider a request containing invalid input.
&lt;/p&gt;

&lt;p&gt;
Returning only:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;message&quot;: &quot;Validation failed&quot;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
forces the consumer to guess which fields are invalid.
&lt;/p&gt;

&lt;p&gt;
NERV Exception can expose field validation errors
through the &lt;code&gt;details.errors&lt;/code&gt; structure.
&lt;/p&gt;

&lt;p&gt;
For example:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  &quot;code&quot;: &quot;VALIDATION_ERROR&quot;,
  &quot;message&quot;: &quot;Validation error&quot;,
  &quot;status&quot;: 400,
  &quot;retryable&quot;: false,
  &quot;category&quot;: &quot;VALIDATION&quot;,
  &quot;details&quot;: {
    &quot;errors&quot;: {
      &quot;name&quot;: &quot;Name is required&quot;
    }
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This is an abbreviated example of the supported
validation response structure.
&lt;/p&gt;

&lt;p&gt;
The complete response can also include tracing,
path, timestamp, and origin information.
&lt;/p&gt;

&lt;p&gt;
The field errors are represented as an object mapping
field names to messages, not as an array.
&lt;/p&gt;

&lt;p&gt;
The mapper retains the first message for each field key.
&lt;/p&gt;

&lt;p&gt;
This allows frontend applications to associate validation
messages with specific form fields.
&lt;/p&gt;

&lt;p&gt;
The availability of details depends on the configured
exception-handling settings.
&lt;/p&gt;

&lt;h2&gt;8. Designing Error Contracts for Evolution&lt;/h2&gt;

&lt;p&gt;
An error contract is part of an application&#39;s public interface.
&lt;/p&gt;

&lt;p&gt;
Once clients depend on specific error codes and semantics,
changes must be introduced carefully.
&lt;/p&gt;

&lt;h3&gt;Keep Error Codes Stable&lt;/h3&gt;

&lt;p&gt;
Avoid renaming published error codes without a
compatibility strategy.
&lt;/p&gt;

&lt;h3&gt;Separate Codes from Messages&lt;/h3&gt;

&lt;p&gt;
Messages may change for clarity or localization.
Application behavior should depend on stable error codes.
&lt;/p&gt;

&lt;h3&gt;Define Unknown Error Behavior&lt;/h3&gt;

&lt;p&gt;
Clients should be prepared to encounter error codes
introduced after they were deployed.
&lt;/p&gt;

&lt;p&gt;
An unknown error code should not automatically cause
the entire error response to become unusable.
&lt;/p&gt;

&lt;h3&gt;Use Additive Changes Carefully&lt;/h3&gt;

&lt;p&gt;
New optional fields can make an error contract more useful,
but consumers must be configured to tolerate them.
&lt;/p&gt;

&lt;p&gt;
NERV Exception does not automatically enforce
a complete error schema versioning strategy.
&lt;/p&gt;

&lt;p&gt;
Compatibility policies remain an architectural responsibility.
&lt;/p&gt;

&lt;h3&gt;Preserve Semantic Meaning&lt;/h3&gt;

&lt;p&gt;
Changing an error from non-retryable to retryable
can affect application behavior.
&lt;/p&gt;

&lt;p&gt;
Changing its HTTP status or category can also affect
clients and operational systems.
&lt;/p&gt;

&lt;p&gt;
These changes should be treated as behavioral
API contract changes.
&lt;/p&gt;

&lt;h2&gt;9. Implementing the Contract with NERV Exception&lt;/h2&gt;

&lt;p&gt;
The principles described in this article can be implemented
using Spring&#39;s exception-handling infrastructure.
&lt;/p&gt;

&lt;p&gt;
However, maintaining the same infrastructure independently
across multiple services introduces duplicated code
and inconsistent behavior.
&lt;/p&gt;

&lt;p&gt;
NERV Exception provides reusable components for
standardizing error handling in Java and Spring Boot.
&lt;/p&gt;

&lt;p&gt;
Its modules include:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;nerv-exception-api&lt;/li&gt;
  &lt;li&gt;nerv-exception-core&lt;/li&gt;
  &lt;li&gt;nerv-exception-spring-web&lt;/li&gt;
  &lt;li&gt;nerv-exception-spring-feign&lt;/li&gt;
  &lt;li&gt;nerv-exception-spring-boot-starter&lt;/li&gt;
  &lt;li&gt;nerv-exception-jpa&lt;/li&gt;
  &lt;li&gt;nerv-exception-event&lt;/li&gt;
  &lt;li&gt;nerv-exception-spring-kafka&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The library separates shared error definitions,
exception handling, HTTP integration, and
transport-specific functionality.
&lt;/p&gt;

&lt;p&gt;
Applications can define their own error codes
through the &lt;code&gt;NervErrorCode&lt;/code&gt; interface.
&lt;/p&gt;

&lt;p&gt;
The interface exposes the application error code,
message, and HTTP status, with optional definitions
for additional semantics.
&lt;/p&gt;

&lt;p&gt;
The default category is GENERAL,
and the default retryability is false.
&lt;/p&gt;

&lt;p&gt;
Applications may implement these definitions using
Java enums, although enums are not mandatory.
&lt;/p&gt;

&lt;p&gt;
The library also provides error code registries
for resolving known codes.
&lt;/p&gt;

&lt;p&gt;
A composite registry can combine multiple registries,
with resolution using the first matching definition.
&lt;/p&gt;

&lt;p&gt;
This is useful for applications that maintain
multiple groups of error definitions.
&lt;/p&gt;

&lt;p&gt;
However, duplicate detection is not globally enforced
across all composite registry delegates.
&lt;/p&gt;

&lt;p&gt;
Applications should establish clear ownership
and naming conventions for their error codes.
&lt;/p&gt;

&lt;h3&gt;Spring Boot Integration&lt;/h3&gt;

&lt;p&gt;
The Spring Boot starter provides auto-configuration
for supported exception-handling components.
&lt;/p&gt;

&lt;p&gt;
Spring Web integration supports common MVC failures,
including validation errors, unreadable request bodies,
missing parameters, and unexpected exceptions.
&lt;/p&gt;

&lt;p&gt;
The implementation also supports application-defined
NERV exceptions.
&lt;/p&gt;

&lt;p&gt;
However, not every exception occurring in a Spring Boot
application passes through MVC exception advice.
&lt;/p&gt;

&lt;p&gt;
For example, authentication failures occurring inside
Spring Security filters require appropriate handling
at the security boundary.
&lt;/p&gt;

&lt;p&gt;
Applications should not assume that every authentication
or authorization failure automatically receives
the same NERV error response.
&lt;/p&gt;

&lt;h3&gt;Production Security Configuration&lt;/h3&gt;

&lt;p&gt;
Error contracts should provide useful information
without exposing internal implementation details.
&lt;/p&gt;

&lt;p&gt;
This is particularly important for unexpected exceptions.
&lt;/p&gt;

&lt;p&gt;
In the reviewed NERV Exception 1.4.0 implementation,
the Spring Boot starter property defaults enable
internal message exposure and exception causes.
&lt;/p&gt;

&lt;p&gt;
The standalone default settings object uses
more restrictive values.
&lt;/p&gt;

&lt;p&gt;
For public APIs, explicitly configure the application
to avoid exposing internal exception messages and causes.
&lt;/p&gt;

&lt;p&gt;
Stack traces should also remain disabled in public responses.
&lt;/p&gt;

&lt;p&gt;
The exact configuration property names should be taken
from the version of NERV Exception used by the application.
&lt;/p&gt;

&lt;p&gt;
Also remember that disabling general details alone
does not necessarily disable separately configured
cause or stack-trace exposure.
&lt;/p&gt;

&lt;p&gt;
A consistent error contract should make failures
easier to understand without making the application
easier to exploit.
&lt;/p&gt;

&lt;h2&gt;10. A Shared Contract Is Not a Shared Business Model&lt;/h2&gt;

&lt;p&gt;
There is an important architectural distinction
between sharing an error contract and sharing
business error definitions.
&lt;/p&gt;

&lt;p&gt;
Consider three independent services.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Customer Service
  CUSTOMER_NOT_FOUND
  CUSTOMER_DISABLED

Payment Service
  PAYMENT_ALREADY_PROCESSED
  PAYMENT_DECLINED

Inventory Service
  INVENTORY_NOT_AVAILABLE
  INVENTORY_RESERVATION_EXPIRED&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Each service owns its business error codes.
&lt;/p&gt;

&lt;p&gt;
However, all three can expose the same structural contract.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Application Error
    |
    +-- Code
    |
    +-- Message
    |
    +-- Status
    |
    +-- Category
    |
    +-- Retryability
    |
    +-- Trace Information
    |
    +-- Origin
    |
    +-- Details&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
This provides consistency without requiring
every service to import every other service&#39;s
business error definitions.
&lt;/p&gt;

&lt;p&gt;
It also allows services to evolve independently
while preserving a common language for failures.
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;
Share the structure of errors.
Keep ownership of business errors within
the services that define them.
&lt;/strong&gt;
&lt;/p&gt;

&lt;h2&gt;11. Common Mistakes When Designing Error Contracts&lt;/h2&gt;

&lt;h3&gt;Returning Every Failure as HTTP 500&lt;/h3&gt;

&lt;p&gt;
A validation error or business conflict should not
automatically become an internal server error.
&lt;/p&gt;

&lt;h3&gt;Using Exception Messages as Error Identifiers&lt;/h3&gt;

&lt;p&gt;
Messages can change.
Stable error codes are more appropriate for
machine-readable application behavior.
&lt;/p&gt;

&lt;h3&gt;Assuming Error Categories Determine HTTP Status&lt;/h3&gt;

&lt;p&gt;
Category, status, and retryability are separate concerns.
&lt;/p&gt;

&lt;p&gt;
Applications should not assume that a particular
category always maps to one HTTP status.
&lt;/p&gt;

&lt;h3&gt;Assuming Every Integration Error Is Retryable&lt;/h3&gt;

&lt;p&gt;
A downstream service may reject a request
because of a permanent business condition.
&lt;/p&gt;

&lt;p&gt;
Retrying without understanding the failure
can create unnecessary load and unexpected behavior.
&lt;/p&gt;

&lt;h3&gt;Assuming Retryability Guarantees Retries&lt;/h3&gt;

&lt;p&gt;
Retryability describes an error property.
Actual retries depend on the client and its configured policy.
&lt;/p&gt;

&lt;h3&gt;Discarding Unknown Downstream Codes&lt;/h3&gt;

&lt;p&gt;
A service should not need to recognize every downstream
business error to preserve a valid error contract.
&lt;/p&gt;

&lt;h3&gt;Exposing Internal Exception Details&lt;/h3&gt;

&lt;p&gt;
Structured error responses should not expose
credentials, stack traces, or sensitive implementation
details to unauthorized consumers.
&lt;/p&gt;

&lt;h3&gt;Assuming Error Propagation Is Lossless&lt;/h3&gt;

&lt;p&gt;
A receiving service may resolve an error using
a local definition and generate its own request
path, timestamp, and tracing information.
&lt;/p&gt;

&lt;p&gt;
Applications should understand these boundaries
rather than assume every downstream field
is preserved unchanged.
&lt;/p&gt;

&lt;h2&gt;12. Final Thoughts&lt;/h2&gt;

&lt;p&gt;
Consistent exception handling is not simply about
returning the same JSON structure from every controller.
&lt;/p&gt;

&lt;p&gt;
It is about establishing a reliable language
for communicating failures between systems.
&lt;/p&gt;

&lt;p&gt;
A well-designed error contract separates
several responsibilities:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;HTTP status communicates the protocol outcome.&lt;/li&gt;
  &lt;li&gt;Error codes identify application failures.&lt;/li&gt;
  &lt;li&gt;Messages explain failures to humans.&lt;/li&gt;
  &lt;li&gt;Categories classify the nature of failures.&lt;/li&gt;
  &lt;li&gt;Retryability informs recovery decisions.&lt;/li&gt;
  &lt;li&gt;Tracing connects failures to request execution.&lt;/li&gt;
  &lt;li&gt;Origin identifies the service associated with the failure.&lt;/li&gt;
  &lt;li&gt;Details provide structured additional context.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
These responsibilities should remain distinct,
even when they are represented in a single response.
&lt;/p&gt;

&lt;p&gt;
NERV Exception provides one implementation of this approach,
with reusable components for Spring Boot exception handling,
error code resolution, and controlled downstream propagation.
&lt;/p&gt;

&lt;p&gt;
The broader architectural lesson is independent
of the library itself.
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;
A good error contract does not merely report
that something failed. It helps the receiving system
understand the failure and make an informed decision
about what to do next.
&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;
That is the foundation of reliable error handling
in distributed applications.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h3&gt;About NERV Exception&lt;/h3&gt;

&lt;p&gt;
NERV Exception is part of the NERV ecosystem
(Next-Generation Engineering for Runtime Velocity),
a collection of reusable Java and Spring Boot libraries
focused on production-oriented application architecture.
&lt;/p&gt;

&lt;p&gt;
Explore the open-source projects:
&lt;a href=&quot;https://github.com/czetsuyatech&quot;
   target=&quot;_blank&quot;
   rel=&quot;noopener noreferrer&quot;&gt;
  CzetsuyaTech on GitHub
&lt;/a&gt;.
&lt;/p&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/07/stop-copying-exception-handlers-between-spring-boot-projects.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Stop Copying Exception Handlers Between Spring Boot Projects
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Exception&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/7348948419470692653/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/10/designing-consistent-error-contract-spring-boot.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/7348948419470692653'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/7348948419470692653'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/10/designing-consistent-error-contract-spring-boot.html' title='Designing a Consistent Error Contract for Spring Boot APIs'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGeZA1kO17WM1a8Eo6cU1N5p8x09uNWfa65JI893aAcksxo3dmwxmUgzHXjP3WxfMPBpCiis8kgUwG6xb40YdJMJqOp_jjgg9xzjkS0JUBh3cGANAqe_UMyo3qaVVEeUgK2iMl2TP5coUZ35ZA5Rk2Z84XptQWIGiSajCLFHfP-wsHhL0lcVoMZFIsBJyq/s72-c/spring-boot-consistent-error-contract.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-4758509153186473578</id><published>2026-10-17T14:24:31.641+08:00</published><updated>2026-10-17T14:32:24.452+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithmic Trading"/><category scheme="http://www.blogger.com/atom/ns#" term="Deterministic Systems"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Trade"/><category scheme="http://www.blogger.com/atom/ns#" term="Software Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><category scheme="http://www.blogger.com/atom/ns#" term="Trading Engine"/><title type='text'>Deterministic Trading: Why the Same Market Data Must Produce the Same Decision</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjk4LIlai1ISxhP20X1oAFlVGpTm-nGoFIksYltMy7mU6VQAYruaGazJh4IIO1zSG1AfOfbZnZ5K0RUWwsF6PD-c0vQyb9afyk8op-Q8f8tTrvZJGaPP-N_REcbxvnAOYGcSHHr-W7001irvLG0e1m77IE88ht2VQKDa9rzMmroMaxbNz29oteDclxaedDS/s1600/nerv-trade-deterministic-trading-engine.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;Two trading engine runs processing identical market data and producing identical decisions, illustrating deterministic trading&quot; border=&quot;0&quot; data-original-height=&quot;941&quot; data-original-width=&quot;1672&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjk4LIlai1ISxhP20X1oAFlVGpTm-nGoFIksYltMy7mU6VQAYruaGazJh4IIO1zSG1AfOfbZnZ5K0RUWwsF6PD-c0vQyb9afyk8op-Q8f8tTrvZJGaPP-N_REcbxvnAOYGcSHHr-W7001irvLG0e1m77IE88ht2VQKDa9rzMmroMaxbNz29oteDclxaedDS/s1600/nerv-trade-deterministic-trading-engine.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;article&gt;

  &lt;p&gt;
    Imagine running a trading strategy against a month of historical market data.
  &lt;/p&gt;

  &lt;p&gt;
    The first run produces 42 trading decisions.
  &lt;/p&gt;

  &lt;p&gt;
    You run it again with exactly the same data and configuration.
  &lt;/p&gt;

  &lt;p&gt;
    This time, it produces 43.
  &lt;/p&gt;

  &lt;p&gt;
    Nothing changed. At least, nothing you intentionally changed.
  &lt;/p&gt;

  &lt;p&gt;
    Which result is correct?
  &lt;/p&gt;

  &lt;p&gt;
    More importantly, how can you trust a trading engine that cannot reproduce its own decisions?
  &lt;/p&gt;

  &lt;p&gt;
    This is one of the fundamental questions we had to address while developing
    &lt;strong&gt;NERV Trade&lt;/strong&gt;, my Java-based trading engine.
  &lt;/p&gt;

  &lt;p&gt;
    In the
    &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Trade&quot;
       target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;
      NERV Trade engineering series
    &lt;/a&gt;,
    we&#39;ve already explored why a trading bot is fundamentally different from a trading engine.
  &lt;/p&gt;

  &lt;p&gt;
    A trading bot can generate BUY and SELL signals.
    A trading engine must also manage their consequences.
  &lt;/p&gt;

  &lt;p&gt;
    But before building a reliable execution lifecycle, we needed to answer
    a more fundamental question:
  &lt;/p&gt;

  &lt;blockquote&gt;
    &lt;p&gt;
      Given the same market observations, initial state, and configuration,
      can the engine produce exactly the same decisions?
    &lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;
    That question led us to one of the earliest architectural foundations
    of NERV Trade: &lt;strong&gt;determinism&lt;/strong&gt;.
  &lt;/p&gt;

  &lt;h2&gt;1. The Problem With a Strategy That Changes Its Mind&lt;/h2&gt;

  &lt;p&gt;
    Most trading strategies are built around indicators.
  &lt;/p&gt;

  &lt;p&gt;
    Moving averages, RSI, MACD, volatility, and other measurements help
    determine whether a particular market condition is favorable.
  &lt;/p&gt;

  &lt;p&gt;
    For example, a simple strategy might generate a BUY signal when
    a fast moving average crosses above a slower one.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;if (fastMovingAverage.compareTo(slowMovingAverage) &amp;gt; 0) {
    return Signal.BUY;
}

return Signal.HOLD;&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The logic appears deterministic.
  &lt;/p&gt;

  &lt;p&gt;
    Given the same two values, the result will always be the same.
  &lt;/p&gt;

  &lt;p&gt;
    But real trading strategies rarely operate on two isolated numbers.
  &lt;/p&gt;

  &lt;p&gt;
    They depend on a sequence of market observations, calculations,
    time boundaries, configuration, and sometimes previously accumulated state.
  &lt;/p&gt;

  &lt;p&gt;
    Consider the following inputs:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code&gt;Market: BTCUSDT
Timeframe: M5

Candles:
10:00
10:05
10:10
10:15
10:20&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The strategy evaluates these candles and produces a BUY signal.
  &lt;/p&gt;

  &lt;p&gt;
    Now imagine replaying the same data, but the application evaluates
    the strategy while the final candle is still being constructed.
  &lt;/p&gt;

  &lt;p&gt;
    The calculated indicator values may differ.
  &lt;/p&gt;

  &lt;p&gt;
    The resulting decision may change.
  &lt;/p&gt;

  &lt;p&gt;
    The problem isn&#39;t necessarily the indicator formula.
  &lt;/p&gt;

  &lt;p&gt;
    The problem is that the strategy did not evaluate the same
    &lt;em&gt;information state&lt;/em&gt;.
  &lt;/p&gt;

  &lt;h2&gt;2. Determinism Is More Than Using the Same Market Data&lt;/h2&gt;

  &lt;p&gt;
    A common definition of deterministic software is that identical inputs
    produce identical outputs.
  &lt;/p&gt;

  &lt;p&gt;
    That definition is useful, but it raises an important question:
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;What exactly counts as an input?&lt;/strong&gt;
  &lt;/p&gt;

  &lt;p&gt;
    For a trading strategy, the answer extends beyond historical prices.
  &lt;/p&gt;

  &lt;p&gt;
    A reproducible trading decision may depend on:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;The exact market-data snapshot.&lt;/li&gt;
    &lt;li&gt;The timeframe and candle boundaries.&lt;/li&gt;
    &lt;li&gt;The decision timestamp or logical evaluation time.&lt;/li&gt;
    &lt;li&gt;The strategy configuration.&lt;/li&gt;
    &lt;li&gt;The initial strategy state.&lt;/li&gt;
    &lt;li&gt;The ordering of observations.&lt;/li&gt;
    &lt;li&gt;The numerical calculation rules.&lt;/li&gt;
    &lt;li&gt;The version of the strategy implementation.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    If any of these change, two evaluations may legitimately produce
    different results.
  &lt;/p&gt;

  &lt;p&gt;
    Therefore, a stronger definition is:
  &lt;/p&gt;

  &lt;blockquote&gt;
    &lt;p&gt;
      A deterministic trading decision is reproducible when the same
      complete input snapshot, initial state, and evaluation rules
      produce the same output.
    &lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;
    This distinction matters because two applications can process
    the same historical price series and still reach different decisions
    if they disagree about which observations were available at a
    particular point in time.
  &lt;/p&gt;

  &lt;h2&gt;3. Time Is an Input, Not a Hidden Dependency&lt;/h2&gt;

  &lt;p&gt;
    One of the easiest ways to introduce nondeterminism is to allow
    trading logic to depend directly on the system clock.
  &lt;/p&gt;

  &lt;p&gt;
    Consider this simplified Java example:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public Signal evaluate(MarketSnapshot snapshot) {

    Instant now = Instant.now();

    if (isTradingWindowOpen(now)) {
        return analyze(snapshot);
    }

    return Signal.HOLD;
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The result now depends on when the method executes.
  &lt;/p&gt;

  &lt;p&gt;
    Run it at 10:00 and it may return BUY.
  &lt;/p&gt;

  &lt;p&gt;
    Run it at 18:00 and it may return HOLD.
  &lt;/p&gt;

  &lt;p&gt;
    The market data hasn&#39;t changed.
  &lt;/p&gt;

  &lt;p&gt;
    But a hidden input has.
  &lt;/p&gt;

  &lt;p&gt;
    For deterministic evaluation, the relevant time should be explicit.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public Signal evaluate(
        MarketSnapshot snapshot,
        Instant evaluationTime) {

    if (isTradingWindowOpen(evaluationTime)) {
        return analyze(snapshot);
    }

    return Signal.HOLD;
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Now the caller controls the evaluation time.
  &lt;/p&gt;

  &lt;p&gt;
    A historical replay can evaluate the strategy using the time associated
    with the historical decision rather than the current wall clock.
  &lt;/p&gt;

  &lt;p&gt;
    Tests can use a fixed timestamp.
  &lt;/p&gt;

  &lt;p&gt;
    Production processing can use an explicitly established
    decision boundary.
  &lt;/p&gt;

  &lt;p&gt;
    This doesn&#39;t mean the entire application must avoid
    &lt;code&gt;Instant.now()&lt;/code&gt;.
  &lt;/p&gt;

  &lt;p&gt;
    Operational timestamps, logging, and monitoring still need the current time.
  &lt;/p&gt;

  &lt;p&gt;
    The important rule is that wall-clock time should not silently influence
    a decision that is supposed to be reproducible.
  &lt;/p&gt;

  &lt;h2&gt;4. A Candle Is Not Complete Until It Is Complete&lt;/h2&gt;

  &lt;p&gt;
    Trading systems often organize market data into candles.
  &lt;/p&gt;

  &lt;p&gt;
    A five-minute candle might represent the interval from
    10:00 to 10:05.
  &lt;/p&gt;

  &lt;p&gt;
    During that interval, its high, low, close, and volume can continue
    changing as new trades arrive.
  &lt;/p&gt;

  &lt;p&gt;
    Consider a candle currently forming:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code&gt;Timeframe: M5
Interval: 10:00 - 10:05

At 10:02:
Open: 100
High: 103
Low:  99
Close: 102

At 10:04:
Open: 100
High: 105
Low:  99
Close: 104

At close:
Open: 100
High: 105
Low:  98
Close:  99&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The final candle looks very different from its intermediate state.
  &lt;/p&gt;

  &lt;p&gt;
    If the strategy evaluates the candle at 10:02, it sees one market condition.
  &lt;/p&gt;

  &lt;p&gt;
    If it evaluates the completed candle, it sees another.
  &lt;/p&gt;

  &lt;p&gt;
    Both observations can be valid for different strategy designs.
  &lt;/p&gt;

  &lt;p&gt;
    But they cannot be treated as interchangeable.
  &lt;/p&gt;

  &lt;p&gt;
    For strategies designed around closed candles, the rule must be explicit:
  &lt;/p&gt;

  &lt;blockquote&gt;
    &lt;p&gt;
      Only candles confirmed as closed may participate in the
      decision snapshot.
    &lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;
    A strategy intentionally using intrabar information requires a different
    contract: it must preserve the actual observations available during
    the candle&#39;s formation.
  &lt;/p&gt;

  &lt;p&gt;
    Replaying only the final candle cannot reconstruct every intrabar decision.
  &lt;/p&gt;

  &lt;p&gt;
    This is an important distinction.
  &lt;/p&gt;

  &lt;p&gt;
    Determinism does not require every trading strategy to wait for
    candle closure.
  &lt;/p&gt;

  &lt;p&gt;
    It requires the strategy&#39;s observation rules to be explicit
    and reproducible.
  &lt;/p&gt;

  &lt;h2&gt;5. Market-Data Ordering Must Be Predictable&lt;/h2&gt;

  &lt;p&gt;
    Another subtle source of inconsistent decisions is observation ordering.
  &lt;/p&gt;

  &lt;p&gt;
    Imagine receiving the following candles:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code&gt;10:00
10:05
10:10
10:15&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The sequence is straightforward.
  &lt;/p&gt;

  &lt;p&gt;
    But live market-data feeds may reconnect, deliver updates late,
    or provide overlapping data during recovery.
  &lt;/p&gt;

  &lt;p&gt;
    An application might encounter:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code&gt;10:00
10:05
10:15
10:10
10:15&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    If calculations blindly depend on arrival order, the result may differ
    from an evaluation performed over correctly ordered historical data.
  &lt;/p&gt;

  &lt;p&gt;
    A reliable market-data boundary needs to establish:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;How candles are identified.&lt;/li&gt;
    &lt;li&gt;How observations are ordered.&lt;/li&gt;
    &lt;li&gt;How duplicate observations are handled.&lt;/li&gt;
    &lt;li&gt;How corrections or revisions are represented.&lt;/li&gt;
    &lt;li&gt;What happens when expected intervals are missing.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    A simplified normalization step might look like this:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;List&amp;lt;Candle&amp;gt; ordered = candles.stream()
        .sorted(Comparator.comparing(Candle::openTime))
        .toList();&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    Sorting is useful, but it is not a complete solution.
  &lt;/p&gt;

  &lt;p&gt;
    If two records represent the same candle interval but contain
    different values, the engine still needs an explicit rule
    for determining which version is authoritative.
  &lt;/p&gt;

  &lt;p&gt;
    Likewise, sorting cannot recover an observation that was never received.
  &lt;/p&gt;

  &lt;p&gt;
    These are data-quality and consistency concerns, not merely
    collection-processing details.
  &lt;/p&gt;

  &lt;h2&gt;6. Mutable State Can Make Identical Data Behave Differently&lt;/h2&gt;

  &lt;p&gt;
    A trading strategy may also maintain state between evaluations.
  &lt;/p&gt;

  &lt;p&gt;
    For example, it might track whether a signal has already been emitted
    for a particular candle.
  &lt;/p&gt;

  &lt;p&gt;
    Or it might remember a previous indicator value to detect a crossover.
  &lt;/p&gt;

  &lt;p&gt;
    Stateful strategies aren&#39;t inherently nondeterministic.
  &lt;/p&gt;

  &lt;p&gt;
    But their initial state and transition rules must be part
    of the reproducibility contract.
  &lt;/p&gt;

  &lt;p&gt;
    Consider this simplified example:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public final class CrossoverStrategy {

    private BigDecimal previousDifference;

    public Signal evaluate(
            BigDecimal fast,
            BigDecimal slow) {

        BigDecimal difference = fast.subtract(slow);

        Signal result = Signal.HOLD;

        if (previousDifference != null
                &amp;amp;&amp;amp; previousDifference.signum() &amp;lt;= 0
                &amp;amp;&amp;amp; difference.signum() &amp;gt; 0) {
            result = Signal.BUY;
        }

        previousDifference = difference;

        return result;
    }
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The strategy&#39;s output depends on its previous evaluation.
  &lt;/p&gt;

  &lt;p&gt;
    If we reuse the same instance without resetting its state,
    a second run may produce different results.
  &lt;/p&gt;

  &lt;p&gt;
    The solution isn&#39;t necessarily to remove state.
  &lt;/p&gt;

  &lt;p&gt;
    Instead, we should make state transitions explicit.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public record StrategyState(
        BigDecimal previousDifference) {
}

public record EvaluationResult(
        Signal signal,
        StrategyState nextState) {
}

public EvaluationResult evaluate(
        MarketSnapshot snapshot,
        StrategyState currentState) {

    // Calculate the decision from the snapshot
    // and the supplied state.

    return new EvaluationResult(
            Signal.HOLD,
            currentState);
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The implementation above illustrates the interface shape rather
    than a complete trading strategy.
  &lt;/p&gt;

  &lt;p&gt;
    The architectural idea is that the next state becomes an explicit
    output of the evaluation.
  &lt;/p&gt;

  &lt;p&gt;
    Given the same snapshot and the same initial state,
    the transition can be reproduced.
  &lt;/p&gt;

  &lt;p&gt;
    This also makes testing easier because the test does not depend
    on whatever happened to a shared strategy instance beforehand.
  &lt;/p&gt;

  &lt;h2&gt;7. Deterministic Calculations Need Numerical Rules&lt;/h2&gt;

  &lt;p&gt;
    Java provides several ways to represent numerical values.
  &lt;/p&gt;

  &lt;p&gt;
    For financial calculations, &lt;code&gt;BigDecimal&lt;/code&gt; is frequently
    useful because it provides explicit decimal arithmetic and rounding rules.
  &lt;/p&gt;

  &lt;p&gt;
    But simply using &lt;code&gt;BigDecimal&lt;/code&gt; does not automatically make
    a calculation correct or reproducible.
  &lt;/p&gt;

  &lt;p&gt;
    Precision and rounding must also be controlled.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;BigDecimal average = total
        .divide(
                BigDecimal.valueOf(count),
                8,
                RoundingMode.HALF_UP);&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The appropriate scale and rounding mode depend on the calculation.
  &lt;/p&gt;

  &lt;p&gt;
    Indicator precision, order quantities, exchange tick sizes,
    and financial accounting may require different policies.
  &lt;/p&gt;

  &lt;p&gt;
    We should not assume that one rounding policy is appropriate
    everywhere.
  &lt;/p&gt;

  &lt;p&gt;
    Deterministic numerical behavior also requires controlling
    calculation order and avoiding unintended differences
    between implementations.
  &lt;/p&gt;

  &lt;p&gt;
    Two mathematically equivalent formulas may produce slightly
    different numerical results depending on their representation
    and rounding steps.
  &lt;/p&gt;

  &lt;p&gt;
    Near a strategy threshold, even a small difference can change
    a decision.
  &lt;/p&gt;

  &lt;p&gt;
    Therefore, numerical conventions are part of the strategy contract.
  &lt;/p&gt;

  &lt;h2&gt;8. Testing Determinism Means Testing Repetition&lt;/h2&gt;

  &lt;p&gt;
    Traditional unit tests often check one input and one expected output.
  &lt;/p&gt;

  &lt;p&gt;
    That&#39;s necessary, but deterministic systems benefit from
    another kind of verification.
  &lt;/p&gt;

  &lt;p&gt;
    Run the same scenario more than once.
  &lt;/p&gt;

  &lt;p&gt;
    Then compare the results.
  &lt;/p&gt;

  &lt;p&gt;
    Conceptually:
  &lt;/p&gt;

  &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Test
void sameInputsProduceSameDecisions() {

    MarketHistory history = fixtureHistory();
    StrategyConfig config = fixtureConfig();

    List&amp;lt;Decision&amp;gt; firstRun =
            replay(history, config);

    List&amp;lt;Decision&amp;gt; secondRun =
            replay(history, config);

    assertEquals(firstRun, secondRun);
}&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    The example assumes that each replay starts from the same
    initial strategy state and uses the same evaluation rules.
  &lt;/p&gt;

  &lt;p&gt;
    Otherwise, comparing the two runs would not be meaningful.
  &lt;/p&gt;

  &lt;p&gt;
    A more comprehensive deterministic test suite should examine:
  &lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;Repeated evaluations using identical input snapshots.&lt;/li&gt;
    &lt;li&gt;Replay from a known initial state.&lt;/li&gt;
    &lt;li&gt;Consistent candle ordering.&lt;/li&gt;
    &lt;li&gt;Duplicate market-data delivery.&lt;/li&gt;
    &lt;li&gt;Missing candle intervals.&lt;/li&gt;
    &lt;li&gt;Boundary timestamps.&lt;/li&gt;
    &lt;li&gt;Partial versus closed candles.&lt;/li&gt;
    &lt;li&gt;Indicator threshold behavior.&lt;/li&gt;
    &lt;li&gt;Different JVM default timezones.&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;
    One important distinction: deterministic analysis does not guarantee
    identical live executions.
  &lt;/p&gt;

  &lt;p&gt;
    A broker may fill the same order differently at different times.
  &lt;/p&gt;

  &lt;p&gt;
    Network conditions, liquidity, fees, and exchange state can change.
  &lt;/p&gt;

  &lt;p&gt;
    The goal is to reproduce the decision-making process under
    controlled inputs—not to pretend that the external market
    is deterministic.
  &lt;/p&gt;

  &lt;h2&gt;9. Why Determinism Matters for Debugging&lt;/h2&gt;

  &lt;p&gt;
    Imagine a strategy unexpectedly generates a BUY signal.
  &lt;/p&gt;

  &lt;p&gt;
    Without reproducibility, debugging becomes guesswork.
  &lt;/p&gt;

  &lt;p&gt;
    You inspect the current market data, but the values have changed.
  &lt;/p&gt;

  &lt;p&gt;
    You rerun the strategy, but the result is different.
  &lt;/p&gt;

  &lt;p&gt;
    You examine the logs, but they don&#39;t contain the exact input
    snapshot used during the decision.
  &lt;/p&gt;

  &lt;p&gt;
    Now you are trying to reconstruct a historical event
    from incomplete evidence.
  &lt;/p&gt;

  &lt;p&gt;
    Determinism makes a different workflow possible.
  &lt;/p&gt;

  &lt;pre&gt;&lt;code&gt;Capture Decision Context
          |
          v
Restore Input Snapshot
          |
          v
Restore Initial State
          |
          v
Run Strategy
          |
          v
Compare Decision&lt;/code&gt;&lt;/pre&gt;

  &lt;p&gt;
    If the output differs, we have evidence of an inconsistency
    in the replay environment, implementation, or captured inputs.
  &lt;/p&gt;

  &lt;p&gt;
    If the output matches, we can investigate the actual decision
    rather than debating whether the software behaved differently.
  &lt;/p&gt;

  &lt;p&gt;
    This is particularly valuable when strategy behavior depends
    on multiple timeframes and several indicators.
  &lt;/p&gt;

  &lt;p&gt;
    Instead of asking why the system produced a decision that
    we cannot reproduce, we can ask why a reproducible decision
    was made.
  &lt;/p&gt;

  &lt;p&gt;
    That&#39;s a much better engineering problem.
  &lt;/p&gt;

  &lt;h2&gt;10. Determinism Also Makes Backtesting More Honest&lt;/h2&gt;

  &lt;p&gt;
    Backtesting is one of the most attractive parts of building
    a trading system.
  &lt;/p&gt;

  &lt;p&gt;
    We can evaluate a strategy against historical data and examine
    how it would have behaved.
  &lt;/p&gt;

  &lt;p&gt;
    But a backtest is only meaningful if it respects the information
    available at each historical decision point.
  &lt;/p&gt;

  &lt;p&gt;
    Consider a strategy evaluating the market at 10:05.
  &lt;/p&gt;

  &lt;p&gt;
    It must not use information that only became available at 10:30.
  &lt;/p&gt;

  &lt;p&gt;
    Otherwise, the strategy is benefiting from future knowledge.
  &lt;/p&gt;

  &lt;p&gt;
    This is commonly known as &lt;strong&gt;look-ahead bias&lt;/strong&gt;.
  &lt;/p&gt;

  &lt;p&gt;
    It can make historical performance appear much better
    than what could have been achieved in live trading.
  &lt;/p&gt;

  &lt;p&gt;
    Determinism and look-ahead prevention are closely related,
    but they are not the same thing.
  &lt;/p&gt;

  &lt;p&gt;
    A backtest can be perfectly deterministic and still contain
    look-ahead bias.
  &lt;/p&gt;

  &lt;p&gt;
    It may consistently reproduce the same incorrect decisions.
  &lt;/p&gt;

  &lt;p&gt;
    Therefore, reproducibility is necessary for trustworthy testing,
    but it is not sufficient.
  &lt;/p&gt;

  &lt;p&gt;
    We must also verify that the strategy&#39;s information boundary
    matches what would actually have been available at the time.
  &lt;/p&gt;

  &lt;p&gt;
    We&#39;ll explore that problem in a dedicated article later
    in the series.
  &lt;/p&gt;

  &lt;h2&gt;11. The Architectural Lesson: Make Decisions Reproducible&lt;/h2&gt;

  &lt;p&gt;
    The deeper lesson from deterministic trading is not limited
    to financial markets.
  &lt;/p&gt;

  &lt;p&gt;
    It applies to any system where decisions must be explainable,
    testable, and recoverable.
  &lt;/p&gt;

  &lt;p&gt;
    Fraud detection.
  &lt;/p&gt;

  &lt;p&gt;
    Pricing engines.
  &lt;/p&gt;

  &lt;p&gt;
    Risk evaluation.
  &lt;/p&gt;

  &lt;p&gt;
    Recommendation systems.
  &lt;/p&gt;

  &lt;p&gt;
    Automated workflows.
  &lt;/p&gt;

  &lt;p&gt;
    In each case, a decision becomes easier to trust when its inputs
    and evaluation rules can be reconstructed.
  &lt;/p&gt;

  &lt;p&gt;
    For NERV Trade, determinism became an important architectural
    foundation because the engine would eventually need to support
    more than simple strategy evaluation.
  &lt;/p&gt;

  &lt;p&gt;
    It would need historical replay, simulation, testing,
    execution accounting, and recovery.
  &lt;/p&gt;

  &lt;p&gt;
    Those capabilities benefit from a decision-making process
    whose behavior is predictable under controlled conditions.
  &lt;/p&gt;

  &lt;blockquote&gt;
    &lt;p&gt;
      Before trusting a trading engine to execute a decision,
      we should be able to explain and reproduce how that
      decision was produced.
    &lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;h2&gt;12. The Next Problem: One Candle Is Never the Whole Story&lt;/h2&gt;

  &lt;p&gt;
    At this point, we have established an important requirement.
  &lt;/p&gt;

  &lt;p&gt;
    Given the same complete input snapshot, initial state,
    and evaluation rules, the strategy should produce
    the same result.
  &lt;/p&gt;

  &lt;p&gt;
    But there is another complication.
  &lt;/p&gt;

  &lt;p&gt;
    Trading decisions rarely depend on a single timeframe.
  &lt;/p&gt;

  &lt;p&gt;
    A five-minute chart might suggest a BUY.
  &lt;/p&gt;

  &lt;p&gt;
    A fifteen-minute chart might indicate consolidation.
  &lt;/p&gt;

  &lt;p&gt;
    The hourly trend might still be bearish.
  &lt;/p&gt;

  &lt;p&gt;
    And the four-hour chart might tell an entirely different story.
  &lt;/p&gt;

  &lt;p&gt;
    How do we combine those observations without accidentally
    mixing information from different points in time?
  &lt;/p&gt;

  &lt;p&gt;
    How do we ensure that higher-timeframe candles were actually
    available when the lower-timeframe decision was made?
  &lt;/p&gt;

  &lt;p&gt;
    And how do we preserve deterministic behavior when several
    timelines must agree?
  &lt;/p&gt;

  &lt;p&gt;
    Those questions led to the next major component of NERV Trade:
    &lt;strong&gt;multi-timeframe analysis&lt;/strong&gt;.
  &lt;/p&gt;

  &lt;p&gt;
    That&#39;s where we&#39;ll continue the story.
  &lt;/p&gt;

  &lt;hr /&gt;

  &lt;h2&gt;Continue the NERV Trade Engineering Series&lt;/h2&gt;

  &lt;p&gt;
    This is &lt;strong&gt;Article #3&lt;/strong&gt; in the NERV Trade engineering series,
    documenting the architectural decisions and engineering challenges
    involved in building a Java-based trading engine.
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;Previous:&lt;/strong&gt;
    &lt;em&gt;A Trading Bot Is Easy. A Trading Engine Is Not.&lt;/em&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;Next:&lt;/strong&gt;
    &lt;em&gt;One Candle Is Never the Whole Story: Building Multi-Timeframe Analysis.&lt;/em&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;strong&gt;
      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Trade&quot;&gt;
        Explore the NERV Trade article series
      &lt;/a&gt;
    &lt;/strong&gt;
  &lt;/p&gt;

  &lt;h2&gt;About NERV Trade&lt;/h2&gt;

  &lt;p&gt;
    &lt;strong&gt;NERV Trade&lt;/strong&gt; is part of
    &lt;strong&gt;NERV — Next-Generation Engineering for Runtime Velocity&lt;/strong&gt;,
    an open-source engineering initiative focused on Java and Spring-based systems.
  &lt;/p&gt;

  &lt;p&gt;
    The project explores deterministic market analysis,
    multi-timeframe strategies, trade lifecycle management,
    execution accounting, durable persistence, broker integration,
    and operational safety.
  &lt;/p&gt;

  &lt;p&gt;
    Follow the project and other NERV libraries on
    &lt;a href=&quot;https://github.com/czetsuyatech&quot;
       target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;
      GitHub
    &lt;/a&gt;.
  &lt;/p&gt;

  &lt;p&gt;
    &lt;em&gt;
      This article discusses software engineering and trading infrastructure.
      It is not financial advice.
    &lt;/em&gt;
  &lt;/p&gt;

&lt;/article&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/10/a-trading-bot-is-easy-trading-engine-is-not.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        A Trading Bot Is Easy. A Trading Engine Is Not
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Trade&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/4758509153186473578/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/10/deterministic-trading-java-market-data-decisions.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/4758509153186473578'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/4758509153186473578'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/10/deterministic-trading-java-market-data-decisions.html' title='Deterministic Trading: Why the Same Market Data Must Produce the Same Decision'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjk4LIlai1ISxhP20X1oAFlVGpTm-nGoFIksYltMy7mU6VQAYruaGazJh4IIO1zSG1AfOfbZnZ5K0RUWwsF6PD-c0vQyb9afyk8op-Q8f8tTrvZJGaPP-N_REcbxvnAOYGcSHHr-W7001irvLG0e1m77IE88ht2VQKDa9rzMmroMaxbNz29oteDclxaedDS/s72-c/nerv-trade-deterministic-trading-engine.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-7769165569406961922</id><published>2026-10-07T20:02:07.699+08:00</published><updated>2026-10-17T11:17:45.323+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Distributed Systems"/><category scheme="http://www.blogger.com/atom/ns#" term="Event-Driven Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="MySQL"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Event"/><category scheme="http://www.blogger.com/atom/ns#" term="PostgreSQL"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><category scheme="http://www.blogger.com/atom/ns#" term="Transactional Outbox"/><title type='text'>Stop Reaching for Redis: Scaling Database Workers with SKIP LOCKED</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGlqSeqjRNqd2MHb3bE5rOVqGehDk5TqZIZb2E6-q0CFYKThugBqFQ4W_Ug3I7Zg2uVZQRhnvy7675ijw5Ao8GjIaRy9Y3fxZ5kv9VrDZVFC3QYRDM4ju4N2rDcC1yq3OWHpmFNJ8n_5aUWUpv5K0Qn61lD7F6FyAVmeYIIsN0M9PFDsHX28VtT_iaAQ4B/s1600/spring-boot-skip-locked-database-workers.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;Spring Boot workers using FOR UPDATE SKIP LOCKED to concurrently process Outbox events from PostgreSQL&quot; border=&quot;0&quot; data-original-height=&quot;887&quot; data-original-width=&quot;1774&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGlqSeqjRNqd2MHb3bE5rOVqGehDk5TqZIZb2E6-q0CFYKThugBqFQ4W_Ug3I7Zg2uVZQRhnvy7675ijw5Ao8GjIaRy9Y3fxZ5kv9VrDZVFC3QYRDM4ju4N2rDcC1yq3OWHpmFNJ8n_5aUWUpv5K0Qn61lD7F6FyAVmeYIIsN0M9PFDsHX28VtT_iaAQ4B/s1600/spring-boot-skip-locked-database-workers.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;p&gt;
Scaling a background worker often starts with a deceptively simple problem.
&lt;/p&gt;

&lt;p&gt;
You have a database table containing work that needs to be processed.
&lt;/p&gt;

&lt;p&gt;
One application instance polls the table, claims some rows, processes them, and moves on.
&lt;/p&gt;

&lt;p&gt;
Then you deploy a second instance.
&lt;/p&gt;

&lt;p&gt;
Then five.
&lt;/p&gt;

&lt;p&gt;
Now every worker is looking at the same rows.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;                 OUTBOX
                    │
        ┌───────────┼───────────┐
        │           │           │
      Pod A       Pod B       Pod C
        │           │           │
        └───────────┼───────────┘
                    │
              Same pending rows&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
At this point, reaching for a distributed coordination mechanism can feel inevitable.
&lt;/p&gt;

&lt;p&gt;
Maybe Redis.
&lt;/p&gt;

&lt;p&gt;
Maybe a distributed lock.
&lt;/p&gt;

&lt;p&gt;
Maybe another service whose job is to decide which worker owns which work.
&lt;/p&gt;

&lt;p&gt;
But there is another question worth asking first:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;strong&gt;If the work already lives in your relational database, does the database already have enough information to coordinate the workers?&lt;/strong&gt;
&lt;/blockquote&gt;

&lt;p&gt;
For many queue-like workloads, PostgreSQL and MySQL provide a remarkably useful answer:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT ... FOR UPDATE SKIP LOCKED&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
It is only a few words of SQL.
&lt;/p&gt;

&lt;p&gt;
But those few words can fundamentally change how concurrent workers cooperate.
&lt;/p&gt;

&lt;h2&gt;Start with One Worker&lt;/h2&gt;

&lt;p&gt;
Imagine an Outbox table containing events waiting to be published:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;+----+----------------------+---------+
| ID | EVENT_TYPE           | STATUS  |
+----+----------------------+---------+
|  1 | PaymentCreated       | PENDING |
|  2 | CustomerUpdated      | PENDING |
|  3 | PaymentAuthorized    | PENDING |
|  4 | OrderCompleted       | PENDING |
+----+----------------------+---------+&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
With one worker, processing this is straightforward.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Worker
   │
   ▼
SELECT pending events
   │
   ▼
Process events
   │
   ▼
Update state&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
There is nobody else competing for the rows.
&lt;/p&gt;

&lt;p&gt;
Now deploy three workers.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Worker A ─┐
Worker B ─┼──► SELECT pending events
Worker C ─┘&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
If all three execute the same ordinary query at roughly the same time, they may all observe the same pending work.
&lt;/p&gt;

&lt;p&gt;
We need a way for a worker to say:
&lt;/p&gt;

&lt;blockquote&gt;
These rows are mine for this transaction. Other workers should find something else to do.
&lt;/blockquote&gt;

&lt;h2&gt;FOR UPDATE Solves Only Half the Problem&lt;/h2&gt;

&lt;p&gt;
A locking read gives us part of the answer:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT id, event_type, payload
FROM outbox_event
WHERE status = &#39;PENDING&#39;
ORDER BY id
LIMIT 100
FOR UPDATE;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The selected rows are locked for the transaction.
&lt;/p&gt;

&lt;p&gt;
That protects them from being concurrently claimed in the same way by another transaction.
&lt;/p&gt;

&lt;p&gt;
But suppose Worker A locks the first 100 rows.
&lt;/p&gt;

&lt;p&gt;
Worker B arrives immediately afterward and wants work.
&lt;/p&gt;

&lt;p&gt;
With ordinary locking behavior, Worker B can end up waiting for rows Worker A already owns.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Worker A ─────► [E1 E2 E3 E4] 🔒
                         │
Worker B ────────────────┘
                       WAIT&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
There may be thousands of other events available.
&lt;/p&gt;

&lt;p&gt;
Worker B does not necessarily need those particular rows.
&lt;/p&gt;

&lt;p&gt;
It just needs some work.
&lt;/p&gt;

&lt;p&gt;
That distinction is exactly where &lt;code&gt;SKIP LOCKED&lt;/code&gt; becomes useful.
&lt;/p&gt;

&lt;h2&gt;Skip Work Another Worker Already Owns&lt;/h2&gt;

&lt;p&gt;
Change the query to:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT id, event_type, payload
FROM outbox_event
WHERE status = &#39;PENDING&#39;
ORDER BY id
LIMIT 100
FOR UPDATE SKIP LOCKED;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Now the behavior changes.
&lt;/p&gt;

&lt;p&gt;
If Worker A already holds locks on some qualifying rows, Worker B does not wait for those row locks.
&lt;/p&gt;

&lt;p&gt;
It skips them and continues looking for other eligible rows.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;                    OUTBOX

          E1   E2   E3   E4   E5   E6
          🔒   🔒   🔒   🔒

Worker A ─┘    │    │    │
               │    │    │
Worker B ───── SKIP LOCKED ───► E5 E6&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Add another worker and the table can naturally distribute available work:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;                 PostgreSQL
              ┌─────────────┐
              │   OUTBOX    │
              │             │
              │ E1 E2 E3 E4 │
              │ E5 E6 E7 E8 │
              └──────┬──────┘
                     │
              FOR UPDATE
               SKIP LOCKED
                     │
        ┌────────────┼────────────┐
        ▼            ▼            ▼
      Pod A        Pod B        Pod C
     E1, E2       E3, E4       E5, E6&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
No worker needs a global lock around the entire queue.
&lt;/p&gt;

&lt;p&gt;
Workers coordinate through the rows representing the work itself.
&lt;/p&gt;

&lt;h2&gt;Why SKIP LOCKED Is Different from an Ordinary Query&lt;/h2&gt;

&lt;p&gt;
There is an important caveat.
&lt;/p&gt;

&lt;p&gt;
&lt;code&gt;SKIP LOCKED&lt;/code&gt; intentionally does not give you a normal, globally consistent view of all matching rows.
&lt;/p&gt;

&lt;p&gt;
Some rows may disappear from one worker&#39;s result because another transaction currently owns their locks.
&lt;/p&gt;

&lt;p&gt;
That would be undesirable for many normal business queries.
&lt;/p&gt;

&lt;p&gt;
Imagine querying account balances and silently ignoring locked accounts.
&lt;/p&gt;

&lt;p&gt;
Obviously wrong.
&lt;/p&gt;

&lt;p&gt;
But a worker queue has different semantics.
&lt;/p&gt;

&lt;p&gt;
The worker isn&#39;t asking:
&lt;/p&gt;

&lt;blockquote&gt;
Show me the complete truth about every pending row.
&lt;/blockquote&gt;

&lt;p&gt;
It is asking:
&lt;/p&gt;

&lt;blockquote&gt;
Give me some currently available work that I can safely claim.
&lt;/blockquote&gt;

&lt;p&gt;
That is why queue-like tables are such a natural fit for this behavior.
&lt;/p&gt;

&lt;h2&gt;This Is Exactly the Problem an Outbox Dispatcher Has&lt;/h2&gt;

&lt;p&gt;
This matters directly to &lt;strong&gt;NERV Event&lt;/strong&gt;.
&lt;/p&gt;

&lt;p&gt;
The Transactional Outbox Pattern gives us durable events.
&lt;/p&gt;

&lt;p&gt;
A business transaction stores both:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Business State
      +
Outbox Event
      │
      ▼
    COMMIT&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
After commit, a dispatcher needs to publish those events.
&lt;/p&gt;

&lt;p&gt;
In production, however, we rarely want one application instance to become the permanent global dispatcher.
&lt;/p&gt;

&lt;p&gt;
Spring Boot services run across multiple pods.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Pod A ─┐
Pod B ─┤
Pod C ─┼──► Shared Outbox Table
Pod D ─┤
Pod E ─┘&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
The challenge becomes:
&lt;/p&gt;

&lt;blockquote&gt;
How can every pod participate in dispatching without every pod processing the same Outbox rows?
&lt;/blockquote&gt;

&lt;p&gt;
Database row claiming gives us an elegant answer.
&lt;/p&gt;

&lt;p&gt;
Each dispatcher transaction claims a bounded batch.
&lt;/p&gt;

&lt;p&gt;
Other dispatchers skip the claimed rows and continue finding work.
&lt;/p&gt;

&lt;p&gt;
The database becomes both:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the durable store for the Outbox event, and&lt;/li&gt;
  &lt;li&gt;the concurrency boundary for claiming it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
That second property deserves more attention than it usually gets.
&lt;/p&gt;

&lt;h2&gt;Why Not Just Put a Distributed Lock in Redis?&lt;/h2&gt;

&lt;p&gt;
We could.
&lt;/p&gt;

&lt;p&gt;
For example:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Worker
   │
   ▼
Acquire Redis Lock
   │
   ▼
Read PostgreSQL
   │
   ▼
Process Work
   │
   ▼
Release Redis Lock&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
There are workloads where Redis is exactly the right technology.
&lt;/p&gt;

&lt;p&gt;
But adding Redis solely for coordination changes the architecture.
&lt;/p&gt;

&lt;p&gt;
Before:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Worker
   │
   ▼
PostgreSQL
   │
   ├── Work
   └── Ownership&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
After:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;             ┌────► Redis
             │       │
Worker ──────┤    Coordination
             │
             └────► PostgreSQL
                     │
                    Work&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
We now operate another distributed system.
&lt;/p&gt;

&lt;p&gt;
It has its own availability, network communication, failure behavior, timeouts, monitoring, deployment, and consistency questions.
&lt;/p&gt;

&lt;p&gt;
That does not make Redis a bad choice.
&lt;/p&gt;

&lt;p&gt;
It means Redis should solve a problem we actually have.
&lt;/p&gt;

&lt;blockquote&gt;
&lt;strong&gt;Infrastructure should earn its place in the architecture.&lt;/strong&gt;
&lt;/blockquote&gt;

&lt;h2&gt;The Database Has One Particularly Useful Property&lt;/h2&gt;

&lt;p&gt;
Suppose a worker starts a transaction and claims some rows.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BEGIN

SELECT ...
FOR UPDATE SKIP LOCKED;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Then the worker crashes before committing.
&lt;/p&gt;

&lt;p&gt;
The database connection disappears.
&lt;/p&gt;

&lt;p&gt;
The transaction rolls back.
&lt;/p&gt;

&lt;p&gt;
The row locks are released.
&lt;/p&gt;

&lt;p&gt;
Another worker can claim the rows.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Worker A
   │
   ├── BEGIN
   ├── Lock E1, E2
   │
   X  CRASH
   │
   ▼
ROLLBACK
   │
   ▼
Locks released
   │
   ▼
Worker B can claim E1, E2&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Ownership is tied to the transaction.
&lt;/p&gt;

&lt;p&gt;
There is no separate lease record that must independently agree with the transaction&#39;s outcome.
&lt;/p&gt;

&lt;p&gt;
But this leads to an equally important warning.
&lt;/p&gt;

&lt;h2&gt;Do Not Hold the Transaction Open While Doing Slow Work&lt;/h2&gt;

&lt;p&gt;
It is easy to misuse this pattern.
&lt;/p&gt;

&lt;p&gt;
Imagine claiming 100 Outbox events and then keeping the transaction open while performing 100 slow network calls.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BEGIN
   │
   ├── Claim 100 rows
   │
   ├── Call Kafka
   │
   ├── Wait
   │
   ├── Call Kafka
   │
   ├── Wait
   │
   ├── ...
   │
   └── 30 seconds later
COMMIT&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Now those row locks and the database connection remain tied to the processing lifetime.
&lt;/p&gt;

&lt;p&gt;
The same principle from long-running workflow design applies here:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;strong&gt;Keep database transactions short.&lt;/strong&gt;
&lt;/blockquote&gt;

&lt;p&gt;
The exact claim-and-dispatch strategy depends on the delivery guarantees of the system, but transaction duration must be deliberate.
&lt;/p&gt;

&lt;p&gt;
&lt;code&gt;SKIP LOCKED&lt;/code&gt; is not permission to turn a database transaction into a worker lease that stays open indefinitely.
&lt;/p&gt;

&lt;h2&gt;SKIP LOCKED Does Not Give You Exactly-Once Processing&lt;/h2&gt;

&lt;p&gt;
This is another important distinction.
&lt;/p&gt;

&lt;p&gt;
Suppose an Outbox worker publishes an event successfully.
&lt;/p&gt;

&lt;p&gt;
Then it crashes before recording the successful publication.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Publish to Kafka
       │
       ▼
    SUCCESS
       │
       X
     CRASH
       │
       ▼
Database still says PENDING&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
After recovery, another worker may publish the event again.
&lt;/p&gt;

&lt;p&gt;
The row lock prevented two workers from owning the same row simultaneously.
&lt;/p&gt;

&lt;p&gt;
It did not eliminate the distributed failure window between the database and the broker.
&lt;/p&gt;

&lt;p&gt;
That is why NERV Event still relies on the broader reliability model:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Transactional Outbox
        +
At-Least-Once Delivery
        +
Idempotent Consumer
        +
Inbox&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Locking solves &lt;strong&gt;concurrent ownership&lt;/strong&gt;.
&lt;/p&gt;

&lt;p&gt;
It does not magically solve every distributed-systems problem around delivery.
&lt;/p&gt;

&lt;h2&gt;SKIP LOCKED Does Not Automatically Preserve Ordering&lt;/h2&gt;

&lt;p&gt;
Suppose these events belong to the same aggregate:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PaymentCreated
      ↓
PaymentAuthorized
      ↓
PaymentCaptured&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Now imagine several workers independently claiming rows.
&lt;/p&gt;

&lt;p&gt;
Simply using:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ORDER BY created_at
FOR UPDATE SKIP LOCKED&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
does not by itself establish a complete business-level ordering guarantee across concurrent transactions.
&lt;/p&gt;

&lt;p&gt;
One worker may have locked an earlier event while another worker sees a later eligible row.
&lt;/p&gt;

&lt;p&gt;
If strict ordering matters, the architecture needs an explicit ordering strategy.
&lt;/p&gt;

&lt;p&gt;
In NERV Event, this is why concepts such as an &lt;code&gt;orderingKey&lt;/code&gt; matter.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;payment-123
   │
   ├── Event A
   ├── Event B
   └── Event C

payment-456
   │
   ├── Event X
   ├── Event Y
   └── Event Z&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
Ideally:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;payment-123 → A → B → C

payment-456 → X → Y → Z&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
We preserve ordering within the required boundary while still allowing unrelated keys to progress concurrently.
&lt;/p&gt;

&lt;p&gt;
This is a useful reminder:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;strong&gt;Row claiming and event ordering are separate problems.&lt;/strong&gt;
&lt;/blockquote&gt;

&lt;h2&gt;Indexes Matter More Than the Clever SQL&lt;/h2&gt;

&lt;p&gt;
Once this pattern is running at meaningful scale, the query needs to find available work efficiently.
&lt;/p&gt;

&lt;p&gt;
A query like:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT id
FROM outbox_event
WHERE status = &#39;PENDING&#39;
  AND next_attempt_at &amp;lt;= CURRENT_TIMESTAMP
ORDER BY created_at, id
LIMIT 100
FOR UPDATE SKIP LOCKED;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
needs indexes that support the way work is discovered.
&lt;/p&gt;

&lt;p&gt;
Otherwise the database may spend significantly more time scanning rows than actually claiming them.
&lt;/p&gt;

&lt;p&gt;
The correct index depends on the schema and workload, but fields involved in eligibility and ordering deserve deliberate attention.
&lt;/p&gt;

&lt;p&gt;
The lesson is simple:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;strong&gt;SKIP LOCKED makes contention behavior better. It does not make a bad query cheap.&lt;/strong&gt;
&lt;/blockquote&gt;

&lt;h2&gt;Batch Size Is Also an Architectural Decision&lt;/h2&gt;

&lt;p&gt;
Why not claim 10,000 rows at once?
&lt;/p&gt;

&lt;p&gt;
Because larger batches affect more than throughput.
&lt;/p&gt;

&lt;p&gt;
They can increase:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;transaction duration,&lt;/li&gt;
  &lt;li&gt;lock lifetime,&lt;/li&gt;
  &lt;li&gt;connection hold time,&lt;/li&gt;
  &lt;li&gt;recovery work after failure,&lt;/li&gt;
  &lt;li&gt;memory consumption, and&lt;/li&gt;
  &lt;li&gt;the amount of work monopolized by one worker.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Too small a batch, however, increases database round trips.
&lt;/p&gt;

&lt;p&gt;
There is no universal magic number.
&lt;/p&gt;

&lt;p&gt;
Batch size should be treated as a throughput-versus-fairness-versus-recovery tradeoff and measured under realistic load.
&lt;/p&gt;

&lt;h2&gt;Shopify Recently Faced a Much Larger Version of This Problem&lt;/h2&gt;

&lt;p&gt;
This pattern is not limited to background job tables.
&lt;/p&gt;

&lt;p&gt;
In 2026, Shopify Engineering published an interesting account of redesigning its inventory reservation system.
&lt;/p&gt;

&lt;p&gt;
The previous reservation model used Redis, while the authoritative inventory ledger lived in MySQL.
&lt;/p&gt;

&lt;p&gt;
That meant reservation and inventory state crossed two different systems.
&lt;/p&gt;

&lt;p&gt;
Shopify moved inventory reservations into MySQL so reservation and inventory changes could share an ACID consistency boundary.
&lt;/p&gt;

&lt;p&gt;
A key part of the new design used MySQL 8&#39;s &lt;code&gt;SKIP LOCKED&lt;/code&gt; behavior so concurrent reservation transactions could skip inventory units already claimed by other transactions instead of waiting on them.
&lt;/p&gt;

&lt;p&gt;
But the interesting part of the story is not simply:
&lt;/p&gt;

&lt;blockquote&gt;
Shopify replaced Redis with MySQL.
&lt;/blockquote&gt;

&lt;p&gt;
That would be an oversimplification.
&lt;/p&gt;

&lt;p&gt;
The interesting lesson is that the team reconsidered whether the extra distributed-system boundary was still necessary for this particular workload.
&lt;/p&gt;

&lt;p&gt;
And making the database approach work required much more than adding &lt;code&gt;SKIP LOCKED&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
They also had to reason about:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;primary-key and index design,&lt;/li&gt;
  &lt;li&gt;transaction isolation,&lt;/li&gt;
  &lt;li&gt;gap locking,&lt;/li&gt;
  &lt;li&gt;consistent lock ordering,&lt;/li&gt;
  &lt;li&gt;batching,&lt;/li&gt;
  &lt;li&gt;database connection consumption, and&lt;/li&gt;
  &lt;li&gt;production observability.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
One of their most interesting findings was that the eventual throughput ceiling was not simply query execution or database CPU.
&lt;/p&gt;

&lt;p&gt;
Database connection usage elsewhere in the checkout path was part of the real bottleneck.
&lt;/p&gt;

&lt;p&gt;
That is a valuable reminder for any worker architecture:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;strong&gt;The database connection is also a finite resource.&lt;/strong&gt;
&lt;/blockquote&gt;

&lt;p&gt;
Optimizing row locking while ignoring connection hold time can simply move the bottleneck somewhere else.
&lt;/p&gt;

&lt;h2&gt;So Should We Stop Using Redis?&lt;/h2&gt;

&lt;p&gt;
No.
&lt;/p&gt;

&lt;p&gt;
That would be the wrong conclusion.
&lt;/p&gt;

&lt;p&gt;
Redis remains extremely useful for workloads such as:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;high-speed caching,&lt;/li&gt;
  &lt;li&gt;ephemeral state,&lt;/li&gt;
  &lt;li&gt;TTL-heavy data,&lt;/li&gt;
  &lt;li&gt;counters,&lt;/li&gt;
  &lt;li&gt;rate limiting,&lt;/li&gt;
  &lt;li&gt;specialized data structures, and&lt;/li&gt;
  &lt;li&gt;workloads that genuinely benefit from coordination outside the transactional database.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The argument is not:
&lt;/p&gt;

&lt;blockquote&gt;
Never use Redis.
&lt;/blockquote&gt;

&lt;p&gt;
The argument is:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;strong&gt;Do not introduce Redis merely because concurrent coordination sounds like something that must require Redis.&lt;/strong&gt;
&lt;/blockquote&gt;

&lt;p&gt;
First understand what the database can already guarantee.
&lt;/p&gt;

&lt;h2&gt;When Database Coordination Is a Good Fit&lt;/h2&gt;

&lt;p&gt;
&lt;code&gt;FOR UPDATE SKIP LOCKED&lt;/code&gt; is particularly attractive when:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the work already lives in the relational database,&lt;/li&gt;
  &lt;li&gt;workers need to claim independent rows,&lt;/li&gt;
  &lt;li&gt;the workload is naturally queue-like,&lt;/li&gt;
  &lt;li&gt;transactions can remain short,&lt;/li&gt;
  &lt;li&gt;the database has enough connection and I/O capacity, and&lt;/li&gt;
  &lt;li&gt;keeping state and ownership within one transactional system simplifies correctness.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Outbox and Inbox processing fit these characteristics surprisingly well.
&lt;/p&gt;

&lt;h2&gt;When You Should Look Beyond the Database&lt;/h2&gt;

&lt;p&gt;
There is also a point where the database should not become your answer to every coordination problem.
&lt;/p&gt;

&lt;p&gt;
You should reconsider the architecture when:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;worker throughput begins competing with critical transactional workloads,&lt;/li&gt;
  &lt;li&gt;connection consumption becomes unacceptable,&lt;/li&gt;
  &lt;li&gt;work distribution requires semantics poorly represented by rows and transactions,&lt;/li&gt;
  &lt;li&gt;extremely low-latency ephemeral coordination dominates the workload,&lt;/li&gt;
  &lt;li&gt;database contention becomes the limiting factor, or&lt;/li&gt;
  &lt;li&gt;a dedicated queue or coordination system better matches the operational requirements.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The goal is not database minimalism.
&lt;/p&gt;

&lt;p&gt;
The goal is deliberate architecture.
&lt;/p&gt;

&lt;h2&gt;The Bigger Lesson&lt;/h2&gt;

&lt;p&gt;
What I like most about &lt;code&gt;SKIP LOCKED&lt;/code&gt; is not the SQL syntax.
&lt;/p&gt;

&lt;p&gt;
It is the architectural question it forces us to ask.
&lt;/p&gt;

&lt;p&gt;
Suppose the work is already durable in PostgreSQL.
&lt;/p&gt;

&lt;p&gt;
Suppose transactions already define ownership.
&lt;/p&gt;

&lt;p&gt;
Suppose the database already knows which rows another worker has claimed.
&lt;/p&gt;

&lt;p&gt;
Do we really need another system just to coordinate access to those rows?
&lt;/p&gt;

&lt;p&gt;
Sometimes the answer is absolutely yes.
&lt;/p&gt;

&lt;p&gt;
But sometimes:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Database State
      +
Transaction
      +
Row Lock
      +
SKIP LOCKED&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
is enough.
&lt;/p&gt;

&lt;p&gt;
That is an important lesson from building infrastructure such as NERV Event.
&lt;/p&gt;

&lt;p&gt;
Production architecture does not become better simply because it contains more specialized infrastructure.
&lt;/p&gt;

&lt;p&gt;
Every additional system introduces another operational and failure boundary.
&lt;/p&gt;

&lt;p&gt;
Sometimes the best distributed system is the one you didn&#39;t need to add.
&lt;/p&gt;

&lt;h2&gt;About NERV Event&lt;/h2&gt;

&lt;p&gt;
&lt;strong&gt;NERV Event&lt;/strong&gt; is an open-source event-driven infrastructure library for Spring Boot focused on reliable event publishing and processing.
&lt;/p&gt;

&lt;p&gt;
It provides infrastructure for Transactional Outbox and Inbox patterns, retries, idempotency, ordering, multi-instance processing, Kafka and SQS integration, scheduler resilience, and operational visibility.
&lt;/p&gt;

&lt;p&gt;
Explore the project:
&lt;/p&gt;

&lt;p&gt;
&lt;a href=&quot;https://github.com/czetsuyatech/nerv-event&quot;&gt;NERV Event on GitHub&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
NERV Event is part of &lt;strong&gt;NERV — Next-Generation Engineering for Runtime Velocity&lt;/strong&gt;.
&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;
&lt;strong&gt;References&lt;/strong&gt;
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    Shopify Engineering — &lt;em&gt;We replaced Redis with MySQL for inventory reservations—and it scaled&lt;/em&gt;
  &lt;/li&gt;
  &lt;li&gt;
    PostgreSQL Documentation — &lt;em&gt;SELECT / Locking Clause&lt;/em&gt;
  &lt;/li&gt;
  &lt;li&gt;
    MySQL Reference Manual — &lt;em&gt;InnoDB Locking Reads&lt;/em&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/long-running-transactions-spring-boot-nerv-event.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Handling Long-Running Transactions in Spring Boot with NERV Event
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Event&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


   

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/7769165569406961922/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/10/spring-boot-skip-locked-database-workers.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/7769165569406961922'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/7769165569406961922'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/10/spring-boot-skip-locked-database-workers.html' title='Stop Reaching for Redis: Scaling Database Workers with SKIP LOCKED'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGlqSeqjRNqd2MHb3bE5rOVqGehDk5TqZIZb2E6-q0CFYKThugBqFQ4W_Ug3I7Zg2uVZQRhnvy7675ijw5Ao8GjIaRy9Y3fxZ5kv9VrDZVFC3QYRDM4ju4N2rDcC1yq3OWHpmFNJ8n_5aUWUpv5K0Qn61lD7F6FyAVmeYIIsN0M9PFDsHX28VtT_iaAQ4B/s72-c/spring-boot-skip-locked-database-workers.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-6578056236608663035</id><published>2026-10-05T18:22:12.628+08:00</published><updated>2026-10-17T14:34:21.366+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithmic Trading"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Trade"/><category scheme="http://www.blogger.com/atom/ns#" term="Software Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><category scheme="http://www.blogger.com/atom/ns#" term="Trading Engine"/><category scheme="http://www.blogger.com/atom/ns#" term="Trading Systems"/><title type='text'>A Trading Bot Is Easy. A Trading Engine Is Not</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOvgwaenD_QB0UC9fTusuw9H4MKP-KdKXZXR4_S6DMGhJX2lf2tRIhWgmRUEv1p3oTf3zxu7tKZilDeJTWzszfodDLPUYMnnQNmlwdV5n3UQFqq5Cy-dQLCnscfjDoeiW6YRws3fpidC_hyphenhyphenV6HpDHFXjh5OOlbUdglcb44yCcq4EQdmKpqimlXXKJmf5Sg/s1774/nerv-trade-bot-vs-trading-engine.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;887&quot; data-original-width=&quot;1774&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOvgwaenD_QB0UC9fTusuw9H4MKP-KdKXZXR4_S6DMGhJX2lf2tRIhWgmRUEv1p3oTf3zxu7tKZilDeJTWzszfodDLPUYMnnQNmlwdV5n3UQFqq5Cy-dQLCnscfjDoeiW6YRws3fpidC_hyphenhyphenV6HpDHFXjh5OOlbUdglcb44yCcq4EQdmKpqimlXXKJmf5Sg/s1600/nerv-trade-bot-vs-trading-engine.png&quot; alt=&quot;Trading bot compared with a production trading engine architecture&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;This is Part 2 of the NERV Trade engineering series. In &lt;strong&gt;Part 1&lt;/strong&gt;, I showed where NERV Trade has reached today. Now we&#39;re going back to the beginning.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;A Trading Bot Is Easy. A Trading Engine Is Not.&lt;/h2&gt;

&lt;p&gt;So where did NERV Trade actually start?&lt;/p&gt;

&lt;p&gt;With a deceptively simple idea.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Market Data
    ↓
Analysis
    ↓
BUY / SELL
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you&#39;ve ever experimented with algorithmic trading, this probably looks familiar.&lt;/p&gt;

&lt;p&gt;Get some candles. Calculate indicators. Decide whether the market looks bullish or bearish. Generate a signal.&lt;/p&gt;

&lt;p&gt;Maybe send an order.&lt;/p&gt;

&lt;p&gt;At this stage, the interesting question seems to be:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;How do I generate a good trading signal?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And that was where much of my attention naturally went at the beginning of NERV Trade.&lt;/p&gt;

&lt;p&gt;But as the project evolved, I discovered something that completely changed how I thought about the system.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Generating the signal wasn&#39;t the difficult part.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The difficult part was deciding what the system should do after generating it—and proving that it would still behave correctly when things stopped going according to plan.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;The First Version of the Problem&lt;/h2&gt;

&lt;p&gt;A basic trading program can be surprisingly small conceptually.&lt;/p&gt;

&lt;p&gt;You have market data:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;open
high
low
close
volume
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You run some analysis.&lt;/p&gt;

&lt;p&gt;The result might be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BULLISH
BEARISH
NEUTRAL
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A strategy interprets that result and eventually produces something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BUY
SELL
HOLD
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For an experiment, that can be enough.&lt;/p&gt;

&lt;p&gt;You can replay historical candles, print trades to the console, calculate theoretical profit and loss, and start tweaking the strategy.&lt;/p&gt;

&lt;p&gt;It&#39;s satisfying because progress is immediate.&lt;/p&gt;

&lt;p&gt;Add an indicator.&lt;/p&gt;

&lt;p&gt;Change a threshold.&lt;/p&gt;

&lt;p&gt;Run the simulation again.&lt;/p&gt;

&lt;p&gt;Maybe the numbers improve.&lt;/p&gt;

&lt;p&gt;It feels like you&#39;re building a trading system.&lt;/p&gt;

&lt;p&gt;But you&#39;re mostly building the part that &lt;strong&gt;decides what it wants to do&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;That distinction eventually became very important.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Then You Ask the Next Question&lt;/h2&gt;

&lt;p&gt;Suppose the strategy says:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BUY BTC
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Great.&lt;/p&gt;

&lt;p&gt;What happens now?&lt;/p&gt;

&lt;p&gt;We need an order.&lt;/p&gt;

&lt;p&gt;So perhaps the architecture becomes:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Market Data
    ↓
Analysis
    ↓
Strategy
    ↓
BUY
    ↓
Order
    ↓
Broker
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Still pretty straightforward.&lt;/p&gt;

&lt;p&gt;But then the questions start.&lt;/p&gt;

&lt;p&gt;Did the broker receive the order?&lt;/p&gt;

&lt;p&gt;Did it accept it?&lt;/p&gt;

&lt;p&gt;Was the order rejected?&lt;/p&gt;

&lt;p&gt;Did it execute immediately?&lt;/p&gt;

&lt;p&gt;Was only part of it executed?&lt;/p&gt;

&lt;p&gt;Is the remaining quantity still open?&lt;/p&gt;

&lt;p&gt;Did the broker execute it more than once?&lt;/p&gt;

&lt;p&gt;What if the application receives the same execution notification twice?&lt;/p&gt;

&lt;p&gt;What if the application crashes after receiving the fill?&lt;/p&gt;

&lt;p&gt;What if the broker accepts the order but the network connection dies before we receive the response?&lt;/p&gt;

&lt;p&gt;Suddenly:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BUY
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;isn&#39;t nearly enough information.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;The Broker Doesn&#39;t Return a Trade&lt;/h2&gt;

&lt;p&gt;This was one of the conceptual shifts that eventually shaped NERV Trade.&lt;/p&gt;

&lt;p&gt;A strategy can express an intention.&lt;/p&gt;

&lt;p&gt;A broker processes orders.&lt;/p&gt;

&lt;p&gt;The market produces executions.&lt;/p&gt;

&lt;p&gt;Those aren&#39;t the same thing.&lt;/p&gt;

&lt;p&gt;Consider an order for 10 units.&lt;/p&gt;

&lt;p&gt;You might imagine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BUY 10
    ↓
FILLED 10
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Reality can look more like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BUY 10
    ↓
ACKNOWLEDGED
    ↓
FILL 3
    ↓
FILL 4
    ↓
FILL 3
    ↓
FILLED
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the system needs to remember what happened between those steps.&lt;/p&gt;

&lt;p&gt;It needs identity.&lt;/p&gt;

&lt;p&gt;It needs state.&lt;/p&gt;

&lt;p&gt;It needs lifecycle.&lt;/p&gt;

&lt;p&gt;And eventually it needs persistence.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Then Failure Becomes Part of the Design&lt;/h2&gt;

&lt;p&gt;The happy path is easy to reason about.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Send Order
    ↓
Broker Accepts
    ↓
Receive Fill
    ↓
Update Position
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But production systems don&#39;t live entirely on the happy path.&lt;/p&gt;

&lt;p&gt;Consider this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NERV
  │
  │ Send BUY order
  ▼
Broker
  │
  │ Order accepted
  ▼
  X  Connection lost
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The broker has the order.&lt;/p&gt;

&lt;p&gt;NERV doesn&#39;t know that.&lt;/p&gt;

&lt;p&gt;What should the application do?&lt;/p&gt;

&lt;p&gt;The obvious answer might be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;retry();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But retrying could create another real order.&lt;/p&gt;

&lt;p&gt;So perhaps the order failed?&lt;/p&gt;

&lt;p&gt;That&#39;s not true either.&lt;/p&gt;

&lt;p&gt;We don&#39;t know whether it failed.&lt;/p&gt;

&lt;p&gt;That means uncertainty itself becomes part of the domain.&lt;/p&gt;

&lt;p&gt;And once that happens, a generic retry mechanism is no longer enough.&lt;/p&gt;

&lt;p&gt;The system needs stable identities and a way to ask the broker:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;What actually happened?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That is reconciliation.&lt;/p&gt;

&lt;p&gt;I certainly wasn&#39;t thinking about reconciliation when the project was simply:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Market Data → Analysis → BUY / SELL
&lt;/code&gt;&lt;/pre&gt;

&lt;hr /&gt;

&lt;h2&gt;Then the Application Restarts&lt;/h2&gt;

&lt;p&gt;Now imagine the engine has been running for hours.&lt;/p&gt;

&lt;p&gt;There are active trades.&lt;/p&gt;

&lt;p&gt;Some orders are filled.&lt;/p&gt;

&lt;p&gt;Others may still be open.&lt;/p&gt;

&lt;p&gt;The system knows its exposure.&lt;/p&gt;

&lt;p&gt;It knows which executions it has already processed.&lt;/p&gt;

&lt;p&gt;Then:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Application stopped.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Maybe it crashed.&lt;/p&gt;

&lt;p&gt;Maybe Kubernetes restarted the container.&lt;/p&gt;

&lt;p&gt;Maybe we deployed a new version.&lt;/p&gt;

&lt;p&gt;The reason doesn&#39;t really matter.&lt;/p&gt;

&lt;p&gt;When the application comes back, what does it know?&lt;/p&gt;

&lt;p&gt;If the answer is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Nothing. Let&#39;s start again.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;then we have a serious problem.&lt;/p&gt;

&lt;p&gt;The broker didn&#39;t forget.&lt;/p&gt;

&lt;p&gt;The account didn&#39;t forget.&lt;/p&gt;

&lt;p&gt;The market didn&#39;t forget.&lt;/p&gt;

&lt;p&gt;Only our application did.&lt;/p&gt;

&lt;p&gt;A trading engine therefore needs to recover its understanding of the world and reconcile that understanding with external reality.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Market Data Has Its Own Version of the Same Problem&lt;/h2&gt;

&lt;p&gt;Execution isn&#39;t the only place where apparently simple assumptions break.&lt;/p&gt;

&lt;p&gt;Market data does too.&lt;/p&gt;

&lt;p&gt;Suppose our strategy runs on five-minute candles.&lt;/p&gt;

&lt;p&gt;Easy enough.&lt;/p&gt;

&lt;p&gt;Then we decide that a five-minute signal should be interpreted in the context of:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;M5
M15
H1
H4
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we have another set of questions.&lt;/p&gt;

&lt;p&gt;When exactly does an M15 candle close?&lt;/p&gt;

&lt;p&gt;Which M5 candles belong to it?&lt;/p&gt;

&lt;p&gt;What happens while the current H1 candle is still forming?&lt;/p&gt;

&lt;p&gt;When analyzing an M5 candle from 10:35, are we accidentally using information from an H1 candle that wasn&#39;t complete at 10:35?&lt;/p&gt;

&lt;p&gt;That last question is particularly dangerous.&lt;/p&gt;

&lt;p&gt;Because the system can look perfectly correct while quietly using information from the future.&lt;/p&gt;

&lt;p&gt;Your backtest might even look fantastic.&lt;/p&gt;

&lt;p&gt;It would also be lying to you.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Eventually the Architecture Started Looking Different&lt;/h2&gt;

&lt;p&gt;The original mental model was:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Market Data
    ↓
Analysis
    ↓
BUY / SELL
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As each new problem appeared, the system had to acquire another responsibility.&lt;/p&gt;

&lt;p&gt;Eventually the picture became closer to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Market Data
    ↓
Multi-Timeframe State
    ↓
Analysis
    ↓
Strategy
    ↓
Risk
    ↓
Trade Intent
    ↓
Order Lifecycle
    ↓
Broker
    ↓
Executions
    ↓
Durable State
    ↓
Recovery &amp;amp; Reconciliation
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&#39;s a very different system.&lt;/p&gt;

&lt;p&gt;And importantly, those boxes weren&#39;t added because I sat down at the beginning and designed the perfect trading architecture.&lt;/p&gt;

&lt;p&gt;They appeared because increasingly difficult problems made the simpler architecture insufficient.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;So What&#39;s the Difference Between a Bot and an Engine?&lt;/h2&gt;

&lt;p&gt;I&#39;m not interested in creating a formal industry definition here.&lt;/p&gt;

&lt;p&gt;For this project, I think about the distinction much more practically.&lt;/p&gt;

&lt;p&gt;A trading bot can answer:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;What should I trade?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A trading engine has to keep answering:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;What happened?&lt;/p&gt;

&lt;p&gt;What do I currently own?&lt;/p&gt;

&lt;p&gt;What am I allowed to do?&lt;/p&gt;

&lt;p&gt;What has already been processed?&lt;/p&gt;

&lt;p&gt;What is still uncertain?&lt;/p&gt;

&lt;p&gt;And can I prove that my internal state still agrees with reality?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That second set of questions turned out to dominate much of the engineering work in NERV Trade.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;This Changed How I Measure Progress&lt;/h2&gt;

&lt;p&gt;Early in a trading project, progress is easy to see.&lt;/p&gt;

&lt;p&gt;A new indicator appears.&lt;/p&gt;

&lt;p&gt;A signal fires.&lt;/p&gt;

&lt;p&gt;A backtest improves.&lt;/p&gt;

&lt;p&gt;A chart looks better.&lt;/p&gt;

&lt;p&gt;Later, some of the most important progress becomes almost invisible.&lt;/p&gt;

&lt;p&gt;The same execution arriving twice changes state once.&lt;/p&gt;

&lt;p&gt;A crash halfway through processing doesn&#39;t corrupt accounting.&lt;/p&gt;

&lt;p&gt;An uncertain order isn&#39;t blindly submitted again.&lt;/p&gt;

&lt;p&gt;A restart reconstructs the same state.&lt;/p&gt;

&lt;p&gt;A missing market-data interval is detected instead of silently ignored.&lt;/p&gt;

&lt;p&gt;A strategy cannot accidentally bypass risk controls.&lt;/p&gt;

&lt;p&gt;None of those features produce an exciting trading chart.&lt;/p&gt;

&lt;p&gt;But they&#39;re the things that started turning NERV Trade from an experiment into an engine.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;But Before Orders, Brokers, and Databases...&lt;/h2&gt;

&lt;p&gt;There&#39;s an earlier problem we need to solve first.&lt;/p&gt;

&lt;p&gt;Suppose I give NERV Trade the same sequence of market data twice.&lt;/p&gt;

&lt;p&gt;Should it make the same decision?&lt;/p&gt;

&lt;p&gt;That sounds like an easy question.&lt;/p&gt;

&lt;p&gt;It isn&#39;t always.&lt;/p&gt;

&lt;p&gt;Time, mutable state, candle boundaries, event ordering and partially formed market data can all introduce subtle differences.&lt;/p&gt;

&lt;p&gt;And if the analysis isn&#39;t reproducible, debugging everything that comes afterward becomes dramatically harder.&lt;/p&gt;

&lt;p&gt;So before worrying about real brokers, persistent orders or restart recovery, NERV Trade needed a more fundamental property:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;determinism.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;That became one of the earliest architectural principles of the project.&lt;/p&gt;

&lt;p&gt;And that&#39;s where we&#39;ll go next.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;strong&gt;Next in the NERV Trade series:&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Deterministic Trading: Why the Same Market Data Must Produce the Same Decision&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;NERV Trade is part of NERV — Next-Generation Engineering for Runtime Velocity. This series documents the real engineering journey behind building a Java trading engine: the design decisions, failures, tests, architectural changes and lessons that shaped the system.&lt;/em&gt;&lt;/p&gt;

&lt;!--NERV Article Navigation--&gt;
&lt;div style=&quot;border-bottom: 1px solid rgb(229, 231, 235); border-top: 1px solid rgb(229, 231, 235); margin: 40px 0px 20px; padding: 20px 0px;&quot;&gt;

  &lt;div style=&quot;align-items: center; display: flex; flex-wrap: wrap; gap: 16px; justify-content: space-between;&quot;&gt;

    &lt;!--Previous Article--&gt;
    &lt;div style=&quot;flex: 1 1 0%; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;color: #6b7280; font-size: 12px; letter-spacing: 0.5px; margin-bottom: 4px; text-transform: uppercase;&quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/i-built-a-trading-engine-in-java.html&quot; style=&quot;font-weight: 600; text-decoration: none;&quot;&gt;
        I Built a Trading Engine in Java — Here’s What It Took
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!--Series / Label--&gt;
    &lt;div style=&quot;flex: 0 0 auto; min-width: 160px; text-align: center;&quot;&gt;
      &lt;div style=&quot;color: #6b7280; font-size: 12px; letter-spacing: 0.5px; margin-bottom: 4px; text-transform: uppercase;&quot;&gt;
        NERV Trade
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Trade&quot; style=&quot;font-weight: 600; text-decoration: none;&quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;
    
    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/10/deterministic-trading-java-market-data-decisions.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Deterministic Trading: Why the Same Market Data Must Produce the Same Decision
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!--/NERV Article Navigation--&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/6578056236608663035/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/10/a-trading-bot-is-easy-trading-engine-is-not.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/6578056236608663035'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/6578056236608663035'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/10/a-trading-bot-is-easy-trading-engine-is-not.html' title='A Trading Bot Is Easy. A Trading Engine Is Not'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOvgwaenD_QB0UC9fTusuw9H4MKP-KdKXZXR4_S6DMGhJX2lf2tRIhWgmRUEv1p3oTf3zxu7tKZilDeJTWzszfodDLPUYMnnQNmlwdV5n3UQFqq5Cy-dQLCnscfjDoeiW6YRws3fpidC_hyphenhyphenV6HpDHFXjh5OOlbUdglcb44yCcq4EQdmKpqimlXXKJmf5Sg/s72-c/nerv-trade-bot-vs-trading-engine.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-1940318442069326704</id><published>2026-09-30T08:14:03.823+08:00</published><updated>2026-10-29T17:45:41.618+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Auditing"/><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate"/><category scheme="http://www.blogger.com/atom/ns#" term="Hibernate Envers"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Audit"/><category scheme="http://www.blogger.com/atom/ns#" term="Production Support"/><category scheme="http://www.blogger.com/atom/ns#" term="Software Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>The Database Tells You What Is. An Audit Trail Tells You What Happened</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-3QBEviEVT-pCT4NiM-2JKNmbSFf6Rw2QGDx2R4D08fd7b3KoCTH9cl-yYkdXohKk_LqyJYGFOI5JDU3kPAJU5rh2jXKO-EnDIki0LsbK7CKCGGonTYunpeKsXWVu55i0DUyhmNyIoRWb565D6mbYumh9XnX9ZvIsZq5Rws1CCU7t1yAEuF5SEiJXXfK1/s1600/nerv-audit-database-state-vs-audit-history.png&quot; style=&quot;display: block; padding: 1em 0px; text-align: center;&quot;&gt;&lt;img alt=&quot;Current state tells us what the data looks like now; audit history shows how it got there.&quot; border=&quot;0&quot; data-original-height=&quot;887&quot; data-original-width=&quot;1774&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-3QBEviEVT-pCT4NiM-2JKNmbSFf6Rw2QGDx2R4D08fd7b3KoCTH9cl-yYkdXohKk_LqyJYGFOI5JDU3kPAJU5rh2jXKO-EnDIki0LsbK7CKCGGonTYunpeKsXWVu55i0DUyhmNyIoRWb565D6mbYumh9XnX9ZvIsZq5Rws1CCU7t1yAEuF5SEiJXXfK1/s1600/nerv-audit-database-state-vs-audit-history.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;h2&gt;The Database Tells You What Is. An Audit Trail Tells You What Happened.&lt;/h2&gt;

&lt;p&gt;A production support ticket comes in:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;“Why is this subscription DEACTIVATED?”&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It sounds like a simple question.&lt;/p&gt;

&lt;p&gt;You query the database:&lt;/p&gt;

&lt;pre&gt;id         = 9217
status     = DEACTIVATED
start_date = 2026-08-15
end_date   = 2026-08-30
updated_at = 2026-08-30 14:32:17&lt;/pre&gt;

&lt;p&gt;The database answered your query perfectly.&lt;/p&gt;

&lt;p&gt;Unfortunately, it didn&#39;t answer the question.&lt;/p&gt;

&lt;p&gt;You know that the subscription is currently &lt;code&gt;DEACTIVATED&lt;/code&gt;. You know when the row was last updated. You may even know which application updated it.&lt;/p&gt;

&lt;p&gt;But the questions that actually matter during the investigation are still unanswered:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;What was the previous status?&lt;/li&gt;
  &lt;li&gt;When did the transition happen?&lt;/li&gt;
  &lt;li&gt;Who—or what—changed it?&lt;/li&gt;
  &lt;li&gt;What other fields changed at the same time?&lt;/li&gt;
  &lt;li&gt;Did the record transition directly from &lt;code&gt;ACTIVE&lt;/code&gt; to &lt;code&gt;DEACTIVATED&lt;/code&gt;?&lt;/li&gt;
  &lt;li&gt;Or did it pass through several states before reaching its current value?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is a situation I&#39;ve encountered repeatedly while supporting enterprise applications.&lt;/p&gt;

&lt;p&gt;And it exposes an important distinction:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;The current state of your data is not its history.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2&gt;The Database Is Doing Exactly What We Asked It to Do&lt;/h2&gt;

&lt;p&gt;There is nothing wrong with the database.&lt;/p&gt;

&lt;p&gt;A normal application table is primarily designed to represent the &lt;strong&gt;current state&lt;/strong&gt; of a business entity.&lt;/p&gt;

&lt;p&gt;If a subscription changes:&lt;/p&gt;

&lt;pre&gt;ACTIVE → SUSPENDED → DEACTIVATED&lt;/pre&gt;

&lt;p&gt;the application may simply update the same row each time.&lt;/p&gt;

&lt;p&gt;Eventually the database contains:&lt;/p&gt;

&lt;pre&gt;status = DEACTIVATED&lt;/pre&gt;

&lt;p&gt;The previous values are gone from the application&#39;s primary table.&lt;/p&gt;

&lt;p&gt;That is usually exactly what we want for normal application processing.&lt;/p&gt;

&lt;p&gt;But production support has a different requirement.&lt;/p&gt;

&lt;p&gt;We don&#39;t only want to know:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;What is the state of this entity?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We often need to know:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;How did this entity reach this state?&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Those are fundamentally different questions.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;So We Start Searching the Logs&lt;/h2&gt;

&lt;p&gt;When the database cannot explain the history, the next place most developers go is the application logs.&lt;/p&gt;

&lt;p&gt;We search for something like:&lt;/p&gt;

&lt;pre&gt;subscriptionId=9217&lt;/pre&gt;

&lt;p&gt;Sometimes that works beautifully.&lt;/p&gt;

&lt;p&gt;You find the request, follow the execution path, identify the operation that changed the entity, and solve the incident.&lt;/p&gt;

&lt;p&gt;But sometimes you don&#39;t.&lt;/p&gt;

&lt;p&gt;The change may have happened several days or weeks ago.&lt;/p&gt;

&lt;p&gt;The relevant logs may have already rotated.&lt;/p&gt;

&lt;p&gt;The operation might have originated from another microservice.&lt;/p&gt;

&lt;p&gt;It might have been triggered by Kafka, a scheduled process, an administrator, a batch job, or an external integration.&lt;/p&gt;

&lt;p&gt;Perhaps the logs tell you that an update occurred but don&#39;t contain the previous field values.&lt;/p&gt;

&lt;p&gt;Or perhaps you find hundreds of related log entries and now have to reconstruct the entity&#39;s history manually.&lt;/p&gt;

&lt;p&gt;Logs are incredibly useful.&lt;/p&gt;

&lt;p&gt;But they solve a different problem.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Logs Tell You What the Application Did&lt;/h2&gt;

&lt;p&gt;Application logs are primarily records of &lt;strong&gt;execution&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;They help us answer questions such as:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Which endpoint was called?&lt;/li&gt;
  &lt;li&gt;Which operation failed?&lt;/li&gt;
  &lt;li&gt;What exception was thrown?&lt;/li&gt;
  &lt;li&gt;Which external service responded with an error?&lt;/li&gt;
  &lt;li&gt;Which branch of the application logic executed?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Distributed tracing extends that visibility across services.&lt;/p&gt;

&lt;p&gt;Metrics help us understand the health and behavior of the system as a whole.&lt;/p&gt;

&lt;p&gt;But during a production investigation, there is another dimension we frequently need to understand:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;the evolution of the business data itself.&lt;/strong&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;What If We Could See the History Directly?&lt;/h2&gt;

&lt;p&gt;Imagine that instead of trying to reconstruct the subscription&#39;s history from scattered logs, we could inspect something like this:&lt;/p&gt;

&lt;pre&gt;Subscription #9217

2026-08-30 14:32

status
SUSPENDED → DEACTIVATED

end_date
null → 2026-08-30

changed by:
subscription-service


2026-08-28 09:17

status
ACTIVE → SUSPENDED

changed by:
third-party-reactivation&lt;/pre&gt;

&lt;p&gt;Suddenly, the investigation looks very different.&lt;/p&gt;

&lt;p&gt;We know the entity did not move directly from &lt;code&gt;ACTIVE&lt;/code&gt; to &lt;code&gt;DEACTIVATED&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We know exactly when each transition occurred.&lt;/p&gt;

&lt;p&gt;We know which fields changed together.&lt;/p&gt;

&lt;p&gt;And if we capture sufficient audit metadata, we can also identify the user, service, or process responsible for each revision.&lt;/p&gt;

&lt;p&gt;Now we can return to our logs and traces with much more precise questions:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Why did the subscription enter &lt;code&gt;SUSPENDED&lt;/code&gt; on August 28?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;What caused &lt;code&gt;subscription-service&lt;/code&gt; to deactivate it on August 30?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Instead of searching blindly through telemetry, we have a timeline that tells us &lt;strong&gt;where to investigate.&lt;/strong&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Auditing Is More Than Compliance&lt;/h2&gt;

&lt;p&gt;When we hear the term &lt;em&gt;audit trail&lt;/em&gt;, it&#39;s natural to think about compliance.&lt;/p&gt;

&lt;p&gt;Who changed the record?&lt;/p&gt;

&lt;p&gt;When was it changed?&lt;/p&gt;

&lt;p&gt;Was the action authorized?&lt;/p&gt;

&lt;p&gt;Can we prove what the data looked like at a particular point in time?&lt;/p&gt;

&lt;p&gt;Those are important reasons to maintain an audit trail.&lt;/p&gt;

&lt;p&gt;But there is another use case that I think deserves much more attention:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Production support.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A well-designed audit trail can become one of the most useful diagnostic tools in a business application.&lt;/p&gt;

&lt;p&gt;Consider what each part of our operational toolbox gives us:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tool&lt;/th&gt;
      &lt;th&gt;Question it helps answer&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Logs&lt;/td&gt;
      &lt;td&gt;What was the application doing?&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Metrics&lt;/td&gt;
      &lt;td&gt;How was the system behaving?&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Distributed tracing&lt;/td&gt;
      &lt;td&gt;How did this request travel through the system?&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Audit history&lt;/td&gt;
      &lt;td&gt;What happened to the business data?&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;None of these replaces the others.&lt;/p&gt;

&lt;p&gt;They answer different questions.&lt;/p&gt;

&lt;p&gt;And when something goes wrong in production, having all of them can dramatically reduce the amount of guesswork involved in understanding what happened.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;The Problem Gets Harder in Distributed Systems&lt;/h2&gt;

&lt;p&gt;This distinction becomes even more important when a business operation crosses multiple components.&lt;/p&gt;

&lt;p&gt;A simple operation might actually look something like this:&lt;/p&gt;

&lt;pre&gt;Client
  ↓
API
  ↓
Application Service
  ↓
Database
  ↓
Event
  ↓
Another Service
  ↓
External System&lt;/pre&gt;

&lt;p&gt;Consider a payment.&lt;/p&gt;

&lt;p&gt;The payment might begin as:&lt;/p&gt;

&lt;pre&gt;PENDING&lt;/pre&gt;

&lt;p&gt;Then transition through:&lt;/p&gt;

&lt;pre&gt;PENDING
   ↓
PROCESSING
   ↓
AUTHORIZED
   ↓
COMPLETED&lt;/pre&gt;

&lt;p&gt;Or perhaps:&lt;/p&gt;

&lt;pre&gt;PENDING
   ↓
PROCESSING
   ↓
FAILED
   ↓
RETRYING
   ↓
COMPLETED&lt;/pre&gt;

&lt;p&gt;Several services, asynchronous messages, callbacks, and external systems may participate in those transitions.&lt;/p&gt;

&lt;p&gt;Hours or days later, someone asks:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Why did this payment end up in this state?”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The original HTTP request is no longer the interesting part of the investigation.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;state transitions&lt;/strong&gt; are.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;History Should Be an Application Capability&lt;/h2&gt;

&lt;p&gt;Many systems technically have audit information somewhere.&lt;/p&gt;

&lt;p&gt;Perhaps there are database triggers.&lt;/p&gt;

&lt;p&gt;Perhaps Hibernate Envers is enabled.&lt;/p&gt;

&lt;p&gt;Perhaps historical tables exist.&lt;/p&gt;

&lt;p&gt;But during an incident, a developer still has to open a database client and manually inspect those tables.&lt;/p&gt;

&lt;p&gt;That means the system has stored history, but it hasn&#39;t necessarily made that history &lt;strong&gt;usable&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I think audit history should be treated as an application capability.&lt;/p&gt;

&lt;p&gt;Support tools should be able to query it.&lt;/p&gt;

&lt;p&gt;Administrative interfaces should be able to display it.&lt;/p&gt;

&lt;p&gt;APIs should be able to expose it safely.&lt;/p&gt;

&lt;p&gt;Developers should be able to inspect it without understanding the internal schema of every audit table.&lt;/p&gt;

&lt;p&gt;And ideally, we should be able to move from:&lt;/p&gt;

&lt;pre&gt;Revision 42
Revision 43&lt;/pre&gt;

&lt;p&gt;to something much closer to what a human actually wants to know:&lt;/p&gt;

&lt;pre&gt;status:
PENDING → PROCESSING

amount:
100.00 → 125.00

changedBy:
payment-service

changedAt:
2026-09-01T10:31:42Z&lt;/pre&gt;

&lt;p&gt;That&#39;s where an audit trail starts becoming genuinely useful for production operations.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;This Is the Problem Behind NERV Audit&lt;/h2&gt;

&lt;p&gt;I&#39;ve encountered variations of this problem repeatedly while building and supporting enterprise Java applications.&lt;/p&gt;

&lt;p&gt;Hibernate Envers already provides a powerful foundation for maintaining entity revision history.&lt;/p&gt;

&lt;p&gt;But storing revisions is only part of the problem.&lt;/p&gt;

&lt;p&gt;Applications still need practical ways to retrieve those revisions, understand what changed, attach useful metadata, and expose that history to the people investigating the system.&lt;/p&gt;

&lt;p&gt;Instead of rebuilding those capabilities from project to project, I wanted them to become reusable.&lt;/p&gt;

&lt;p&gt;That is the motivation behind &lt;strong&gt;NERV Audit&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;NERV Audit is an open-source auditing library for Spring Boot built on top of Hibernate Envers.&lt;/p&gt;

&lt;p&gt;It doesn&#39;t try to replace Envers.&lt;/p&gt;

&lt;p&gt;It builds on it, with the goal of making audit history easier to &lt;strong&gt;query, understand, and use&lt;/strong&gt; in real applications.&lt;/p&gt;

&lt;p&gt;But this series isn&#39;t going to start by walking through library APIs.&lt;/p&gt;

&lt;p&gt;First, I want to explore the engineering problems that made the library necessary in the first place.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Coming Next: Logs Aren&#39;t an Audit Trail&lt;/h2&gt;

&lt;p&gt;Logs and audit history are sometimes treated as interchangeable sources of information.&lt;/p&gt;

&lt;p&gt;They aren&#39;t.&lt;/p&gt;

&lt;p&gt;In the next article, we&#39;ll look more closely at the difference between application logging and business-data auditing—and why production systems often need both.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The database tells you what is.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;An audit trail tells you what happened.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;And when you&#39;re investigating a production incident, that difference can matter enormously.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;strong&gt;NERV Audit&lt;/strong&gt; is part of the open-source NERV ecosystem: reusable Java and Spring components designed around problems encountered in real production systems.&lt;/p&gt;

&lt;p&gt;If you&#39;re interested in the project, you can follow the NERV repositories on GitHub and follow this series as we go deeper into production-ready auditing with Spring Boot and Hibernate Envers.&lt;/p&gt;

&lt;div style=&quot;border-left: 4px solid #f59e0b; margin: 32px 0; padding: 16px 20px;&quot;&gt;
  &lt;h3 style=&quot;margin-top: 0;&quot;&gt;Want to go deeper?&lt;/h3&gt;

  &lt;p&gt;
    Adding &lt;code&gt;@Audited&lt;/code&gt; is the easy part. Production auditing introduces
    harder problems around UTC timestamps, revision metadata, schema evolution,
    PostgreSQL compatibility, vertical history, and testing.
  &lt;/p&gt;

  &lt;p style=&quot;margin-bottom: 0;&quot;&gt;
    I explore those lessons in
    &lt;strong&gt;
      &lt;a href=&quot;https://czetsuya.medium.com/auditing-is-easy-until-production-hibernate-envers-db7b7db0ee8a&quot;
         target=&quot;_blank&quot;
         rel=&quot;noopener noreferrer&quot;&gt;
        Auditing Is Easy Until Production: What Hibernate Envers Doesn&#39;t Solve for You
      &lt;/a&gt;
    &lt;/strong&gt;
    on Medium.
  &lt;/p&gt;
&lt;/div&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/04/spring-boot-audit-trail-hibernate-envers.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Spring Boot Audit Trail Made Easy: Introducing nerv-audit (Hibernate Envers + JPA)
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Audit
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Audit&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;
    
    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/10/logs-arent-an-audit-trail-debugging-business-data.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Logs Aren&#39;t an Audit Trail: Debugging Business Data in Production
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/1940318442069326704/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/09/database-tells-you-what-is-audit-trail-tells-you-what-happened.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/1940318442069326704'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/1940318442069326704'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/09/database-tells-you-what-is-audit-trail-tells-you-what-happened.html' title='The Database Tells You What Is. An Audit Trail Tells You What Happened'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-3QBEviEVT-pCT4NiM-2JKNmbSFf6Rw2QGDx2R4D08fd7b3KoCTH9cl-yYkdXohKk_LqyJYGFOI5JDU3kPAJU5rh2jXKO-EnDIki0LsbK7CKCGGonTYunpeKsXWVu55i0DUyhmNyIoRWb565D6mbYumh9XnX9ZvIsZq5Rws1CCU7t1yAEuF5SEiJXXfK1/s72-c/nerv-audit-database-state-vs-audit-history.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-4932048346949529376</id><published>2026-09-24T07:42:47.621+08:00</published><updated>2026-10-17T11:04:48.491+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Algorithmic Trading"/><category scheme="http://www.blogger.com/atom/ns#" term="Binance"/><category scheme="http://www.blogger.com/atom/ns#" term="Event-Driven Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Trade"/><category scheme="http://www.blogger.com/atom/ns#" term="PostgreSQL"/><category scheme="http://www.blogger.com/atom/ns#" term="Software Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><category scheme="http://www.blogger.com/atom/ns#" term="Trading Systems"/><title type='text'>I Built a Trading Engine in Java — Here’s What It Took</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjka_mt1aar5WDdRBE0WuQqo41cnlQiMUgjx37pf_bChp1JgLXXoj-CBU60e8_sJNxL3hmFyBcSsCIy1jc7tn-z78cCHV8GRrBO_glVEIGxGSN7_kN3qk0r05m648chLaSwZJ7eGQxdK5Ed4TH1pdRN3-8Et5sDvOSkXc5AdfvNVoDTaU_4Xmxzh3fuoheB/s1774/nerv-trade-java-trading-engine-journey.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;NERV Trade Java trading engine architecture&quot; border=&quot;0&quot; data-original-height=&quot;887&quot; data-original-width=&quot;1774&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjka_mt1aar5WDdRBE0WuQqo41cnlQiMUgjx37pf_bChp1JgLXXoj-CBU60e8_sJNxL3hmFyBcSsCIy1jc7tn-z78cCHV8GRrBO_glVEIGxGSN7_kN3qk0r05m648chLaSwZJ7eGQxdK5Ed4TH1pdRN3-8Et5sDvOSkXc5AdfvNVoDTaU_4Xmxzh3fuoheB/s1600/nerv-trade-java-trading-engine-journey.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;h1&gt;I Built a Trading Engine in Java — Here’s What It Took&lt;/h1&gt;

&lt;p&gt;Generating a BUY or SELL signal was the easy part.&lt;/p&gt;

&lt;p&gt;Then came multi-timeframe synchronization, partial fills, duplicate executions, order uncertainty, transaction boundaries, application crashes, restart recovery, and eventually connecting the same engine to a real exchange.&lt;/p&gt;

&lt;p&gt;That&#39;s when a trading bot started becoming a trading engine.&lt;/p&gt;

&lt;p&gt;This is &lt;strong&gt;NERV Trade&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;It is a Java-based trading engine I&#39;ve been building as part of the NERV ecosystem. What started as a system for analyzing market data gradually became something much more interesting: an exercise in designing a deterministic, recoverable, broker-neutral trading architecture.&lt;/p&gt;

&lt;p&gt;And along the way, many of the hardest problems turned out to have very little to do with predicting the market.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;The System We Have Today&lt;/h2&gt;

&lt;p&gt;Before going back to the beginning, let me show you where the project has reached.&lt;/p&gt;

&lt;p&gt;At a high level, NERV Trade now looks something like this:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Market Data
    │
    ▼
M5 ──► M15 ──► H1 ──► H4
    │
    ▼
Analysis
    │
    ▼
Strategy
    │
    ▼
Risk
    │
    ▼
Trade Intent
    │
    ▼
Order Lifecycle
    │
    ├────────────────┐
    ▼                ▼
Simulator          Binance
                     │
                     ▼
               Executions
                     │
                     ▼
              Durable Lifecycle
              │      │       │
              ▼      ▼       ▼
          Position  P&amp;amp;L   Journal
&lt;/pre&gt;

&lt;p&gt;Market data enters the system and is transformed into deterministic multi-timeframe views. Analysis produces decisions. Strategy interprets those decisions. Risk determines whether they can proceed.&lt;/p&gt;

&lt;p&gt;From there, the problem changes.&lt;/p&gt;

&lt;p&gt;We are no longer analyzing the market.&lt;/p&gt;

&lt;p&gt;We are managing &lt;strong&gt;state&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;A Signal Is Not a Trade&lt;/h2&gt;

&lt;p&gt;This distinction became increasingly important as the project evolved.&lt;/p&gt;

&lt;p&gt;A trading strategy might say:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;SELL TSLA
&lt;/pre&gt;

&lt;p&gt;That looks simple.&lt;/p&gt;

&lt;p&gt;But what does it actually mean?&lt;/p&gt;

&lt;p&gt;Has an order been created?&lt;/p&gt;

&lt;p&gt;Has the broker received it?&lt;/p&gt;

&lt;p&gt;Has the broker acknowledged it?&lt;/p&gt;

&lt;p&gt;Has anything actually executed?&lt;/p&gt;

&lt;p&gt;Was it partially filled?&lt;/p&gt;

&lt;p&gt;Was the remaining quantity cancelled?&lt;/p&gt;

&lt;p&gt;Did another strategy already have exposure in the opposite direction?&lt;/p&gt;

&lt;p&gt;Has the resulting trade actually finished?&lt;/p&gt;

&lt;p&gt;Those are completely different states.&lt;/p&gt;

&lt;p&gt;One of the important architectural changes in NERV Trade was therefore separating concepts that are often casually treated as the same thing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;analysis decision,&lt;/li&gt;
  &lt;li&gt;strategy decision,&lt;/li&gt;
  &lt;li&gt;trade intent,&lt;/li&gt;
  &lt;li&gt;order,&lt;/li&gt;
  &lt;li&gt;broker order,&lt;/li&gt;
  &lt;li&gt;execution or fill,&lt;/li&gt;
  &lt;li&gt;position,&lt;/li&gt;
  &lt;li&gt;and completed trade outcome.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once these concepts became explicit, many other design decisions started to make sense.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;A Position Is Not a Trade Either&lt;/h2&gt;

&lt;p&gt;This was another deceptively important realization.&lt;/p&gt;

&lt;p&gt;Imagine two independent strategies trading the same instrument.&lt;/p&gt;

&lt;p&gt;Strategy A owns:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;+10
&lt;/pre&gt;

&lt;p&gt;while Strategy B owns:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;-4
&lt;/pre&gt;

&lt;p&gt;The aggregate position might be:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;+6
&lt;/pre&gt;

&lt;p&gt;But neither strategy owns a trade of +6.&lt;/p&gt;

&lt;p&gt;Each intent needs to own its own exposure, cost basis, realized profit and loss, orders, executions, and eventual outcome.&lt;/p&gt;

&lt;p&gt;The aggregate position is a &lt;strong&gt;derived view&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;That distinction became essential when we started testing reversals, partial exits, multiple orders, and independent strategies operating on the same instrument.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Then Partial Fills Arrive&lt;/h2&gt;

&lt;p&gt;Suppose NERV submits an order for 10 units.&lt;/p&gt;

&lt;p&gt;The broker doesn&#39;t necessarily respond with one neat execution of 10.&lt;/p&gt;

&lt;p&gt;Instead, the system might receive:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Fill #1: 3
Fill #2: 4
Fill #3: 3
&lt;/pre&gt;

&lt;p&gt;Now every execution matters.&lt;/p&gt;

&lt;p&gt;Order accounting must progress correctly.&lt;/p&gt;

&lt;p&gt;Intent exposure must change correctly.&lt;/p&gt;

&lt;p&gt;Cost basis must remain correct.&lt;/p&gt;

&lt;p&gt;Realized P&amp;amp;L must remain correct.&lt;/p&gt;

&lt;p&gt;And the lifecycle must know when the trade is actually finished.&lt;/p&gt;

&lt;p&gt;This led to another important rule:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A trade lifecycle is complete only when its exposure is flat and all of its orders are terminal.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Closing the position alone isn&#39;t sufficient.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Then the Same Fill Arrives Twice&lt;/h2&gt;

&lt;p&gt;Distributed systems make another uncomfortable promise:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;messages can repeat.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An execution can arrive through a live stream and later be rediscovered during reconciliation.&lt;/p&gt;

&lt;p&gt;Or the application might crash after receiving an execution and encounter it again after restart.&lt;/p&gt;

&lt;p&gt;If processing the same execution twice changes the position twice, a trading system has a serious problem.&lt;/p&gt;

&lt;p&gt;So execution identity became a first-class concern.&lt;/p&gt;

&lt;p&gt;NERV Trade now treats accepted executions as durable identities. Replaying an already accepted execution must not change:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;filled quantity,&lt;/li&gt;
  &lt;li&gt;intent exposure,&lt;/li&gt;
  &lt;li&gt;position,&lt;/li&gt;
  &lt;li&gt;realized P&amp;amp;L,&lt;/li&gt;
  &lt;li&gt;lifecycle completion,&lt;/li&gt;
  &lt;li&gt;or journal outcome.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Idempotency isn&#39;t an optimization here.&lt;/p&gt;

&lt;p&gt;It&#39;s part of correctness.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;The Hardest Order Is the One You Don&#39;t Know Exists&lt;/h2&gt;

&lt;p&gt;Consider a more interesting failure.&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;NERV
  │
  │ submit order
  ▼
Broker
  │
  │ order accepted
  ▼
Network connection dies
&lt;/pre&gt;

&lt;p&gt;NERV never receives the response.&lt;/p&gt;

&lt;p&gt;What should it do?&lt;/p&gt;

&lt;p&gt;Retrying sounds reasonable.&lt;/p&gt;

&lt;p&gt;But perhaps the first order already exists.&lt;/p&gt;

&lt;p&gt;A blind retry could create a second real order.&lt;/p&gt;

&lt;p&gt;Marking the first attempt as failed isn&#39;t correct either, because we don&#39;t actually know that it failed.&lt;/p&gt;

&lt;p&gt;The truthful state is:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;uncertain.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;NERV therefore preserves uncertain submissions and relies on stable order identities and broker reconciliation to determine what actually happened.&lt;/p&gt;

&lt;p&gt;Until that uncertainty is resolved, it does not blindly resubmit the order.&lt;/p&gt;

&lt;p&gt;This was one of those moments where modeling reality accurately mattered more than finding a convenient status value.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Transactions Became a Trading Problem&lt;/h2&gt;

&lt;p&gt;Eventually persistence entered the picture.&lt;/p&gt;

&lt;p&gt;Processing an execution can modify several related pieces of state:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Execution
    │
    ├──► Order accounting
    │
    ├──► Intent exposure
    │
    ├──► Cost basis
    │
    ├──► Realized P&amp;amp;L
    │
    ├──► Lifecycle completion
    │
    └──► Journal outcome
&lt;/pre&gt;

&lt;p&gt;What happens if the process crashes halfway through?&lt;/p&gt;

&lt;p&gt;Before durable persistence, failure testing exposed exactly this kind of weakness: in-memory state could be partially mutated before an unexpected exception occurred.&lt;/p&gt;

&lt;p&gt;That discovery influenced the persistence architecture.&lt;/p&gt;

&lt;p&gt;When an execution is accepted now, its identity and the lifecycle state affected by that execution are committed atomically in PostgreSQL.&lt;/p&gt;

&lt;p&gt;Either the execution is processed as a unit, or it isn&#39;t.&lt;/p&gt;

&lt;p&gt;That sounds obvious when stated afterward.&lt;/p&gt;

&lt;p&gt;It wasn&#39;t obvious when the project began.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;And Then the Application Restarts&lt;/h2&gt;

&lt;p&gt;Persistence isn&#39;t very useful if the application cannot reconstruct what it was doing.&lt;/p&gt;

&lt;p&gt;Restart recovery therefore became another milestone.&lt;/p&gt;

&lt;p&gt;NERV Trade persists enough lifecycle information to recover:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;decisions,&lt;/li&gt;
  &lt;li&gt;trade intents,&lt;/li&gt;
  &lt;li&gt;orders,&lt;/li&gt;
  &lt;li&gt;broker mappings,&lt;/li&gt;
  &lt;li&gt;accepted executions,&lt;/li&gt;
  &lt;li&gt;exposure and accounting state,&lt;/li&gt;
  &lt;li&gt;and completed outcomes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;More importantly, recovery follows a conservative rule.&lt;/p&gt;

&lt;p&gt;If an order was in an uncertain state when the application stopped, restarting the application does &lt;strong&gt;not&lt;/strong&gt; automatically submit it again.&lt;/p&gt;

&lt;p&gt;The external broker must first be reconciled.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;The Simulator Became More Than a Simulator&lt;/h2&gt;

&lt;p&gt;One of the most useful pieces of NERV Trade has been its deterministic simulator.&lt;/p&gt;

&lt;p&gt;Originally, simulation might sound like something used primarily to test strategies.&lt;/p&gt;

&lt;p&gt;Instead, it became our reference implementation for the entire execution pipeline.&lt;/p&gt;

&lt;p&gt;Given the same market data, we can verify the same analysis, strategy decision, risk decision, order, execution, and resulting position.&lt;/p&gt;

&lt;p&gt;That allowed architectural changes to happen while continuously checking that the trading pipeline still behaved deterministically.&lt;/p&gt;

&lt;p&gt;By the time persistence and recovery were introduced, hundreds of automated tests were exercising the architecture.&lt;/p&gt;

&lt;p&gt;But there was still an important limitation.&lt;/p&gt;

&lt;p&gt;Everything was happening inside an environment we controlled.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;So We Connected It to Binance&lt;/h2&gt;

&lt;p&gt;This changed the nature of the project again.&lt;/p&gt;

&lt;p&gt;Instead of teaching NERV Trade about Binance internally, the goal was to keep the trading engine broker-neutral.&lt;/p&gt;

&lt;p&gt;Binance became an adapter around the existing architecture.&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;                 NERV Trade

 Analysis / Strategy / Risk / Lifecycle
                    │
                    ▼
                BrokerPort
                    │
                    ▼
           Binance Adapter
                    │
                    ▼
          Binance Spot Testnet
                    │
                 fills
                    │
                    ▼
          ExecutionReportPort
                    │
                    ▼
           Durable Lifecycle
&lt;/pre&gt;

&lt;p&gt;Binance owns exchange-specific concerns:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;authentication,&lt;/li&gt;
  &lt;li&gt;symbols,&lt;/li&gt;
  &lt;li&gt;exchange filters,&lt;/li&gt;
  &lt;li&gt;order submission,&lt;/li&gt;
  &lt;li&gt;exchange order identities,&lt;/li&gt;
  &lt;li&gt;WebSocket communication,&lt;/li&gt;
  &lt;li&gt;and reconciliation inputs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;NERV continues to own:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;analysis,&lt;/li&gt;
  &lt;li&gt;strategy,&lt;/li&gt;
  &lt;li&gt;risk,&lt;/li&gt;
  &lt;li&gt;trade intent,&lt;/li&gt;
  &lt;li&gt;order lifecycle,&lt;/li&gt;
  &lt;li&gt;execution processing,&lt;/li&gt;
  &lt;li&gt;positions,&lt;/li&gt;
  &lt;li&gt;P&amp;amp;L,&lt;/li&gt;
  &lt;li&gt;and trade outcomes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That boundary matters because Binance isn&#39;t intended to be the last broker.&lt;/p&gt;

&lt;p&gt;A trading engine shouldn&#39;t need a new lifecycle architecture every time another venue is introduced.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;935 Tests Later...&lt;/h2&gt;

&lt;p&gt;At the end of the first Binance Spot Testnet adapter milestone, NERV Trade had reached &lt;strong&gt;935 automated tests&lt;/strong&gt; with zero failures, errors, or skipped tests.&lt;/p&gt;

&lt;p&gt;The original deterministic simulator still produced the expected result after the Binance integration was introduced.&lt;/p&gt;

&lt;p&gt;That was important.&lt;/p&gt;

&lt;p&gt;Adding a real exchange adapter should not silently change the behavior of the core trading engine.&lt;/p&gt;

&lt;p&gt;But 935 green tests don&#39;t prove that an exchange integration works.&lt;/p&gt;

&lt;p&gt;They prove that the system behaves according to the assumptions encoded in those tests.&lt;/p&gt;

&lt;p&gt;The next question is much more interesting:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;What happens when those assumptions meet a real exchange?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That&#39;s where the next stage of NERV Trade begins.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;This Isn&#39;t a Series About Predicting the Market&lt;/h2&gt;

&lt;p&gt;There will certainly be articles about analysis, strategies, scoring, and multi-timeframe market data.&lt;/p&gt;

&lt;p&gt;But the deeper theme of this series is software architecture.&lt;/p&gt;

&lt;p&gt;We&#39;ll look at questions such as:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;How do you build deterministic multi-timeframe analysis without accidentally using future data?&lt;/li&gt;
  &lt;li&gt;Who should actually own a trading decision?&lt;/li&gt;
  &lt;li&gt;Why isn&#39;t a position the same thing as a trade?&lt;/li&gt;
  &lt;li&gt;How should partial fills change lifecycle state?&lt;/li&gt;
  &lt;li&gt;How do you make execution processing idempotent?&lt;/li&gt;
  &lt;li&gt;What happens when a broker receives an order but your application never receives the response?&lt;/li&gt;
  &lt;li&gt;Where should transaction boundaries exist in a trading system?&lt;/li&gt;
  &lt;li&gt;What needs to survive an application restart?&lt;/li&gt;
  &lt;li&gt;How do live execution events and broker reconciliation coexist without double-counting fills?&lt;/li&gt;
  &lt;li&gt;Can the same architecture survive integration with fundamentally different brokers?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These are the problems that turned NERV Trade into a much more interesting engineering project than I originally expected.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Back to the Beginning&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;NERV Trade didn&#39;t start with this architecture.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It evolved as increasingly difficult problems exposed weaknesses in the previous design. Each one—multi-timeframe analysis, execution ownership, partial fills, idempotency, transaction boundaries, restart recovery, and eventually connecting to a real exchange—forced another architectural decision.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This series documents that journey.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Not just the final architecture.&lt;/p&gt;

&lt;p&gt;The mistakes, the tests that exposed them, the alternatives we considered, the boundaries that had to move, and the reasoning behind the system that exists today.&lt;/p&gt;

&lt;p&gt;In the next article, we&#39;ll go back to where NERV Trade actually started—and follow the architecture forward from there.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;em&gt;NERV Trade is part of NERV — Next-Generation Engineering for Runtime Velocity. The project explores production-oriented architecture for trading systems using Java and the broader NERV ecosystem.&lt;/em&gt;&lt;/p&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Trade
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Trade&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;
    
    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/10/a-trading-bot-is-easy-trading-engine-is-not.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
		A Trading Bot Is Easy. A Trading Engine Is Not
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/4932048346949529376/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/09/i-built-a-trading-engine-in-java.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/4932048346949529376'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/4932048346949529376'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/09/i-built-a-trading-engine-in-java.html' title='I Built a Trading Engine in Java — Here’s What It Took'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjka_mt1aar5WDdRBE0WuQqo41cnlQiMUgjx37pf_bChp1JgLXXoj-CBU60e8_sJNxL3hmFyBcSsCIy1jc7tn-z78cCHV8GRrBO_glVEIGxGSN7_kN3qk0r05m648chLaSwZJ7eGQxdK5Ed4TH1pdRN3-8Et5sDvOSkXc5AdfvNVoDTaU_4Xmxzh3fuoheB/s72-c/nerv-trade-java-trading-engine-journey.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-6583045428737904337</id><published>2026-09-16T10:12:40.520+08:00</published><updated>2026-10-17T11:16:15.767+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Distributed Systems"/><category scheme="http://www.blogger.com/atom/ns#" term="Event-Driven Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Inbox Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Event"/><category scheme="http://www.blogger.com/atom/ns#" term="Outbox Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Payment Systems"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><category scheme="http://www.blogger.com/atom/ns#" term="Transactions"/><title type='text'>Handling Long-Running Transactions in Spring Boot with NERV Event</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7zjMiaKZmXfv3KkMeKt7zIH1Plcqat6lKOdkc_FLyWa4EfNTTuVZ9Wycf9x9YfQjURFYuSlMHRIo5cfh__agMSUpRDB4JPVm5-zqsZ2RnoFHBZwqeXMUOXYGirATNQveydq_u2Wv60DKUGCe8K-Uh8UxFpwAmNYb5lop1kRLVSfycuOaNK2P73fukLeb0/s1600/nerv-event-long-running-payment-workflows.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;&quot; border=&quot;0&quot; data-original-height=&quot;887&quot; data-original-width=&quot;1774&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7zjMiaKZmXfv3KkMeKt7zIH1Plcqat6lKOdkc_FLyWa4EfNTTuVZ9Wycf9x9YfQjURFYuSlMHRIo5cfh__agMSUpRDB4JPVm5-zqsZ2RnoFHBZwqeXMUOXYGirATNQveydq_u2Wv60DKUGCe8K-Uh8UxFpwAmNYb5lop1kRLVSfycuOaNK2P73fukLeb0/s1600/nerv-event-long-running-payment-workflows.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;p&gt;
What happens when an event-driven application needs to perform an operation that can take &lt;strong&gt;30 minutes&lt;/strong&gt;?
&lt;/p&gt;

&lt;p&gt;
This question came up while integrating &lt;strong&gt;NERV Event&lt;/strong&gt; into a realistic payment workflow.
&lt;/p&gt;

&lt;p&gt;
A payment request arrives. We need to persist it, submit it to a third-party payment system, wait for validation, update our local payment state, and eventually publish the result.
&lt;/p&gt;

&lt;p&gt;
The complication is that the third-party system may take 30 minutes — or potentially much longer — before producing a final result.
&lt;/p&gt;

&lt;p&gt;
At first, this sounds like a transaction-management problem:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
Which Spring transaction propagation should we use for the 30-minute operation?
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
But that&#39;s not really the right question.
&lt;/p&gt;

&lt;p&gt;
The better question is:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
&lt;strong&gt;How do we make a 30-minute business process durable without keeping a database transaction, Java thread, or event handler alive for 30 minutes?&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
The answer changes the architecture considerably.
&lt;/p&gt;

&lt;p&gt;
A 30-minute payment isn&#39;t a 30-minute transaction.
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;It&#39;s a durable workflow containing several very short transactions.&lt;/strong&gt;
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;1. Why a 30-Minute Database Transaction Is the Wrong Model&lt;/h2&gt;

&lt;p&gt;
Consider the naive implementation:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@Transactional
public void processPayment(PaymentRequest request) {

    Payment payment = repository.save(...);

    PaymentResult result =
        paymentGateway.validate(request);

    payment.complete(result);

    eventPublisher.publish(...);
}
&lt;/pre&gt;

&lt;p&gt;
If &lt;code&gt;paymentGateway.validate()&lt;/code&gt; takes 30 minutes, the transaction potentially spans the entire external operation:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;BEGIN TRANSACTION
      |
      +-- INSERT payment
      |
      +-- Call payment gateway
      |       |
      |       +-- wait...
      |       +-- wait...
      |       +-- 30 minutes
      |
      +-- UPDATE payment
      |
      +-- INSERT Outbox event
      |
COMMIT
&lt;/pre&gt;

&lt;p&gt;
This can create several operational problems:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;long-held database connections;&lt;/li&gt;
  &lt;li&gt;long-lived locks;&lt;/li&gt;
  &lt;li&gt;connection-pool pressure;&lt;/li&gt;
  &lt;li&gt;larger contention windows;&lt;/li&gt;
  &lt;li&gt;transaction timeouts;&lt;/li&gt;
  &lt;li&gt;more complicated failure recovery;&lt;/li&gt;
  &lt;li&gt;and poor scalability under concurrent workloads.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
More importantly, the transaction does not give us the guarantee we might think it does.
&lt;/p&gt;

&lt;p&gt;
Our local database cannot roll back an operation that already succeeded inside an external payment system.
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
&lt;strong&gt;A Spring database transaction does not turn an external HTTP request into part of the same ACID transaction.&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
So holding the transaction open for 30 minutes gives us significant cost without providing distributed atomicity.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;2. The First Improvement: Short Transactions Around External Work&lt;/h2&gt;

&lt;p&gt;
A better first step is to separate local database work from the external operation.
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;SHORT TX
+--------------------------+
| Create payment           |
| status = VALIDATING      |
|                          |
| COMMIT                   |
+--------------------------+
             |
             v
       NO TRANSACTION
+--------------------------+
| Third-party validation   |
|                          |
| 30+ minutes              |
+--------------------------+
             |
             v
SHORT TX
+--------------------------+
| Update payment           |
| SUCCESS / FAILED         |
|                          |
| Insert Outbox event      |
|                          |
| COMMIT                   |
+--------------------------+
&lt;/pre&gt;

&lt;p&gt;
In Spring, an orchestrator could explicitly refuse to participate in a transaction:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@Service
@RequiredArgsConstructor
public class PaymentService {

    private final PaymentTransactionService txService;
    private final PaymentGatewayClient gateway;

    @Transactional(
        propagation = Propagation.NEVER
    )
    public void processPayment(
        PaymentRequest request) {

        Long paymentId =
            txService.create(request);

        PaymentValidationResult result =
            gateway.validate(
                paymentId,
                request);

        txService.complete(
            paymentId,
            result);
    }
}
&lt;/pre&gt;

&lt;p&gt;
The database operations can then use short independent transactions:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@Transactional(
    propagation = Propagation.REQUIRES_NEW
)
public Long create(PaymentRequest request) {

    Payment payment = new Payment();

    payment.setStatus(
        PaymentStatus.VALIDATING);

    return repository
        .save(payment)
        .getId();
}
&lt;/pre&gt;

&lt;p&gt;
while the external integration explicitly avoids transaction participation:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@Transactional(
    propagation = Propagation.NOT_SUPPORTED
)
public PaymentValidationResult validate(...) {

    return paymentGatewayApi.validate(...);
}
&lt;/pre&gt;

&lt;p&gt;
This gives us a useful transaction policy:
&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Component&lt;/th&gt;
      &lt;th&gt;Propagation&lt;/th&gt;
      &lt;th&gt;Purpose&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Long-running orchestrator&lt;/td&gt;
      &lt;td&gt;&lt;code&gt;NEVER&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Prevent the workflow from inheriting a transaction&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Database operation&lt;/td&gt;
      &lt;td&gt;&lt;code&gt;REQUIRES_NEW&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Short, isolated database transaction&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;External gateway&lt;/td&gt;
      &lt;td&gt;&lt;code&gt;NOT_SUPPORTED&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Keep remote I/O outside database transactions&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;
This solves the long database transaction.
&lt;/p&gt;

&lt;p&gt;
But for a 30-minute operation, &lt;strong&gt;it still isn&#39;t enough&lt;/strong&gt;.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;3. The Reliability Gap&lt;/h2&gt;

&lt;p&gt;
Suppose the payment workflow starts from a &lt;code&gt;PaymentRequested&lt;/code&gt; event consumed through NERV Event.
&lt;/p&gt;

&lt;p&gt;
NERV Event 2.1 atomically commits local Inbox handler effects together with the Inbox transition to &lt;code&gt;PROCESSED&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
We might therefore implement:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@NervEventHandler
public void handle(PaymentRequested event) {

    payment.setStatus(
        PaymentStatus.VALIDATION_PENDING);
}
&lt;/pre&gt;

&lt;p&gt;
NERV then commits:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;BEGIN TRANSACTION

    payment = VALIDATION_PENDING

    Inbox(PaymentRequested)
        = PROCESSED

COMMIT
&lt;/pre&gt;

&lt;p&gt;
So far, this is correct.
&lt;/p&gt;

&lt;p&gt;
The problem appears afterward.
&lt;/p&gt;

&lt;p&gt;
Suppose we start a detached worker:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Inbox = PROCESSED
       |
       v
Gateway validation
       |
       | 30 minutes
       v
Gateway = SUCCESS
       |
       v
completePayment()
       |
       X
Database failure
&lt;/pre&gt;

&lt;p&gt;
We now have:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Inbox
    = PROCESSED

Local Payment
    = VALIDATION_PENDING

Payment Gateway
    = SUCCESS

Outbox
    = NOTHING
&lt;/pre&gt;

&lt;p&gt;
And this is the important part:
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;NERV Inbox will not retry &lt;code&gt;PaymentRequested&lt;/code&gt;.&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;
It shouldn&#39;t.
&lt;/p&gt;

&lt;p&gt;
The original event was already processed successfully.
&lt;/p&gt;

&lt;p&gt;
The problem is that we allowed the transition from Inbox processing to long-running work to become an &lt;strong&gt;in-memory handoff&lt;/strong&gt;.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;4. Every Important Handoff Must Be Durable&lt;/h2&gt;

&lt;p&gt;
The Inbox handler should not merely update:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;payment = VALIDATION_PENDING
&lt;/pre&gt;

&lt;p&gt;
It should also durably schedule the next step before the Inbox event becomes &lt;code&gt;PROCESSED&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
NERV Event already gives us a natural mechanism for this:
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;the transactional Outbox.&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;
The Inbox transaction becomes:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;BEGIN TRANSACTION

    payment =
        VALIDATION_PENDING

          +

    Outbox =
        StartPaymentValidation

          +

    Inbox(PaymentRequested) =
        PROCESSED

COMMIT
&lt;/pre&gt;

&lt;p&gt;
Now we have a much stronger invariant:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
&lt;strong&gt;PaymentRequested can never become PROCESSED without durably scheduling the next step of the payment workflow.&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
If the transaction fails, all three changes roll back.
&lt;/p&gt;

&lt;p&gt;
NERV can retry the Inbox event.
&lt;/p&gt;

&lt;p&gt;
If the transaction succeeds, the next workflow step exists durably in the Outbox.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;5. Publishing the Next Workflow Step&lt;/h2&gt;

&lt;p&gt;
Conceptually, our Inbox handler now looks like:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@NervEventHandler
public void handle(PaymentRequested event) {

    Payment payment =
        repository.findById(
            event.paymentId())
            .orElseThrow();

    payment.setStatus(
        PaymentStatus.VALIDATION_PENDING);

    eventPublisher.publish(
        new EventPublication(
            &quot;START_PAYMENT_VALIDATION&quot;,
            event.paymentId().toString(),
            event.paymentId().toString()
        )
    );
}
&lt;/pre&gt;

&lt;p&gt;
Because the handler executes inside the NERV Inbox transaction, the business-state change and Outbox insertion participate in the same local transaction as Inbox completion.
&lt;/p&gt;

&lt;p&gt;
The resulting flow becomes:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;PaymentRequested
       |
       v
+------------------------------+
| NERV Inbox Transaction       |
|                              |
| Payment                      |
|   -&amp;gt; VALIDATION_PENDING       |
|                              |
| Outbox                       |
|   + StartPaymentValidation   |
|                              |
| Inbox                        |
|   -&amp;gt; PROCESSED                |
+------------------------------+
       |
       v
     COMMIT
       |
       v
 NERV Outbox Dispatcher
       |
       v
StartPaymentValidation
&lt;/pre&gt;

&lt;p&gt;
We&#39;ve now made the transition to the next workflow step durable.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;6. But Don&#39;t Move the 30-Minute Transaction to Another Consumer&lt;/h2&gt;

&lt;p&gt;
At this point it is tempting to create another NERV Inbox handler:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@NervEventHandler
public void validate(
    StartPaymentValidation event) {

    paymentGateway.validate(event);

    // potentially 30+ minutes
}
&lt;/pre&gt;

&lt;p&gt;
But that recreates the original problem somewhere else.
&lt;/p&gt;

&lt;p&gt;
The NERV Inbox transaction would remain active while the handler waits for the payment gateway.
&lt;/p&gt;

&lt;p&gt;
We haven&#39;t solved the long-running transaction.
&lt;/p&gt;

&lt;p&gt;
We&#39;ve only moved it.
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
&lt;strong&gt;Long-running external work should not execute inside a transactional event handler.&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2&gt;7. Treat the Payment Gateway as an Asynchronous Process&lt;/h2&gt;

&lt;p&gt;
If a payment provider genuinely takes 30 minutes to determine a result, the integration should ideally be modeled asynchronously.
&lt;/p&gt;

&lt;p&gt;
Instead of:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;POST payment
     |
     | block for 30 minutes
     |
     v
return result
&lt;/pre&gt;

&lt;p&gt;
prefer:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Submit Validation
       |
       v
Gateway accepts request
       |
       v
Persist external reference
       |
       v
Return
&lt;/pre&gt;

&lt;p&gt;
The provider processes the payment independently.
&lt;/p&gt;

&lt;p&gt;
The result arrives later through:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;a webhook;&lt;/li&gt;
  &lt;li&gt;a callback;&lt;/li&gt;
  &lt;li&gt;a status API;&lt;/li&gt;
  &lt;li&gt;or durable polling.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Now no application thread needs to wait for 30 minutes.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;8. Callback-Based Payment Completion&lt;/h2&gt;

&lt;p&gt;
If the gateway supports callbacks, the architecture becomes:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;PaymentRequested
       |
       v
NERV Inbox
       |
       | SHORT TX
       v
VALIDATION_PENDING
       +
Outbox StartValidation
       +
Inbox PROCESSED
       |
       v
     COMMIT
       |
       v
NERV Outbox
       |
       v
Validation Worker
       |
       | NO LONG DB TX
       v
Submit to Gateway
       |
       v
Gateway Processing
       |
       | 30+ minutes
       v
Webhook / Callback
       |
       v
SHORT TRANSACTION
       |
       +-- Payment = SUCCESS / FAILED
       |
       +-- Outbox = PaymentCompleted
       |
       v
     COMMIT
       |
       v
NERV Outbox
       |
       v
Kafka / SQS
&lt;/pre&gt;

&lt;p&gt;
The 30-minute period exists entirely outside a local database transaction.
&lt;/p&gt;

&lt;p&gt;
And more importantly, the application does not need to remain alive for those 30 minutes.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;9. What If the Gateway Doesn&#39;t Support Callbacks?&lt;/h2&gt;

&lt;p&gt;
Then we can use durable polling.
&lt;/p&gt;

&lt;p&gt;
After submitting the payment, persist:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;payment.status =
    VALIDATION_PENDING

gatewayRequestId =
    ABC123

nextCheckAt =
    2026-09-16T10:30:00Z
&lt;/pre&gt;

&lt;p&gt;
A worker later finds records whose &lt;code&gt;nextCheckAt&lt;/code&gt; has arrived:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;VALIDATION_PENDING
       |
       v
nextCheckAt reached
       |
       v
GET gateway/status/ABC123
       |
       +-- PENDING
       |      |
       |      v
       |  update nextCheckAt
       |
       +-- SUCCESS
       |      |
       |      v
       |  complete payment
       |
       +-- FAILED
              |
              v
          fail payment
&lt;/pre&gt;

&lt;p&gt;
Each database update is a short transaction.
&lt;/p&gt;

&lt;p&gt;
No thread sleeps for 30 minutes.
&lt;/p&gt;

&lt;p&gt;
No database transaction waits for 30 minutes.
&lt;/p&gt;

&lt;p&gt;
And application restarts do not destroy the workflow because the current state is persisted.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;10. The Hardest Failure Window&lt;/h2&gt;

&lt;p&gt;
Now consider the most interesting failure:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Payment Gateway
       |
       v
SUCCESS
       |
       v
Local completion TX
       |
       +-- payment = SUCCESS
       |
       +-- Outbox PaymentCompleted
       |
       X
Database failure
       |
       v
ROLLBACK
&lt;/pre&gt;

&lt;p&gt;
Locally, the transaction correctly rolls everything back:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Payment
    = VALIDATION_PENDING

Outbox
    = NOTHING
&lt;/pre&gt;

&lt;p&gt;
But the external system already says:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Payment Gateway
    = SUCCESS
&lt;/pre&gt;

&lt;p&gt;
Our database transaction cannot undo that.
&lt;/p&gt;

&lt;p&gt;
This is the fundamental consistency boundary between our application and the external payment provider.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;11. Idempotency and Reconciliation Close the Gap&lt;/h2&gt;

&lt;p&gt;
The external payment request should use a stable idempotency identifier whenever the provider supports one.
&lt;/p&gt;

&lt;p&gt;
For example:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;paymentId
    |
    v
Idempotency-Key
    |
    v
Payment Gateway
&lt;/pre&gt;

&lt;p&gt;
We should also retain the provider&#39;s external transaction reference:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Payment
-------------------------
id
status
idempotencyKey
gatewayTransactionId
validationStartedAt
validationCompletedAt
nextCheckAt
&lt;/pre&gt;

&lt;p&gt;
If our local completion transaction fails, we don&#39;t blindly create another payment.
&lt;/p&gt;

&lt;p&gt;
Instead, we reconcile:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Local Payment
    = VALIDATION_PENDING
          |
          v
Query Gateway
using gatewayTransactionId
          |
          v
Gateway says SUCCESS
          |
          v
REQUIRES_NEW
+---------------------------+
| payment = SUCCESS         |
|                           |
| gatewayRef = ABC123       |
|                           |
| Outbox                    |
|   + PaymentCompleted      |
|                           |
| COMMIT                    |
+---------------------------+
&lt;/pre&gt;

&lt;p&gt;
If that transaction fails again, reconciliation can retry again.
&lt;/p&gt;

&lt;p&gt;
The external payment is not duplicated because we&#39;re referring to the same logical operation.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;12. NERV Event Handles the Local Atomicity Boundary&lt;/h2&gt;

&lt;p&gt;
Once we know the external result, NERV Event gives us a strong local guarantee.
&lt;/p&gt;

&lt;p&gt;
The final transaction contains:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;BEGIN TRANSACTION

    payment.status =
        SUCCESS

          +

    payment.gatewayRef =
        ABC123

          +

    Outbox =
        PaymentCompleted

COMMIT
&lt;/pre&gt;

&lt;p&gt;
This means we cannot commit:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Payment = SUCCESS
&lt;/pre&gt;

&lt;p&gt;
without also durably recording:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;PaymentCompleted
&lt;/pre&gt;

&lt;p&gt;
for eventual delivery.
&lt;/p&gt;

&lt;p&gt;
If Kafka or SQS is unavailable afterward, that is no longer the payment transaction&#39;s problem.
&lt;/p&gt;

&lt;p&gt;
The Outbox record already exists.
&lt;/p&gt;

&lt;p&gt;
NERV Event can retry delivery independently.
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Payment SUCCESS
       |
       v
Outbox PaymentCompleted
       |
       | broker unavailable
       X
       |
       | retry
       | retry
       v
Kafka / SQS
&lt;/pre&gt;

&lt;hr /&gt;

&lt;h2&gt;13. Three Different Failure Boundaries, Three Different Mechanisms&lt;/h2&gt;

&lt;p&gt;
This payment workflow reveals an important architectural principle.
&lt;/p&gt;

&lt;p&gt;
There isn&#39;t one reliability mechanism that solves every failure.
&lt;/p&gt;

&lt;p&gt;
There are several boundaries:
&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Boundary&lt;/th&gt;
      &lt;th&gt;Failure&lt;/th&gt;
      &lt;th&gt;Mechanism&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Inbox + local handler effects&lt;/td&gt;
      &lt;td&gt;Handler or DB failure&lt;/td&gt;
      &lt;td&gt;NERV Inbox transaction + retry&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Workflow step handoff&lt;/td&gt;
      &lt;td&gt;Application crashes after Inbox completion&lt;/td&gt;
      &lt;td&gt;Transactional Outbox&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Application + payment gateway&lt;/td&gt;
      &lt;td&gt;Unknown or externally committed result&lt;/td&gt;
      &lt;td&gt;Idempotency + reconciliation&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Payment state + completion event&lt;/td&gt;
      &lt;td&gt;Local DB failure&lt;/td&gt;
      &lt;td&gt;Database transaction + NERV Outbox&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Outbox + Kafka/SQS&lt;/td&gt;
      &lt;td&gt;Broker unavailable&lt;/td&gt;
      &lt;td&gt;NERV durable dispatch + retry&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;
Trying to solve all of these with one giant transaction is both unrealistic and unnecessary.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;14. The Complete Durable Payment Workflow&lt;/h2&gt;

&lt;p&gt;
Putting everything together gives us:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;PaymentRequested
       |
       v
+-------------------------------+
| NERV Inbox TX                 |
|                               |
| Payment                       |
|   -&amp;gt; VALIDATION_PENDING        |
|                               |
| Outbox                        |
|   + StartPaymentValidation    |
|                               |
| Inbox                         |
|   -&amp;gt; PROCESSED                 |
+-------------------------------+
       |
       v
     COMMIT
       |
       v
+-------------------------------+
| NERV Outbox                   |
|                               |
| durable delivery              |
+-------------------------------+
       |
       v
StartPaymentValidation
       |
       v
+-------------------------------+
| Submit to Payment Gateway     |
|                               |
| idempotencyKey = paymentId    |
|                               |
| NO LONG DB TRANSACTION        |
+-------------------------------+
       |
       v
 Gateway processing
       |
       | 30+ minutes
       |
       +----------------------+
       |                      |
       v                      v
    callback             durable polling
       |                      |
       +----------+-----------+
                  |
                  v
          Gateway Result
                  |
                  v
+--------------------------------+
| SHORT COMPLETION TX            |
|                                |
| Payment = SUCCESS / FAILED     |
|                                |
| Save gateway reference         |
|                                |
| Outbox                         |
|   + PaymentCompleted           |
+--------------------------------+
                  |
                  v
                COMMIT
                  |
                  v
+--------------------------------+
| NERV Outbox                    |
|                                |
| Kafka / SQS                    |
+--------------------------------+
&lt;/pre&gt;

&lt;p&gt;
Notice what is missing from this architecture:
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;There is no 30-minute database transaction.&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;
There isn&#39;t even necessarily a 30-minute Java method.
&lt;/p&gt;

&lt;p&gt;
Instead, we have a sequence of durable state transitions.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;15. Transaction Boundaries Should Follow Consistency Boundaries&lt;/h2&gt;

&lt;p&gt;
This is the broader lesson.
&lt;/p&gt;

&lt;p&gt;
A Java method might represent one business operation:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;processPayment()
&lt;/pre&gt;

&lt;p&gt;
but that does not mean one database transaction should span the entire business operation.
&lt;/p&gt;

&lt;p&gt;
The transaction boundary should follow what the local database can actually guarantee atomically.
&lt;/p&gt;

&lt;p&gt;
For example:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Local state
    +
Outbox event
    =
one transaction
&lt;/pre&gt;

&lt;p&gt;
and:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Inbox completion
    +
local handler effects
    +
next durable workflow step
    =
one transaction
&lt;/pre&gt;

&lt;p&gt;
But:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Local database
    +
30-minute remote operation
&lt;/pre&gt;

&lt;p&gt;
is not one useful ACID boundary.
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
&lt;strong&gt;Transaction boundaries should follow consistency boundaries, not method boundaries.&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2&gt;16. This Pattern Isn&#39;t Just for Payments&lt;/h2&gt;

&lt;p&gt;
The same architecture applies whenever external work is slow, unpredictable, or asynchronous:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;payment authorization;&lt;/li&gt;
  &lt;li&gt;fraud analysis;&lt;/li&gt;
  &lt;li&gt;identity verification;&lt;/li&gt;
  &lt;li&gt;document processing;&lt;/li&gt;
  &lt;li&gt;AI inference;&lt;/li&gt;
  &lt;li&gt;large file processing;&lt;/li&gt;
  &lt;li&gt;third-party provisioning;&lt;/li&gt;
  &lt;li&gt;shipping operations;&lt;/li&gt;
  &lt;li&gt;external approval workflows;&lt;/li&gt;
  &lt;li&gt;and long-running integrations.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The common structure is:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;SHORT TX
    |
    v
DURABLE STATE
    |
    v
DURABLE HANDOFF
    |
    v
EXTERNAL WORK
    |
    v
RECONCILIATION
    |
    v
SHORT TX
    |
    v
DURABLE EVENT
&lt;/pre&gt;

&lt;hr /&gt;

&lt;h2&gt;The Bigger Lesson&lt;/h2&gt;

&lt;p&gt;
When we talk about reliable event-driven systems, it&#39;s easy to focus entirely on whether messages are delivered.
&lt;/p&gt;

&lt;p&gt;
But reliable delivery is only part of the problem.
&lt;/p&gt;

&lt;p&gt;
We also need to ask:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;What happens if the application crashes between workflow steps?&lt;/li&gt;
  &lt;li&gt;What happens if the external operation succeeds but our database fails?&lt;/li&gt;
  &lt;li&gt;What happens if we don&#39;t know whether the external operation succeeded?&lt;/li&gt;
  &lt;li&gt;What happens if Kafka is unavailable after the payment commits?&lt;/li&gt;
  &lt;li&gt;What happens if the application restarts during the 30-minute wait?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
A reliable design needs an answer for each boundary.
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Short Transactions
        +
Durable State
        +
Durable Handoffs
        +
NERV Inbox / Outbox
        +
External Idempotency
        +
Reconciliation
        =
Reliable Long-Running Workflows
&lt;/pre&gt;

&lt;p&gt;
And that brings us back to the central idea:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
&lt;strong&gt;A 30-minute payment isn&#39;t a 30-minute transaction. It&#39;s a durable workflow composed of several very short transactions.&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
NERV Event doesn&#39;t try to make a remote payment provider part of your local database transaction.
&lt;/p&gt;

&lt;p&gt;
Instead, it helps make the boundaries where strong guarantees &lt;em&gt;are&lt;/em&gt; possible durable, atomic, retryable, and observable.
&lt;/p&gt;

&lt;p&gt;
For real-world distributed systems, that&#39;s the guarantee that matters.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Try NERV Event&lt;/h2&gt;

&lt;p&gt;
&lt;strong&gt;NERV Event&lt;/strong&gt; is an open-source Spring Boot library for building reliable event-driven applications using transactional Outbox and Inbox patterns.
&lt;/p&gt;

&lt;p&gt;It provides infrastructure for:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;transactional Outbox publishing;&lt;/li&gt;
  &lt;li&gt;durable Inbox consumption;&lt;/li&gt;
  &lt;li&gt;atomic Inbox handler processing;&lt;/li&gt;
  &lt;li&gt;idempotent event processing;&lt;/li&gt;
  &lt;li&gt;automatic retries and failure tracking;&lt;/li&gt;
  &lt;li&gt;multi-instance-safe claiming;&lt;/li&gt;
  &lt;li&gt;aggregate-aware ordering;&lt;/li&gt;
  &lt;li&gt;Kafka integration;&lt;/li&gt;
  &lt;li&gt;Amazon SQS integration;&lt;/li&gt;
  &lt;li&gt;scheduler resilience;&lt;/li&gt;
  &lt;li&gt;and operational inspection.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;strong&gt;GitHub:&lt;/strong&gt;
&lt;a href=&quot;https://github.com/czetsuyatech/nerv-event&quot;
   rel=&quot;noopener noreferrer&quot;
   target=&quot;_blank&quot;&gt;
https://github.com/czetsuyatech/nerv-event
&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
If you&#39;re building long-running workflows with Spring Boot, I&#39;d be interested to hear how you&#39;re handling durable handoffs, external idempotency, and reconciliation — particularly for payments and other slow third-party operations.
&lt;/p&gt;

&lt;p&gt;
If NERV Event is useful to you, consider starring the repository. Feedback, issues, and contributions are always welcome.
&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;
&lt;strong&gt;NERV — Next-Generation Engineering for Runtime Velocity&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;
Production-ready infrastructure for Java engineers building reliable enterprise systems.
&lt;/p&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/hardening-event-driven-systems-nerv-event-2-1.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Hardening Event-Driven Systems: Lessons from NERV Event 2.1
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Event&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/10/spring-boot-skip-locked-database-workers.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Stop Reaching for Redis: Scaling Database Workers with SKIP LOCKED
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/6583045428737904337/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/09/long-running-transactions-spring-boot-nerv-event.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/6583045428737904337'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/6583045428737904337'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/09/long-running-transactions-spring-boot-nerv-event.html' title='Handling Long-Running Transactions in Spring Boot with NERV Event'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7zjMiaKZmXfv3KkMeKt7zIH1Plcqat6lKOdkc_FLyWa4EfNTTuVZ9Wycf9x9YfQjURFYuSlMHRIo5cfh__agMSUpRDB4JPVm5-zqsZ2RnoFHBZwqeXMUOXYGirATNQveydq_u2Wv60DKUGCe8K-Uh8UxFpwAmNYb5lop1kRLVSfycuOaNK2P73fukLeb0/s72-c/nerv-event-long-running-payment-workflows.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-720826277017967990</id><published>2026-09-14T12:04:25.000+08:00</published><updated>2026-10-17T11:14:08.435+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Amazon SQS"/><category scheme="http://www.blogger.com/atom/ns#" term="Distributed Systems"/><category scheme="http://www.blogger.com/atom/ns#" term="Event-Driven Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Inbox Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Kafka"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Event"/><category scheme="http://www.blogger.com/atom/ns#" term="Outbox Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>Hardening Event-Driven Systems: Lessons from NERV Event 2.1</title><content type='html'>&lt;!--TITLE:
Hardening Event-Driven Systems: Lessons from NERV Event 2.1

PERMALINK:
hardening-event-driven-systems-nerv-event-2-1

META DESCRIPTION:
NERV Event 2.1 hardens Inbox transactions, Outbox validation, aggregate ordering, Kafka/SQS delivery, and Java runtime portability.

LABELS:
NERV, NERV Event, Spring Boot, Java, Event-Driven Architecture, Outbox Pattern, Inbox Pattern, Kafka, Amazon SQS, Distributed Systems

HERO IMAGE:
nerv-event-2-1-production-hardening-aggregate-ordering.webp

HERO ALT:
NERV Event 2.1 production hardening with transactional Inbox, Outbox, aggregate ordering, Kafka and SQS--&gt;

&lt;!--Insert hero image here--&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFD-0J9a18vaTDSHZ-nq_s8c6qoMbxELxhDHb0n64owAKlutg-YO_yN-Ty5Y4_XRvb8FgaRxzZSBiTuTBLNjN-CSSaLmPaD1CrhYP7GWaVm02Ngxjqz3jR9v4PvihEvJdgfbJJZH3h3qlaZ_NROzcxFeQPiVnmuPdYe0VJLRVugR25BD3dJ4SqTR7X0fzQ/s1774/nerv-event-2-1-production-hardening-aggregate-ordering.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;887&quot; data-original-width=&quot;1774&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFD-0J9a18vaTDSHZ-nq_s8c6qoMbxELxhDHb0n64owAKlutg-YO_yN-Ty5Y4_XRvb8FgaRxzZSBiTuTBLNjN-CSSaLmPaD1CrhYP7GWaVm02Ngxjqz3jR9v4PvihEvJdgfbJJZH3h3qlaZ_NROzcxFeQPiVnmuPdYe0VJLRVugR25BD3dJ4SqTR7X0fzQ/s1600/nerv-event-2-1-production-hardening-aggregate-ordering.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;
Building an event-driven library is one thing. Putting it inside a realistic application is another.
&lt;/p&gt;

&lt;p&gt;
While integrating &lt;strong&gt;NERV Event&lt;/strong&gt; into a full payment showcase, several edge cases surfaced that were easy to overlook when looking at the Outbox and Inbox patterns individually.
&lt;/p&gt;

&lt;p&gt;
None of them changed the fundamental architecture. The Outbox still provides durable publication. The Inbox still provides durable consumption, retries, and idempotency.
&lt;/p&gt;

&lt;p&gt;
But they exposed something more important:
&lt;strong&gt;production reliability lives in the boundaries between those mechanisms.&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;
Those findings became the focus of &lt;strong&gt;NERV Event 2.1&lt;/strong&gt;.
&lt;/p&gt;

&lt;p&gt;This release strengthens four areas:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;atomic Inbox processing&lt;/strong&gt;;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;fail-fast Outbox configuration&lt;/strong&gt;;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;aggregate-aware event ordering&lt;/strong&gt;;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;runtime portability for polling&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Let&#39;s look at why each one matters — and what these changes taught us about building reliable event-driven systems.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;1. The Inbox Transaction Boundary Matters&lt;/h2&gt;

&lt;p&gt;
Consider a consumer processing an event:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Inbox Event
    |
    v
Handler
    |
    +--&amp;gt; Update local database
    |
    v
Mark Inbox PROCESSED
&lt;/pre&gt;

&lt;p&gt;
At first glance, this looks correct.
&lt;/p&gt;

&lt;p&gt;
But there is a dangerous failure window if the handler&#39;s database transaction commits independently from the Inbox state transition.
&lt;/p&gt;

&lt;p&gt;Imagine the following sequence:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;1. Claim Inbox event
2. Execute handler
3. Commit handler database changes
4. Application crashes
5. Inbox record is still not PROCESSED
6. Event is retried
7. Handler executes again
&lt;/pre&gt;

&lt;p&gt;
The Inbox correctly believes the event still requires processing.
&lt;/p&gt;

&lt;p&gt;
The business database, however, has already been changed.
&lt;/p&gt;

&lt;p&gt;
The result can be &lt;strong&gt;duplicate local effects&lt;/strong&gt;.
&lt;/p&gt;

&lt;h3&gt;The NERV Event 2.1 Transaction Model&lt;/h3&gt;

&lt;p&gt;
NERV Event 2.1 closes this failure window.
&lt;/p&gt;

&lt;p&gt;
Local handler database effects and the Inbox transition to &lt;code&gt;PROCESSED&lt;/code&gt; now execute within the &lt;strong&gt;same transaction&lt;/strong&gt;.
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Claim event
    |
    v
BEGIN TRANSACTION
    |
    +--&amp;gt; Execute handler
    |
    +--&amp;gt; Update business data
    |
    +--&amp;gt; Mark Inbox PROCESSED
    |
COMMIT
&lt;/pre&gt;

&lt;p&gt;If anything fails:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;BEGIN TRANSACTION
    |
    +--&amp;gt; Execute handler
    |
    +--&amp;gt; FAILURE
    |
ROLLBACK
&lt;/pre&gt;

&lt;p&gt;
Both the business changes and Inbox completion are rolled back.
&lt;/p&gt;

&lt;p&gt;
Only after that rollback does NERV Event record the retry or failure metadata through a separate transactional boundary.
&lt;/p&gt;

&lt;p&gt;
This gives us an important invariant:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
&lt;strong&gt;Local handler effects and successful Inbox completion either commit together or do not commit at all.&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;What This Does Not Solve&lt;/h3&gt;

&lt;p&gt;
This guarantee applies to transactional work performed against the local database.
&lt;/p&gt;

&lt;p&gt;
It cannot magically make an external system part of that database transaction.
&lt;/p&gt;

&lt;p&gt;If a handler performs:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Inbox Handler
    |
    +--&amp;gt; Local PostgreSQL update
    |
    +--&amp;gt; External payment API
&lt;/pre&gt;

&lt;p&gt;
the HTTP request cannot simply be rolled back because the database transaction failed afterward.
&lt;/p&gt;

&lt;p&gt;
External side effects therefore still require &lt;strong&gt;idempotency&lt;/strong&gt;.
&lt;/p&gt;

&lt;p&gt;
This distinction is important:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
&lt;strong&gt;Atomic transactions protect local effects. Idempotency protects effects outside the transaction boundary.&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
Reliable consumer processing needs both.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;2. Silent Outbox Misconfiguration Is a Reliability Problem&lt;/h2&gt;

&lt;p&gt;
Another issue appeared while configuring the showcase.
&lt;/p&gt;

&lt;p&gt;
Imagine an application that can successfully write events into its Outbox, but has no functional dispatcher capable of delivering them.
&lt;/p&gt;

&lt;p&gt;
The application starts normally.
&lt;/p&gt;

&lt;p&gt;
Business transactions succeed.
&lt;/p&gt;

&lt;p&gt;
Outbox records accumulate.
&lt;/p&gt;

&lt;p&gt;
And nothing gets published.
&lt;/p&gt;

&lt;p&gt;
This is one of the more dangerous infrastructure failures because the system can appear healthy while event delivery is effectively disabled.
&lt;/p&gt;

&lt;h3&gt;Fail Fast Instead&lt;/h3&gt;

&lt;p&gt;
NERV Event 2.1 validates active Outbox publication during application startup.
&lt;/p&gt;

&lt;p&gt;
Publication is considered active when the application indicates publishing intent through mechanisms such as:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;nerv.event.outbox.enabled=true

RetryPolicy

custom OutboxDispatcher

configured outbound destinations
&lt;/pre&gt;

&lt;p&gt;
If publication is active but there is no functional dispatcher, startup fails with an actionable configuration error.
&lt;/p&gt;

&lt;p&gt;That changes the failure model from:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Production traffic
    |
    v
Outbox grows
    |
    v
Events are never delivered
    |
    v
Someone eventually notices
&lt;/pre&gt;

&lt;p&gt;into:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Application startup
    |
    v
Configuration validation
    |
    v
FAIL FAST
&lt;/pre&gt;

&lt;p&gt;
For infrastructure configuration, finding the problem before production traffic reaches the application is considerably safer than silently accepting a non-functional configuration.
&lt;/p&gt;

&lt;h3&gt;What About Consumer-Only Applications?&lt;/h3&gt;

&lt;p&gt;
Fail-fast validation introduced another design question.
&lt;/p&gt;

&lt;p&gt;
Some applications use NERV Event only for Inbox consumption.
&lt;/p&gt;

&lt;p&gt;
Requiring every consumer-only application to add:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;nerv.event.outbox.enabled=false
&lt;/pre&gt;

&lt;p&gt;
would make an otherwise backward-compatible upgrade unnecessarily disruptive.
&lt;/p&gt;

&lt;p&gt;
NERV Event 2.1 therefore distinguishes between &lt;strong&gt;having the library installed&lt;/strong&gt; and &lt;strong&gt;actually expressing publication intent&lt;/strong&gt;.
&lt;/p&gt;

&lt;p&gt;
Consumer-only applications continue to start without additional configuration.
&lt;/p&gt;

&lt;p&gt;
Explicitly disabling the Outbox remains available, but isn&#39;t required merely because NERV Event is present.
&lt;/p&gt;

&lt;p&gt;
The result is both:
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;backward compatibility and fail-fast publication safety.&lt;/strong&gt;
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;3. Kafka Keys Alone Don&#39;t Guarantee Application-Level Ordering&lt;/h2&gt;

&lt;p&gt;
The largest new capability in NERV Event 2.1 is &lt;strong&gt;aggregate-aware ordering&lt;/strong&gt;.
&lt;/p&gt;

&lt;p&gt;
Consider an Order aggregate producing:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;OrderCreated
PaymentAuthorized
OrderConfirmed
&lt;/pre&gt;

&lt;p&gt;
These events have a natural sequence.
&lt;/p&gt;

&lt;p&gt;
But with multiple Outbox workers, retrieving records in database order alone does not guarantee that they will actually reach the broker in that same order.
&lt;/p&gt;

&lt;p&gt;Worker A might claim:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;OrderCreated
&lt;/pre&gt;

&lt;p&gt;while Worker B claims:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;PaymentAuthorized
&lt;/pre&gt;

&lt;p&gt;
If Worker B publishes first, downstream consumers could observe:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;PaymentAuthorized
OrderCreated
&lt;/pre&gt;

&lt;p&gt;
The database rows were ordered correctly.
&lt;/p&gt;

&lt;p&gt;
The actual dispatch was not.
&lt;/p&gt;

&lt;h3&gt;&quot;Just Use a Kafka Key&quot;&lt;/h3&gt;

&lt;p&gt;
Kafka developers will immediately recognize one part of the solution:
&lt;/p&gt;

&lt;p&gt;
Events belonging to the same aggregate should use the same Kafka record key.
&lt;/p&gt;

&lt;p&gt;
That&#39;s necessary.
&lt;/p&gt;

&lt;p&gt;
But it isn&#39;t sufficient.
&lt;/p&gt;

&lt;p&gt;
Kafka can preserve ordering within a partition, but the Outbox dispatcher still controls the order in which records are handed to Kafka.
&lt;/p&gt;

&lt;p&gt;If two concurrent workers effectively perform:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;send(event2)
send(event1)
&lt;/pre&gt;

&lt;p&gt;
using the same Kafka key doesn&#39;t magically reverse those calls.
&lt;/p&gt;

&lt;p&gt;
The ordering guarantee therefore has to begin &lt;strong&gt;before the broker&lt;/strong&gt;.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;4. Introducing &lt;code&gt;orderingKey&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;
NERV Event 2.1 introduces an optional &lt;code&gt;orderingKey&lt;/code&gt; throughout the publication pipeline.
&lt;/p&gt;

&lt;p&gt;Conceptually:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;EventPublication.builder()
    .type(&quot;ORDER_UPDATED&quot;)
    .payload(payload)
    .orderingKey(orderId)
    .build();
&lt;/pre&gt;

&lt;p&gt;
The ordering identity travels through the full pipeline:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Application
    |
    v
EventPublication
    |
    v
Outbox Persistence
    |
    v
Claiming
    |
    v
Dispatcher
    |
    v
Transport
    |
    +--&amp;gt; Kafka
    |
    +--&amp;gt; SQS
&lt;/pre&gt;

&lt;p&gt;
The ordering key is persisted in the Outbox so retries continue using the same ordering identity.
&lt;/p&gt;

&lt;p&gt;
It is deliberately optional.
&lt;/p&gt;

&lt;p&gt;
Existing applications do not need to provide one, and unkeyed events retain their existing concurrent dispatch behavior.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;5. Ordering Starts in the Outbox&lt;/h2&gt;

&lt;p&gt;
The interesting part isn&#39;t adding another property to the publication API.
&lt;/p&gt;

&lt;p&gt;
The important change is how Outbox records are claimed.
&lt;/p&gt;

&lt;p&gt;
NERV Event now ensures that events sharing the same ordering key are claimed and dispatched sequentially.
&lt;/p&gt;

&lt;p&gt;Conceptually:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Order A / Event 1 --┐
Order A / Event 2 --+-- sequential
Order A / Event 3 --┘

Order B / Event 1 --┐
Order B / Event 2 --+-- sequential
Order B / Event 3 --┘
&lt;/pre&gt;

&lt;p&gt;
But Order A and Order B remain independent:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;             +-- Order A events -- sequential
Workers -----+
             +-- Order B events -- sequential
&lt;/pre&gt;

&lt;p&gt;
This distinction matters.
&lt;/p&gt;

&lt;p&gt;
We could preserve ordering by forcing everything through a single global worker:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;ALL EVENTS
    |
    v
single queue
    |
    v
single worker
&lt;/pre&gt;

&lt;p&gt;
But that would sacrifice much of the scalability gained through concurrent Outbox dispatch.
&lt;/p&gt;

&lt;p&gt;
Instead, serialization occurs at the &lt;strong&gt;ordering-key level&lt;/strong&gt;.
&lt;/p&gt;

&lt;p&gt;
Events belonging to the same aggregate remain ordered while unrelated aggregates can continue progressing concurrently.
&lt;/p&gt;

&lt;p&gt;
This protection also applies across batches and application replicas.
&lt;/p&gt;

&lt;p&gt;
Adding more NERV Event instances should increase concurrency between independent ordering keys without allowing two instances to reorder events belonging to the same key.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;6. Transport-Specific Ordering&lt;/h2&gt;

&lt;p&gt;
Once the Outbox establishes the ordering boundary, each transport can map that identity onto the guarantees offered by the underlying broker.
&lt;/p&gt;

&lt;h3&gt;Kafka&lt;/h3&gt;

&lt;p&gt;
For Kafka, &lt;code&gt;orderingKey&lt;/code&gt; becomes the Kafka record key.
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;orderingKey
    |
    v
Kafka record key
    |
    v
partition selection
&lt;/pre&gt;

&lt;p&gt;
Events sharing an ordering key therefore follow Kafka&#39;s key and partition ordering semantics.
&lt;/p&gt;

&lt;h3&gt;Amazon SQS FIFO&lt;/h3&gt;

&lt;p&gt;
For SQS FIFO queues, the ordering key becomes:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;MessageGroupId = orderingKey
&lt;/pre&gt;

&lt;p&gt;
NERV Event also uses:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;MessageDeduplicationId = eventId
&lt;/pre&gt;

&lt;p&gt;
This maps aggregate ordering naturally onto SQS FIFO message groups while retaining event-level deduplication identity.
&lt;/p&gt;

&lt;h3&gt;Amazon SQS Standard&lt;/h3&gt;

&lt;p&gt;
SQS Standard queues do not provide FIFO ordering guarantees.
&lt;/p&gt;

&lt;p&gt;
NERV Event therefore does not pretend otherwise.
&lt;/p&gt;

&lt;p&gt;
An event may still carry an ordering key at the publication level, but choosing SQS Standard does not transform the underlying transport into an ordered queue.
&lt;/p&gt;

&lt;p&gt;
A useful abstraction should provide stronger guarantees where possible without hiding the limitations of the infrastructure underneath it.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;7. Minimal Runtime Images Expose Hidden Dependencies&lt;/h2&gt;

&lt;p&gt;
The showcase also uncovered a smaller issue with an important lesson.
&lt;/p&gt;

&lt;p&gt;
Polling previously relied on a random-generator implementation whose provider was not guaranteed to be available in minimal Java runtime images.
&lt;/p&gt;

&lt;p&gt;
On a normal development JDK, this is easy to miss.
&lt;/p&gt;

&lt;p&gt;
Inside a deliberately reduced production runtime, it becomes a deployment failure.
&lt;/p&gt;

&lt;p&gt;
For NERV Event 2.1, that dependency has been replaced with:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;ThreadLocalRandom
&lt;/pre&gt;

&lt;p&gt;
from &lt;code&gt;java.base&lt;/code&gt;.
&lt;/p&gt;

&lt;p&gt;
For polling jitter and backoff behavior, requiring an additional random provider was adding deployment complexity without providing a meaningful architectural benefit.
&lt;/p&gt;

&lt;p&gt;
Using a standard Java runtime facility removes that unnecessary dependency and makes NERV Event friendlier to minimal runtime images.
&lt;/p&gt;

&lt;p&gt;
There is a broader lesson here:
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;
&lt;strong&gt;The deployment environment is part of the architecture.&lt;/strong&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;
A library that works perfectly inside a developer&#39;s full JDK can still contain assumptions that surface only once the application is packaged for production.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;8. Database Compatibility&lt;/h2&gt;

&lt;p&gt;
Supporting durable aggregate ordering requires preserving the ordering key with the event itself.
&lt;/p&gt;

&lt;p&gt;
NERV Event 2.1 therefore adds the PostgreSQL migration:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;006-add-outbox-ordering-key.sql
&lt;/pre&gt;

&lt;p&gt;
The new Outbox column is nullable.
&lt;/p&gt;

&lt;p&gt;
That is intentional because ordering remains opt-in.
&lt;/p&gt;

&lt;p&gt;
Existing Outbox records remain valid, and applications that do not require aggregate ordering do not need to change how they publish events.
&lt;/p&gt;

&lt;p&gt;
Existing two-argument &lt;code&gt;EventPublication&lt;/code&gt; construction also remains supported.
&lt;/p&gt;

&lt;p&gt;
This allows the new capabilities to ship as a backward-compatible &lt;strong&gt;2.1.0 minor release&lt;/strong&gt; rather than requiring a new major version.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;9. The Showcase Was the Important Test&lt;/h2&gt;

&lt;p&gt;
The most interesting part of these changes isn&#39;t any individual feature.
&lt;/p&gt;

&lt;p&gt;
It&#39;s where the problems were discovered.
&lt;/p&gt;

&lt;p&gt;
The basic Outbox pattern was already working.
&lt;/p&gt;

&lt;p&gt;
The basic Inbox pattern was already working.
&lt;/p&gt;

&lt;p&gt;
Retries were working.
&lt;/p&gt;

&lt;p&gt;
Kafka was working.
&lt;/p&gt;

&lt;p&gt;
SQS was working.
&lt;/p&gt;

&lt;p&gt;
The edge cases appeared when those components were combined inside a realistic application with:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;transactional business logic;&lt;/li&gt;
  &lt;li&gt;multiple services;&lt;/li&gt;
  &lt;li&gt;concurrent processing;&lt;/li&gt;
  &lt;li&gt;multiple application replicas;&lt;/li&gt;
  &lt;li&gt;Kafka and SQS transports;&lt;/li&gt;
  &lt;li&gt;real failure scenarios;&lt;/li&gt;
  &lt;li&gt;and production-style deployment constraints.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
This is exactly why I wanted a full NERV showcase rather than another isolated example application.
&lt;/p&gt;

&lt;p&gt;
Examples demonstrate APIs.
&lt;/p&gt;

&lt;p&gt;
Realistic showcases challenge architectural guarantees.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;10. The Bigger Lesson&lt;/h2&gt;

&lt;p&gt;
An Outbox isn&#39;t reliable merely because events are stored before publication.
&lt;/p&gt;

&lt;p&gt;
An Inbox isn&#39;t reliable merely because consumed event IDs are persisted.
&lt;/p&gt;

&lt;p&gt;
Kafka ordering isn&#39;t guaranteed merely because a message has a key.
&lt;/p&gt;

&lt;p&gt;
And an application isn&#39;t correctly configured merely because Spring Boot managed to start.
&lt;/p&gt;

&lt;p&gt;
The guarantees have to survive the &lt;strong&gt;boundaries between those components&lt;/strong&gt;.
&lt;/p&gt;

&lt;p&gt;
That is what NERV Event 2.1 focuses on:
&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Durability
    +
Atomicity
    +
Idempotency
    +
Ordering
    +
Fail-fast configuration
    =
Predictable event processing
&lt;/pre&gt;

&lt;p&gt;
The goal isn&#39;t to eliminate failure.
&lt;/p&gt;

&lt;p&gt;
Distributed systems will fail.
&lt;/p&gt;

&lt;p&gt;
The goal is to make those failures:
&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;explicit&lt;/strong&gt; instead of silent;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;recoverable&lt;/strong&gt; instead of destructive;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;observable&lt;/strong&gt; instead of hidden;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;deterministic&lt;/strong&gt; instead of surprising.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
That&#39;s the direction NERV Event continues to take: providing Spring applications with event-delivery infrastructure whose behavior remains understandable not only when everything works, but especially when it doesn&#39;t.
&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Try NERV Event&lt;/h2&gt;

&lt;p&gt;
&lt;strong&gt;NERV Event&lt;/strong&gt; is an open-source Spring Boot library for building reliable event-driven applications using transactional Outbox and Inbox patterns.
&lt;/p&gt;

&lt;p&gt;It provides infrastructure for:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;transactional Outbox publishing;&lt;/li&gt;
  &lt;li&gt;durable Inbox consumption;&lt;/li&gt;
  &lt;li&gt;idempotent event processing;&lt;/li&gt;
  &lt;li&gt;automatic retries and failure tracking;&lt;/li&gt;
  &lt;li&gt;multi-instance-safe event claiming;&lt;/li&gt;
  &lt;li&gt;aggregate-aware event ordering;&lt;/li&gt;
  &lt;li&gt;Kafka integration;&lt;/li&gt;
  &lt;li&gt;Amazon SQS integration;&lt;/li&gt;
  &lt;li&gt;scheduler resilience;&lt;/li&gt;
  &lt;li&gt;and operational inspection APIs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;strong&gt;GitHub:&lt;/strong&gt;
&lt;a href=&quot;https://github.com/czetsuyatech/nerv-event&quot; rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;
https://github.com/czetsuyatech/nerv-event
&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
If you&#39;re building event-driven Spring Boot systems, I&#39;d especially like to hear how you&#39;re handling ordering, consumer transaction boundaries, and multi-instance Outbox dispatch in production.
&lt;/p&gt;

&lt;p&gt;
If NERV Event is useful to you, consider starring the project on GitHub. Feedback, issues, and contributions are always welcome.
&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;
&lt;strong&gt;NERV — Next-Generation Engineering for Runtime Velocity&lt;/strong&gt;
&lt;/p&gt;

&lt;p&gt;
Production-ready infrastructure for Java engineers building reliable enterprise systems.
&lt;/p&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/transactional-outbox-pattern-spring-boot.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Transactional Outbox Pattern with Spring Boot: Reliable Event Publishing Without Dual Writes
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Event&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/long-running-transactions-spring-boot-nerv-event.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Handling Long-Running Transactions in Spring Boot with NERV Event
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/720826277017967990/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/09/hardening-event-driven-systems-nerv-event-2-1.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/720826277017967990'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/720826277017967990'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/09/hardening-event-driven-systems-nerv-event-2-1.html' title='Hardening Event-Driven Systems: Lessons from NERV Event 2.1'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFD-0J9a18vaTDSHZ-nq_s8c6qoMbxELxhDHb0n64owAKlutg-YO_yN-Ty5Y4_XRvb8FgaRxzZSBiTuTBLNjN-CSSaLmPaD1CrhYP7GWaVm02Ngxjqz3jR9v4PvihEvJdgfbJJZH3h3qlaZ_NROzcxFeQPiVnmuPdYe0VJLRVugR25BD3dJ4SqTR7X0fzQ/s72-c/nerv-event-2-1-production-hardening-aggregate-ordering.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-6177256827405774340</id><published>2026-09-11T06:59:02.131+08:00</published><updated>2026-10-27T12:47:07.536+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Persistence"/><category scheme="http://www.blogger.com/atom/ns#" term="Persistence"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>Building a Production-Ready Persistence Layer in Spring Boot</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjo4nyo1xkVdolUPWAPTnpRgC5gOCdR4gbvYROQ9h1Ve-pQWJn4j4g2BBK-fSmm33f0_iNN-rWs2qaU2TZ5GBl5tfQU0SHVIeCKGZYT7tNILvc1zOQfGXYkk4JUsrRtXS8yfl2iqfInm2ILjMMTqxCDWCRceKsqbj2hDM4CgWmnfSmhAoCSAXQHA5ZTCbzv/s1679/production-ready-persistence-layer-spring-boot.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;937&quot; data-original-width=&quot;1679&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjo4nyo1xkVdolUPWAPTnpRgC5gOCdR4gbvYROQ9h1Ve-pQWJn4j4g2BBK-fSmm33f0_iNN-rWs2qaU2TZ5GBl5tfQU0SHVIeCKGZYT7tNILvc1zOQfGXYkk4JUsrRtXS8yfl2iqfInm2ILjMMTqxCDWCRceKsqbj2hDM4CgWmnfSmhAoCSAXQHA5ZTCbzv/s1600/production-ready-persistence-layer-spring-boot.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;h1&gt;Building a Production-Ready Persistence Layer in Spring Boot&lt;/h1&gt;

&lt;p&gt;Spring Data JPA makes persistence remarkably easy to get started with.&lt;/p&gt;

&lt;p&gt;Define an entity, create a repository, extend &lt;code&gt;JpaRepository&lt;/code&gt;, and you already have CRUD operations, pagination, sorting, and a powerful query abstraction.&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;public interface CustomerRepository
    extends JpaRepository&amp;lt;Customer, Long&amp;gt; {
}&lt;/pre&gt;

&lt;p&gt;For a small application, this may be all you need.&lt;/p&gt;

&lt;p&gt;But as a Spring Boot application grows, persistence requirements rarely remain that simple.&lt;/p&gt;

&lt;p&gt;You start adding audit fields to entities. Search endpoints require increasingly complex filters. Repository interfaces accumulate query methods. Specifications appear in multiple places. Different services implement pagination and filtering differently.&lt;/p&gt;

&lt;p&gt;Eventually, the problem is no longer:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;How do I persist an entity?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It becomes:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;How do I build a persistence layer that remains consistent, reusable, and maintainable as the application grows?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That is the problem a production-ready persistence foundation should solve.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;The Persistence Layer Grows Faster Than You Expect&lt;/h2&gt;

&lt;p&gt;Consider a typical Spring Boot application.&lt;/p&gt;

&lt;p&gt;You might begin with a repository like this:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;public interface CustomerRepository
    extends JpaRepository&amp;lt;Customer, Long&amp;gt; {

  List&amp;lt;Customer&amp;gt; findByStatus(CustomerStatus status);
}&lt;/pre&gt;

&lt;p&gt;Then another requirement appears.&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;List&amp;lt;Customer&amp;gt; findByStatusAndCountry(
    CustomerStatus status,
    String country);&lt;/pre&gt;

&lt;p&gt;Then another.&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;List&amp;lt;Customer&amp;gt; findByStatusAndCountryAndType(
    CustomerStatus status,
    String country,
    CustomerType type);&lt;/pre&gt;

&lt;p&gt;Soon the API needs optional filters:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;GET /customers
    ?status=ACTIVE
    &amp;amp;country=PH
    &amp;amp;type=PREMIUM&lt;/pre&gt;

&lt;p&gt;Each parameter may or may not be present.&lt;/p&gt;

&lt;p&gt;Creating a repository method for every possible combination quickly becomes impractical.&lt;/p&gt;

&lt;p&gt;At the same time, other concerns start appearing across your entities:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;createdAt
updatedAt
createdBy
updatedBy&lt;/pre&gt;

&lt;p&gt;Pagination needs to behave consistently.&lt;/p&gt;

&lt;p&gt;Sorting needs validation.&lt;/p&gt;

&lt;p&gt;Specifications need common utilities.&lt;/p&gt;

&lt;p&gt;Some queries should return full entities, while others only need a subset of fields.&lt;/p&gt;

&lt;p&gt;None of these problems is particularly difficult on its own.&lt;/p&gt;

&lt;p&gt;The problem is that they appear repeatedly.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Repetition Is Often a Sign of Missing Infrastructure&lt;/h2&gt;

&lt;p&gt;A common response is to create utility classes whenever duplication appears.&lt;/p&gt;

&lt;p&gt;One helper for specifications.&lt;/p&gt;

&lt;p&gt;Another for pagination.&lt;/p&gt;

&lt;p&gt;A base entity for auditing.&lt;/p&gt;

&lt;p&gt;Some repository helpers.&lt;/p&gt;

&lt;p&gt;A few mapper utilities.&lt;/p&gt;

&lt;p&gt;This works initially.&lt;/p&gt;

&lt;p&gt;But across multiple applications or microservices, these implementations tend to evolve independently.&lt;/p&gt;

&lt;p&gt;One service handles auditing one way.&lt;/p&gt;

&lt;p&gt;Another uses a slightly different base entity.&lt;/p&gt;

&lt;p&gt;Another builds specifications directly inside its service layer.&lt;/p&gt;

&lt;p&gt;Another exposes entities from repository queries because creating a proper projection feels like too much work.&lt;/p&gt;

&lt;p&gt;The individual decisions may all be reasonable.&lt;/p&gt;

&lt;p&gt;The inconsistency is the problem.&lt;/p&gt;

&lt;p&gt;A persistence foundation should establish a small set of conventions that application code can build upon.&lt;/p&gt;

&lt;p&gt;Not a framework that replaces Spring Data JPA.&lt;/p&gt;

&lt;p&gt;Not another abstraction hiding Hibernate.&lt;/p&gt;

&lt;p&gt;Just enough reusable infrastructure to remove repetitive persistence plumbing.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Start with Consistent Entity Models&lt;/h2&gt;

&lt;p&gt;Most business entities need some common persistence metadata.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@MappedSuperclass
public abstract class AuditableModel {

  @CreatedDate
  private Instant createdAt;

  @LastModifiedDate
  private Instant updatedAt;

  @CreatedBy
  private String createdBy;

  @LastModifiedBy
  private String updatedBy;
}&lt;/pre&gt;

&lt;p&gt;Then business entities can focus on business data:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@Entity
public class Customer extends AuditableModel {

  @Id
  @GeneratedValue
  private Long id;

  private String name;

  private String country;

  @Enumerated(EnumType.STRING)
  private CustomerStatus status;
}&lt;/pre&gt;

&lt;p&gt;The important part is not saving four fields.&lt;/p&gt;

&lt;p&gt;The important part is establishing a predictable model across the application.&lt;/p&gt;

&lt;p&gt;When every persisted entity follows the same conventions, infrastructure becomes easier to build around it.&lt;/p&gt;

&lt;p&gt;Operations teams know where to find creation and modification information.&lt;/p&gt;

&lt;p&gt;Developers do not need to reinvent auditing for every entity.&lt;/p&gt;

&lt;p&gt;Support investigations become easier because persistence metadata is consistent.&lt;/p&gt;

&lt;p&gt;Consistency is one of the less glamorous benefits of shared infrastructure, but in production systems it is often one of the most valuable.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Dynamic Queries Should Be Composable&lt;/h2&gt;

&lt;p&gt;Repository query methods are excellent when the query is fixed.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Optional&amp;lt;Customer&amp;gt; findByExternalId(String externalId);&lt;/pre&gt;

&lt;p&gt;There is nothing wrong with this.&lt;/p&gt;

&lt;p&gt;Problems begin when repository methods are used to represent every possible combination of optional search parameters.&lt;/p&gt;

&lt;p&gt;This:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;findByStatusAndCountryAndType(...)&lt;/pre&gt;

&lt;p&gt;eventually becomes:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;findByStatusAndCountryAndTypeAndCreatedAtBetween(...)&lt;/pre&gt;

&lt;p&gt;and then multiple variations of the same method appear because some filters are optional.&lt;/p&gt;

&lt;p&gt;For dynamic search requirements, queries should instead be composed from individual conditions.&lt;/p&gt;

&lt;p&gt;Spring Data JPA already provides an excellent abstraction for this:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Specification&amp;lt;T&amp;gt;&lt;/pre&gt;

&lt;p&gt;A condition can be represented independently:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Specification&amp;lt;Customer&amp;gt; hasStatus(CustomerStatus status)&lt;/pre&gt;

&lt;p&gt;Another condition can handle country:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Specification&amp;lt;Customer&amp;gt; hasCountry(String country)&lt;/pre&gt;

&lt;p&gt;And another can represent customer type:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Specification&amp;lt;Customer&amp;gt; hasType(CustomerType type)&lt;/pre&gt;

&lt;p&gt;These can then be composed:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Specification&amp;lt;Customer&amp;gt; specification =
    Specification.where(hasStatus(status))
        .and(hasCountry(country))
        .and(hasType(type));&lt;/pre&gt;

&lt;p&gt;Now the query structure follows the actual search model rather than the number of possible parameter combinations.&lt;/p&gt;

&lt;p&gt;This becomes especially useful when building REST APIs with optional filtering.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Specifications Should Be Reusable Too&lt;/h2&gt;

&lt;p&gt;Using &lt;code&gt;Specification&lt;/code&gt; solves the query-combination problem, but large applications can still accumulate repetitive specification code.&lt;/p&gt;

&lt;p&gt;You repeatedly write predicates for:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;equality&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;IN&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;ranges&lt;/li&gt;
  &lt;li&gt;dates&lt;/li&gt;
  &lt;li&gt;strings&lt;/li&gt;
  &lt;li&gt;null checks&lt;/li&gt;
  &lt;li&gt;relationships&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;At that point, the same principle applies again.&lt;/p&gt;

&lt;p&gt;The application should define &lt;strong&gt;what it wants to filter&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The persistence infrastructure should handle the repetitive mechanics of building those predicates.&lt;/p&gt;

&lt;p&gt;The goal is not to hide JPA.&lt;/p&gt;

&lt;p&gt;It is to keep application-specific query logic readable.&lt;/p&gt;

&lt;p&gt;A specification should tell you something meaningful about the domain:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;CustomerSpecifications.activeCustomers()&lt;/pre&gt;

&lt;p&gt;or:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;CustomerSpecifications.createdBetween(from, to)&lt;/pre&gt;

&lt;p&gt;rather than forcing every developer to repeatedly reconstruct the same Criteria API plumbing.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Don&#39;t Load an Entire Entity When You Don&#39;t Need It&lt;/h2&gt;

&lt;p&gt;Another persistence problem appears when reads become more complex.&lt;/p&gt;

&lt;p&gt;Suppose a &lt;code&gt;Customer&lt;/code&gt; entity eventually contains dozens of fields and several relationships.&lt;/p&gt;

&lt;p&gt;A search endpoint might only need:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;id
name
status
country
createdAt&lt;/pre&gt;

&lt;p&gt;Returning the complete entity is unnecessary.&lt;/p&gt;

&lt;p&gt;It can also create additional problems:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;unnecessary data retrieval&lt;/li&gt;
  &lt;li&gt;accidental lazy loading&lt;/li&gt;
  &lt;li&gt;larger persistence contexts&lt;/li&gt;
  &lt;li&gt;unwanted entity serialization&lt;/li&gt;
  &lt;li&gt;tighter coupling between APIs and database models&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is where projections become valuable.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;public interface CustomerSummary {

  Long getId();

  String getName();

  CustomerStatus getStatus();

  String getCountry();

  Instant getCreatedAt();
}&lt;/pre&gt;

&lt;p&gt;The persistence layer can retrieve the representation required by the use case rather than always materializing the complete entity.&lt;/p&gt;

&lt;p&gt;This also reinforces an important architectural principle:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;A persisted entity is not automatically the correct model for every read operation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Entities, DTOs, and projections serve different purposes.&lt;/p&gt;

&lt;p&gt;A good persistence foundation should make those distinctions easy to maintain.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Pagination and Sorting Are Infrastructure Concerns&lt;/h2&gt;

&lt;p&gt;Pagination looks simple:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;PageRequest.of(page, size)&lt;/pre&gt;

&lt;p&gt;But APIs eventually need consistent behavior around:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;default page size&lt;/li&gt;
  &lt;li&gt;maximum page size&lt;/li&gt;
  &lt;li&gt;allowed sorting fields&lt;/li&gt;
  &lt;li&gt;sort direction&lt;/li&gt;
  &lt;li&gt;multiple sort fields&lt;/li&gt;
  &lt;li&gt;invalid parameters&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If every endpoint independently interprets these rules, subtle inconsistencies appear.&lt;/p&gt;

&lt;p&gt;One API may treat page numbering as zero-based.&lt;/p&gt;

&lt;p&gt;Another may expose one-based pagination.&lt;/p&gt;

&lt;p&gt;One endpoint may allow arbitrary sorting.&lt;/p&gt;

&lt;p&gt;Another validates fields.&lt;/p&gt;

&lt;p&gt;A reusable persistence layer gives applications a common foundation for these mechanics while leaving business-specific decisions in the application.&lt;/p&gt;

&lt;p&gt;Again, the objective is not more abstraction.&lt;/p&gt;

&lt;p&gt;It is less repetition.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;A Persistence Library Should Work With Spring Data, Not Against It&lt;/h2&gt;

&lt;p&gt;There is a danger when creating reusable infrastructure.&lt;/p&gt;

&lt;p&gt;It is easy to keep adding abstractions until developers can no longer recognize the framework underneath them.&lt;/p&gt;

&lt;p&gt;A persistence library should not require developers to forget how Spring Data JPA works.&lt;/p&gt;

&lt;p&gt;If a developer knows:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;JpaRepository&lt;/pre&gt;

&lt;pre class=&quot;brush: java&quot;&gt;JpaSpecificationExecutor&lt;/pre&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Specification&lt;/pre&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Pageable&lt;/pre&gt;

&lt;p&gt;those concepts should remain useful.&lt;/p&gt;

&lt;p&gt;The library should provide reusable building blocks around those APIs rather than replacing them with an entirely different persistence model.&lt;/p&gt;

&lt;p&gt;This matters for another reason: debugging.&lt;/p&gt;

&lt;p&gt;When something goes wrong in production, developers should be able to follow the execution path from the application to Spring Data to Hibernate to the database.&lt;/p&gt;

&lt;p&gt;Infrastructure that removes boilerplate is useful.&lt;/p&gt;

&lt;p&gt;Infrastructure that hides behavior is much harder to support.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;This Is Why I Built NERV Persistence&lt;/h2&gt;

&lt;p&gt;These are the problems that led to &lt;strong&gt;nerv-persistence&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;NERV Persistence is an open-source persistence foundation for Spring Boot applications built on top of Spring Data JPA.&lt;/p&gt;

&lt;p&gt;It provides reusable building blocks for concerns that tend to appear repeatedly in real applications, including:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;common persistence models&lt;/li&gt;
  &lt;li&gt;auditable entities&lt;/li&gt;
  &lt;li&gt;reusable specification infrastructure&lt;/li&gt;
  &lt;li&gt;dynamic querying&lt;/li&gt;
  &lt;li&gt;projections&lt;/li&gt;
  &lt;li&gt;repository conventions&lt;/li&gt;
  &lt;li&gt;consistent persistence patterns&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The intention is deliberately conservative.&lt;/p&gt;

&lt;p&gt;NERV Persistence does not try to replace Spring Data JPA or Hibernate.&lt;/p&gt;

&lt;p&gt;It builds on them.&lt;/p&gt;

&lt;p&gt;Application developers should still recognize the underlying Spring concepts and be able to use them directly when necessary.&lt;/p&gt;

&lt;p&gt;The library simply provides a common foundation so every application does not have to rebuild the same persistence infrastructure from scratch.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Where NERV Persistence Fits&lt;/h2&gt;

&lt;p&gt;A typical Spring Boot application might look something like this:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;Application
    |
    +-- REST / API
    |
    +-- Application Services
    |
    +-- DTOs / Mappers
    |
    +-- Domain Logic
            |
            v
    NERV Persistence
            |
            +-- Persistence Models
            +-- Specifications
            +-- Query Infrastructure
            +-- Projections
            +-- Repository Foundation
                    |
                    v
            Spring Data JPA
                    |
                    v
                Hibernate
                    |
                    v
                Database&lt;/pre&gt;

&lt;p&gt;NERV Persistence sits close to the persistence boundary.&lt;/p&gt;

&lt;p&gt;It should not contain your business rules.&lt;/p&gt;

&lt;p&gt;It should not determine your domain model.&lt;/p&gt;

&lt;p&gt;And it should not force every service to use identical database structures.&lt;/p&gt;

&lt;p&gt;Instead, it standardizes the technical concerns that are genuinely reusable.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Why This Matters More in Microservices&lt;/h2&gt;

&lt;p&gt;Persistence duplication becomes particularly noticeable in a microservice architecture.&lt;/p&gt;

&lt;p&gt;Imagine several services:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;customer-service
payment-service
order-service
subscription-service
notification-service&lt;/pre&gt;

&lt;p&gt;Each service owns its database and domain model.&lt;/p&gt;

&lt;p&gt;That independence is important.&lt;/p&gt;

&lt;p&gt;But independence does not mean every service needs a different implementation of:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;auditing
pagination
specifications
query helpers
repository conventions&lt;/pre&gt;

&lt;p&gt;These are infrastructure concerns.&lt;/p&gt;

&lt;p&gt;A shared persistence foundation allows teams to standardize them while keeping domain-specific persistence inside each service.&lt;/p&gt;

&lt;p&gt;The distinction is important:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Share infrastructure conventions, not domain models.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A &lt;code&gt;Customer&lt;/code&gt; entity should not become a shared library just because several services know what a customer is.&lt;/p&gt;

&lt;p&gt;But the infrastructure used to audit, query, paginate, and persist entities can often be shared safely.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Production-Ready Doesn&#39;t Mean Complicated&lt;/h2&gt;

&lt;p&gt;A production-ready persistence layer does not need hundreds of abstractions.&lt;/p&gt;

&lt;p&gt;In fact, the opposite is often true.&lt;/p&gt;

&lt;p&gt;Good persistence infrastructure should make the common path boring:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;define entity
    ↓
define repository
    ↓
compose query
    ↓
retrieve the required model
    ↓
map to application response&lt;/pre&gt;

&lt;p&gt;The complexity should remain visible only when the use case actually requires it.&lt;/p&gt;

&lt;p&gt;That is the philosophy behind NERV Persistence and, more broadly, the NERV libraries.&lt;/p&gt;

&lt;p&gt;Build reusable infrastructure around problems that repeatedly appear in production systems, while keeping the underlying technology understandable and debuggable.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;What&#39;s Next?&lt;/h2&gt;

&lt;p&gt;This article provides the broader architecture behind NERV Persistence.&lt;/p&gt;

&lt;p&gt;In the next articles, we&#39;ll go deeper into individual persistence problems, including:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;dynamic queries without repository method explosion&lt;/li&gt;
  &lt;li&gt;composable Spring Data JPA specifications&lt;/li&gt;
  &lt;li&gt;auditable base entities&lt;/li&gt;
  &lt;li&gt;projections and efficient read models&lt;/li&gt;
  &lt;li&gt;reusable pagination, sorting, and filtering&lt;/li&gt;
  &lt;li&gt;entity vs DTO vs projection&lt;/li&gt;
  &lt;li&gt;designing base JPA entities without over-abstracting&lt;/li&gt;
  &lt;li&gt;reusable repository infrastructure&lt;/li&gt;
  &lt;li&gt;consistent persistence patterns across Spring Boot services&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Each topic will focus on the engineering problem first and then show how it can be implemented using Spring Data JPA and NERV Persistence.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;NERV Persistence&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;nerv-persistence&lt;/strong&gt; is part of the NERV open-source ecosystem — &lt;strong&gt;Next-Generation Engineering for Runtime Velocity&lt;/strong&gt; — a collection of Spring libraries focused on reusable infrastructure for production applications.&lt;/p&gt;

&lt;p&gt;If you&#39;re building Spring Boot applications and repeatedly implementing the same persistence infrastructure across projects or services, NERV Persistence is intended to provide a reusable starting point.&lt;/p&gt;

&lt;p&gt;
  Explore the project on GitHub:&lt;br /&gt;
  &lt;a href=&quot;https://github.com/czetsuyatech/nerv-persistence&quot; rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;
    https://github.com/czetsuyatech/nerv-persistence
  &lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
  More NERV libraries and engineering articles:&lt;br /&gt;
  &lt;a href=&quot;https://www.czetsuyatech.com/&quot; rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;
    https://www.czetsuyatech.com/
  &lt;/a&gt;
&lt;/p&gt;


&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Persistence&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/10/dynamic-queries-spring-data-jpa.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Dynamic Queries in Spring Data JPA Without Repository Method Explosion
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/6177256827405774340/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/09/building-production-ready-persistence-layer-spring-boot.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/6177256827405774340'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/6177256827405774340'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/09/building-production-ready-persistence-layer-spring-boot.html' title='Building a Production-Ready Persistence Layer in Spring Boot'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjo4nyo1xkVdolUPWAPTnpRgC5gOCdR4gbvYROQ9h1Ve-pQWJn4j4g2BBK-fSmm33f0_iNN-rWs2qaU2TZ5GBl5tfQU0SHVIeCKGZYT7tNILvc1zOQfGXYkk4JUsrRtXS8yfl2iqfInm2ILjMMTqxCDWCRceKsqbj2hDM4CgWmnfSmhAoCSAXQHA5ZTCbzv/s72-c/production-ready-persistence-layer-spring-boot.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-71645515009221612</id><published>2026-09-05T22:40:02.000+08:00</published><updated>2026-10-17T11:11:22.901+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Distributed Systems"/><category scheme="http://www.blogger.com/atom/ns#" term="Event-Driven Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Featured"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Event"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>Transactional Outbox Pattern with Spring Boot: Reliable Event Publishing Without Dual Writes</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR4lJjp3wUJFZnGkro5J8Wr0Ify4rNtjqsVc1u9V6QNxcvedwBYfM60jgUy_oHaptUyRJyNZTp7XM93CDaEqZ9Ia9p62LE5sZBLm2cg1GsnAnSUCwTw5dFOlu2Gtuh27EIkWgwnB5nSvmrCFHuwC8SGf0nf5IPE3rlZSdUUHv8nqQblQrfU2DJIc577qGQ/s1672/transactional-outbox-pattern.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;941&quot; data-original-width=&quot;1672&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR4lJjp3wUJFZnGkro5J8Wr0Ify4rNtjqsVc1u9V6QNxcvedwBYfM60jgUy_oHaptUyRJyNZTp7XM93CDaEqZ9Ia9p62LE5sZBLm2cg1GsnAnSUCwTw5dFOlu2Gtuh27EIkWgwnB5nSvmrCFHuwC8SGf0nf5IPE3rlZSdUUHv8nqQblQrfU2DJIc577qGQ/s1600/transactional-outbox-pattern.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;Event-driven architecture looks straightforward at first.&lt;/p&gt;
&lt;p&gt;A service updates its database, publishes an event to Kafka, and another service reacts to it.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Payment Service
    |
    +-- Save payment
    |
    +-- Publish PaymentCompleted
              |
              v
            Kafka
&lt;/pre&gt;
&lt;p&gt;But there is a reliability problem hidden in those two operations.&lt;/p&gt;
&lt;p&gt;What happens if the database transaction succeeds, but publishing the event fails?&lt;/p&gt;
&lt;p&gt;Your payment exists, but the rest of the system never hears about it.&lt;/p&gt;
&lt;p&gt;And if publishing succeeds first but the database transaction later fails, consumers may receive an event describing something that never actually happened.&lt;/p&gt;
&lt;p&gt;This is the &lt;strong&gt;dual-write problem&lt;/strong&gt;. &lt;/p&gt;
&lt;p&gt;The transactional outbox pattern is one of the most practical ways to solve it.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;The Dual-Write Problem&lt;/h2&gt;
&lt;p&gt;Consider a typical Spring service:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;@Transactional
public void completePayment(Payment payment) {
    paymentRepository.save(payment);

    kafkaTemplate.send(
        &quot;payments&quot;,
        new PaymentCompletedEvent(payment.getId())
    );
}&lt;/pre&gt;
&lt;p&gt;It looks reasonable.&lt;/p&gt;
&lt;p&gt;The problem is that two different systems participate in this method:&lt;/p&gt;
&lt;ol data-spread=&quot;false&quot; start=&quot;1&quot;&gt;
  &lt;li&gt;
    &lt;p&gt;the application database&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Kafka&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The database transaction does not automatically include Kafka.&lt;/p&gt;
&lt;p&gt;Several failure scenarios are therefore possible.&lt;/p&gt;
&lt;h3&gt;Database succeeds, Kafka fails&lt;/h3&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Database
Payment = COMPLETED  ✓

Kafka
PaymentCompleted     ✗
&lt;/pre&gt;
&lt;p&gt;The local state says the payment completed, but downstream services never receive the event.&lt;/p&gt;
&lt;h3&gt;Kafka succeeds, database fails&lt;/h3&gt;
&lt;p&gt;Depending on when and how publishing occurs, the opposite problem can also happen.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Kafka
PaymentCompleted     ✓

Database
Payment = COMPLETED  ✗
&lt;/pre&gt;
&lt;p&gt;A consumer may now process an event representing state that was never committed.&lt;/p&gt;
&lt;p&gt;Trying to coordinate these operations manually quickly becomes complicated.&lt;/p&gt;
&lt;p&gt;What we really want is a simple guarantee:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;If the business transaction commits, the intention to publish its event must commit with it.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;That is where the outbox comes in.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;The Transactional Outbox&lt;/h2&gt;
&lt;p&gt;
  &lt;span&gt;Instead of publishing directly to Kafka inside the business transaction, we store the event in the same database transaction as the business data.&lt;/span&gt;
&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;     DATABASE TRANSACTION
        ┌─────────────────────────────┐
        │                             │
        │  Update Payment             │
        │         +                   │
        │  Insert Outbox Event        │
        │                             │
        └──────────────┬──────────────┘
                       │
                    COMMIT
                       │
                       v
                 Outbox Dispatcher
                       │
                       v
                     Kafka&lt;/pre&gt;&lt;p&gt; Now the database determines the atomic boundary. Either both records commit:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Payment       ✓
Outbox Event  ✓&lt;/pre&gt;
&lt;p&gt; or neither does:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Payment       ✗
Outbox Event  ✗&lt;/pre&gt;
&lt;p&gt;Kafka no longer needs to participate in the business transaction.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;What Goes Into the Outbox?&lt;/h2&gt;
&lt;p&gt;An outbox table normally contains enough information to publish the event later.&lt;/p&gt;
&lt;p&gt;Conceptually, a record could look like:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;event_id       = 01J...
event_type     = PaymentCompleted
source         = payment-service
payload        = {...}
content_type   = application/json
status         = PENDING
created_at     = ...&lt;/pre&gt;
&lt;p&gt;The important part is that the payload and its delivery state are persisted.&lt;/p&gt;
&lt;p&gt;I particularly prefer keeping the payload readable rather than hiding it behind opaque serialization.&lt;/p&gt;
&lt;p&gt;When something goes wrong in production, being able to inspect the exact event that was supposed to leave the service is extremely useful.&lt;/p&gt;
&lt;p&gt;The outbox isn&#39;t merely a delivery mechanism.&lt;/p&gt;
&lt;p&gt;It becomes part of your operational history.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Publishing the Event&lt;/h2&gt;
&lt;p&gt;A separate dispatcher polls pending outbox records.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;PENDING
   |
   v
PROCESSING
   |
   +--------------------+
   |                    |
   v                    v
PUBLISHED           retryable failure
                        |
                        v
                     PENDING
                        |
                     retry later&lt;/pre&gt;
&lt;p&gt; After a configurable number of attempts, permanently failing events can transition to:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;FAILED&lt;/pre&gt;
&lt;p&gt;This separation is important.&lt;/p&gt;
&lt;p&gt;Your business transaction is responsible for recording &lt;strong&gt;what happened&lt;/strong&gt;. &lt;/p&gt;
&lt;p&gt;The dispatcher is responsible for &lt;strong&gt;delivering that information&lt;/strong&gt;. &lt;/p&gt;
&lt;p&gt;Those are different responsibilities and should fail independently.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Why Not Just Retry Kafka Inside the Transaction?&lt;/h2&gt;
&lt;p&gt;A common first solution is to retry publishing:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;@Transactional
public void completePayment(Payment payment) {
    paymentRepository.save(payment);

    retryTemplate.execute(context -&amp;gt;
        kafkaTemplate.send(&quot;payments&quot;, event)
    );
}&lt;/pre&gt;
&lt;p&gt;Retries can help with temporary failures.&lt;/p&gt;
&lt;p&gt;But they do not remove the fundamental coupling.&lt;/p&gt;
&lt;p&gt;Imagine Kafka is unavailable for several minutes.&lt;/p&gt;
&lt;p&gt;Should your payment transaction remain open while the application repeatedly attempts to contact Kafka?&lt;/p&gt;
&lt;p&gt;Probably not.&lt;/p&gt;
&lt;p&gt;Long-running transactions consume database resources, increase lock duration, and couple business availability to messaging availability.&lt;/p&gt;
&lt;p&gt;
  &lt;span&gt;With an outbox:&lt;/span&gt;
&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Payment transaction
      |
      +---- commits quickly
      |
      v
Outbox

Kafka unavailable
      |
      +---- dispatcher retries independently&lt;/pre&gt;
&lt;p&gt;The business operation can succeed even while the broker is temporarily unavailable.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;At-Least-Once Delivery Changes the Problem&lt;/h2&gt;
&lt;p&gt;There is an important consequence.&lt;/p&gt;
&lt;p&gt;An outbox dispatcher can usually provide &lt;strong&gt;at-least-once delivery&lt;/strong&gt;, not magically guaranteed exactly-once business processing. &lt;/p&gt;
&lt;p&gt;Consider this sequence:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;1. Dispatcher publishes event to Kafka
2. Kafka accepts the event
3. Application crashes
4. Outbox record was not yet marked PUBLISHED
5. Application restarts
6. Dispatcher publishes the event again&lt;/pre&gt;
&lt;p&gt;The same event may be delivered twice.&lt;/p&gt;
&lt;p&gt;That is not necessarily a bug.&lt;/p&gt;
&lt;p&gt;It is a consequence of choosing reliability over silently losing messages.&lt;/p&gt;
&lt;p&gt;The architecture therefore becomes:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Transactional Outbox
        +
At-Least-Once Delivery
        +
Idempotent Consumer&lt;/pre&gt;
&lt;p&gt;This is why the &lt;strong&gt;inbox pattern&lt;/strong&gt; naturally complements the outbox pattern. &lt;/p&gt;
&lt;p&gt;We&#39;ll cover that separately.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Multiple Application Instances&lt;/h2&gt;
&lt;p&gt;Production systems rarely run a single instance.&lt;/p&gt;
&lt;p&gt;Imagine three pods:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;        OUTBOX
                 |
        +--------+--------+
        |        |        |
       Pod A    Pod B    Pod C&lt;/pre&gt;
&lt;p&gt;Without coordination, multiple pods could select the same pending events.&lt;/p&gt;
&lt;p&gt;One common approach is database-level locking.&lt;/p&gt;
&lt;p&gt;Conceptually:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;SELECT ...
FROM outbox
WHERE status = &#39;PENDING&#39;
FOR UPDATE SKIP LOCKED;&lt;/pre&gt;
&lt;p&gt; Suppose the outbox contains: &lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;1
2
3
4
5
6&lt;/pre&gt;
&lt;p&gt; Pod A may lock: &lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;1 2 3&lt;/pre&gt;
&lt;p&gt; while Pod B skips those locked rows and receives: &lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;4 5 6&lt;/pre&gt;
&lt;p&gt;This allows multiple workers to process the outbox concurrently without waiting on the same rows.&lt;/p&gt;
&lt;p&gt;The exact implementation depends on the database and persistence strategy, but the principle is important:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;Scaling the dispatcher horizontally should not mean publishing every event multiple times.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;What About CDC?&lt;/h2&gt;
&lt;p&gt;Polling isn&#39;t the only way to implement an outbox.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;	&lt;code class=&quot;language-text&quot;&gt;&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;
  &lt;span&gt;Another common architecture uses Change Data Capture:&lt;/span&gt;
&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Application
     |
     v
Database Outbox
     |
     v
    CDC
     |
     v
   Kafka

&lt;/pre&gt;
&lt;p&gt;Tools such as Debezium can stream database changes instead of having application workers poll the table.&lt;/p&gt;
&lt;p&gt;CDC can be an excellent choice at larger scale or when an organization already operates the necessary infrastructure.&lt;/p&gt;
&lt;p&gt;But it introduces another operational component.&lt;/p&gt;
&lt;p&gt;Application-level polling has different advantages:&lt;/p&gt;
&lt;ul data-spread=&quot;false&quot;&gt;
  &lt;li&gt;
    &lt;p&gt;simpler infrastructure&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;easier local development&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;easier debugging&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;broker independence&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;application-controlled retry behavior&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Neither approach is universally better.&lt;/p&gt;
&lt;p&gt;The important architectural idea is not the polling mechanism.&lt;/p&gt;
&lt;p&gt;It is the &lt;strong&gt;transactional boundary provided by the outbox&lt;/strong&gt;. &lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Making This Reusable&lt;/h2&gt;
&lt;p&gt;After implementing this pattern several times, a lot of infrastructure starts repeating:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Outbox persistence
Event serialization
Dispatch scheduling
Retry handling
Concurrency
Failure states
Metrics
Kafka integration
SQS integration
Operational endpoints&lt;/pre&gt;
&lt;p&gt;Business applications shouldn&#39;t need to rebuild all of that every time they need reliable event delivery.&lt;/p&gt;
&lt;p&gt;That is one of the reasons I built &lt;strong&gt;NERV Event&lt;/strong&gt;. &lt;/p&gt;
&lt;p&gt;With NERV Event, the goal is to keep the application focused on expressing the event while the library handles the delivery lifecycle.&lt;/p&gt;
&lt;p&gt;Conceptually:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;eventPublisher.publish(
    &quot;PaymentCompleted&quot;,
    paymentCompletedEvent
);&lt;/pre&gt;
&lt;p&gt;Behind that operation is the infrastructure required to persist and eventually dispatch the event reliably.&lt;/p&gt;
&lt;p&gt;
  &lt;span&gt;The architecture becomes:&lt;/span&gt;
&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Business Service
      |
      v
  NERV Event
      |
      v
Transactional Outbox
      |
      v
Dispatcher
      |
   +--+--+
   |     |
 Kafka  SQS&lt;/pre&gt;
&lt;p&gt;The application owns the business event.&lt;/p&gt;
&lt;p&gt;The infrastructure owns its reliable delivery.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Reliability Doesn&#39;t End at the Producer&lt;/h2&gt;
&lt;p&gt;The transactional outbox solves an important problem:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;How do I make sure an event isn&#39;t lost after my business transaction commits?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;But once that event reaches another service, a new set of problems begins.&lt;/p&gt;
&lt;p&gt;What if the consumer processes the same event twice?&lt;/p&gt;
&lt;p&gt;What happens if processing succeeds but acknowledgement fails?&lt;/p&gt;
&lt;p&gt;How do we retry safely?&lt;/p&gt;
&lt;p&gt;How do we know whether an event has already been processed?&lt;/p&gt;
&lt;p&gt;Those are consumer-side reliability problems.&lt;/p&gt;
&lt;p&gt;And that is where the &lt;strong&gt;Inbox Pattern&lt;/strong&gt; comes in. &lt;/p&gt;
&lt;p&gt;In the next article, we&#39;ll look at &lt;strong&gt;Inbox Pattern and Idempotent Consumers&lt;/strong&gt; and build the other half of reliable event delivery. &lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;NERV Event&lt;/h2&gt;
&lt;p&gt;NERV Event is an open-source event reliability framework for Spring Boot designed around transactional outbox/inbox processing, retries, idempotency, Kafka and SQS integration, and production operations.&lt;/p&gt;
&lt;p&gt;GitHub: &lt;a href=&quot;https://www.github.com/czetsuyatech/nerv-event&quot;&gt;https://www.github.com/czetsuyatech/nerv-event&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The broader introduction to the architecture is covered in:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;&lt;a href=&quot;https://www.czetsuyatech.com/2026/08/reliable-event-driven-architecture-spring-boot-outbox-inbox.html&quot; target=&quot;_blank&quot;&gt;Reliable Event-Driven Architecture in Spring Boot: Outbox, Inbox, Retries, and Idempotency&lt;/a&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;This series goes deeper into each of the reliability problems individually.&lt;/p&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Previous Article --&gt;
    &lt;div style=&quot;flex: 1; min-width: 200px;&quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        ← Previous
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/08/reliable-event-driven-architecture-spring-boot-outbox-inbox.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Reliable Event-Driven Architecture in Spring Boot: Outbox, Inbox, Retries, and Idempotency
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Event&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/hardening-event-driven-systems-nerv-event-2-1.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Hardening Event-Driven Systems: Lessons from NERV Event 2.1
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/71645515009221612/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/09/transactional-outbox-pattern-spring-boot.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/71645515009221612'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/71645515009221612'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/09/transactional-outbox-pattern-spring-boot.html' title='Transactional Outbox Pattern with Spring Boot: Reliable Event Publishing Without Dual Writes'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR4lJjp3wUJFZnGkro5J8Wr0Ify4rNtjqsVc1u9V6QNxcvedwBYfM60jgUy_oHaptUyRJyNZTp7XM93CDaEqZ9Ia9p62LE5sZBLm2cg1GsnAnSUCwTw5dFOlu2Gtuh27EIkWgwnB5nSvmrCFHuwC8SGf0nf5IPE3rlZSdUUHv8nqQblQrfU2DJIc577qGQ/s72-c/transactional-outbox-pattern.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-2101031399037344448</id><published>2026-09-01T13:46:17.000+08:00</published><updated>2026-10-17T11:09:58.927+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Distributed Systems"/><category scheme="http://www.blogger.com/atom/ns#" term="Event-Driven Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Featured"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Event"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>Reliable Event-Driven Architecture in Spring Boot: Outbox, Inbox, Retries, and Idempotency</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
  &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4Udr56O2l2WPsC001518pGbk743tqj_mUDGbgX96jXVYlbLrFMSCOqnzWIYhdMubDnyUugF1TLK1SbnMfwOfYaVfi9NzixjJWvOmjj5UzJb7z-CF6Or0KA6DvNLgf_ev97rI7LWc1wd20-Xe-xh27krJ_ZWwVEJvfgvu8ffBTcenzPibC3wodCbHWbMim/s1536/reliable-event-driven-architecture-spring-boot-nerv-event.png.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;
    &lt;img border=&quot;0&quot; data-original-height=&quot;1024&quot; data-original-width=&quot;1536&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4Udr56O2l2WPsC001518pGbk743tqj_mUDGbgX96jXVYlbLrFMSCOqnzWIYhdMubDnyUugF1TLK1SbnMfwOfYaVfi9NzixjJWvOmjj5UzJb7z-CF6Or0KA6DvNLgf_ev97rI7LWc1wd20-Xe-xh27krJ_ZWwVEJvfgvu8ffBTcenzPibC3wodCbHWbMim/s1600/reliable-event-driven-architecture-spring-boot-nerv-event.png.png&quot; /&gt;
  &lt;/a&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Event-driven architecture looks simple at first.&lt;/p&gt;
&lt;p&gt;Your application performs a business operation, publishes an event to Kafka or SQS, and another service consumes it.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;@Transactional
public void createOrder(CreateOrderCommand command) {
  Order order = orderRepository.save(...);

  kafkaTemplate.send(
      &quot;orders&quot;,
      new OrderCreatedEvent(order.getId())
  );
}
&lt;/pre&gt;
&lt;p&gt;The order is saved, an &lt;code&gt;OrderCreatedEvent&lt;/code&gt; is published, and other services can react to it. &lt;/p&gt;
&lt;p&gt;But there is a problem hiding in those few lines.&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;What happens if the database transaction succeeds, but publishing the event fails?&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;And on the other side:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;What happens if the consumer receives the same event twice?&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;These two questions lead to some of the most important patterns in reliable event-driven systems: the &lt;strong&gt;Transactional Outbox&lt;/strong&gt;, &lt;strong&gt;Inbox&lt;/strong&gt;, &lt;strong&gt;Idempotent Consumer&lt;/strong&gt;, and &lt;strong&gt;Durable Retry&lt;/strong&gt; patterns. &lt;/p&gt;
&lt;p&gt;Let&#39;s build the architecture step by step and see what changes when these patterns have to work in a real Spring Boot application running across multiple instances&lt;/p&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;The Dual-Write Problem&lt;/h2&gt;
&lt;p&gt;Imagine an order service that needs to do two things:&lt;/p&gt;
&lt;ol data-spread=&quot;false&quot; start=&quot;1&quot;&gt;
  &lt;li&gt;
    &lt;p&gt;Save an order to PostgreSQL.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Publish &lt;code&gt;OrderCreated&lt;/code&gt; to Kafka. &lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Conceptually:&lt;/p&gt;
&lt;pre&gt;Database ──────&amp;gt; COMMIT ✓
                   |
Kafka ─────────&amp;gt; PUBLISH ✗
&lt;/pre&gt;
&lt;p&gt; The database and Kafka are two independent systems. A successful database commit does not guarantee a successful Kafka publish. Consider this sequence: &lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;1. INSERT order
2. COMMIT
3. Publish OrderCreated
4. Application crashes
&lt;/pre&gt;
&lt;p&gt;If the application crashes between steps 2 and 3, the order exists but the event doesn&#39;t.&lt;/p&gt;
&lt;p&gt;Other services may never know that the order was created.&lt;/p&gt;
&lt;p&gt;Reversing the operations doesn&#39;t solve the problem either:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;1. Publish OrderCreated
2. INSERT order
3. Database transaction fails
&lt;/pre&gt;
&lt;p&gt;Now consumers may receive an event for an order that doesn&#39;t exist.&lt;/p&gt;
&lt;p&gt;This is the classic &lt;strong&gt;dual-write problem&lt;/strong&gt;. &lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;The Transactional Outbox Pattern&lt;/h2&gt;
&lt;p&gt;Instead of trying to atomically update the database and message broker, we make the event part of the same database transaction as the business operation.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;             Database Transaction
        ┌─────────────────────────────┐
        │                             │
Request ──&amp;gt; Business Data             │
        │       +                     │
        │   Outbox Event              │
        │                             │
        └────────── COMMIT ───────────┘
                       |
                       v
                Outbox Dispatcher
                       |
                       v
                  Kafka / SQS
&lt;/pre&gt;
&lt;p&gt;When an order is created, we persist both the business data and the event:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;ORDER
  +
OUTBOX EVENT
&lt;/pre&gt;
&lt;p&gt;inside the same database transaction.&lt;/p&gt;
&lt;p&gt;Either both are committed or neither is committed.&lt;/p&gt;
&lt;p&gt;A separate dispatcher then finds pending outbox records and publishes them to the broker.&lt;/p&gt;
&lt;p&gt;A simplified lifecycle might look like this:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;PENDING
   |
   v
PROCESSING
   |
   +──── success ────&amp;gt; PUBLISHED
   |
   └──── failure ────&amp;gt; RETRY / FAILED
&lt;/pre&gt;
&lt;p&gt;This removes the dangerous database-and-broker dual write from the business transaction.&lt;/p&gt;
&lt;p&gt;But it also gives us something extremely valuable in production:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;persistent delivery state.&lt;/strong&gt;
&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Your Outbox Should Be Debuggable&lt;/h2&gt;
&lt;p&gt;Reliability isn&#39;t only about retrying failed operations.&lt;/p&gt;
&lt;p&gt;When something goes wrong in production, someone eventually needs to answer:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;What happened to this event?&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;A useful outbox record should contain enough information to answer that question:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;eventId
eventType
source
correlationId
payload
status
attempts
createdAt
availableAt
publishedAt
lastError
&lt;/pre&gt;
&lt;p&gt; Instead of searching through distributed logs hoping to reconstruct what happened, an engineer can inspect the actual delivery state: &lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;SELECT *
FROM event_outbox
WHERE status = &#39;FAILED&#39;;
&lt;/pre&gt;
&lt;p&gt;This leads to an important principle:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;Reliability mechanisms should also improve debuggability.&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;If an event cannot be delivered, that failure should be visible and inspectable.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Publishing Reliably Is Only Half the Problem&lt;/h2&gt;
&lt;p&gt;Suppose our outbox works perfectly.&lt;/p&gt;
&lt;p&gt;Every event eventually reaches Kafka.&lt;/p&gt;
&lt;p&gt;We still aren&#39;t finished.&lt;/p&gt;
&lt;p&gt;Most event-driven architectures use &lt;strong&gt;at-least-once delivery&lt;/strong&gt;. That means the same event may be delivered more than once. &lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Producer
   |
   v
Kafka
   |
   +──── OrderCreated #123 ────&amp;gt; Consumer
   |
   +──── OrderCreated #123 ────&amp;gt; Consumer
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;A consumer might successfully process an event but crash before acknowledging it. The broker can then deliver it again.&lt;/p&gt;
&lt;p&gt;If processing means sending an email, the customer might receive two emails.&lt;/p&gt;
&lt;p&gt;If processing means performing a financial operation, the consequences can be much worse.&lt;/p&gt;
&lt;p&gt;A reliable consumer therefore needs to assume:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;Every event can arrive more than once.&lt;/strong&gt;
&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;The Inbox Pattern&lt;/h2&gt;
&lt;p&gt;The Inbox Pattern provides a durable record of received events.&lt;/p&gt;
&lt;p&gt;Before processing an event, the consumer registers its unique event ID.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Broker
   |
   v
Inbox Registration
   |
   +── event already exists ──&amp;gt; DUPLICATE
   |
   └── new event
          |
          v
       RECEIVED
          |
          v
      PROCESSING
        /     \
       v       v
 PROCESSED   FAILED
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;If the same &lt;code dir=&quot;ltr&quot;&gt;eventId&lt;/code&gt; arrives again, the consumer knows that it has already seen the event. &lt;/p&gt;
&lt;p&gt;The event ID becomes an &lt;strong&gt;idempotency boundary&lt;/strong&gt;. &lt;/p&gt;
&lt;p&gt;Instead of depending on exactly-once delivery, we design the consumer so duplicate delivery does not result in duplicate business effects.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;The Inbox Is More Than a Deduplication Table&lt;/h2&gt;
&lt;p&gt;A minimal inbox could contain nothing more than processed event IDs.&lt;/p&gt;
&lt;p&gt;For production systems, however, it can provide something much more useful:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;a durable history of event processing.&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;Consider storing:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;eventId
eventType
source
correlationId
payload
status
attempts
receivedAt
processedAt
availableAt
lastError
&lt;/pre&gt;
&lt;p&gt;Now imagine someone reports:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;Order 123 was created, but the downstream action never happened.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;You can inspect the inbox.&lt;/p&gt;
&lt;p&gt;Was the event received?&lt;/p&gt;
&lt;p&gt;Was processing started?&lt;/p&gt;
&lt;p&gt;Did processing fail?&lt;/p&gt;
&lt;p&gt;How many times was it attempted?&lt;/p&gt;
&lt;p&gt;When is the next retry?&lt;/p&gt;
&lt;p&gt;What was the last error?&lt;/p&gt;
&lt;p&gt;Those questions become much easier to answer when processing state is explicit.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Retries Should Survive Application Restarts&lt;/h2&gt;
&lt;p&gt;Spring provides excellent retry mechanisms.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;	&lt;code class=&quot;language-java&quot;&gt;&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;
  &lt;span&gt;For example:&lt;/span&gt;
&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;@Retryable
public void handle(OrderCreatedEvent event) {
  ...
}
&lt;/pre&gt;
&lt;p&gt;This can be perfectly appropriate for short-lived transient failures.&lt;/p&gt;
&lt;p&gt;But event processing introduces another question:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;What happens if the JVM dies?&lt;/strong&gt;
&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Event processing fails
        |
        v
Retry scheduled in memory
        |
        v
Application restarts
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;If retry state exists only in memory, it disappears with the process.&lt;/p&gt;
&lt;p&gt;For durable event processing, retry state can instead be persisted:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;FAILED
   |
   | availableAt &amp;lt;= now
   v
PROCESSING
   |
   +──── success ────&amp;gt; PROCESSED
   |
   └──── failure ────&amp;gt; FAILED
                         |
                         + attempts++
                         + availableAt = next retry
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;A scheduler periodically finds events whose retry time has arrived and attempts them again.&lt;/p&gt;
&lt;p&gt;Because the state lives in the database, restarting the application doesn&#39;t destroy the retry information.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Use Backoff Instead of Hammering a Failing Dependency&lt;/h2&gt;
&lt;p&gt;Retrying immediately and continuously can make an outage worse.&lt;/p&gt;
&lt;p&gt;Suppose a downstream service is unavailable.&lt;/p&gt;
&lt;p&gt;Thousands of failed events retrying as quickly as possible simply add more pressure to an already failing system.&lt;/p&gt;
&lt;p&gt;A better strategy is exponential backoff:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Attempt 1 → immediate
Attempt 2 → +1 second
Attempt 3 → +2 seconds
Attempt 4 → +4 seconds
Attempt 5 → +8 seconds
&lt;/pre&gt;
&lt;p&gt;Eventually, the configured retry limit is exhausted.&lt;/p&gt;
&lt;p&gt;At that point, the event can remain explicitly marked as failed:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;status = FAILED
availableAt = null
&lt;/pre&gt;
&lt;p&gt;Automatic processing stops, but the event doesn&#39;t disappear.&lt;/p&gt;
&lt;p&gt;It remains available for investigation and operational recovery.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;What About Dead-Letter Queues?&lt;/h2&gt;
&lt;p&gt;Dead-letter queues are valuable, particularly for broker-level failures.&lt;/p&gt;
&lt;p&gt;But a broker DLQ doesn&#39;t necessarily have to become the application&#39;s primary record of processing failure.&lt;/p&gt;
&lt;p&gt;There is a useful distinction:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Broker concern               Application concern

Delivery failure             Processing failure
Malformed message            Business handler failure
Transport problem            Retry exhaustion
        |                            |
        v                            v
       DLQ                         INBOX
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;The two mechanisms can coexist.&lt;/p&gt;
&lt;p&gt;A database-backed inbox gives the application direct visibility into its own processing state, while a DLQ remains available for appropriate broker and transport-level failures.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Then You Deploy Multiple Pods&lt;/h2&gt;
&lt;p&gt;Everything becomes more interesting once the application runs more than one instance.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;                 OUTBOX
                     |
               pending event
                     |
          ┌──────────┴──────────┐
          v                     v
        Pod A                 Pod B
     Dispatcher             Dispatcher
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;Both instances may discover the same pending event.&lt;/p&gt;
&lt;p&gt;Without concurrency control, both may attempt to process it.&lt;/p&gt;
&lt;p&gt;Production implementations therefore need a concept of &lt;strong&gt;claiming or locking&lt;/strong&gt;. &lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;status
lockOwner
lockedAt
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;An instance claims records transactionally before processing them.&lt;/p&gt;
&lt;p&gt;Other instances can then determine that those records are already being processed.&lt;/p&gt;
&lt;p&gt;But this creates another question:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;What happens if a pod claims an event and then dies?&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;The system needs a deterministic mechanism for recovering stale claims after an appropriate timeout.&lt;/p&gt;
&lt;p&gt;At this point, the outbox is no longer just a database table plus a scheduled query.&lt;/p&gt;
&lt;p&gt;It has become infrastructure.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Even the Scheduler Can Fail&lt;/h2&gt;
&lt;p&gt;There is another failure mode that is surprisingly easy to overlook.&lt;/p&gt;
&lt;p&gt;Suppose the dispatcher completes successfully and schedules its next execution:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Dispatcher completes
        |
        v
schedule(nextRun)
        |
        X
TaskScheduler rejects the task
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;If the scheduler continues reporting itself as running, the application has entered a dangerous state.&lt;/p&gt;
&lt;p&gt;Everything appears healthy.&lt;/p&gt;
&lt;p&gt;But no future dispatch will happen.&lt;/p&gt;
&lt;p&gt;Events can quietly accumulate in the outbox.&lt;/p&gt;
&lt;p&gt;A reliable scheduler therefore benefits from an explicit lifecycle:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;STOPPED
   |
   v
STARTING
   |
   v
RUNNING
   |
   +──── scheduling failure ────&amp;gt; FAILED
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;A useful invariant is:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;A scheduler must not report itself as running if no task is scheduled and no work is currently executing.&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;Scheduling infrastructure itself needs observable failure semantics.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Observability Is Part of Reliability&lt;/h2&gt;
&lt;p&gt;Imagine receiving a production incident at 2 AM:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;We created the order, but the downstream system didn&#39;t process it.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;	&lt;code class=&quot;language-text&quot;&gt;&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;
  &lt;span&gt;Ideally, you should be able to follow the event:&lt;/span&gt;
&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Order
  |
  v
Outbox Event
  |
  +── created
  +── claimed
  +── publish attempts
  +── published
  |
  v
Broker
  |
  v
Inbox Event
  |
  +── received
  +── processing attempts
  +── failure reason
  +── retry schedule
  +── processed
&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;Correlation metadata should connect the pieces.&lt;/p&gt;
&lt;p&gt;Payloads should be readable.&lt;/p&gt;
&lt;p&gt;State transitions should be explicit.&lt;/p&gt;
&lt;p&gt;Failures should remain inspectable.&lt;/p&gt;
&lt;p&gt;Logs should explain what the infrastructure is doing without becoming the only source of truth.&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;A reliable system isn&#39;t only one that recovers from failures. It is one that helps engineers understand those failures.&lt;/strong&gt;
&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;From Architecture to Implementation: NERV Event&lt;/h2&gt;
&lt;p&gt;These are the problems I wanted to solve consistently across Spring Boot applications.&lt;/p&gt;
&lt;p&gt;None of the individual patterns are new.&lt;/p&gt;
&lt;p&gt;Transactional outbox is well understood. Idempotent consumers are well understood. Retries, locking, and message brokers are well understood.&lt;/p&gt;
&lt;p&gt;The difficulty is making all of them work together consistently in a production application.&lt;/p&gt;
&lt;p&gt;That led me to build &lt;strong&gt;NERV Event&lt;/strong&gt;: an open-source event infrastructure library for Spring Boot. &lt;/p&gt;
&lt;p&gt;At a high level, the architecture looks like this:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;             Spring Boot Application
                         |
              ┌──────────┴──────────┐
              |                     |
              v                     v
           OUTBOX                  INBOX
              |                     ^
              v                     |
        Outbox Dispatcher           |
              |                     |
              v                     |
         Kafka / AWS SQS ───────────┘&lt;/pre&gt;
&lt;p data-pm-slice=&quot;1 1 []&quot;&gt;NERV Event brings together:&lt;/p&gt;
&lt;ul data-spread=&quot;false&quot;&gt;
  &lt;li&gt;
    &lt;p&gt;Transactional outbox persistence&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Durable inbox processing&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Idempotent event consumption&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Persistent retries&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Exponential retry policies&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Multi-instance-safe processing&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Kafka integration&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;AWS SQS integration&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Scheduler lifecycle and failure visibility&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Event retention&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Operational inspection&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Correlation metadata&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Human-readable persisted payloads&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The goal isn&#39;t to hide event-driven architecture behind magic.&lt;/p&gt;
&lt;p&gt;The goal is to make its behavior &lt;strong&gt;predictable, observable, and easy to debug&lt;/strong&gt;. &lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Explore NERV Event&lt;/h2&gt;
&lt;p&gt;NERV Event is open source and available on GitHub.&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;Source code, documentation, configuration, and examples:&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;NERV Event on GitHub: &lt;br /&gt;
  &lt;a data-rich-text-autolink=&quot;&quot; href=&quot;https://github.com/czetsuyatech/nerv-event&quot;&gt;https://github.com/czetsuyatech/nerv-event&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;If you&#39;re building event-driven Spring Boot services, you can also use the project as a reference architecture even if you don&#39;t adopt the library itself.&lt;/p&gt;
&lt;p&gt;I&#39;ll be writing more about the individual pieces behind NERV Event—including transactional publishing, inbox processing, Kafka and SQS integration, retries, multi-pod deployment, and operational tooling—in future articles.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;h2&gt;Final Thoughts&lt;/h2&gt;
&lt;p&gt;Adding Kafka or SQS to a Spring Boot application doesn&#39;t automatically make the application reliably event-driven.&lt;/p&gt;
&lt;p&gt;The difficult parts exist around the broker:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;Business Transaction
        |
        v
Transactional Outbox
        |
        v
Reliable Delivery
        |
        v
At-Least-Once Messaging
        |
        v
Inbox + Idempotency
        |
        v
Durable Processing
        |
        v
Retries + Recovery
        |
        v
Observability&lt;/pre&gt;
&lt;p&gt;Each layer addresses a different failure mode.&lt;/p&gt;
&lt;p&gt;And in distributed systems, those failure modes aren&#39;t theoretical. Processes restart. Networks fail. Messages are redelivered. Dependencies become unavailable. Schedulers stop. Multiple instances compete for the same work.&lt;/p&gt;
&lt;p&gt;The goal isn&#39;t to pretend those failures won&#39;t happen.&lt;/p&gt;
&lt;p&gt;The goal is to design the system so that when they do happen:&lt;/p&gt;
&lt;p&gt;
  &lt;strong&gt;state is preserved, recovery is predictable, and engineers can understand exactly what happened.&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;That&#39;s the philosophy behind NERV Event.&lt;/p&gt;
&lt;div&gt;
  &lt;hr /&gt;
&lt;/div&gt;
&lt;p&gt;
  &lt;strong&gt;NERV Event&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;Open-source event infrastructure for reliable Spring Boot applications.&lt;/p&gt;
&lt;p&gt;GitHub: &lt;a data-rich-text-autolink=&quot;&quot; href=&quot;https://github.com/czetsuyatech/nerv-event&quot;&gt;https://github.com/czetsuyatech/nerv-event&lt;/a&gt;
&lt;/p&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;


    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Event
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Event&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/transactional-outbox-pattern-spring-boot.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Transactional Outbox Pattern with Spring Boot: Reliable Event Publishing Without Dual Writes
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/2101031399037344448/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/08/reliable-event-driven-architecture-spring-boot-outbox-inbox.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/2101031399037344448'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/2101031399037344448'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/08/reliable-event-driven-architecture-spring-boot-outbox-inbox.html' title='Reliable Event-Driven Architecture in Spring Boot: Outbox, Inbox, Retries, and Idempotency'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4Udr56O2l2WPsC001518pGbk743tqj_mUDGbgX96jXVYlbLrFMSCOqnzWIYhdMubDnyUugF1TLK1SbnMfwOfYaVfi9NzixjJWvOmjj5UzJb7z-CF6Or0KA6DvNLgf_ev97rI7LWc1wd20-Xe-xh27krJ_ZWwVEJvfgvu8ffBTcenzPibC3wodCbHWbMim/s72-c/reliable-event-driven-architecture-spring-boot-nerv-event.png.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-1440531714013119487</id><published>2026-07-06T18:49:23.000+08:00</published><updated>2026-10-18T22:35:07.695+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Cloud"/><category scheme="http://www.blogger.com/atom/ns#" term="Featured"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Exception"/><category scheme="http://www.blogger.com/atom/ns#" term="REST API"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><category scheme="http://www.blogger.com/atom/ns#" term="Troubleshooting"/><title type='text'>Stop Copying Exception Handlers Between Spring Boot Projects</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDKs5qOjyoxneSwd6hmEPmiUMlAjYJLzjwgfmN9OEN6ikfkSJF131-mBlNpTlEuR4edzdqGAFvhZzNspCX2z8LmA-282r1LnXLegVdxamcB7vWsy09VROU6NT348SLvyI9XWdNAJNO2o1jgRFnVRySmG3gn22XW47YxDYoF5X3LDKzXlNUUBPhXiHQONlF/s1536/ChatGPT%20Image%20Jul%206,%202026,%2009_06_19%20PM.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1024&quot; data-original-width=&quot;1536&quot; height=&quot;427&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDKs5qOjyoxneSwd6hmEPmiUMlAjYJLzjwgfmN9OEN6ikfkSJF131-mBlNpTlEuR4edzdqGAFvhZzNspCX2z8LmA-282r1LnXLegVdxamcB7vWsy09VROU6NT348SLvyI9XWdNAJNO2o1jgRFnVRySmG3gn22XW47YxDYoF5X3LDKzXlNUUBPhXiHQONlF/w640-h427/ChatGPT%20Image%20Jul%206,%202026,%2009_06_19%20PM.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;If you&#39;ve built more than one Spring Boot application, you&#39;ve probably experienced this.&lt;/p&gt;
&lt;p&gt;You start with a few REST endpoints and a simple &lt;code dir=&quot;ltr&quot;&gt;@RestControllerAdvice&lt;/code&gt;. &lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;@RestControllerAdvice 
public class GlobalExceptionHandler {
    @ExceptionHandler(UserNotFoundException.class) 
    public ResponseEntity &amp;lt; ? &amp;gt; handle(UserNotFoundException ex) {
      // ... 
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity &amp;lt; ? &amp;gt; handle(MethodArgumentNotValidException ex) {
      // ... 
    }
}
&lt;/pre&gt;
&lt;p class=&quot;isSelectedEnd&quot;&gt;Everything looks fine.&lt;/p&gt;
&lt;p class=&quot;isSelectedEnd&quot;&gt;Then the application grows.&lt;/p&gt;
&lt;p class=&quot;isSelectedEnd&quot;&gt;You introduce custom business exceptions. Validation errors need a different response format. Another microservice returns completely different error payloads. Feign clients need their own error decoder. Kafka consumers have another way of reporting failures.&lt;/p&gt;
&lt;p class=&quot;isSelectedEnd&quot;&gt;Before long, your application no longer has one exception handling strategy—it has several.&lt;/p&gt;
&lt;p class=&quot;isSelectedEnd&quot;&gt;I&#39;ve seen this happen in multiple Spring Boot projects over the years.&lt;/p&gt;
&lt;p class=&quot;isSelectedEnd&quot;&gt;Ironically, while the business logic was always different, the exception handling infrastructure was almost identical.&lt;/p&gt;
&lt;p&gt;I found myself copying the same classes from project to project:&lt;/p&gt;
&lt;ul data-spread=&quot;false&quot;&gt;
  &lt;li&gt;Global exception handlers&lt;/li&gt;
  &lt;li&gt;Error response models&lt;/li&gt;
  &lt;li&gt;Error codes&lt;/li&gt;
  &lt;li&gt;Validation handlers&lt;/li&gt;
  &lt;li&gt;Feign decoders&lt;/li&gt;
  &lt;li&gt;Utility classes&lt;/li&gt;
  &lt;li&gt;Configuration&lt;/li&gt;
&lt;/ul&gt;
&lt;p class=&quot;isSelectedEnd&quot;&gt;Every new project started with the same foundation.&lt;/p&gt;
&lt;p&gt;Eventually I stopped and asked myself:&lt;/p&gt;
&lt;p&gt;
  &lt;i&gt;Why am I rebuilding this every single time?&lt;/i&gt;
&lt;/p&gt;
&lt;p&gt;That question became &lt;strong&gt;nerv-exception&lt;/strong&gt;. &lt;/p&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;What I Wanted to Build&lt;/h2&gt;
&lt;div&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;I wasn&#39;t trying to create another framework.&lt;/p&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;Spring Boot is already an excellent framework.&lt;/p&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;Instead, I wanted a reusable library that provides a solid foundation for one specific concern:&lt;/p&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;
    &lt;strong&gt;Consistent exception handling.&lt;/strong&gt;
  &lt;/p&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;The library should be:&lt;/p&gt;
  &lt;ul data-spread=&quot;false&quot;&gt;
    &lt;li&gt;Production-ready&lt;/li&gt;
    &lt;li&gt;Modular&lt;/li&gt;
    &lt;li&gt;Lightweight&lt;/li&gt;
    &lt;li&gt;Easy to customize&lt;/li&gt;
    &lt;li&gt;Easy to integrate&lt;/li&gt;
    &lt;li&gt;Easy to remove if needed&lt;/li&gt;
  &lt;/ul&gt;
  &lt;h2 style=&quot;text-align: left;&quot;&gt;Introducing nerv-exception&lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;
    &lt;strong&gt;nerv-exception&lt;/strong&gt; is a modular Spring Boot library that standardizes exception handling across your application.
  &lt;/p&gt;
  &lt;p&gt;Instead of rebuilding the same infrastructure, you simply add the starter.&lt;/p&gt;
&lt;/div&gt;
&lt;pre class=&quot;brush: java&quot;&gt;&amp;lt;dependency&amp;gt; 
	&amp;lt;groupId&amp;gt;com.czetsuyatech&amp;lt;/groupId&amp;gt; 
	&amp;lt;artifactId&amp;gt;nerv-exception-spring-boot-starter&amp;lt;/artifactId&amp;gt; 
	&amp;lt;version&amp;gt;1.0.0&amp;lt;/version&amp;gt; 
&amp;lt;/dependency&amp;gt;
&lt;/pre&gt;
&lt;p class=&quot;isSelectedEnd&quot;&gt;The library provides:&lt;/p&gt;
&lt;ul data-spread=&quot;false&quot;&gt;
  &lt;li&gt;Standardized API error responses&lt;/li&gt;
  &lt;li&gt;RFC 7807 Problem Details support&lt;/li&gt;
  &lt;li&gt;Centralized error codes&lt;/li&gt;
  &lt;li&gt;Global exception handling&lt;/li&gt;
  &lt;li&gt;Bean Validation integration&lt;/li&gt;
  &lt;li&gt;Spring Boot auto-configuration&lt;/li&gt;
  &lt;li&gt;Feign client integration&lt;/li&gt;
  &lt;li&gt;Event and Kafka support&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Designed to Be Modular&lt;/h2&gt;
&lt;div&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;One thing I dislike about many libraries is that they force you to adopt everything.&lt;/p&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;I wanted the opposite.&lt;/p&gt;
  &lt;p&gt;The project is divided into focused modules.&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;nerv-exception-api&amp;nbsp;&lt;/li&gt;
    &lt;li&gt;nerv-exception-core&amp;nbsp;&lt;/li&gt;
    &lt;li&gt;nerv-exception-spring-web&amp;nbsp;&lt;/li&gt;
    &lt;li&gt;nerv-exception-spring-boot-starter&amp;nbsp;&lt;/li&gt;
    &lt;li&gt;nerv-exception-spring-feign&amp;nbsp;&lt;/li&gt;
    &lt;li&gt;nerv-exception-event&amp;nbsp;&lt;/li&gt;
    &lt;li&gt;nerv-exception-spring-kafka&lt;/li&gt;
  &lt;/ul&gt;
  &lt;div&gt;Applications can depend on only the modules they need.&lt;/div&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Consistent Error Responses&lt;/h2&gt;
&lt;div&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;One of the biggest benefits is consistency.&lt;/p&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;Instead of every controller returning a different error payload, clients receive predictable responses.&lt;/p&gt;
  &lt;p&gt;For example, a &quot;User Not Found&quot; error can be represented using RFC 7807 Problem Details.&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;  {
  &quot;type&quot;: &quot;https://example.com/problems/user-not-found&quot;,
  &quot;title&quot;: &quot;User not found&quot;,
  &quot;status&quot;: 404,
  &quot;detail&quot;: &quot;User 123 was not found.&quot;,
  &quot;instance&quot;: &quot;/users/123&quot;
}
  &lt;/pre&gt; Consistent responses make APIs easier to consume, easier to document, and easier to troubleshoot.
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Real Examples Matter&lt;/h2&gt;
&lt;div&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;Documentation is important.&lt;/p&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;But I believe runnable code is even more valuable.&lt;/p&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;That&#39;s why I also created the &lt;strong&gt;nerv-examples&lt;/strong&gt; repository, which contains complete Spring Boot applications demonstrating how to integrate the library in real projects. &lt;/p&gt;
  &lt;p class=&quot;isSelectedEnd&quot;&gt;Rather than reading isolated snippets, you can clone the repository, run the application, and explore the implementation yourself.&lt;/p&gt;
  &lt;h2 style=&quot;text-align: left;&quot;&gt;Why Open Source?&lt;/h2&gt;
  &lt;div&gt;
    &lt;p class=&quot;isSelectedEnd&quot;&gt;Throughout my career, open source libraries have saved me thousands of hours.&lt;/p&gt;
    &lt;p class=&quot;isSelectedEnd&quot;&gt;This project is my opportunity to give something back.&lt;/p&gt;
    &lt;p&gt;If &lt;strong&gt;nerv-exception&lt;/strong&gt; saves another developer from copying the same exception handlers into yet another Spring Boot project, then it has accomplished exactly what I hoped. &lt;/p&gt;
    &lt;h2 style=&quot;text-align: left;&quot;&gt;Try It Yourself&lt;/h2&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;ul style=&quot;text-align: left;&quot;&gt;
      &lt;li&gt;GitHub:&amp;nbsp; &lt;a href=&quot;https://github.com/czetsuyatech/nerv-exception&quot;&gt;https://github.com/czetsuyatech/nerv-exception&lt;/a&gt;
      &lt;/li&gt;
      &lt;li&gt;Example Applications:&amp;nbsp; &lt;a href=&quot;https://github.com/czetsuyatech/nerv-examples&quot;&gt;https://github.com/czetsuyatech/nerv-examples&lt;/a&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
    &lt;div&gt;Available on Maven Central&lt;/div&gt;
    &lt;div&gt;
      &lt;br /&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;pre class=&quot;brush: java&quot;&gt;&amp;lt;dependency&amp;gt; 
	&amp;lt;groupId&amp;gt;com.czetsuyatech&amp;lt;/groupId&amp;gt; 
	&amp;lt;artifactId&amp;gt;nerv-exception-spring-boot-starter&amp;lt;/artifactId&amp;gt; 
	&amp;lt;version&amp;gt;1.0.0&amp;lt;/version&amp;gt; 
&amp;lt;/dependency&amp;gt;
&lt;/pre&gt;
&lt;p class=&quot;isSelectedEnd&quot;&gt;If you have ideas, questions, or suggestions, I&#39;d love to hear them. Feedback from the community is one of the best ways to improve an open source project.&lt;/p&gt;
&lt;p&gt;Happy coding!&lt;/p&gt;

&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Exception
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Exception&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/10/designing-consistent-error-contract-spring-boot.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        Designing a Consistent Error Contract for Spring Boot APIs
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/1440531714013119487/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/07/stop-copying-exception-handlers-between-spring-boot-projects.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/1440531714013119487'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/1440531714013119487'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/07/stop-copying-exception-handlers-between-spring-boot-projects.html' title='Stop Copying Exception Handlers Between Spring Boot Projects'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDKs5qOjyoxneSwd6hmEPmiUMlAjYJLzjwgfmN9OEN6ikfkSJF131-mBlNpTlEuR4edzdqGAFvhZzNspCX2z8LmA-282r1LnXLegVdxamcB7vWsy09VROU6NT348SLvyI9XWdNAJNO2o1jgRFnVRySmG3gn22XW47YxDYoF5X3LDKzXlNUUBPhXiHQONlF/s72-w640-h427-c/ChatGPT%20Image%20Jul%206,%202026,%2009_06_19%20PM.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-3625590463796725529</id><published>2026-04-19T20:06:00.000+08:00</published><updated>2026-09-10T13:13:07.804+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Automation"/><category scheme="http://www.blogger.com/atom/ns#" term="CI/CD"/><category scheme="http://www.blogger.com/atom/ns#" term="DevOps"/><category scheme="http://www.blogger.com/atom/ns#" term="GitHub Actions"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Maven"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Actions"/><title type='text'>Reusable GitHub Actions for Maven Projects — Stop Rewriting CI/CD Pipelines</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXBt19h1bXFhSqpW-igE7-lLVI2ef61rgDXzfLgOKiw4uNcauZmxcg4GVg4WnRx1PhffKXfqyjjHEhDuFeeVB5G1KpCWUx9LlCZnuxo1TiSZ_Jv1d890MeooZtpMYSek_HncEXYJ81ZY54d2N0Vqk338LjTDeAQJDts4YABdkeJJ8zZPq96_FsDe2k5ji9/s1536/nerv-actions.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1024&quot; data-original-width=&quot;1536&quot; height=&quot;426&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXBt19h1bXFhSqpW-igE7-lLVI2ef61rgDXzfLgOKiw4uNcauZmxcg4GVg4WnRx1PhffKXfqyjjHEhDuFeeVB5G1KpCWUx9LlCZnuxo1TiSZ_Jv1d890MeooZtpMYSek_HncEXYJ81ZY54d2N0Vqk338LjTDeAQJDts4YABdkeJJ8zZPq96_FsDe2k5ji9/w640-h426/nerv-actions.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;If you’ve worked on multiple Java projects, you’ve probably noticed something frustrating:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Every repository has its own version of a CI/CD pipeline.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Slightly different. Slightly broken. Slightly outdated.&lt;/p&gt;

&lt;p&gt;And every time you start a new project, you end up:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Copying an old GitHub Actions workflow&lt;/li&gt;
  &lt;li&gt;Tweaking it to make it work&lt;/li&gt;
  &lt;li&gt;Fixing versioning logic&lt;/li&gt;
  &lt;li&gt;Relearning release steps&lt;/li&gt;
  &lt;li&gt;Debugging the same issues again&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It’s repetitive, inconsistent, and honestly… a waste of time.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;🚨 The Real Pain Points&lt;/h2&gt;

&lt;p&gt;After going through this multiple times, a few patterns became obvious:&lt;/p&gt;

&lt;h3&gt;1. No Standardization&lt;/h3&gt;
&lt;p&gt;Each project defines CI/CD differently.&lt;br /&gt;
→ Hard to maintain across teams&lt;/p&gt;

&lt;h3&gt;2. Versioning is Messy&lt;/h3&gt;
&lt;p&gt;Manual version bumps, forgotten tags, inconsistent releases.&lt;br /&gt;
→ Leads to broken or confusing releases&lt;/p&gt;

&lt;h3&gt;3. Releases Are Too Manual&lt;/h3&gt;
&lt;p&gt;Even with automation, there’s still too much friction.&lt;br /&gt;
→ Slows down delivery&lt;/p&gt;

&lt;h3&gt;4. Pipelines Don’t Scale&lt;/h3&gt;
&lt;p&gt;What works for one repo doesn’t work for ten.&lt;br /&gt;
→ No easy way to reuse workflows&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;💡 The Solution: nerv-actions&lt;/h2&gt;

&lt;p&gt;Instead of rewriting pipelines every time, I built &lt;strong&gt;nerv-actions&lt;/strong&gt; — a set of reusable GitHub Actions workflows for Maven projects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The idea is simple:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Define CI/CD once. Reuse it everywhere.&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;⚙️ What It Does&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Analyze commit history&lt;/li&gt;
  &lt;li&gt;Determine semantic version&lt;/li&gt;
  &lt;li&gt;Update Maven project version&lt;/li&gt;
  &lt;li&gt;Build and test&lt;/li&gt;
  &lt;li&gt;Publish artifacts&lt;/li&gt;
  &lt;li&gt;Create GitHub Release&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;All automated. No manual steps.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;🔥 What This Fixes&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;✅ Consistent pipelines across all repositories&lt;/li&gt;
  &lt;li&gt;✅ Automatic semantic versioning&lt;/li&gt;
  &lt;li&gt;✅ Fully automated releases&lt;/li&gt;
  &lt;li&gt;✅ Reusable workflows&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You stop thinking about CI/CD… and it just works.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;📦 Minimal Setup&lt;/h2&gt;

&lt;pre class=&quot;brush: java&quot;&gt;jobs:
  cd:
    uses: czetsuyatech/nerv-actions/.github/workflows/cd.yml@main
    with:
      javaVersion: &#39;25&#39;
    secrets:
      githubAppId: ${{ secrets.NERV_RELEASE_APP_ID }}
      githubAppPrivateKey: ${{ secrets.NERV_RELEASE_APP_PRIVATE_KEY }}
      githubToken: ${{ secrets.GH_PKG_TOKEN }}
&lt;/pre&gt;

&lt;p&gt;That’s it.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;🧩 When You Start Scaling&lt;/h2&gt;

&lt;p&gt;The reality is, most teams don’t stay in a single stack.&lt;/p&gt;

&lt;p&gt;Eventually, you’ll need:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Node.js pipelines&lt;/li&gt;
  &lt;li&gt;Go releases&lt;/li&gt;
  &lt;li&gt;Container builds&lt;/li&gt;
  &lt;li&gt;Cross-repository orchestration&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To support this, I built &lt;strong&gt;nerv-actions Pro&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;👉 Request access to Pro workflows: czetsuya@gmail.com&lt;/strong&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;🛠️ Need Help Setting This Up?&lt;/h2&gt;

&lt;p&gt;If you want to skip the trial-and-error, I also offer services to:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Design CI/CD pipelines for your architecture&lt;/li&gt;
  &lt;li&gt;Implement GitHub Actions workflows&lt;/li&gt;
  &lt;li&gt;Set up automated releases&lt;/li&gt;
  &lt;li&gt;Optimize performance and reliability&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The goal:&lt;/strong&gt; a clean, scalable pipeline without the headaches.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;👉 Request consulting: your-email@example.com&lt;/strong&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;💭 Final Thought&lt;/h2&gt;

&lt;p&gt;CI/CD shouldn’t be something every project reinvents.&lt;/p&gt;

&lt;p&gt;Once standardized, it becomes:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Predictable&lt;/li&gt;
  &lt;li&gt;Maintainable&lt;/li&gt;
  &lt;li&gt;Scalable&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s what nerv-actions is aiming for.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;🔗 Project Link&lt;/h2&gt;

&lt;ul&gt;
  	&lt;li&gt;&lt;a href=&quot;https://github.com/czetsuyatech/nerv-actions&quot; target=&quot;_blank&quot;&gt;
https://github.com/czetsuyatech/nerv-actions
&lt;/a&gt;
	&lt;/li&gt;&lt;li&gt;Demo: &lt;a href=&quot;https://github.com/czetsuyatech/nerv-audit&quot; target=&quot;_blank&quot;&gt;
https://github.com/czetsuyatech/nerv-audit
      &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/3625590463796725529/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/04/reusable-github-actions-for-maven.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/3625590463796725529'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/3625590463796725529'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/04/reusable-github-actions-for-maven.html' title='Reusable GitHub Actions for Maven Projects — Stop Rewriting CI/CD Pipelines'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXBt19h1bXFhSqpW-igE7-lLVI2ef61rgDXzfLgOKiw4uNcauZmxcg4GVg4WnRx1PhffKXfqyjjHEhDuFeeVB5G1KpCWUx9LlCZnuxo1TiSZ_Jv1d890MeooZtpMYSek_HncEXYJ81ZY54d2N0Vqk338LjTDeAQJDts4YABdkeJJ8zZPq96_FsDe2k5ji9/s72-w640-h426-c/nerv-actions.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-3157051915790930471</id><published>2026-04-07T22:17:00.000+08:00</published><updated>2026-10-01T16:36:58.889+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Featured"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV"/><category scheme="http://www.blogger.com/atom/ns#" term="NERV Audit"/><category scheme="http://www.blogger.com/atom/ns#" term="Persistence"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>Spring Boot Audit Trail Made Easy: Introducing nerv-audit (Hibernate Envers + JPA)</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvJCibKUvqGjRyk1FsaOmnc9RuJLs3tITUGq53EQ7X0amVAcwVKkpkZFQt0jyOsy_ti4O1OxMz-hjdae8eGZdsPft2FhqNkkpqvdBZJCxG-5Ipz1tnY2PgsW2P5oM6yK8PhPRTsUrOUUUCZrc2E4__0q8k2MYjtqIl6PGN-6D0I1J7f0MgciX1kC8RwTpx/s1536/nerv-audit.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1024&quot; data-original-width=&quot;1536&quot; height=&quot;427&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvJCibKUvqGjRyk1FsaOmnc9RuJLs3tITUGq53EQ7X0amVAcwVKkpkZFQt0jyOsy_ti4O1OxMz-hjdae8eGZdsPft2FhqNkkpqvdBZJCxG-5Ipz1tnY2PgsW2P5oM6yK8PhPRTsUrOUUUCZrc2E4__0q8k2MYjtqIl6PGN-6D0I1J7f0MgciX1kC8RwTpx/w640-h427/nerv-audit.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;
   If you&#39;re building a &lt;b&gt;Spring Boot application&lt;/b&gt;, sooner or later
   you&#39;ll need a &lt;b&gt;reliable audit trail&lt;/b&gt;.
&lt;/p&gt;
&lt;p&gt;Whether it&#39;s for:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
   &lt;li&gt;Compliance (finance, healthcare, enterprise systems)&lt;/li&gt;
   &lt;li&gt;Debugging production issues&lt;/li&gt;
   &lt;li&gt;Tracking data changes&lt;/li&gt;
   &lt;li&gt;User activity monitoring&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;The problem?&lt;/p&gt;
&lt;p&gt;Building audit logging properly is harder than it looks.&lt;/p&gt;
&lt;p&gt;
   That’s why I built
   &lt;b&gt;nerv-audit — a production-ready audit trail library for Spring Boot using
      Hibernate Envers.&lt;/b&gt;
&lt;/p&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;What is nerv-audit?&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;nerv-audit&lt;/b&gt; is a modular audit logging framework for:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
   &lt;li&gt;Spring Boot&lt;/li&gt;
   &lt;li&gt;JPA / Hibernate&lt;/li&gt;
   &lt;li&gt;Hibernate Envers&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;It provides:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
   &lt;li&gt;Automatic audit tracking&lt;/li&gt;
   &lt;li&gt;Queryable audit history&lt;/li&gt;
   &lt;li&gt;Flexible audit strategies (vertical and horizontal)&lt;/li&gt;
   &lt;li&gt;A plug-and-play Spring Boot starter&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;👉 Designed for real-world systems—not tutorials.&lt;/p&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Why You Need an Audit Trail in Spring Boot&lt;/h2&gt;
&lt;p&gt;Many developers search for:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
   &lt;li&gt;&lt;i&gt;“How to implement audit logging in Spring Boot”&lt;/i&gt;&lt;/li&gt;
   &lt;li&gt;&lt;i&gt;“Hibernate Envers example”&lt;/i&gt;&lt;/li&gt;
   &lt;li&gt;&lt;i&gt;“Track entity changes in JPA”&lt;/i&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;But most solutions:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
   &lt;li&gt;Only log changes&lt;/li&gt;
   &lt;li&gt;Don’t support querying&lt;/li&gt;
   &lt;li&gt;Are hard to maintain&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;A proper audit system should:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
   &lt;li&gt;Track &lt;b&gt;who changed what and when&lt;/b&gt;&lt;/li&gt;
   &lt;li&gt;Support &lt;b&gt;filtering and history queries&lt;/b&gt;&lt;/li&gt;
   &lt;li&gt;Be &lt;b&gt;consistent across services&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;That’s exactly what nerv-audit solves.&lt;/p&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Key Features of nerv-audit&lt;/h2&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;
   ✅ 1. Hibernate Envers Integration (Done Right)
&lt;/h3&gt;
&lt;p&gt;Instead of manually wiring Envers, nerv-audit:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
   &lt;li&gt;Auto-configures listeners&lt;/li&gt;
   &lt;li&gt;Provides extension points&lt;/li&gt;
   &lt;li&gt;Standardizes audit table handling&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;✅ 2. Vertical vs Horizontal Audit Strategies&lt;/h2&gt;
&lt;div&gt;
   &lt;div&gt;Choose how you store audit data:&lt;/div&gt;
   &lt;h3 style=&quot;text-align: left;&quot;&gt;Horizontal Audit (Snapshot-based)&lt;/h3&gt;
   &lt;div&gt;
      &lt;ul style=&quot;text-align: left;&quot;&gt;
         &lt;li&gt;One row per revision&lt;/li&gt;
         &lt;li&gt;Full entity state&lt;/li&gt;
      &lt;/ul&gt;
   &lt;/div&gt;
   &lt;h3 style=&quot;text-align: left;&quot;&gt;Vertical Audit (Change-based)&lt;/h3&gt;
   &lt;div&gt;
      &lt;ul style=&quot;text-align: left;&quot;&gt;
         &lt;li&gt;One row per field change&lt;/li&gt;
         &lt;li&gt;Tracks:&lt;/li&gt;
         &lt;ul&gt;
            &lt;li&gt;old value&lt;/li&gt;
            &lt;li&gt;new value&lt;/li&gt;
            &lt;li&gt;changed field&lt;/li&gt;
         &lt;/ul&gt;
      &lt;/ul&gt;
   &lt;/div&gt;
   &lt;div&gt;👉 Best for:&lt;/div&gt;
   &lt;div&gt;
      &lt;ul style=&quot;text-align: left;&quot;&gt;
         &lt;li&gt;Debugging&lt;/li&gt;
         &lt;li&gt;Compliance&lt;/li&gt;
         &lt;li&gt;Change tracking systems&lt;/li&gt;
      &lt;/ul&gt;
      &lt;div&gt;
         &lt;h3 style=&quot;text-align: left;&quot;&gt;
            ✅ 3. Queryable Audit API (Spring Boot REST)
         &lt;/h3&gt;
         &lt;div&gt;
            Unlike most audit setups, nerv-audit lets you
            &lt;b&gt;query audit logs via API.&lt;/b&gt;
         &lt;/div&gt;
         &lt;div&gt;&lt;br /&gt;&lt;/div&gt;
         &lt;div&gt;Example:&lt;/div&gt;
      &lt;/div&gt;
   &lt;/div&gt;
&lt;/div&gt;
&lt;pre class=&quot;brush: java&quot;&gt;GET /nerv-audit/vertical/UserEntity?id=101&amp;amp;updatedBy=admin&lt;/pre&gt;
&lt;div&gt;Supports:&lt;/div&gt;
&lt;div&gt;
   &lt;ul style=&quot;text-align: left;&quot;&gt;
      &lt;li&gt;Filtering by user&lt;/li&gt;
      &lt;li&gt;Field-level filtering&lt;/li&gt;
      &lt;li&gt;Date ranges&lt;/li&gt;
      &lt;li&gt;Pagination &amp;amp; sorting&lt;/li&gt;
   &lt;/ul&gt;
   &lt;div&gt;
      &lt;h3 style=&quot;text-align: left;&quot;&gt;
         ✅ 4. Modular Architecture for Scalability
      &lt;/h3&gt;
      &lt;div&gt;Built as a &lt;b&gt;multi-module Maven project:&lt;/b&gt;&lt;/div&gt;
      &lt;div&gt;
         &lt;ul style=&quot;text-align: left;&quot;&gt;
            &lt;li&gt;&lt;i&gt;nerv-audit-api&lt;/i&gt; → contracts &amp;amp; DTOs&lt;/li&gt;
            &lt;li&gt;&lt;i&gt;nerv-audit-core&lt;/i&gt; → Envers logic&lt;/li&gt;
            &lt;li&gt;&lt;i&gt;nerv-audit-lite&lt;/i&gt; → simplified version&lt;/li&gt;
            &lt;li&gt;&lt;i&gt;nerv-audit-spring-boot-starter&lt;/i&gt; → auto-config&lt;/li&gt;
         &lt;/ul&gt;
      &lt;/div&gt;
      &lt;div&gt;Perfect for:&lt;/div&gt;
      &lt;div&gt;
         &lt;ul style=&quot;text-align: left;&quot;&gt;
            &lt;li&gt;Microservices&lt;/li&gt;
            &lt;li&gt;Internal platforms&lt;/li&gt;
            &lt;li&gt;Enterprise systems&lt;/li&gt;
         &lt;/ul&gt;
         &lt;div&gt;
            &lt;h2 style=&quot;text-align: left;&quot;&gt;✅ 5. Lite vs Pro Editions&lt;/h2&gt;
            &lt;h3 style=&quot;text-align: left;&quot;&gt;Lite (Free)&lt;/h3&gt;
            &lt;div&gt;
               &lt;ul style=&quot;text-align: left;&quot;&gt;
                  &lt;li&gt;Create operation auditing&lt;/li&gt;
                  &lt;li&gt;Basic setup&lt;/li&gt;
                  &lt;li&gt;Lightweight integration&lt;/li&gt;
               &lt;/ul&gt;
            &lt;/div&gt;
            &lt;h3 style=&quot;text-align: left;&quot;&gt;Pro&lt;/h3&gt;
            &lt;div&gt;
               &lt;ul style=&quot;text-align: left;&quot;&gt;
                  &lt;li&gt;Full CRUD auditing (create, update, delete)&lt;/li&gt;
                  &lt;li&gt;List tracking&lt;/li&gt;
                  &lt;li&gt;REST API&lt;/li&gt;
                  &lt;li&gt;Advanced filtering&lt;/li&gt;
               &lt;/ul&gt;
               &lt;div&gt;
                  &lt;h2 style=&quot;text-align: left;&quot;&gt;
                     How to Add Audit Logging in Spring Boot (Quick Start)
                  &lt;/h2&gt;
                  &lt;h3 style=&quot;text-align: left;&quot;&gt;1. Add Dependency&lt;/h3&gt;
               &lt;/div&gt;
            &lt;/div&gt;
         &lt;/div&gt;
      &lt;/div&gt;
   &lt;/div&gt;
&lt;/div&gt;
&lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;&amp;lt;dependency&amp;gt;
  &amp;lt;groupId&amp;gt;com.czetsuyatech&lt;/pre&gt;
  &amp;lt;artifactId&amp;gt;nerv-audit-spring-boot-starter
&amp;lt;/dependency&amp;gt;


&lt;h3 style=&quot;text-align: left;&quot;&gt;2. Enable Audit API&lt;/h3&gt;
&lt;pre class=&quot;brush: java&quot;&gt;nerv:
  audit:
    web:
      enabled: true&lt;/pre&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;3. Start Tracking Entity Changes&lt;/h3&gt;
&lt;div&gt;Just annotate your entities with:&lt;/div&gt;
&lt;div&gt;
   &lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;/div&gt;
&lt;div&gt;&lt;i&gt;@Audited&lt;/i&gt;&lt;/div&gt;
&lt;div&gt;&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
   &lt;div&gt;Done. You now have:&lt;/div&gt;
   &lt;div&gt;
      &lt;ul style=&quot;text-align: left;&quot;&gt;
         &lt;li&gt;Audit tracking&lt;/li&gt;
         &lt;li&gt;Queryable history&lt;/li&gt;
         &lt;li&gt;Production-ready setup&lt;/li&gt;
      &lt;/ul&gt;
      &lt;div&gt;
         &lt;h2 style=&quot;text-align: left;&quot;&gt;Use Cases: When to Use nerv-audit&lt;/h2&gt;
         &lt;div&gt;This library is ideal if you are building:&lt;/div&gt;
         &lt;h3 style=&quot;text-align: left;&quot;&gt;🔹 Enterprise Applications&lt;/h3&gt;
         &lt;div&gt;
            &lt;ul style=&quot;text-align: left;&quot;&gt;
               &lt;li&gt;Financial systems&lt;/li&gt;
               &lt;li&gt;ERP platforms&lt;/li&gt;
               &lt;li&gt;Internal tools&lt;/li&gt;
            &lt;/ul&gt;
         &lt;/div&gt;
         &lt;h3 style=&quot;text-align: left;&quot;&gt;🔹 SaaS Platforms&lt;/h3&gt;
         &lt;div&gt;
            &lt;ul style=&quot;text-align: left;&quot;&gt;
               &lt;li&gt;User activity tracking&lt;/li&gt;
               &lt;li&gt;Data history&lt;/li&gt;
               &lt;li&gt;Debugging production issues&lt;/li&gt;
            &lt;/ul&gt;
         &lt;/div&gt;
         &lt;h3 style=&quot;text-align: left;&quot;&gt;🔹 Regulated Systems&lt;/h3&gt;
         &lt;div&gt;
            &lt;ul style=&quot;text-align: left;&quot;&gt;
               &lt;li&gt;Compliance logging&lt;/li&gt;
               &lt;li&gt;Audit trails for legal requirements&lt;/li&gt;
            &lt;/ul&gt;
            &lt;h2 style=&quot;text-align: left;&quot;&gt;
               nerv-audit vs Custom Audit Implementation
            &lt;/h2&gt;
         &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;table&gt;
    &lt;tbody&gt;&lt;tr&gt;
    &lt;th&gt;Feature&lt;/th&gt;
    &lt;th&gt;Custom Build&lt;/th&gt;
    &lt;th&gt;nerv-audit&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
	  &lt;td&gt;Envers setup&lt;/td&gt;
      &lt;td&gt;Manual&lt;/td&gt;
      &lt;td&gt;Auto configured&lt;/td&gt;
	&lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Audit querying&lt;/td&gt;
      &lt;td&gt;Hard&lt;/td&gt;
      &lt;td&gt;Built-in API&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Maintainability&lt;/td&gt;
      &lt;td&gt;Low&lt;/td&gt;
      &lt;td&gt;High&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Time to implement&lt;/td&gt;
      &lt;td&gt;Weeks&lt;/td&gt;
      &lt;td&gt;Minutes&lt;/td&gt;
  &lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;div&gt;
      &lt;h2 style=&quot;text-align: left;&quot;&gt;
         Built for Production (Not Just Tutorials)
      &lt;/h2&gt;
      &lt;div&gt;
         &lt;div&gt;Most audit examples online are:&lt;/div&gt;
         &lt;div&gt;
            &lt;ul style=&quot;text-align: left;&quot;&gt;
               &lt;li&gt;Simplified&lt;/li&gt;
               &lt;li&gt;Incomplete&lt;/li&gt;
               &lt;li&gt;Not scalable&lt;/li&gt;
            &lt;/ul&gt;
         &lt;/div&gt;
         &lt;div&gt;nerv-audit is different.&lt;/div&gt;
         &lt;div&gt;&lt;br /&gt;&lt;/div&gt;
         &lt;div&gt;It’s built with:&lt;/div&gt;
         &lt;div&gt;
            &lt;ul style=&quot;text-align: left;&quot;&gt;
               &lt;li&gt;Real production constraints&lt;/li&gt;
               &lt;li&gt;Clean architecture&lt;/li&gt;
               &lt;li&gt;Extension points for customization&lt;/li&gt;
               &lt;li&gt;Focus on long-term maintainability&lt;/li&gt;
            &lt;/ul&gt;
            &lt;h2 style=&quot;text-align: left;&quot;&gt;
               Future Roadmap (SEO Boost Section 🚀)
            &lt;/h2&gt;
         &lt;/div&gt;
      &lt;/div&gt;
      &lt;div&gt;
         &lt;div&gt;Planned features:&lt;/div&gt;
         &lt;div&gt;
            &lt;ul style=&quot;text-align: left;&quot;&gt;
               &lt;li&gt;Multi-tenant audit support&lt;/li&gt;
               &lt;li&gt;Kafka integration (event-driven audit)&lt;/li&gt;
               &lt;li&gt;SIEM integrations&lt;/li&gt;
               &lt;li&gt;Advanced analytics&lt;/li&gt;
            &lt;/ul&gt;
            &lt;div&gt;
               &lt;h2 style=&quot;text-align: left;&quot;&gt;About the Author&lt;/h2&gt;
               &lt;div&gt;I build:&lt;/div&gt;
               &lt;div&gt;
                  &lt;ul style=&quot;text-align: left;&quot;&gt;
                     &lt;li&gt;Spring Boot backend systems&lt;/li&gt;
                     &lt;li&gt;Internal developer platforms&lt;/li&gt;
                     &lt;li&gt;Production-grade reusable libraries&lt;/li&gt;
                  &lt;/ul&gt;
               &lt;/div&gt;
               &lt;div&gt;If your team needs:&lt;/div&gt;
               &lt;div&gt;
                  &lt;ul style=&quot;text-align: left;&quot;&gt;
                     &lt;li&gt;Audit systems&lt;/li&gt;
                     &lt;li&gt;Backend architecture&lt;/li&gt;
                     &lt;li&gt;Platform engineering&lt;/li&gt;
                  &lt;/ul&gt;
               &lt;/div&gt;
               &lt;div&gt;Let’s work together.&lt;/div&gt;
            &lt;/div&gt;
         &lt;/div&gt;
      &lt;/div&gt;
      &lt;div&gt;
         &lt;h2 style=&quot;text-align: left;&quot;&gt;
            Final Thoughts: Stop Rebuilding Audit Systems
         &lt;/h2&gt;
         &lt;div&gt;If you&#39;re searching for:&lt;/div&gt;
         &lt;div&gt;
            &lt;ul style=&quot;text-align: left;&quot;&gt;
               &lt;li&gt;“Spring Boot audit logging best practices”&lt;/li&gt;
               &lt;li&gt;“Hibernate Envers production setup”&lt;/li&gt;
               &lt;li&gt;“JPA entity change tracking”&lt;/li&gt;
            &lt;/ul&gt;
         &lt;/div&gt;
         &lt;div&gt;Then nerv-audit is exactly what you need.&lt;/div&gt;
         &lt;div&gt;
            &lt;ul style=&quot;text-align: left;&quot;&gt;
               &lt;li&gt;👉 It saves time&lt;/li&gt;
               &lt;li&gt;👉 It standardizes auditing&lt;/li&gt;
               &lt;li&gt;👉 It works in production&lt;/li&gt;
            &lt;/ul&gt;
            &lt;div&gt;
               &lt;h2 style=&quot;text-align: left;&quot;&gt;Try nerv-audit Today&lt;/h2&gt;
               &lt;div&gt;
                  Start adding audit trails to your Spring Boot app in minutes.
               &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a href=&quot;https://github.com/czetsuyatech/nerv-audit&quot;&gt;https://github.com/czetsuyatech/nerv-audit&lt;/a&gt;&lt;/div&gt;
            &lt;/div&gt;
         &lt;/div&gt;
      &lt;/div&gt;
   &lt;/div&gt;
&lt;/div&gt;
&lt;!-- NERV Article Navigation --&gt;
&lt;div style=&quot;
  margin: 40px 0 20px;
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
&quot;&gt;

  &lt;div style=&quot;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
  &quot;&gt;

    &lt;!-- Series / Label --&gt;
    &lt;div style=&quot;
      flex: 0 0 auto;
      text-align: center;
      min-width: 160px;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        NERV Audit
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/search/label/NERV%20Audit&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        View all articles
      &lt;/a&gt;
    &lt;/div&gt;


    &lt;!-- Next Article --&gt;
    &lt;div style=&quot;
      flex: 1;
      min-width: 200px;
      text-align: right;
    &quot;&gt;
      &lt;div style=&quot;
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      &quot;&gt;
        Next →
      &lt;/div&gt;

      &lt;a href=&quot;https://www.czetsuyatech.com/2026/09/database-tells-you-what-is-audit-trail-tells-you-what-happened.html&quot;
         style=&quot;
           font-weight: 600;
           text-decoration: none;
         &quot;&gt;
        The Database Tells You What Is. An Audit Trail Tells You What Happened
      &lt;/a&gt;
    &lt;/div&gt;

  &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /NERV Article Navigation --&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/3157051915790930471/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2026/04/spring-boot-audit-trail-hibernate-envers.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/3157051915790930471'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/3157051915790930471'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2026/04/spring-boot-audit-trail-hibernate-envers.html' title='Spring Boot Audit Trail Made Easy: Introducing nerv-audit (Hibernate Envers + JPA)'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvJCibKUvqGjRyk1FsaOmnc9RuJLs3tITUGq53EQ7X0amVAcwVKkpkZFQt0jyOsy_ti4O1OxMz-hjdae8eGZdsPft2FhqNkkpqvdBZJCxG-5Ipz1tnY2PgsW2P5oM6yK8PhPRTsUrOUUUCZrc2E4__0q8k2MYjtqIl6PGN-6D0I1J7f0MgciX1kC8RwTpx/s72-w640-h427-c/nerv-audit.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-584812358318607788</id><published>2025-11-04T09:24:00.000+08:00</published><updated>2026-09-08T23:51:06.327+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>How to Log Method Execution Time in Spring Boot Using AOP</title><content type='html'>&lt;h2 style=&quot;text-align: left;&quot;&gt;Overview&lt;/h2&gt;&lt;div&gt;&lt;p data-end=&quot;1119&quot; data-start=&quot;475&quot;&gt;Monitoring method execution time is one of the easiest yet most effective ways to understand your application’s performance. In this guide, we’ll explore how to use &lt;strong data-end=&quot;655&quot; data-start=&quot;640&quot;&gt;&lt;a data-preview=&quot;&quot; href=&quot;https://www.google.com/search?ved=1t:260882&amp;amp;q=Spring+Boot&amp;amp;bbid=6581802047354010081&amp;amp;bpid=584812358318607788&quot; target=&quot;_blank&quot;&gt;Spring Boot&lt;/a&gt;&lt;/strong&gt; with &lt;strong data-end=&quot;698&quot; data-start=&quot;661&quot;&gt;Aspect-Oriented Programming (AOP)&lt;/strong&gt; to log method execution times cleanly—without cluttering your business logic. By leveraging the &lt;code data-end=&quot;804&quot; data-start=&quot;795&quot;&gt;@Aspect&lt;/code&gt; annotation, we can intercept method calls, measure how long they take, and log this information for performance analysis. This approach is flexible, reusable, and perfect for tracking &lt;a data-preview=&quot;&quot; href=&quot;https://www.google.com/search?ved=1t:260882&amp;amp;q=performance+bottlenecks+analysis+tools&amp;amp;bbid=6581802047354010081&amp;amp;bpid=584812358318607788&quot; target=&quot;_blank&quot;&gt;performance bottlenecks&lt;/a&gt; in large-scale applications. Let’s dive in and build a lightweight &lt;a data-preview=&quot;&quot; href=&quot;https://www.google.com/search?ved=1t:260882&amp;amp;q=Spring+AOP+execution+time+logger+example&amp;amp;bbid=6581802047354010081&amp;amp;bpid=584812358318607788&quot; target=&quot;_blank&quot;&gt;execution time logger&lt;/a&gt; using Spring AOP.&lt;/p&gt;&lt;/div&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Aspect Annotation
&lt;/h2&gt;&lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackExecutionTime {
 //
}
&lt;/pre&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;
Aspect Interceptor
&lt;/h2&gt;&lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;@Aspect
@Component
@Slf4j
public class ExecutionTimeAspect {

  @Around(&quot;@annotation(com.dcx.nba.actions.annotations.TrackExecutionTime)&quot;)
  public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {

    long startTime = System.currentTimeMillis();

    Object result = joinPoint.proceed();

    long endTime = System.currentTimeMillis();
    long executionTime = endTime - startTime;

    log.info(&quot;{} executed in {}ms&quot;, joinPoint.getSignature().toShortString(), executionTime);

    return result;
  }
}
&lt;/pre&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;
Annotation Usage
&lt;/h2&gt;&lt;div&gt;This method runs via scheduler and computes the total elapsed time during the execution&lt;/div&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Override
@TrackExecutionTime
@SchedulerLock(name = JOB_NAME)
@Scheduled(cron = &quot;${app.schedulers.update-action-status.cron}&quot;)
public void scheduleUpdateStatus() {
}
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/584812358318607788/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2025/11/how-to-log-method-execution-time-in-spring-boot-using-aop.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/584812358318607788'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/584812358318607788'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2025/11/how-to-log-method-execution-time-in-spring-boot-using-aop.html' title='How to Log Method Execution Time in Spring Boot Using AOP'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-5860202626945923728</id><published>2025-07-13T19:31:00.000+08:00</published><updated>2026-09-08T23:51:07.892+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="React"/><category scheme="http://www.blogger.com/atom/ns#" term="Security"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>Secure React and Spring Boot with Microsoft Entra SSO and Bearer Token Authentication</title><content type='html'>&lt;h2 style=&quot;text-align: left;&quot;&gt;Introduction&lt;/h2&gt;&lt;div&gt;Implementing secure, seamless login across a modern full-stack application is essential—but it doesn’t have to be complicated. In this guide, we’ll walk through how to integrate Microsoft Entra (formerly Azure AD) for Single Sign-On (SSO) in a React frontend and Spring Boot backend. The Spring Boot application acts as a resource server, validating JWT bearer tokens issued by Entra. Beyond authentication, we’ll also demonstrate how to map Microsoft Entra groups to internal application roles, dynamically fetched from your own database. Whether you&#39;re building internal tools or enterprise-grade platforms, this setup gives your app robust security, fine-grained access control, and a smooth user experience across services.&lt;/div&gt;&lt;div&gt;&lt;h2&gt;Problem&lt;/h2&gt;&lt;/div&gt;&lt;div&gt;You need SSO in your frontend to allow users to login to your system and authorize the call of backend endpoints by sending the bearer token. In the backend we will get the user group attached to the currently log user and fetch the corresponding internal permissions which we will add as roles to the JWT.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Our schema will look like:&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAaCBZcW8WxfhqBiSSs_rt3zFVxoVbYrVmbPJOsT0Y0_uedLB0Tkz1HUuQpb22bewVTc9EMUXt95dE5frjTp96f2oTsMx4PvleObWIKYb0HB19uHfh59yvGazCkaflfrnGsTD63FGeqbdVLtaBukIjVJBcMGAaUk1lw4UKCprjRn-13pvXLLacBA7uNoYm/s481/Role%20Permission.drawio.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;41&quot; data-original-width=&quot;481&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAaCBZcW8WxfhqBiSSs_rt3zFVxoVbYrVmbPJOsT0Y0_uedLB0Tkz1HUuQpb22bewVTc9EMUXt95dE5frjTp96f2oTsMx4PvleObWIKYb0HB19uHfh59yvGazCkaflfrnGsTD63FGeqbdVLtaBukIjVJBcMGAaUk1lw4UKCprjRn-13pvXLLacBA7uNoYm/s16000/Role%20Permission.drawio.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Prerequisites for this Exercise&lt;/h2&gt;&lt;div&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;Microsoft Entrata account (&lt;a href=&quot;https://entra.microsoft.com&quot;&gt;https://entra.microsoft.com&lt;/a&gt;)&lt;/li&gt;&lt;li&gt;Familiar with React&lt;/li&gt;&lt;li&gt;Experience in Spring REST programming&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;Microsoft Entrata&lt;/h2&gt;&lt;div&gt;If you haven&#39;t sign up yet visit Microsoft Entrata website and register a new account. After a successful registration you should be logged and redirect to the dashboard page where you can get the tenant id. Take a note because we will use it in the client and backend configuration later.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbHE11U_0GmaPOdgzQCgprUI0i9tf3PcwHZ_vl4XQbLeQW9dArMmzUTB586cH69LZefk_FiRdD2YklZhGPgETEOF-nao703SJ8QD7psIQ20XGBicmpC2LKVIaMP64us-V4ywz241WDPojB_GwZ0zRNRp5kt-CXaHvUPwoTcrCmHPPsESCP3KjFn0c1F3of/s1465/1%20-%20MS%20Entrata%20dashboard.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;469&quot; data-original-width=&quot;1465&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbHE11U_0GmaPOdgzQCgprUI0i9tf3PcwHZ_vl4XQbLeQW9dArMmzUTB586cH69LZefk_FiRdD2YklZhGPgETEOF-nao703SJ8QD7psIQ20XGBicmpC2LKVIaMP64us-V4ywz241WDPojB_GwZ0zRNRp5kt-CXaHvUPwoTcrCmHPPsESCP3KjFn0c1F3of/s16000/1%20-%20MS%20Entrata%20dashboard.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;/h2&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;/h2&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;App Registration&lt;/h3&gt;&lt;div&gt;Inside Entrata, under Manage / App Registrations click New Registrations. For this exercise since we will be doing the authentication in the frontend we need to register an app of type &lt;b&gt;SPA&lt;/b&gt;. Don&#39;t forget to fill-in the redirect URI.&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjS15Z202tF2PW5HezIG9a-wZ5-Y54Bfc-mVVx1szxiTxwcV9OgDQFnyhn4SE4LGgpAnNnxWToM-Wd-IL6w3GJvHqu1kUA-6ogIgRrsf_Px7R7YffUi24glW3KtPRILGYYF-WHaKvsCvpefj2A00blHtGeqZNcKIpQSPhkyhiIRlMlbAOihMQZcqL2H247g/s1547/2%20-%20App%20registration.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1149&quot; data-original-width=&quot;1547&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjS15Z202tF2PW5HezIG9a-wZ5-Y54Bfc-mVVx1szxiTxwcV9OgDQFnyhn4SE4LGgpAnNnxWToM-Wd-IL6w3GJvHqu1kUA-6ogIgRrsf_Px7R7YffUi24glW3KtPRILGYYF-WHaKvsCvpefj2A00blHtGeqZNcKIpQSPhkyhiIRlMlbAOihMQZcqL2H247g/s16000/2%20-%20App%20registration.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;p style=&quot;text-align: left;&quot;&gt;Take note of the Application (client) ID.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcvT2YWnDsg7-myH6WQTjh2GqJmbeG5UsBOZeoJHQSPKw_KSQvkNUZF4gXnNQ3i0z5RIRb25w4jhjTObkLiiNgzKW_hmsMIbAv7TaBStmQHOYcYj1-foDjJIiUU6Q558GXi5f52TUDeJIVWjddxrzrXQYztiG8cayJxrBUZjlRv82FImwIU1PI62YdPN5Q/s782/3%20-%20App%20client%20detail.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;328&quot; data-original-width=&quot;782&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcvT2YWnDsg7-myH6WQTjh2GqJmbeG5UsBOZeoJHQSPKw_KSQvkNUZF4gXnNQ3i0z5RIRb25w4jhjTObkLiiNgzKW_hmsMIbAv7TaBStmQHOYcYj1-foDjJIiUU6Q558GXi5f52TUDeJIVWjddxrzrXQYztiG8cayJxrBUZjlRv82FImwIU1PI62YdPN5Q/s16000/3%20-%20App%20client%20detail.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Expose an API&lt;/h3&gt;&lt;div&gt;Now we need to add a scope that we will use during login. This will allow us to use the MS Graph version 2. Without a defined scope Entrata will use version 1 which will throw an error during JWT validation in the backend.&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggZMf-WD1YuvOy8CQhzF30Nu4rDGF2bOZbG7wt1z12r6-V5w0nkTUt-hCp_hBoWXTR810z_2vNIevImBO_9suFdpm_HsMbfGWzXymmWj4pRyPIyJNBM2S1JoQOeH6ZV4lBpsuTdDfYlp8XmIGgzOzvnHO3r-OQvYeVAbLkXSMONNo9uhBUuU1ntCD9JGYM/s1059/4%20-%20Add%20a%20scope.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1059&quot; data-original-width=&quot;782&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggZMf-WD1YuvOy8CQhzF30Nu4rDGF2bOZbG7wt1z12r6-V5w0nkTUt-hCp_hBoWXTR810z_2vNIevImBO_9suFdpm_HsMbfGWzXymmWj4pRyPIyJNBM2S1JoQOeH6ZV4lBpsuTdDfYlp8XmIGgzOzvnHO3r-OQvYeVAbLkXSMONNo9uhBUuU1ntCD9JGYM/s16000/4%20-%20Add%20a%20scope.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;p style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Update Token Version in the Manifest&lt;/h3&gt;&lt;p style=&quot;text-align: left;&quot;&gt;In the left menu, find the Manifest.&lt;/p&gt;&lt;p style=&quot;text-align: left;&quot;&gt;In the JSON document, find the&amp;nbsp;&lt;b&gt;requestedAccessTokenVersion &lt;/b&gt;and set its value to 2.&lt;/p&gt;&lt;p style=&quot;text-align: left;&quot;&gt;Note that the change takes time to propagate.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgim93Q2I8oDXM-M7b5r7cnphSYXhhjgI8j21LSdL50JmxfrNKk6G-8XNQe4sF_fRWnIEksb5QY04veiCpbyAEoR1C8_jeZ-8RLoWpFGFA6aomrelfzc2gWltLSNekyYQ55CTK8Bq_ikljNyTHmGN07sYCr_D0_XXTaQs9okO8YnqrYzLau8Z0ujO2wxj8u/s1351/5%20-%20Manifest.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;701&quot; data-original-width=&quot;1351&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgim93Q2I8oDXM-M7b5r7cnphSYXhhjgI8j21LSdL50JmxfrNKk6G-8XNQe4sF_fRWnIEksb5QY04veiCpbyAEoR1C8_jeZ-8RLoWpFGFA6aomrelfzc2gWltLSNekyYQ55CTK8Bq_ikljNyTHmGN07sYCr_D0_XXTaQs9okO8YnqrYzLau8Z0ujO2wxj8u/s16000/5%20-%20Manifest.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;div&gt;&lt;h2&gt;&lt;br /&gt;&lt;/h2&gt;&lt;p style=&quot;text-align: left;&quot;&gt;Now, our Entrata app is ready for integration.&lt;/p&gt;&lt;div&gt;&lt;h2&gt;React SPA Client Application&lt;/h2&gt;&lt;/div&gt;&lt;div&gt;This exercise will use a SPA project provided by Microsoft available at&amp;nbsp;&lt;a href=&quot;https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/tree/main/2-Authorization/1-call-api-react/SPA&quot;&gt;https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/tree/main/2-Authorization/1-call-api-react/SPA&lt;/a&gt;. It uses MSAL library to authenticate the users and access secured APIs by acquiring security tokens from Microsoft Entrata.&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;SPA Modifications&lt;/h3&gt;&lt;div&gt;We need to do several updates on the project.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Open &lt;i&gt;authConfig.js&lt;/i&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Replace the &lt;b&gt;clientId&lt;/b&gt; with the value of Application (client) Id that we have generated when we register the app in Entrata.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Update the value of &lt;b&gt;authority &lt;/b&gt;using the Directory / Tenant Id.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiv-FCb7z6YaE0hDAusB3k5-NUZivQBvnMS3fSWEhF4Lwt_C0AFnmewkM5q8IjqhftxFZtzuMV-em_-uSt0iGxF-__VhdpQnnyvMj3l2D0OMv0LgpZLr9W1XZ2JzE39vdxxNPlqSkxymSC8apxAT-s5g7kcZRvaHltkb3j2PXuc6hzvsGTLhZoKnxJ9ZKvq/s1378/6%20-%20SPA%20config.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;291&quot; data-original-width=&quot;1378&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiv-FCb7z6YaE0hDAusB3k5-NUZivQBvnMS3fSWEhF4Lwt_C0AFnmewkM5q8IjqhftxFZtzuMV-em_-uSt0iGxF-__VhdpQnnyvMj3l2D0OMv0LgpZLr9W1XZ2JzE39vdxxNPlqSkxymSC8apxAT-s5g7kcZRvaHltkb3j2PXuc6hzvsGTLhZoKnxJ9ZKvq/s16000/6%20-%20SPA%20config.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;p style=&quot;text-align: left;&quot;&gt;Then to enable Graph V2 when signing in, we need to request access to the scope which we defined earlier.&lt;/p&gt;&lt;p style=&quot;text-align: left;&quot;&gt;In the same file &lt;i&gt;authConfig.js, &lt;/i&gt;at the end of the file.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_Y0qO1H-DAdYWmG2kSG-kQoGY6SZEsFrCAi3oRYYEmE-0IrhvryFTUr0OOYJcqG7-pkU2TnfxL2opp3AIEg9BLhdYrP05ezev8swqT-5_YZ7h3nRWawYrIWfCilwUegLOKyVy7tRurnFuH2ZF0VKKYJ8pu24feIcHc6Vqz3zphEvfjpMilUQ66EQ_Gj8M/s1217/7%20-%20Add%20scope%20me.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;706&quot; data-original-width=&quot;1217&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_Y0qO1H-DAdYWmG2kSG-kQoGY6SZEsFrCAi3oRYYEmE-0IrhvryFTUr0OOYJcqG7-pkU2TnfxL2opp3AIEg9BLhdYrP05ezev8swqT-5_YZ7h3nRWawYrIWfCilwUegLOKyVy7tRurnFuH2ZF0VKKYJ8pu24feIcHc6Vqz3zphEvfjpMilUQ66EQ_Gj8M/s16000/7%20-%20Add%20scope%20me.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;p style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;/div&gt;&lt;div&gt;&lt;p style=&quot;text-align: left;&quot;&gt;The SPA is now ready to login via SSO using Microsoft Entrata.&lt;/p&gt;&lt;/div&gt;&lt;div&gt;&lt;h2&gt;Backend Spring Service&lt;/h2&gt;&lt;/div&gt;&lt;div&gt;We will start with an empty Spring Boot project and add each piece.&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Maven Dependencies&lt;/h3&gt;&lt;div&gt;We need to have at least the following. This project will exchange Entrata group mapping it to an internal role map to permissions as shown in the diagram above. The permissions will be used as roles.&lt;/div&gt;&lt;div&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5kuQ3jHcAgBiAyiKZcMotB-_NdZ9ZCHEukpE3HYFC_U_NEvSnqUb9dvJlycTufoJSzaje4-padK8ufTxAvMq6JVCCua1wQbdVmX2ErLuGxsmzzJIzgQuTIsxZYpTRiRwWSNf6BWQAsdzVtJaOD2JgoDyRXO7cEgZ14wRF9dGcrB8YuXxC1SzEFBR3dLsX/s1169/8%20-%20Dependencies.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; margin-bottom: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1091&quot; data-original-width=&quot;1169&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5kuQ3jHcAgBiAyiKZcMotB-_NdZ9ZCHEukpE3HYFC_U_NEvSnqUb9dvJlycTufoJSzaje4-padK8ufTxAvMq6JVCCua1wQbdVmX2ErLuGxsmzzJIzgQuTIsxZYpTRiRwWSNf6BWQAsdzVtJaOD2JgoDyRXO7cEgZ14wRF9dGcrB8YuXxC1SzEFBR3dLsX/s16000/8%20-%20Dependencies.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;Convert Entrata Group to Internal Roles&lt;/h3&gt;&lt;div&gt;In this step, we will be using our internal tables where roles and permissions are stored. The Entrata group&#39;s UUID is searched in the auth_role table and the role&#39;s permissions are added as authorities to the JWT token.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiW4po4hupDHsCxytC1gX13ADgT1r0yI6vdnE9WsMdzTQDHeypns97AJvXBvEP9tqA9iQV05Rf8HPSKda3j2gMgu4-Yv33CENyNXunyEDfpxKDRGER4ZckdHRYUSbToE1ZqfOmxYr6AsOohlw82DANHZKsOVeYWUoMff3gDI7qnmoyvs5ajWP-W1jsDc1et/s1375/9%20-%20Entrata%20group%20conversion.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;971&quot; data-original-width=&quot;1375&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiW4po4hupDHsCxytC1gX13ADgT1r0yI6vdnE9WsMdzTQDHeypns97AJvXBvEP9tqA9iQV05Rf8HPSKda3j2gMgu4-Yv33CENyNXunyEDfpxKDRGER4ZckdHRYUSbToE1ZqfOmxYr6AsOohlw82DANHZKsOVeYWUoMff3gDI7qnmoyvs5ajWP-W1jsDc1et/s16000/9%20-%20Entrata%20group%20conversion.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;This converter is used as the AuthenticationConverter when setting up the oauth2ResourceServer in the securityFilterChain. Furthermore, we need to set the resourceserver&#39;s issuer-uri in the application yml file. This URL will be used when validating the token.&lt;h2 style=&quot;text-align: left;&quot;&gt;Testing&amp;nbsp;&lt;/h2&gt;&lt;div&gt;To test the integration we will be creating a new controller with PreAuthorize annotated endpoints validating the authority bound to the JWT token.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOyaxgXxHk5-PR6trELo692MwGw-3hCFLP7OUpk09WYQw53J4GuWFvfnepNnUN4KEpOtPq3It1D41WvBVVPS3hiN1u9cTkmXyPKh4jDZ6pb8lHfCYrY_m_gmhgDMWeiaZfEoMgruWlkHQivkwF3nVR_4m7yeDO2fiTzK-Uzhb4Q063sjunjRV-SlzkmBTP/s1337/10%20-%20Testing.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1337&quot; data-original-width=&quot;1241&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOyaxgXxHk5-PR6trELo692MwGw-3hCFLP7OUpk09WYQw53J4GuWFvfnepNnUN4KEpOtPq3It1D41WvBVVPS3hiN1u9cTkmXyPKh4jDZ6pb8lHfCYrY_m_gmhgDMWeiaZfEoMgruWlkHQivkwF3nVR_4m7yeDO2fiTzK-Uzhb4Q063sjunjRV-SlzkmBTP/s16000/10%20-%20Testing.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To enable the method level security we need to annotate a configuration class with&amp;nbsp;&lt;b&gt;@EnableMethodSecurity&lt;/b&gt;.&lt;/div&gt;&lt;div&gt;&lt;h2&gt;Development and Support&lt;/h2&gt;&lt;div&gt;The Spring project used in this tutorial is available at&amp;nbsp;&lt;a href=&quot;https://github.com/czetsuyatech/spring-ms-entrata-oauth&quot;&gt;https://github.com/czetsuyatech/spring-ms-entrata-oauth&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Unlock the full coding experience! As a&amp;nbsp;&lt;a href=&quot;https://github.com/sponsors/czetsuya&quot; target=&quot;_blank&quot;&gt;GitHub Sponsor&lt;/a&gt;, you gain exclusive access to the code behind this article—start learning and building today!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I&#39;m available for contracting services and support. You can reach me at:&amp;nbsp;&lt;a href=&quot;https://www.czetsuyatech.com/p/consultation-services.html&quot;&gt;https://www.czetsuyatech.com/p/consultation-services.html&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/5860202626945923728/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2025/07/spring-sso-with-microsoft-entrata.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/5860202626945923728'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/5860202626945923728'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2025/07/spring-sso-with-microsoft-entrata.html' title='Secure React and Spring Boot with Microsoft Entra SSO and Bearer Token Authentication'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAaCBZcW8WxfhqBiSSs_rt3zFVxoVbYrVmbPJOsT0Y0_uedLB0Tkz1HUuQpb22bewVTc9EMUXt95dE5frjTp96f2oTsMx4PvleObWIKYb0HB19uHfh59yvGazCkaflfrnGsTD63FGeqbdVLtaBukIjVJBcMGAaUk1lw4UKCprjRn-13pvXLLacBA7uNoYm/s72-c/Role%20Permission.drawio.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-1302458893965737422</id><published>2025-03-04T15:27:00.000+08:00</published><updated>2026-09-09T18:57:57.331+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Featured"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="JPA"/><category scheme="http://www.blogger.com/atom/ns#" term="Persistence"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring"/><title type='text'>Spring Data JPA: Creating Dynamic Search Filters with Specifications</title><content type='html'>&lt;h2 style=&quot;text-align: left;&quot;&gt;1. Introduction&lt;/h2&gt;
&lt;div&gt;In this article, I will share an implementation that utilizes a common base class to streamline the process of implementing search functionality in Spring Data JPA using Specifications. By creating a reusable base class, you can efficiently manage and extend your search logic across multiple entities. This approach reduces redundancy and promotes cleaner, more maintainable code while allowing for dynamic query creation based on varying search criteria. Whether you&#39;re dealing with simple or complex filtering requirements, this solution will simplify your data querying layer in Spring applications.&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;2. Supported Operations&lt;/h2&gt;
&lt;div&gt;The following operations are supported:&lt;/div&gt;
&lt;div&gt;
  &lt;ul style=&quot;text-align: left;&quot;&gt;
    &lt;li&gt;greater than&lt;/li&gt;
    &lt;li&gt;less than&lt;/li&gt;
    &lt;li&gt;greater than or equal&lt;/li&gt;
    &lt;li&gt;less than or equal&lt;/li&gt;
    &lt;li&gt;equal&lt;/li&gt;
    &lt;li&gt;isnull&lt;/li&gt;
    &lt;li&gt;like&lt;/li&gt;
  &lt;/ul&gt;
  &lt;div&gt;These operation will be listed as enum for easier reference.&lt;/div&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;3. Base Model&lt;/h2&gt;
&lt;div&gt;We will use a user entity to demonstrate the filter.&lt;/div&gt;
&lt;div&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;package com.czetsuyatech.persistence.entities;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import lombok.Data;

@Table(name = &quot;user_profile&quot;)
@Entity
@Data
public class UserEntity extends BaseEntity {

  @Column(name = &quot;first_name&quot;)
  private String firstName;

  @Column(name = &quot;last_name&quot;)
  private String lastName;

  @Column(name = &quot;role&quot;)
  private String role;

  @Column(name = &quot;age&quot;)
  private int age;
}

  &lt;/pre&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;4. Class / Flow Diagram&lt;/h2&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
  &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhL8TJEoY2aupZbp729iGtoreiPvEgywQjdm6w3aQLpxWg2E_pJZOteMMpuIc52rYqMPsEei1Qx52UaOv3D93wal-lvbzK4PrKvaN11RfsonOaSRbaQ3N5UEpmaZXspo3SUW8953l9RTZwXHda363xnezaLJTfHNvIxQxaqKJXSEUDowBUkxNPPNIHQGakA/s481/Spring-Data-Search-with-Specification.drawio.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;
    &lt;img border=&quot;0&quot; data-original-height=&quot;441&quot; data-original-width=&quot;481&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhL8TJEoY2aupZbp729iGtoreiPvEgywQjdm6w3aQLpxWg2E_pJZOteMMpuIc52rYqMPsEei1Qx52UaOv3D93wal-lvbzK4PrKvaN11RfsonOaSRbaQ3N5UEpmaZXspo3SUW8953l9RTZwXHda363xnezaLJTfHNvIxQxaqKJXSEUDowBUkxNPPNIHQGakA/s16000/Spring-Data-Search-with-Specification.drawio.png&quot; /&gt;
  &lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;As we can see above we will need a query builder that accepts UserSpecification and UserFields to generate the user entity specification that we need to feed to the UserRepository extending SliceJpaRepository, which is implemented by SimpleSliceJpaRepositoryImpl.&amp;nbsp;&lt;/div&gt;&lt;h2 style=&quot;clear: both; text-align: left;&quot;&gt;5. Repositories and Services&lt;/h2&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;5.1 Anatomy of the user repository&lt;/h3&gt;
&lt;div&gt;
&lt;pre class=&quot;brush: java&quot;&gt;@Repository
public interface UserRepository extends SliceJpaRepository&amp;lt;UserEntity, Long&amp;gt; {

}
&lt;/pre&gt;
  &lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;@NoRepositoryBean
public interface SliceJpaRepository&amp;lt;ENTITY, ID extends Serializable&amp;gt; extends JpaRepository&amp;lt;ENTITY, ID&amp;gt;,
    JpaSpecificationExecutor&amp;lt;ENTITY&amp;gt;, JpaSpecificationExecutorWithProjection&amp;lt;ENTITY&amp;gt; {

  Slice&amp;lt;ENTITY&amp;gt; findAllSlice(@Nullable Specification&amp;lt;ENTITY&amp;gt; specification, Pageable pageable);
}
&lt;/pre&gt;
&lt;/div&gt;&lt;h3 style=&quot;text-align: left;&quot;&gt;
5.2 Query Builder&lt;/h3&gt;&lt;div&gt;The query builder accepts the available filterable parameters of the user entity and the specification which define how we are going to implement the filter using criteria builder.&lt;/div&gt;
&lt;pre class=&quot;brush: java&quot;&gt;public enum UserSearchFields {

  FIRSTNAME {
    @Override
    public String toString() {
      return &quot;firstName&quot;;
    }
  },
  LASTNAME {
    @Override
    public String toString() {
      return &quot;lastName&quot;;
    }
  },
  ROLE {
    @Override
    public String toString() {
      return &quot;role&quot;;
    }
  },
  AGE {
    @Override
    public String toString() {
      return &quot;age&quot;;
    }
  }
}
&lt;/pre&gt;
&lt;div&gt;&lt;br /&gt;&lt;/div&gt;
&lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;@AllArgsConstructor
public class UserSpecification implements Specification&amp;lt;UserEntity&amp;gt; {

  private transient SearchCriteria criteria;

  @Override
  public Predicate toPredicate(Root&amp;lt;UserEntity&amp;gt; root, CriteriaQuery&amp;lt;?&amp;gt; query, CriteriaBuilder criteriaBuilder) {

    UserSearchFields key = UserSearchFields.valueOf(StringUtils.upperCase(criteria.getKey()));
    RelationalOperators operator = RelationalOperators.getOperator(criteria.getOperation());
    Object value = criteria.getValue();
    Expression&amp;lt;?&amp;gt; expression = root.&amp;lt;String&amp;gt;get(key.toString());

    Predicate predicate = null;

    switch (operator) {
      case LIKE -&amp;gt; predicate = buildLike(key, value, expression, criteriaBuilder);
      case EQUAL -&amp;gt; predicate = buildEqual(key, value, expression, criteriaBuilder);
      case GREATER, GREATER_THAN_EQUAL -&amp;gt; predicate = buildGreater(key, value, expression, criteriaBuilder);
      case LESS, LESS_THAN_EQUAL -&amp;gt; predicate = buildLess(key, value, expression, criteriaBuilder);
      default -&amp;gt; throw new IllegalStateException(&quot;Unexpected value: &quot; + operator);
    }

    return predicate;
  }

  private Predicate buildLess(UserSearchFields key, Object value, Expression&amp;lt;?&amp;gt; expression,
      CriteriaBuilder criteriaBuilder) {

    return criteriaBuilder.lessThanOrEqualTo((Expression&amp;lt;Integer&amp;gt;) expression, Integer.parseInt(value.toString()));
  }

  private Predicate buildGreater(UserSearchFields key, Object value, Expression&amp;lt;?&amp;gt; expression,
      CriteriaBuilder criteriaBuilder) {

    return criteriaBuilder.greaterThanOrEqualTo((Expression&amp;lt;Integer&amp;gt;) expression, Integer.parseInt(value.toString()));
  }

  private Predicate buildEqual(UserSearchFields key, Object value, Expression&amp;lt;?&amp;gt; expression,
      CriteriaBuilder criteriaBuilder) {

    return criteriaBuilder.equal(expression, value);
  }

  private Predicate buildLike(UserSearchFields key, Object value, Expression&amp;lt;?&amp;gt; expression,
      CriteriaBuilder criteriaBuilder) {

    return criteriaBuilder.like((Expression&amp;lt;String&amp;gt;) expression,
        value.toString() + SpecificationConstant.LIKE_WILDCARD);
  }
}
&lt;/pre&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;5.3 The user service that invokes the repository.&lt;/h3&gt;
&lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

  private final UserRepository userRepository;
  private final UserMapper userMapper;

  @Transactional(readOnly = true)
  @Override
  public Slice&amp;lt;UserDTO&amp;gt; findUsers(String searchParams, Pageable pageable) {

    try {
      Specification&amp;lt;UserEntity&amp;gt; specResult = QueryBuilder.build(searchParams, UserSpecification.class,
          UserSearchFields.class);

      return userRepository.findAllSlice(specResult, pageable).map(userMapper::userToUserDTO);

    } catch (Exception e) {
      e.printStackTrace();
    }

    return new SliceImpl&amp;lt;&amp;gt;(Collections.emptyList());
  }
}
&lt;/pre&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;
6. Controller&lt;/h2&gt;&lt;div&gt;And this is how we are going to call the service from the controller.&lt;/div&gt;
&lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;@RequestMapping(&quot;/users&quot;)
@RestController
@RequiredArgsConstructor
@Slf4j
public class UserController {

  private final UserService userService;

  @GetMapping
  public ResponseEntity&amp;lt;Slice&amp;lt;UserDTO&amp;gt;&amp;gt; findUsers(@RequestParam(name = &quot;search&quot;, required = false) String search,
      @PageableDefault Pageable pageable) {

    log.debug(&quot;Search: &quot; + search);

    return ResponseEntity.ok(userService.findUsers(search, pageable));
  }
}
&lt;/pre&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;7. Postman Tests&lt;/h2&gt;&lt;div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/a/AVvXsEg_w6Q6meQfUMxroTF64vCcO3K9AG0lAWZiUibrFGk2WLzfCua4LxWibiXwXTm4zDNwYXDz5mMv5UYSw-PYqhN-hhGyFgAFqdvSgHSLHevGtMiMSqyAzn8vhvZ-ZquP6SvUS_qIhr_cX8_cTs7KCTkEAi3VbxT3f5ShpP2XdYSE5yH8cdh6Dgn8V3HhzoJQ&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img data-original-height=&quot;898&quot; data-original-width=&quot;1072&quot; src=&quot;https://blogger.googleusercontent.com/img/a/AVvXsEg_w6Q6meQfUMxroTF64vCcO3K9AG0lAWZiUibrFGk2WLzfCua4LxWibiXwXTm4zDNwYXDz5mMv5UYSw-PYqhN-hhGyFgAFqdvSgHSLHevGtMiMSqyAzn8vhvZ-ZquP6SvUS_qIhr_cX8_cTs7KCTkEAi3VbxT3f5ShpP2XdYSE5yH8cdh6Dgn8V3HhzoJQ=s16000&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;&lt;h2 style=&quot;text-align: left;&quot;&gt;8. Development and Support&lt;/h2&gt;&lt;div&gt;Unlock the full coding experience! As a &lt;a href=&quot;https://github.com/sponsors/czetsuya&quot; target=&quot;_blank&quot;&gt;GitHub Sponsor&lt;/a&gt;, you gain exclusive access to the code behind this article—start learning and building today!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I&#39;m available for contracting services and support. You can reach me at:&amp;nbsp;&lt;a href=&quot;https://www.czetsuyatech.com/p/consultation-services.html&quot;&gt;https://www.czetsuyatech.com/p/consultation-services.html&lt;/a&gt;.&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/1302458893965737422/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2025/03/spring-data-jpa-creating-dynamic-search-filters-with-specification.html.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/1302458893965737422'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/1302458893965737422'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2025/03/spring-data-jpa-creating-dynamic-search-filters-with-specification.html.html' title='Spring Data JPA: Creating Dynamic Search Filters with Specifications'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhL8TJEoY2aupZbp729iGtoreiPvEgywQjdm6w3aQLpxWg2E_pJZOteMMpuIc52rYqMPsEei1Qx52UaOv3D93wal-lvbzK4PrKvaN11RfsonOaSRbaQ3N5UEpmaZXspo3SUW8953l9RTZwXHda363xnezaLJTfHNvIxQxaqKJXSEUDowBUkxNPPNIHQGakA/s72-c/Spring-Data-Search-with-Specification.drawio.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-9027534657043846550</id><published>2024-12-07T08:27:00.000+08:00</published><updated>2026-09-08T23:51:09.723+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><title type='text'>How to Handle Daylight Saving Time Conversion in Java</title><content type='html'>&lt;p&gt;Learn how to handle daylight saving time (DST) conversions in Java with clear, practical code examples. This guide focuses on using the right classes and methods to accurately convert dates and times across DST boundaries. Perfect for developers looking to simplify time zone management in their applications.&lt;/p&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Code&lt;/h2&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;Version 1&lt;/h3&gt;
&lt;pre class=&quot;brush: java&quot;&gt;
public class TimeZoneConversion {
    public static void main(String[] args) {
        // Example UTC date-time
        // String utcDateTimeStr = &quot;2024-11-01T00:00:00&quot;;
		String utcDateTimeStr = &quot;2024-03-24T00:00:00&quot;;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss&quot;);
 
        // Parse UTC date-time
        LocalDateTime utcDateTime = LocalDateTime.parse(utcDateTimeStr, formatter);
 
        // Convert to UTC ZonedDateTime
        ZonedDateTime utcZonedDateTime = utcDateTime.atZone(ZoneId.of(&quot;UTC&quot;));
 
        // Convert to Netherlands time zone
        ZonedDateTime netherlandsTime = utcZonedDateTime.withZoneSameInstant(ZoneId.of(&quot;Europe/Amsterdam&quot;));
 
        // Format and print the result
        System.out.println(&quot;UTC Time: &quot; + utcZonedDateTime);
        System.out.println(&quot;Netherlands Time: &quot; + netherlandsTime.format(formatter));
    }
}
&lt;/pre&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;Version 2&lt;/h3&gt;
&lt;pre class=&quot;brush: java&quot;&gt;
public class TimeZoneConversion {
    public static void main(String[] args) {
		TimeZone tz = TimeZone.getTimeZone(&quot;Europe/Amsterdam&quot;);
		TimeZone.setDefault(tz);
		Calendar cal = Calendar.getInstance(tz, Locale.ITALIAN);
		DateFormat df = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm&quot;, Locale.ITALIAN);
		Date dateBeforeDST = df.parse(&quot;2018-03-25 01:55&quot;);
		cal.setTime(dateBeforeDST);
		cal.add(Calendar.MINUTE, 10);

		System.out.println(cal.get(Calendar.ZONE_OFFSET));
		System.out.println(cal.get(Calendar.DST_OFFSET));
	}
}
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/9027534657043846550/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2024/12/how-to-handle-daylight-saving-time.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/9027534657043846550'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/9027534657043846550'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2024/12/how-to-handle-daylight-saving-time.html' title='How to Handle Daylight Saving Time Conversion in Java'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-111934355531639029</id><published>2024-06-09T16:37:00.000+08:00</published><updated>2026-09-08T23:51:10.897+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JasperReports"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><title type='text'>How to Create a Jasper Report from an XML Datasource: A Step-by-Step Guide</title><content type='html'>&lt;h2 style=&quot;text-align: left;&quot;&gt;1. Introduction&lt;/h2&gt;
&lt;div&gt;JasperReports is an open-source Java reporting tool that allows developers to create sophisticated reports for display, printing, or exporting into a variety of formats such as PDF, HTML, CSV, and others. It&#39;s widely used in Java-based applications for generating pixel-perfect reports with rich content like charts, tables, and images. JasperReports provides a flexible and customizable framework for designing and generating reports from various data sources, including databases, XML files, and custom data sources. It&#39;s often integrated into Java web applications and enterprise systems for generating dynamic and professional-looking reports.&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;2. Use Case&lt;/h2&gt;
&lt;div&gt;In this article, we will take a look at how Opencell an open-source billing platform integrates Jasper reports to generate its invoicing documents.&lt;/div&gt;
&lt;div&gt;
	&lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;The goal of this exercise is to:&lt;/div&gt;
&lt;div&gt;
	&lt;ol style=&quot;text-align: left;&quot;&gt;
		&lt;li&gt;Generate a financial document (invoice) using Jasper reports.&lt;/li&gt;
		&lt;li&gt;Use a custom font.&lt;/li&gt;
		&lt;li&gt;Use an XML document.&lt;/li&gt;
	&lt;/ol&gt;
	&lt;div&gt;Using XML as a data source in JasperReports can be ideal for several reasons:&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
	&lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;
	&lt;div&gt;
		&lt;ol style=&quot;text-align: left;&quot;&gt;
			&lt;li&gt;
				&lt;b&gt;Flexibility:&lt;/b&gt; XML is a highly flexible data format that can represent structured data in a hierarchical manner. This makes it suitable for a wide range of data sources, including relational databases, web services, and custom data structures.
			
			&lt;/li&gt;
			&lt;li&gt;
				&lt;b&gt;Platform-agnostic:&lt;/b&gt; XML is platform-independent, meaning it can be easily generated and consumed by different programming languages and technologies. This makes it a versatile choice for integrating with various systems and applications.
			
			&lt;/li&gt;
			&lt;li&gt;
				&lt;b&gt;Ease of Integration:&lt;/b&gt; Many applications and systems already generate or consume XML data, so using XML as a data source can simplify integration with existing infrastructure.
			
			&lt;/li&gt;
			&lt;li&gt;
				&lt;b&gt;Customizability:&lt;/b&gt; XML allows developers to define custom data structures and schemas tailored to their specific reporting needs. This enables precise control over the data consumed by JasperReports and the structure of the resulting reports.
			
			&lt;/li&gt;
			&lt;li&gt;
				&lt;b&gt;Separation of Concerns:&lt;/b&gt; Using XML as a data source promotes a clean separation between data and presentation layers. This separation allows for easier maintenance, scalability, and reuse of report templates across different datasets.
			
			&lt;/li&gt;
			&lt;li&gt;
				&lt;b&gt;Performance:&lt;/b&gt; When properly optimized, XML processing can offer good performance characteristics for report generation. Techniques such as indexing, caching, and streaming can be employed to efficiently handle large XML datasets.
			
			&lt;/li&gt;
		&lt;/ol&gt;
	&lt;/div&gt;
	&lt;div&gt;Overall, XML serves as a versatile and effective data source for JasperReports, offering flexibility, interoperability, and ease of integration with diverse data sources and systems.&lt;/div&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;3. Coding&lt;/h2&gt;
&lt;div&gt;We&#39;ll develop a Java application to produce a PDF invoice by utilizing a Jasper template sourced from an XML data provider.&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;3.1 XML Datasource&lt;/h3&gt;
&lt;div&gt;Our XML document is generated from Opencell that contains customer and usage information.&lt;/div&gt;
&lt;div&gt;
	&lt;pre class=&quot;brush: java&quot;&gt;  &amp;lt;invoice customerAccountCode=&quot;CA_2000000021&quot; customerId=&quot;CUST_2000000021&quot; id=&quot;101&quot;
    invoiceCounter=&quot;00000027&quot; number=&quot;INV00000027&quot; templateName=&quot;invoice&quot; type=&quot;INV&quot;&amp;gt;
  &amp;lt;header&amp;gt;
    &amp;lt;provider code=&quot;CT&quot; description=&quot;CZETSUYATECH&quot;&amp;gt;
      &amp;lt;bankCoordinates&amp;gt;
        &amp;lt;ics&amp;gt;FRXXZZZ123456&amp;lt;/ics&amp;gt;
        &amp;lt;iban&amp;gt;FR763000600001123456790189&amp;lt;/iban&amp;gt;
        &amp;lt;bic&amp;gt;CTDEFRPPCCT&amp;lt;/bic&amp;gt;
      &amp;lt;/bankCoordinates&amp;gt;
    &amp;lt;/provider&amp;gt;
    &amp;lt;customer brand=&quot;&quot; category=&quot;CLIENT&quot; code=&quot;CUST_2000000021&quot; externalRef1=&quot;&quot; externalRef2=&quot;&quot;
        id=&quot;565&quot; jobTitle=&quot;&quot; registrationNo=&quot;&quot; sellerCode=&quot;CZETSUYATECH&quot; vatNo=&quot;&quot;&amp;gt;
      &amp;lt;address&amp;gt;
        &amp;lt;address1/&amp;gt;
        &amp;lt;address2/&amp;gt;
        &amp;lt;address3/&amp;gt;
        &amp;lt;city/&amp;gt;
        &amp;lt;postalCode/&amp;gt;
        &amp;lt;state/&amp;gt;
        &amp;lt;country/&amp;gt;
        &amp;lt;countryName/&amp;gt;
      &amp;lt;/address&amp;gt;
      &amp;lt;contact/&amp;gt;
    &amp;lt;/customer&amp;gt;
    &amp;lt;seller code=&quot;CZETSUYATECH&quot; description=&quot;CZETSUYATECH&quot;&amp;gt;
      &amp;lt;address&amp;gt;
        &amp;lt;address1/&amp;gt;
        &amp;lt;address2/&amp;gt;
        &amp;lt;address3/&amp;gt;
        &amp;lt;city/&amp;gt;
        &amp;lt;postalCode/&amp;gt;
        &amp;lt;state/&amp;gt;
        &amp;lt;country/&amp;gt;
        &amp;lt;countryName/&amp;gt;
      &amp;lt;/address&amp;gt;
      &amp;lt;contact/&amp;gt;
    &amp;lt;/seller&amp;gt;
    &amp;lt;customerAccount accountTerminated=&quot;false&quot; code=&quot;CA_2000000021&quot; currency=&quot;EUR&quot;
        description=&quot;Edward&#39;s Account&quot; externalRef1=&quot;&quot; externalRef2=&quot;&quot; id=&quot;566&quot; jobTitle=&quot;&quot;
        language=&quot;English&quot; vatNo=&quot;xxx&quot;&amp;gt;
      &amp;lt;contact email=&quot;czetsuya@gmail.com&quot; fax=&quot;&quot; mobile=&quot;&quot; phone=&quot;(303) 829-5342&quot;/&amp;gt;
      &amp;lt;paymentMethod type=&quot;CHECK&quot;/&amp;gt;
      &amp;lt;name&amp;gt;
        &amp;lt;quality/&amp;gt;
        &amp;lt;name&amp;gt;Edward&#39;s Account&amp;lt;/name&amp;gt;
      &amp;lt;/name&amp;gt;
      &amp;lt;address&amp;gt;
        &amp;lt;address1&amp;gt;1234 Balamb Garden&amp;lt;/address1&amp;gt;
        &amp;lt;address2/&amp;gt;
        &amp;lt;address3/&amp;gt;
        &amp;lt;city&amp;gt;Los Banos&amp;lt;/city&amp;gt;
        &amp;lt;postalCode&amp;gt;4030&amp;lt;/postalCode&amp;gt;
        &amp;lt;state/&amp;gt;
        &amp;lt;country&amp;gt;PH&amp;lt;/country&amp;gt;
        &amp;lt;countryName&amp;gt;Philippines&amp;lt;/countryName&amp;gt;
      &amp;lt;/address&amp;gt;
    &amp;lt;/customerAccount&amp;gt;
    &amp;lt;billingAccount billingCycleCode=&quot;MONTHLY_POST_PAID&quot; code=&quot;BA_2000000021&quot;
        description=&quot;BA_2000000021&quot; endPeriod=&quot;31/05/2024&quot; externalRef1=&quot;&quot; externalRef2=&quot;&quot; id=&quot;567&quot;
        jobTitle=&quot;&quot; startPeriod=&quot;09/05/2024&quot;&amp;gt;
      &amp;lt;billingCycle code=&quot;MONTHLY_POST_PAID&quot; description=&quot;Monthly Invoice Cycle&quot; id=&quot;6&quot;&amp;gt;
      &amp;lt;/billingCycle&amp;gt;
      &amp;lt;email&amp;gt;czetsuya@gmail.com&amp;lt;/email&amp;gt;
      &amp;lt;name&amp;gt;
        &amp;lt;quality/&amp;gt;
        &amp;lt;name&amp;gt;Edward&#39;s Account&amp;lt;/name&amp;gt;
      &amp;lt;/name&amp;gt;
      &amp;lt;address&amp;gt;
        &amp;lt;address1&amp;gt;1234 Balamb Garden&amp;lt;/address1&amp;gt;
        &amp;lt;address2/&amp;gt;
        &amp;lt;address3/&amp;gt;
        &amp;lt;city&amp;gt;Los Banos&amp;lt;/city&amp;gt;
        &amp;lt;postalCode&amp;gt;4030&amp;lt;/postalCode&amp;gt;
        &amp;lt;state/&amp;gt;
        &amp;lt;country&amp;gt;PH&amp;lt;/country&amp;gt;
        &amp;lt;countryName&amp;gt;Philippines&amp;lt;/countryName&amp;gt;
      &amp;lt;/address&amp;gt;
      &amp;lt;message/&amp;gt;
      &amp;lt;billTo&amp;gt;
        &amp;lt;![CDATA[Edward&#39;s Account&amp;lt;br/&amp;gt;1234 Balamb Garden&amp;lt;br/&amp;gt;Los Banos, Laguna 4030&amp;lt;br/&amp;gt;PH]]&amp;gt;
      &amp;lt;/billTo&amp;gt;
      &amp;lt;fees/&amp;gt;
      &amp;lt;charges licensePlate=&quot;NLEDW_LE2021&quot;
          urlImage=&quot;https://czetsuyatech.com/PHEDW_LE2021.latest.jpg&quot;&amp;gt;
        &amp;lt;charge amount=&quot;-161.000000000000&quot; date=&quot;05/28/24 19:45&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/9/24 9:29 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566170&quot;/&amp;gt;
        &amp;lt;charge amount=&quot;161.000000000000&quot; date=&quot;5/10/24 7:52 AM&quot; description=&quot;GoPlus&quot;
            transactionId=&quot;566171&quot;/&amp;gt;
      &amp;lt;/charges&amp;gt;
      &amp;lt;topups/&amp;gt;
    &amp;lt;/billingAccount&amp;gt;
    &amp;lt;invoiceDate&amp;gt;13/05/2024&amp;lt;/invoiceDate&amp;gt;
    &amp;lt;dueDate&amp;gt;13/06/2024&amp;lt;/dueDate&amp;gt;
    &amp;lt;paymentMethod&amp;gt;CHECK&amp;lt;/paymentMethod&amp;gt;
    &amp;lt;comment&amp;gt;
    &amp;lt;/comment&amp;gt;
    &amp;lt;categories&amp;gt;
      &amp;lt;category code=&quot;CLASSIC_USAGE&quot; label=&quot;Service Usage&quot;&amp;gt;
        &amp;lt;amountWithoutTax&amp;gt;322.000000000000&amp;lt;/amountWithoutTax&amp;gt;
        &amp;lt;subCategories&amp;gt;
          &amp;lt;subCategory amountWithoutTax=&quot;322.000000000000&quot; code=&quot;CLASSIC_USAGE&quot;
              label=&quot;Service Usage&quot; taxCode=&quot;TAX_00&quot; taxPercent=&quot;0.000000000000&quot;/&amp;gt;
        &amp;lt;/subCategories&amp;gt;
      &amp;lt;/category&amp;gt;
    &amp;lt;/categories&amp;gt;
    &amp;lt;discounts/&amp;gt;
    &amp;lt;locale&amp;gt;en-US&amp;lt;/locale&amp;gt;
  &amp;lt;/header&amp;gt;
  &amp;lt;amount&amp;gt;
    &amp;lt;currency&amp;gt;EUR&amp;lt;/currency&amp;gt;
    &amp;lt;amountWithoutTax&amp;gt;322.000000000000&amp;lt;/amountWithoutTax&amp;gt;
    &amp;lt;amountWithTax&amp;gt;322.000000000000&amp;lt;/amountWithTax&amp;gt;
    &amp;lt;netToPay&amp;gt;322.000000000000&amp;lt;/netToPay&amp;gt;
    &amp;lt;taxes total=&quot;0.000000000000&quot;&amp;gt;
      &amp;lt;tax code=&quot;TAX_00&quot; id=&quot;1&quot;&amp;gt;
        &amp;lt;name&amp;gt;0 Percent Tax&amp;lt;/name&amp;gt;
        &amp;lt;percent&amp;gt;0.000000000000&amp;lt;/percent&amp;gt;
        &amp;lt;amount&amp;gt;0.000000000000&amp;lt;/amount&amp;gt;
        &amp;lt;amountHT&amp;gt;322.000000000000&amp;lt;/amountHT&amp;gt;
      &amp;lt;/tax&amp;gt;
    &amp;lt;/taxes&amp;gt;
  &amp;lt;/amount&amp;gt;
  &amp;lt;detail&amp;gt;
    &amp;lt;userAccounts&amp;gt;
      &amp;lt;userAccount code=&quot;UA_2000000021&quot; description=&quot;UA_2000000021&quot; id=&quot;568&quot; jobTitle=&quot;&quot;&amp;gt;
        &amp;lt;customFields&amp;gt;
          &amp;lt;customField code=&quot;CUSTOMER_NUMBER&quot; description=&quot;Customer Number&quot;&amp;gt;1190017814&amp;lt;/customField&amp;gt;
          &amp;lt;customField code=&quot;ACCOUNT_NUMBER&quot; description=&quot;Account Number&quot;&amp;gt;2000000021&amp;lt;/customField&amp;gt;
        &amp;lt;/customFields&amp;gt;
        &amp;lt;subscriptions&amp;gt;
          &amp;lt;subscription code=&quot;SUBS_2000000021_NLEDW_LE2021_1590017830&quot;
              description=&quot;SUBS_2000000021_NLEDW_LE2021_1590017830&quot; id=&quot;309&quot; offerCode=&quot;GoPlus&quot;&amp;gt;
            &amp;lt;subscriptionDate&amp;gt;13/10/2023&amp;lt;/subscriptionDate&amp;gt;
            &amp;lt;endAgreementDate/&amp;gt;
          &amp;lt;/subscription&amp;gt;
        &amp;lt;/subscriptions&amp;gt;
        &amp;lt;name&amp;gt;
          &amp;lt;quality/&amp;gt;
          &amp;lt;firstName&amp;gt;Ed&amp;lt;/firstName&amp;gt;
          &amp;lt;name/&amp;gt;
        &amp;lt;/name&amp;gt;
        &amp;lt;address&amp;gt;
          &amp;lt;address1/&amp;gt;
          &amp;lt;address2/&amp;gt;
          &amp;lt;address3/&amp;gt;
          &amp;lt;city/&amp;gt;
          &amp;lt;postalCode/&amp;gt;
          &amp;lt;state/&amp;gt;
          &amp;lt;country/&amp;gt;
          &amp;lt;countryName/&amp;gt;
        &amp;lt;/address&amp;gt;
        &amp;lt;categories&amp;gt;
          &amp;lt;category code=&quot;CLASSIC_USAGE&quot; label=&quot;Service Usage&quot;&amp;gt;
            &amp;lt;amountWithoutTax&amp;gt;322.000000000000&amp;lt;/amountWithoutTax&amp;gt;
            &amp;lt;subCategories&amp;gt;
              &amp;lt;subCategory amountWithoutTax=&quot;322.000000000000&quot; code=&quot;CLASSIC_USAGE&quot;
                  label=&quot;Service Usage&quot; taxCode=&quot;TAX_00&quot; taxPercent=&quot;0.000000000000&quot;&amp;gt;
                &amp;lt;line code=&quot;GoPlus_CT&quot;
                    param1=&quot;fad4c36b-215a-308d-a19d-b6074543d414:fad4c36b-215a-308d-a19d-b6074543d414&quot;
                    param2=&quot;1&quot; param3=&quot;566170&quot;&amp;gt;
                  &amp;lt;walletOperation code=&quot;GoPlus_CT&quot; periodEndDate=&quot;&quot; periodStartDate=&quot;&quot;/&amp;gt;
                  &amp;lt;paramExtra&amp;gt;USAGE&amp;lt;/paramExtra&amp;gt;
                  &amp;lt;pricePlan code=&quot;GoPlus_CT&quot; description=&quot;Price Plan for GoPlus CT&quot;/&amp;gt;
                  &amp;lt;label&amp;gt;
                    GoPlus||EUR|1.0|0.00|161.00|161.00|0E-12|161.000000000000|161.000000000000|USE_TRX_PRICE
                  &amp;lt;/label&amp;gt;
                  &amp;lt;unitAmountWithoutTax&amp;gt;161.000000000000&amp;lt;/unitAmountWithoutTax&amp;gt;
                  &amp;lt;amountWithoutTax&amp;gt;161.000000000000&amp;lt;/amountWithoutTax&amp;gt;
                  &amp;lt;quantity&amp;gt;1.000000000000&amp;lt;/quantity&amp;gt;
                  &amp;lt;usageDate&amp;gt;09/05/2024&amp;lt;/usageDate&amp;gt;
                  &amp;lt;edr accessCode=&quot;AP_2000000021_NLEDW_LE2021&quot; dateParam1=&quot;&quot; dateParam2=&quot;&quot;
                      dateParam3=&quot;&quot; dateParam4=&quot;&quot; dateParam5=&quot;&quot; decimalParam1=&quot;161.000000000000&quot;
                      decimalParam2=&quot;&quot; decimalParam3=&quot;&quot; decimalParam4=&quot;&quot; decimalParam5=&quot;&quot;
                      eventDate=&quot;2024-05-09T09:29:46&quot; originBatch=&quot;API_192.168.67.123&quot;
                      originRecord=&quot;opencell.admin_1715247534640&quot;
                      parameter1=&quot;fad4c36b-215a-308d-a19d-b6074543d414:fad4c36b-215a-308d-a19d-b6074543d414&quot;
                      parameter2=&quot;1&quot; parameter3=&quot;566170&quot; parameter4=&quot;CHARGE_GoPlus_CT&quot;
                      parameter5=&quot;VTOLL&quot; parameter6=&quot;NLEDW_LE2021&quot; parameter7=&quot;&quot;
                      parameter8=&quot;USE_TRX_PRICE&quot; parameter9=&quot;&quot; quantity=&quot;1.000000000000&quot;
                      rejectReason=&quot;&quot; status=&quot;RATED&quot;
                      subscription=&quot;SUBS_2000000021_NLEDW_LE2021_1590017830&quot;/&amp;gt;
                &amp;lt;/line&amp;gt;
                &amp;lt;line code=&quot;GoPlus_CT&quot;
                    param1=&quot;fad4c36b-215a-308d-a19d-b6074543d414:fad4c36b-215a-308d-a19d-b6074543d414&quot;
                    param2=&quot;1&quot; param3=&quot;566171&quot;&amp;gt;
                  &amp;lt;walletOperation code=&quot;GoPlus_CT&quot; periodEndDate=&quot;&quot; periodStartDate=&quot;&quot;/&amp;gt;
                  &amp;lt;paramExtra&amp;gt;USAGE&amp;lt;/paramExtra&amp;gt;
                  &amp;lt;pricePlan code=&quot;GoPlus_CT&quot; description=&quot;Price Plan for GoPlus CT&quot;/&amp;gt;
                  &amp;lt;label&amp;gt;
                    GoPlus||EUR|1.0|0.00|161.00|161.00|0E-12|161.000000000000|161.000000000000|USE_TRX_PRICE
                  &amp;lt;/label&amp;gt;
                  &amp;lt;unitAmountWithoutTax&amp;gt;161.000000000000&amp;lt;/unitAmountWithoutTax&amp;gt;
                  &amp;lt;amountWithoutTax&amp;gt;161.000000000000&amp;lt;/amountWithoutTax&amp;gt;
                  &amp;lt;quantity&amp;gt;1.000000000000&amp;lt;/quantity&amp;gt;
                  &amp;lt;usageDate&amp;gt;10/05/2024&amp;lt;/usageDate&amp;gt;
                  &amp;lt;edr accessCode=&quot;AP_2000000021_NLEDW_LE2021&quot; dateParam1=&quot;&quot; dateParam2=&quot;&quot;
                      dateParam3=&quot;&quot; dateParam4=&quot;&quot; dateParam5=&quot;&quot; decimalParam1=&quot;161.000000000000&quot;
                      decimalParam2=&quot;&quot; decimalParam3=&quot;&quot; decimalParam4=&quot;&quot; decimalParam5=&quot;&quot;
                      eventDate=&quot;2024-05-10T07:52:12&quot; originBatch=&quot;API_192.168.67.60&quot;
                      originRecord=&quot;opencell.admin_1715327638732&quot;
                      parameter1=&quot;fad4c36b-215a-308d-a19d-b6074543d414:fad4c36b-215a-308d-a19d-b6074543d414&quot;
                      parameter2=&quot;1&quot; parameter3=&quot;566171&quot; parameter4=&quot;CHARGE_GoPlus_CT&quot;
                      parameter5=&quot;VTOLL&quot; parameter6=&quot;NLEDW_LE2021&quot; parameter7=&quot;&quot;
                      parameter8=&quot;USE_TRX_PRICE&quot; parameter9=&quot;&quot; quantity=&quot;1.000000000000&quot;
                      rejectReason=&quot;&quot; status=&quot;RATED&quot;
                      subscription=&quot;SUBS_2000000021_NLEDW_LE2021_1590017830&quot;/&amp;gt;
                &amp;lt;/line&amp;gt;
              &amp;lt;/subCategory&amp;gt;
            &amp;lt;/subCategories&amp;gt;
          &amp;lt;/category&amp;gt;
        &amp;lt;/categories&amp;gt;
      &amp;lt;/userAccount&amp;gt;
      &amp;lt;userAccount description=&quot;-&quot;&amp;gt;
        &amp;lt;categories/&amp;gt;
      &amp;lt;/userAccount&amp;gt;
    &amp;lt;/userAccounts&amp;gt;
  &amp;lt;/detail&amp;gt;
  &amp;lt;offers&amp;gt;
    &amp;lt;offer code=&quot;GoPlus&quot; description=&quot;GoPlus&quot; id=&quot;1&quot;&amp;gt;
      &amp;lt;customFields&amp;gt;
        &amp;lt;customField code=&quot;CF_SHARED&quot; description=&quot;Offer Shared&quot;&amp;gt;INDIVIDUAL&amp;lt;/customField&amp;gt;
      &amp;lt;/customFields&amp;gt;
    &amp;lt;/offer&amp;gt;
  &amp;lt;/offers&amp;gt;
  &amp;lt;services&amp;gt;
    &amp;lt;service code=&quot;CT&quot; description=&quot;CT&quot; offerCode=&quot;GoPlus&quot;/&amp;gt;
  &amp;lt;/services&amp;gt;
  &amp;lt;priceplans&amp;gt;
    &amp;lt;priceplan code=&quot;GoPlus_CT&quot; description=&quot;Price Plan for GoPlus CT&quot;&amp;gt;
    &amp;lt;/priceplan&amp;gt;
  &amp;lt;/priceplans&amp;gt;
  &amp;lt;orders/&amp;gt;
  &amp;lt;qrCode
      value=&quot;xxx&quot;/&amp;gt;
  &amp;lt;invoiceQRCodeEmail
      value=&quot;xxx&quot;/&amp;gt;
  &amp;lt;summary currentBalance=&quot;-644.00&quot; outstandingBalance=&quot;0.00&quot; previousBalance=&quot;0.00&quot;
      totalAmountDue=&quot;322.00&quot;/&amp;gt;
&amp;lt;/invoice&amp;gt;
		
		&lt;br /&gt;
	&lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
	&lt;div style=&quot;text-align: left;&quot;&gt;As we can see the root of our document is 
		
		&lt;b&gt;
			&lt;i&gt;&quot;invoice&quot;&lt;/i&gt;
		&lt;/b&gt;.
	
	&lt;/div&gt;
	&lt;h3 style=&quot;text-align: left;&quot;&gt;3.2 Jasper Dependencies&lt;/h3&gt;
	&lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;&amp;lt;dependency&amp;gt;
  &amp;lt;groupId&amp;gt;net.sf.jasperreports&amp;lt;/groupId&amp;gt;
  &amp;lt;artifactId&amp;gt;jasperreports&amp;lt;/artifactId&amp;gt;
  &amp;lt;version&amp;gt;6.21.0&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
  &amp;lt;groupId&amp;gt;jaxen&amp;lt;/groupId&amp;gt;
  &amp;lt;artifactId&amp;gt;jaxen&amp;lt;/artifactId&amp;gt;
  &amp;lt;version&amp;gt;1.2.0&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
  &amp;lt;groupId&amp;gt;org.apache.groovy&amp;lt;/groupId&amp;gt;
  &amp;lt;artifactId&amp;gt;groovy&amp;lt;/artifactId&amp;gt;
  &amp;lt;version&amp;gt;4.0.21&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
  &amp;lt;groupId&amp;gt;net.sf.jasperreports&amp;lt;/groupId&amp;gt;
  &amp;lt;artifactId&amp;gt;jasperreports-fonts&amp;lt;/artifactId&amp;gt;
  &amp;lt;version&amp;gt;6.20.0&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
	&lt;h3 style=&quot;text-align: left;&quot;&gt;3.3 Java Code&lt;/h3&gt;
	&lt;pre class=&quot;brush: java&quot;&gt;package com.czetsuyatech;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JRPropertiesUtil;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRXmlDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class InvoiceReportGenerator {

  private final String jasperReportsPath;
  private ClassLoader cl;
  private String INVOICE_TAG_NAME = &quot;invoice&quot;;

  public InvoiceReportGenerator(String jasperReportsPath, URLClassLoader cl) {

    this.jasperReportsPath = jasperReportsPath;
    this.cl = cl;
  }

  public void generate(String jasperPath, String xmlDataSource)
      throws IOException, ParserConfigurationException, SAXException, TransformerException, JRException {

    File jasperFile = new File(jasperReportsPath, jasperPath);
    String pdfFullFilename = jasperReportsPath + &quot;/output.pdf&quot;;
    File invoiceXmlFile = new File(jasperReportsPath, xmlDataSource);
    Map&amp;lt;String, Object&amp;gt; parameters = getParameters();

    InputStream reportTemplate = new FileInputStream(jasperFile);
    Node invoiceNode = getInvoiceNode(invoiceXmlFile);

    JRXmlDataSource dataSource = new JRXmlDataSource(getJasperReportContext(invoiceNode), &quot;/&quot; + INVOICE_TAG_NAME);

    Map&amp;lt;String, JasperReport&amp;gt; jasperReportMap = new HashMap&amp;lt;&amp;gt;();

    String fileKey = jasperFile.getPath() + jasperFile.lastModified();
    JasperReport jasperReport = jasperReportMap.get(fileKey);
    if (jasperReport == null) {
      jasperReport = (JasperReport) JRLoader.loadObject(reportTemplate);
      jasperReportMap.put(fileKey, jasperReport);
    }

    DefaultJasperReportsContext context = DefaultJasperReportsContext.getInstance();
    JRPropertiesUtil.getInstance(context).setProperty(&quot;net.sf.jasperreports.xpath.executer.factory&quot;,
        &quot;net.sf.jasperreports.engine.util.xml.JaxenXPathExecuterFactory&quot;);

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);

    JasperExportManager.exportReportToPdfFile(jasperPrint, pdfFullFilename);
  }

  private Node getInvoiceNode(File invoiceXmlFile)
      throws TransformerException, ParserConfigurationException, IOException, SAXException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    dbf.setNamespaceAware(true);
    Document xmlDocument = db.parse(invoiceXmlFile);
    xmlDocument.getDocumentElement().normalize();
    Node invoiceNode = xmlDocument.getElementsByTagName(INVOICE_TAG_NAME).item(0);
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    trans.setOutputProperty(OutputKeys.INDENT, &quot;yes&quot;);
    StringWriter writer = new StringWriter();
    trans.transform(new DOMSource(xmlDocument), new StreamResult(writer));

    return invoiceNode;
  }

  private ByteArrayInputStream getJasperReportContext(Node invoiceNode) throws TransformerException {

    return new ByteArrayInputStream(getNodeXmlString(invoiceNode).getBytes(
        StandardCharsets.UTF_8));
  }

  private Map&amp;lt;String, Object&amp;gt; getParameters() {

    return new HashMap&amp;lt;&amp;gt;() {{
      put(JRParameter.REPORT_CLASS_LOADER, cl);
    }};
  }

  protected String getNodeXmlString(Node node) throws TransformerException {

    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();
    StringWriter buffer = new StringWriter();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, &quot;yes&quot;);
    transformer.transform(new DOMSource(node), new StreamResult(buffer));

    return buffer.toString();
  }
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
	&lt;h2 style=&quot;text-align: left;&quot;&gt;4. Resources&lt;/h2&gt;
	The complete source code is available at GitHub:		
	&lt;a href=&quot;https://github.com/czetsuyatech/jasperreports-xml-datasource&quot;&gt;https://github.com/czetsuyatech/jasperreports-xml-datasource&lt;/a&gt;
&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;h2&gt;5. Development and Support&lt;/h2&gt;&lt;div&gt;Unlock the full coding experience! As a&amp;nbsp;&lt;a href=&quot;https://github.com/sponsors/czetsuya&quot; target=&quot;_blank&quot;&gt;GitHub Sponsor&lt;/a&gt;, you gain exclusive access to the code behind this article—start learning and building today!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I&#39;m available for contracting services and support. You can reach me at:&amp;nbsp;&lt;a href=&quot;https://www.czetsuyatech.com/p/consultation-services.html&quot;&gt;https://www.czetsuyatech.com/p/consultation-services.html&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/111934355531639029/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2024/06/java-how-to-create-jasper-report-from-xml-datasource.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/111934355531639029'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/111934355531639029'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2024/06/java-how-to-create-jasper-report-from-xml-datasource.html' title='How to Create a Jasper Report from an XML Datasource: A Step-by-Step Guide'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-8271294245588918610</id><published>2024-04-20T18:03:00.000+08:00</published><updated>2026-09-08T23:51:12.022+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="REST API"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring Boot"/><title type='text'>Hands-on Coding: Spring Boot Common Exceptions Handling</title><content type='html'>&lt;h2 style=&quot;text-align: left;&quot;&gt;
  &lt;br /&gt;
&lt;/h2&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Overview&lt;/h2&gt;
&lt;div&gt;
  &lt;p&gt;What is an exception?&lt;/p&gt;
  &lt;p&gt;An exception is an unexpected event, behavior, or state during software execution. In Java, it is a subclass of java.lang.Throwable.&lt;/p&gt;&lt;p&gt;In this diagram where a user withdraws money from an account the system throws an exception when the amount is less than or equal to the account balance.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivoUHEaPofu8qF1wfsSFYY9ZyA5O3VLKa9SQs37sGBr4jLk8c9jc03P6Qr_AILj0Mha4ME4oz_8Bc4GgK4c7n7xgddNw2r-Hwe5dI_njLH8VHZw77KUDduiCoPvQL1favnIVgIjQCz-APQ14Qcygg0ss6UQ_0BODKwK41eloYS4TQBldFEDpUUF5QcOmvR/s471/Basic%20Exceptions.drawio.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;471&quot; data-original-width=&quot;291&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivoUHEaPofu8qF1wfsSFYY9ZyA5O3VLKa9SQs37sGBr4jLk8c9jc03P6Qr_AILj0Mha4ME4oz_8Bc4GgK4c7n7xgddNw2r-Hwe5dI_njLH8VHZw77KUDduiCoPvQL1favnIVgIjQCz-APQ14Qcygg0ss6UQ_0BODKwK41eloYS4TQBldFEDpUUF5QcOmvR/s16000/Basic%20Exceptions.drawio.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;&lt;b&gt;Exception Class Diagram&lt;/b&gt;&lt;/p&gt;
  &lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
    &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9pBOF9PpNK_uZludnYZ9QcV3_mx505AITAT_AaQyUrh_vcwLuz0R28TmDLJD0GkLeY5VJBVL694B1A__HLNlBvTvyuANvly7ZHLboPP1Xs9mbz7aVNsKJahpbdll0GgRbxlkzHBTAHh56rQgyPaBsUYL9QuYTYTaiNe7SXWcWZBCp4ni4Ptcu8W9IJSff/s901/java_lang_exception.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;
      &lt;img border=&quot;0&quot; data-original-height=&quot;531&quot; data-original-width=&quot;901&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9pBOF9PpNK_uZludnYZ9QcV3_mx505AITAT_AaQyUrh_vcwLuz0R28TmDLJD0GkLeY5VJBVL694B1A__HLNlBvTvyuANvly7ZHLboPP1Xs9mbz7aVNsKJahpbdll0GgRbxlkzHBTAHh56rQgyPaBsUYL9QuYTYTaiNe7SXWcWZBCp4ni4Ptcu8W9IJSff/s16000/java_lang_exception.png&quot; /&gt;
    &lt;/a&gt;
  &lt;/div&gt;
  &lt;br /&gt;
  &lt;p&gt;In this diagram, we can see two types of Throwable.&amp;nbsp;&lt;/p&gt;
  &lt;p&gt;&lt;/p&gt;
  &lt;ol style=&quot;text-align: left;&quot;&gt;
    &lt;li&gt;Exception - recoverable&lt;/li&gt;
    &lt;li&gt;Error - unrecoverable&lt;/li&gt;
  &lt;/ol&gt;
  &lt;div&gt;
    &lt;b&gt;Exception VS RuntimeException&lt;/b&gt;
  &lt;/div&gt;
  &lt;p&gt;&lt;/p&gt;
  &lt;p&gt;Exception - we need to declare the thrown exception in the method signature&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;public String readFromInputStream(InputStream inputStream) throws IOException {
  StringBuilder resultStringBuilder = new StringBuilder();
  try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
    String line;
    // BufferedReader.readLine throws IOException
    while ((line = br.readLine()) != null) {
      resultStringBuilder.append(line).append(&quot;\n&quot;);
    }
  }
  return resultStringBuilder.toString();
}
  &lt;/pre&gt;
  &lt;p&gt;RuntimeException - there is no need to add the exception in the method signature&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;public void rtException() {
  int arr[] = null; // null array
  System.out.println(&quot;NullPointerException: &quot; + arr.length);
}
  &lt;/pre&gt;
  &lt;p&gt;In the calling block, we can catch the exception that was thrown.&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;try {
  readFromInputStream(is);
  rtException()
  
} catch (IOException ioe) {
  //
} catch (NullPointerException npe) {
  //  
}
  &lt;/pre&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Pre-Spring Boot 3&lt;/h2&gt;
&lt;div&gt;
  &lt;p&gt;Before Spring Boot 3 there are several approaches on how we handle the exceptions. This article is opinionated so I will just list them for reference.&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;@ExceptionHandler annotation inside a controller&lt;/li&gt;
    &lt;li&gt;Implement HandlerExceptionResolver or extend AbstractHandlerExceptionResolver&lt;/li&gt;
    &lt;li&gt;Extending ResponseStatusException&lt;/li&gt;
    &lt;li&gt;Zalando exception handling library&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Microservice&lt;/h2&gt;
&lt;div&gt;
  &lt;p&gt;Microservice is a software architecture that builds products as collections of small services. Often, these services are powered by Spring Boot, and they interact with each other via HTTP calls through REST endpoints. Before Spring Boot 3, developers often used Zalando to wrap and handle exceptions, but Spring patched this gap and now provides an elegant solution.&lt;/p&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyFJgLhLdRyxNPxPC_FnWgIXCd8x5BWf2wWPlojZM29tjt9M9UWk3SMpjXxOmoTIS7x5mHVroNbiCJ8HpLtO3dg4jPOynHxw1IVpAgLtggOVOXMj9xXf3c-Uyo0U_Xfh7vPoCKFfKq4FiycXGBOkCTaFa8JDMaBuoNyNxyYCGEkaFW6RJxP321PKR6oIZN/s539/Microservice_Architecture.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;370&quot; data-original-width=&quot;539&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyFJgLhLdRyxNPxPC_FnWgIXCd8x5BWf2wWPlojZM29tjt9M9UWk3SMpjXxOmoTIS7x5mHVroNbiCJ8HpLtO3dg4jPOynHxw1IVpAgLtggOVOXMj9xXf3c-Uyo0U_Xfh7vPoCKFfKq4FiycXGBOkCTaFa8JDMaBuoNyNxyYCGEkaFW6RJxP321PKR6oIZN/s16000/Microservice_Architecture.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;https://microservices.io/patterns/microservices.html&lt;/p&gt;&lt;p&gt;In this diagram, we can see that the API gateway calls other services. And internal services can also call each other. During these calls it’s possible to encounter exceptions. That’s why it’s important to have a common library that we can add as a dependency and customize the errors based on the domain.&lt;/p&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Commons Web Exceptions&lt;/h2&gt;
&lt;div&gt;
  &lt;p&gt;Commons Web Exceptions is a project I created in Spring Boot 3, it is built around:&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;RestControllerAdvice - for centralizing the exceptions&lt;/li&gt;
    &lt;li&gt;ResponseEntityExceptionHandler - for providing the basic exception information structure&lt;/li&gt;
    &lt;li&gt;ErrorResponseException - for initializing an exception&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
  &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1iGv2csgY8eYRx5io7zu6Ius3sSi6WlckOqXyOV031Z62swldMXGQM1cHZDs6slJmmmJkgJrWMi3r1TQl1XXNJjbiZglak1jvkyRUFlt2yWJ5q7b6uKRgSJ6495m5eJNUnGqcL7zv0H_nrNDm5jXgUlopPBLzeQHY70QdKy39tSw2kaP2O-bP9BcpRNiX/s1161/class-diagram.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;
    &lt;img border=&quot;0&quot; data-original-height=&quot;511&quot; data-original-width=&quot;1161&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1iGv2csgY8eYRx5io7zu6Ius3sSi6WlckOqXyOV031Z62swldMXGQM1cHZDs6slJmmmJkgJrWMi3r1TQl1XXNJjbiZglak1jvkyRUFlt2yWJ5q7b6uKRgSJ6495m5eJNUnGqcL7zv0H_nrNDm5jXgUlopPBLzeQHY70QdKy39tSw2kaP2O-bP9BcpRNiX/s16000/class-diagram.png&quot; /&gt;
  &lt;/a&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;p&gt;In this image, all the classes and enums inside the blue block are part of the commons web exceptions library that we can use and extend in our service.&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;b&gt;NativeWebExceptionEnumCodes&lt;/b&gt; - is an enum where native exceptions such as BAD_REQUEST, and INVALID_FORMAT are defined. In here, we can also add the class name of an exception in case we want to provide a specific code. Eg. HTTP_REQUEST_METHOD_NOT_SUPPORTED_EXCEPTION.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;AbstractWebExceptions &lt;/b&gt;- is a container for all the native and service-defined exceptions that we can register by extending this class.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;WebBaseException &lt;/b&gt;- a model class that extends ErrorResponseException. It provides the basic structure of the exception.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;AbstractWebExceptionHandler &lt;/b&gt;- which extends the ResponseEntityExceptionHandler class. It gives us default handlers for the most common exceptions such as HttpRequestMethodNotSupportedException, HttpMediaTypeNotSupportedException, and HttpMediaTypeNotAcceptableException. In this class, we override some methods that will allow us to provide custom decorations to our exceptions. For example, when handling the invalid method argument exception we can list the errors (eg notNull) in the custom property &quot;ERRORS&quot;.&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Usage&lt;/h2&gt;
&lt;div&gt;
  &lt;p&gt;In this section, I will provide some examples of how we can use this library.&lt;/p&gt;
 &lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;Initializing the Library&lt;/h3&gt;
&lt;div&gt;
  &lt;p&gt;Before we can define our custom exception handlers, we should extend the necessary base classes first.&lt;/p&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;p&gt;1. Define the service&#39;s exception codes as enum. For example, in one of the services I have in
    Hivemaster, a custom Keycloak project that provides a multi-tenant feature.&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;@Getter
public enum AppExceptionCodes {

  USER_CREATION_FAILED(&quot;A1001&quot;, &quot;Use creation failed&quot;),
  USER_EID_NOT_FOUND(&quot;A1002&quot;, &quot;User EID not found&quot;),
  USER_EMAIL_NOT_FOUND(&quot;A1003&quot;, &quot;User email not found&quot;),
  USER_PHONE_NOT_FOUND(&quot;A1004&quot;, &quot;User phone not found&quot;),
  ORGANIZATION_NOT_FOUND(&quot;A1005&quot;, &quot;Organization not found&quot;);

  private String code;
  private String message;

  AppExceptionCodes(String code, String message) {
    this.code = code;
    this.message = message;
  }

  public static Map&amp;lt;String, String&amp;gt; getMapValues() {

    Map&amp;lt;String, String&amp;gt; map = new LinkedHashMap&amp;lt;&amp;gt;();
    for (AppExceptionCodes errCode : values()) {
      map.put(errCode.getCode(), errCode.getMessage());
    }

    return map;
  }
}
  &lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;p&gt;2. Register the exception codes by extending the class AbstractWebExceptionCodes, so that they can be accessed by the commons-exception project.&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;@Component
public class WebExceptions extends AbstractWebExceptions {

  @Value(&quot;${spring.application.name}&quot;)
  private String serviceName;

  public WebExceptions() {

    super(HttpStatus.OK);

    registerExceptionMap(AppExceptionCodes.getMapValues());
  }

  @Override
  public String getServiceName() {
    return serviceName;
  }
}
  &lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;p&gt;3. Extend the WebBaseException class. So that we can handle business exceptions specific to the service. This class extends ErrorResponseException and RuntimeException which should be extended by the service exception classes. This will allow us to override the decoration that happens on the base WebBaseException class.&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;public class WebException extends WebBaseException {

  public WebException(HttpStatusCode status, String code) {
    this(status, code, null);
  }

  public WebException(HttpStatusCode status, String code, String message) {
    super(status, code, message);
  }
}
  &lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;p&gt;4. Extend the base exception handler AbstractWebExceptionHandler, which provides custom error handling and decoration for exceptions like method argument, runtime, invalid format, etc.&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;@Slf4j
@RestControllerAdvice
@RequiredArgsConstructor
public class WebExceptionHandler extends AbstractWebExceptionHandler {

  private final WebExceptions webExceptions;

  @Override
  public String getServiceName() {
    return webExceptions.getServiceName();
  }
}
  &lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;p&gt;5. And finally, import the library into your project.&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;@EnableConfigurationProperties
@SpringBootApplication
@Import({WebExceptionHandlerConfig.class})
public class Application {}
  &lt;/pre&gt;
&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;Use Cases&lt;/h3&gt;
&lt;div&gt;
  &lt;p&gt;Once all of these are done, we can now begin customizing our exceptions.&lt;/p&gt;  
&lt;/div&gt;
&lt;div&gt;
  &lt;p&gt;1. Handling native exceptions such as method invalid argument.&lt;/p&gt;
  &lt;p&gt;Here are the possible results that we may get:&lt;/p&gt;
  &lt;p&gt;Using custom assertion&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;{
    &quot;type&quot;: &quot;http://localhost:8080/errors/S404&quot;,
    &quot;title&quot;: &quot;Bad Request&quot;,
    &quot;status&quot;: 400,
    &quot;detail&quot;: &quot;Validation failed for fields (object:userV1, field:emailOrPhoneOnly, message:AssertTrue)&quot;,
    &quot;instance&quot;: &quot;/api/native-exceptions/method-arguments&quot;,
    &quot;code&quot;: &quot;S404&quot;,
    &quot;service&quot;: &quot;commons-web-exception-client&quot;,
    &quot;timestamp&quot;: &quot;2024-04-20T09:41:21.660650900Z&quot;,
    &quot;errors&quot;: [
        &quot;object:userV1, field:emailOrPhoneOnly, message:AssertTrue&quot;
    ]
}
  &lt;/pre&gt;
  &lt;p&gt;Missing field&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;{
    &quot;type&quot;: &quot;http://localhost:8080/errors/S404&quot;,
    &quot;title&quot;: &quot;Bad Request&quot;,
    &quot;status&quot;: 400,
    &quot;detail&quot;: &quot;Validation failed for fields (object:userV1, field:organization, message:NotNull)&quot;,
    &quot;instance&quot;: &quot;/api/native-exceptions/method-arguments&quot;,
    &quot;code&quot;: &quot;S404&quot;,
    &quot;service&quot;: &quot;commons-web-exception-client&quot;,
    &quot;timestamp&quot;: &quot;2024-04-20T09:43:25.418080500Z&quot;,
    &quot;errors&quot;: [
        &quot;object:userV1, field:organization, message:NotNull&quot;
    ]
}
  &lt;/pre&gt;
  &lt;p&gt;Invalid format&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;{
    &quot;type&quot;: &quot;http://localhost:8080/errors/S401&quot;,
    &quot;title&quot;: &quot;Bad Request&quot;,
    &quot;status&quot;: 400,
    &quot;detail&quot;: &quot;Invalid format for (field: birthdate, value: xxx, type: Instant)&quot;,
    &quot;instance&quot;: &quot;/api/native-exceptions/method-arguments&quot;,
    &quot;code&quot;: &quot;S401&quot;,
    &quot;service&quot;: &quot;commons-web-exception-client&quot;,
    &quot;timestamp&quot;: &quot;2024-04-20T09:43:44.065740700Z&quot;,
    &quot;errors&quot;: [
        &quot;field:birthdate, value:xxx, type:Instant&quot;
    ]
}
  &lt;/pre&gt;
  &lt;p&gt;Invalid date&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;{
    &quot;type&quot;: &quot;http://localhost:8080/errors/S404&quot;,
    &quot;title&quot;: &quot;Bad Request&quot;,
    &quot;status&quot;: 400,
    &quot;detail&quot;: &quot;Validation failed for fields (object:userV1, field:birthdate, message:Past)&quot;,
    &quot;instance&quot;: &quot;/api/native-exceptions/method-arguments&quot;,
    &quot;code&quot;: &quot;S404&quot;,
    &quot;service&quot;: &quot;commons-web-exception-client&quot;,
    &quot;timestamp&quot;: &quot;2024-04-20T09:44:28.829450600Z&quot;,
    &quot;errors&quot;: [
        &quot;object:userV1, field:birthdate, message:Past&quot;
    ]
}
  &lt;/pre&gt;
  &lt;p&gt;Missing resource&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;{
    &quot;type&quot;: &quot;http://localhost:8080/errors/S405&quot;,
    &quot;title&quot;: &quot;Not Found&quot;,
    &quot;status&quot;: 404,
    &quot;detail&quot;: &quot;No static resource native-exceptions/resource-not-found.&quot;,
    &quot;instance&quot;: &quot;/api/native-exceptions/resource-not-found&quot;,
    &quot;code&quot;: &quot;S405&quot;,
    &quot;service&quot;: &quot;commons-web-exception-client&quot;,
    &quot;timestamp&quot;: &quot;2024-04-20T09:44:44.294238700Z&quot;,
    &quot;errors&quot;: []
}
  &lt;/pre&gt;
  &lt;p&gt;Unsupported method&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;{
    &quot;type&quot;: &quot;http://localhost:8080/errors/S402&quot;,
    &quot;title&quot;: &quot;Method Not Allowed&quot;,
    &quot;status&quot;: 405,
    &quot;detail&quot;: &quot;Method &#39;PUT&#39; is not supported.&quot;,
    &quot;instance&quot;: &quot;/api/native-exceptions/method-arguments&quot;,
    &quot;code&quot;: &quot;S402&quot;,
    &quot;service&quot;: &quot;commons-web-exception-client&quot;,
    &quot;timestamp&quot;: &quot;2024-04-20T09:45:00.240704900Z&quot;,
    &quot;errors&quot;: []
}
  &lt;/pre&gt;
  &lt;p&gt;Forbidden&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;{
    &quot;type&quot;: &quot;http://localhost:8080/errors/S501&quot;,
    &quot;title&quot;: &quot;Forbidden&quot;,
    &quot;status&quot;: 403,
    &quot;instance&quot;: &quot;/api/native-exceptions/forbidden&quot;,
    &quot;code&quot;: &quot;S501&quot;,
    &quot;service&quot;: &quot;commons-web-exception-client&quot;,
    &quot;timestamp&quot;: &quot;2024-04-20T09:45:20.566494300Z&quot;,
    &quot;errors&quot;: []
}
  &lt;/pre&gt;
  &lt;p&gt;Exception defined in our service exception enum which could be business, application, or entity.&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;{
    &quot;type&quot;: &quot;http://localhost:8080/errors/A1001&quot;,
    &quot;title&quot;: &quot;Use creation failed&quot;,
    &quot;status&quot;: 400,
    &quot;instance&quot;: &quot;/api/service-exceptions/users/exceptions&quot;,
    &quot;code&quot;: &quot;A1001&quot;,
    &quot;service&quot;: &quot;commons-web-exception-client&quot;,
    &quot;timestamp&quot;: &quot;2024-04-20T09:55:49.061434900Z&quot;,
    &quot;errors&quot;: []
}
&lt;/pre&gt;
  &lt;p&gt;Custom exception&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;{
    &quot;type&quot;: &quot;http://localhost:8080/errors/B1001&quot;,
    &quot;title&quot;: &quot;Business exception&quot;,
    &quot;status&quot;: 400,
    &quot;detail&quot;: &quot;Custom exception message&quot;,
    &quot;instance&quot;: &quot;/api/service-exceptions/users/custom-exceptions&quot;,
    &quot;code&quot;: &quot;B1001&quot;,
    &quot;service&quot;: &quot;commons-web-exception-client&quot;,
    &quot;timestamp&quot;: &quot;2024-04-20T09:56:30.612646200Z&quot;,
    &quot;errors&quot;: []
}
  &lt;/pre&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;Git Repository&lt;/h2&gt;
&lt;div&gt;
  &lt;p&gt;Once again the repositories are available in GitHub.&lt;/p&gt;&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/czetsuyatech/commons-web-exception&quot;&gt;https://github.com/czetsuyatech/commons-web-exception&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/czetsuyatech/commons-web-exception-client&quot;&gt;https://github.com/czetsuyatech/commons-web-exception-client&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;h2&gt;Development and Support&lt;/h2&gt;&lt;div&gt;Unlock the full coding experience! As a&amp;nbsp;&lt;a href=&quot;https://github.com/sponsors/czetsuya&quot; target=&quot;_blank&quot;&gt;GitHub Sponsor&lt;/a&gt;, you gain exclusive access to the code behind this article—start learning and building today!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I&#39;m available for contracting services and support. You can reach me at:&amp;nbsp;&lt;a href=&quot;https://www.czetsuyatech.com/p/consultation-services.html&quot;&gt;https://www.czetsuyatech.com/p/consultation-services.html&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/8271294245588918610/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2024/04/spring-boot-common-exceptions-handling.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/8271294245588918610'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/8271294245588918610'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2024/04/spring-boot-common-exceptions-handling.html' title='Hands-on Coding: Spring Boot Common Exceptions Handling'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivoUHEaPofu8qF1wfsSFYY9ZyA5O3VLKa9SQs37sGBr4jLk8c9jc03P6Qr_AILj0Mha4ME4oz_8Bc4GgK4c7n7xgddNw2r-Hwe5dI_njLH8VHZw77KUDduiCoPvQL1favnIVgIjQCz-APQ14Qcygg0ss6UQ_0BODKwK41eloYS4TQBldFEDpUUF5QcOmvR/s72-c/Basic%20Exceptions.drawio.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-2277630675979384350</id><published>2024-04-06T17:36:00.000+08:00</published><updated>2026-09-08T23:51:12.875+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Observability"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring"/><title type='text'>Hands on Coding: Spring Logging for Beginners</title><content type='html'>&lt;h2 style=&quot;text-align: left;&quot;&gt;1. Overview&lt;/h2&gt;
&lt;div&gt;Logging is a vital aspect of programming for both beginners and experts, often underestimated but crucial for understanding application behavior. Strategic placement of logging statements aids in debugging and comprehending program execution, especially in production environments.&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;This tutorial is hands-on so I&#39;ll just paste the reference for you: &lt;a href=&quot;https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.logging&quot;&gt;https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.logging&lt;/a&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;2. Hands-On Coding&lt;/h2&gt;
&lt;div&gt;Logging is available out-of-the-box from Spring, but we can customize its level, format, etc as defined in the document above.&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;I created a Spring Boot project to capture the behavior of the logging levels that you can use as a reference as you code.&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;2.1 Common Logging Interface&lt;/h3&gt;
&lt;div&gt;
  &lt;p&gt;Let&#39;s introduce an interface that we will implement with different logging-level classes. The method logLevels will print all the logs applicable to a particular package.&lt;/p&gt;
  &lt;pre class=&quot;brush: java&quot;&gt;package com.czetsuyatech.logger;

import org.slf4j.Logger;

public interface LoggerComponent {

  default void logLevels() {
    System.out.println(getClass().getPackageName() + &quot;: &quot; + &quot;-&quot;.repeat(50));

    getLogger().info(&quot;Hello World&quot;);
    getLogger().debug(&quot;Hello World&quot;);
    getLogger().warn(&quot;Hello World&quot;);
    getLogger().trace(&quot;Hello World&quot;);
    getLogger().error(&quot;Hello World&quot;);
  }

  Logger getLogger();
}
  &lt;/pre&gt;
&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;2.2 Configure Package Names&lt;/h3&gt;
&lt;p&gt;We will define the following packages.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;debug&lt;/li&gt;
  &lt;li&gt;error&lt;/li&gt;
  &lt;li&gt;info&lt;/li&gt;
  &lt;li&gt;trace&lt;/li&gt;
  &lt;li&gt;warn&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For each package, we need to define a concrete class of interface LoggerComponent&lt;/p&gt;
&lt;p&gt;For example, in the debug we will have something like:&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;@Component
@Slf4j
public class DebugLogger implements LoggerComponent {

  @Override
  public Logger getLogger() {
    return log;
  }
}
&lt;/pre&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;2.3 Spring Boot Application Class&lt;/h3&gt;
&lt;p&gt;We will inject the instances of LoggerComponent in a list so that we can iterate through each component. We will call the logLevels method to print the log.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot; style=&quot;text-align: left;&quot;&gt;@SpringBootApplication
@RequiredArgsConstructor
public class Application {

  private final List&amp;lt;LoggerComponent&amp;gt; loggers;

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @EventListener
  public void onStartup(ContextRefreshedEvent event) {

    loggers.stream().forEach(LoggerComponent::logLevels);
  }
}
&lt;/pre&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;2.4 Spring Configuration File&lt;/h3&gt;
&lt;p&gt;And finally, we will configure the log level per package.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;logging:
  level:
    root: info
    com.czetsuyatech.logger.info: info
    com.czetsuyatech.logger.debug: debug
    com.czetsuyatech.logger.warn: warn
    com.czetsuyatech.logger.trace: trace
    com.czetsuyatech.logger.error: error
&lt;/pre&gt;
&lt;div&gt;We should have the following logs in our console which should pretty much explain the logging behavior. For example, error level only prints errors, while debug prints info, warn, and error as well.&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
  &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjO-lTx0JSAuTVKS3475fcqGAoorfbJ7vzbvI8bSRVP6W_CFWEFBYJPYPp6Vsn4V6xXN1IKIFb4s7DLVOraCoZ1LPP1jyeO2LG96wC0EW1TKvWZYrN77szmhHsj445X4rOAbSgridKxe3Sj1c7kQT0Jx1TBRM7QGSWsSdvgToDZ5RdZskWicucRT2D7r0bZ/s2751/1-spring-log-levels.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;
    &lt;img border=&quot;0&quot; data-original-height=&quot;914&quot; data-original-width=&quot;2751&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjO-lTx0JSAuTVKS3475fcqGAoorfbJ7vzbvI8bSRVP6W_CFWEFBYJPYPp6Vsn4V6xXN1IKIFb4s7DLVOraCoZ1LPP1jyeO2LG96wC0EW1TKvWZYrN77szmhHsj445X4rOAbSgridKxe3Sj1c7kQT0Jx1TBRM7QGSWsSdvgToDZ5RdZskWicucRT2D7r0bZ/s16000/1-spring-log-levels.png&quot; /&gt;
  &lt;/a&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;3. When to Use Each Logger&lt;/h2&gt;
&lt;div&gt;
  There is no standard on how and when to use the different logging levels. In my own experience, this is how I use them. Coupled with proper package structure, so I can control the logging level of a particular process.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;b&gt;Info&lt;/b&gt;&lt;/div&gt;&lt;div&gt;- Informational messages without state such as component startup and configuration settings.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Warn&lt;/b&gt;&lt;/div&gt;&lt;div&gt;- Informational state that can be ignored by the system.&amp;nbsp;&lt;/div&gt;&lt;div&gt;- Example: An unknown status of an entity.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Debug&lt;/b&gt;&lt;/div&gt;&lt;div&gt;- Informational events with state that are useful for developers. I use this in public methods.&lt;/div&gt;&lt;div&gt;- Example: Controller endpoints and service methods.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Trace&lt;/b&gt;&lt;/div&gt;&lt;div&gt;- Informational events with state that are useful for developers. I use this in private methods.&lt;/div&gt;&lt;div&gt;- Example: Private methods in a service.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Error&lt;/b&gt;&lt;/div&gt;&lt;div&gt;- Event that causes the application to get into an error state. Recoverable.&lt;/div&gt;&lt;div&gt;- Example: Unable to communicate to an external service. Having a mechanism to retry sending the message.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Fatal&lt;/b&gt;&lt;/div&gt;&lt;div&gt;- Event that causes the application to get into an error state. Unrecoverable.&lt;/div&gt;&lt;div&gt;- Example: Database instance going down.&lt;/div&gt;&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;4. Code Repository&lt;/h2&gt;
&lt;div&gt;The code is available at&amp;nbsp; &lt;a href=&quot;https://github.com/czetsuya/lab-spring-logging&quot;&gt;https://github.com/czetsuya/lab-spring-logging&lt;/a&gt;. &lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/2277630675979384350/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2024/04/spring-logging-for-beginner.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/2277630675979384350'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/2277630675979384350'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2024/04/spring-logging-for-beginner.html' title='Hands on Coding: Spring Logging for Beginners'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjO-lTx0JSAuTVKS3475fcqGAoorfbJ7vzbvI8bSRVP6W_CFWEFBYJPYPp6Vsn4V6xXN1IKIFb4s7DLVOraCoZ1LPP1jyeO2LG96wC0EW1TKvWZYrN77szmhHsj445X4rOAbSgridKxe3Sj1c7kQT0Jx1TBRM7QGSWsSdvgToDZ5RdZskWicucRT2D7r0bZ/s72-c/1-spring-log-levels.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6581802047354010081.post-5258970771438068685</id><published>2024-04-06T10:53:00.000+08:00</published><updated>2026-09-08T23:51:13.859+08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Grafana"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Observability"/><category scheme="http://www.blogger.com/atom/ns#" term="Prometheus"/><category scheme="http://www.blogger.com/atom/ns#" term="Spring"/><title type='text'>Hands on Coding: Spring Metrics with Prometheus for Beginner</title><content type='html'>&lt;h2 style=&quot;text-align: left;&quot;&gt;1. Overview&lt;/h2&gt;
&lt;p&gt;Welcome to our hands-on guide where we&#39;ll delve into the world of monitoring Spring Boot applications using Prometheus and Grafana. In today&#39;s fast-paced digital landscape, ensuring the smooth operation and performance of our applications is paramount. With the powerful combination of Prometheus and Grafana, we can gather insightful metrics and visualize them in a meaningful way, allowing us to monitor and optimize our Spring Boot applications effectively.&lt;/p&gt;
&lt;p&gt;In this guide, we&#39;ll walk through the process step-by-step, covering everything you need to know to set up basic monitoring for your Spring Boot 3 application with Docker.&lt;/p&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;2. Spring Boot 3 Application&lt;/h2&gt;
&lt;p&gt;The Spring Boot project contains the basic configuration needed for demonstration.&lt;/p&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;2.1 Dependencies&lt;/h3&gt;
&lt;div&gt;
  &lt;p&gt;We need the actuator to expose the Spring metrics and use the micrometer registry to convert it to Prometheus.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;&amp;lt;dependency&amp;gt;
  &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
  &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
  &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
  &amp;lt;artifactId&amp;gt;spring-boot-starter-actuator&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
  &amp;lt;groupId&amp;gt;io.micrometer&amp;lt;/groupId&amp;gt;
  &amp;lt;artifactId&amp;gt;micrometer-registry-prometheus&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;2.2 Configuration&lt;/h3&gt;
&lt;div&gt;
  &lt;p&gt;In this section, we allow health and Prometheus endpoints from the actuator. By default, the actuator endpoint is/actuator, which lists all the enabled endpoints.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;logging:
  level:
    root: info

server:
  port: 8080

spring:
  application:
    name: lab-spring-prometheus

management:
  endpoints:
    web:
      exposure:
        include: health, prometheus
  endpoint:
    health:
      show-details: always
  prometheus:
    metrics:
      export:
        enabled: true
&lt;/pre&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;3. Prometheus&lt;/h2&gt;
&lt;div&gt;
  &lt;p&gt;In Prometheus configuration, we need to specify the metrics path and set some labels that we will need in our Grafana dashboard later.&lt;/p&gt;
  &lt;p&gt;Note: If you want to scrape data from a Spring Boot app that runs on your IDE, you must change the targets to host.docker.internal. Don&#39;t forget to update the extra_hosts in the docker-compose file as well.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;scrape_configs:
  - job_name: &#39;lab-spring-prometheus&#39;
    metrics_path: &#39;/actuator/prometheus&#39;
    scrape_interval: 5s
    static_configs:
      #      - targets: [ &#39;host.docker.internal:8080&#39; ]
      - targets: [ &#39;spring-app:8080&#39; ]
        labels:
          namespace: czetsuyatech
          application: &#39;lab-spring-prometheus&#39;
&lt;/pre&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;4. Grafana&lt;/h2&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;4.1 Spring Boot Statistics&lt;/h3&gt;
&lt;p&gt;If you want a Spring Boot statistics dashboard out of the box you may check the following plugin in Grafana&#39;s marketplace. Or simply, import them.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;19004 -&amp;nbsp;https://grafana.com/grafana/dashboards/19004-spring-boot-statistics/&lt;/li&gt;
  &lt;li&gt;11378 -&amp;nbsp;https://grafana.com/grafana/dashboards/11378-justai-system-monitor/&lt;/li&gt;
&lt;/ul&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSDCqMC2stIM4t-rpwXKZ9hjyKJQmaD4qu1o3bJYDwqd6-zoi1Q65l7d07RmTAqEQmvMDGiLE0f_AfBnV1UAPEej1qMMrE2khaz_dzgVkf072N3QbC3RSvA1Zk4E2sv5oPl9hcAZBCNKyU_nWO1YL162KXjGu_jxK6eZDa1r8Gs_BvCJeZ9bgK5-FSQPHN/s3709/1-grafana-spring-dashboard.png&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1916&quot; data-original-width=&quot;3709&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSDCqMC2stIM4t-rpwXKZ9hjyKJQmaD4qu1o3bJYDwqd6-zoi1Q65l7d07RmTAqEQmvMDGiLE0f_AfBnV1UAPEej1qMMrE2khaz_dzgVkf072N3QbC3RSvA1Zk4E2sv5oPl9hcAZBCNKyU_nWO1YL162KXjGu_jxK6eZDa1r8Gs_BvCJeZ9bgK5-FSQPHN/s16000/1-grafana-spring-dashboard.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
  &lt;p&gt;For Grafana, we can start with a basic data source configuration. This points to the Prometheus URL we define in docker-compose. Note that you can also do this in the Grafana user interface.&lt;/p&gt;
  &lt;p&gt;Grafana&#39;s default username and password is &quot;admin&quot;.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;apiVersion: 1
datasources:
  - name: Lab Prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true
&lt;/pre&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;5. Docker Configuration&lt;/h2&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;5.1 Dockerfile&lt;/h3&gt;
&lt;div&gt;
  &lt;p&gt;We are loading the Spring Boot jar to our docker container. Make sure to build the project first in your IDE, so that the jar is generated.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;FROM eclipse-temurin:17-jdk-alpine
VOLUME /tmp
COPY ./target/*.jar app.jar
ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]
&lt;/pre&gt;
&lt;/div&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;5.2 Docker Compose File&lt;/h3&gt;
&lt;div&gt;
  &lt;p&gt;This configuration runs our Spring boot app, Prometheus, and Grafana in docker with a common network. Thus, each service can access each other using the service name. If you want to access a non-docker component, let&#39;s say the Spring Boot app, you need to do the necessary configuration with the host.&lt;/p&gt;
&lt;pre class=&quot;brush: java&quot;&gt;version: &#39;3.8&#39;

networks:
  backend:

services:
  spring-app:
    build:
      dockerfile: docker/Dockerfile
      context: ../
    ports:
      - &quot;8080:8080&quot;
    networks:
      - backend

  prometheus:
    image: prom/prometheus:v2.51.1
    container_name: lab-prometheus
    restart: no
    ports:
      - &quot;9090:9090&quot;
    volumes:
      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
    networks:
      - backend
#    extra_hosts:
#      - &#39;host.docker.internal:host-gateway&#39;

  grafana:
    image: grafana/grafana
    container_name: lab-grafana
    restart: no
    ports:
      - &quot;3000:3000&quot;
    volumes:
      - ./grafana/datasources:/etc/grafana/provisioning/datasources
    networks:
      - backend
&lt;/pre&gt;
  &lt;p&gt;
  To run, simply go to docker folder of this project and execute:

&lt;i&gt;docker-compose up --build
  &lt;/i&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;h2 style=&quot;text-align: left;&quot;&gt;6. GitHub Repository&lt;/h2&gt;
&lt;p&gt;The code is available in GitHub including the docker-compose file.&lt;/p&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;&lt;li&gt;&lt;a href=&quot;https://github.com/czetsuyatech/lab-spring-prometheus&quot;&gt;https://github.com/czetsuyatech/lab-spring-prometheus&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;h2&gt;7. Development and Support&lt;/h2&gt;&lt;div&gt;Unlock the full coding experience! As a&amp;nbsp;&lt;a href=&quot;https://github.com/sponsors/czetsuya&quot; target=&quot;_blank&quot;&gt;GitHub Sponsor&lt;/a&gt;, you gain exclusive access to the code behind this article—start learning and building today!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I&#39;m available for contracting services and support. You can reach me at:&amp;nbsp;&lt;a href=&quot;https://www.czetsuyatech.com/p/consultation-services.html&quot;&gt;https://www.czetsuyatech.com/p/consultation-services.html&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='https://www.czetsuyatech.com/feeds/5258970771438068685/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.czetsuyatech.com/2024/04/spring-metrics-with-prometheus-grafana-for-beginner.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/5258970771438068685'/><link rel='self' type='application/atom+xml' href='https://www.blogger.com/feeds/6581802047354010081/posts/default/5258970771438068685'/><link rel='alternate' type='text/html' href='https://www.czetsuyatech.com/2024/04/spring-metrics-with-prometheus-grafana-for-beginner.html' title='Hands on Coding: Spring Metrics with Prometheus for Beginner'/><author><name>czetsuya</name><uri>http://www.blogger.com/profile/05992265396469184599</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSDCqMC2stIM4t-rpwXKZ9hjyKJQmaD4qu1o3bJYDwqd6-zoi1Q65l7d07RmTAqEQmvMDGiLE0f_AfBnV1UAPEej1qMMrE2khaz_dzgVkf072N3QbC3RSvA1Zk4E2sv5oPl9hcAZBCNKyU_nWO1YL162KXjGu_jxK6eZDa1r8Gs_BvCJeZ9bgK5-FSQPHN/s72-c/1-grafana-spring-dashboard.png" height="72" width="72"/><thr:total>0</thr:total></entry></feed>