<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by czetsuya on Medium]]></title>
        <description><![CDATA[Stories by czetsuya on Medium]]></description>
        <link>https://medium.com/@czetsuya?source=rss-f795956d2899------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l2nReUhTeL3iirD69bSvjw.jpeg</url>
            <title>Stories by czetsuya on Medium</title>
            <link>https://medium.com/@czetsuya?source=rss-f795956d2899------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 01:37:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@czetsuya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Specification Pattern in Spring Data JPA: Building Composable Queries That Scale]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://czetsuya.medium.com/specification-pattern-spring-data-jpa-composable-queries-a9e9f9f21b5c?source=rss-f795956d2899------2"><img src="https://cdn-images-1.medium.com/max/1672/1*BXRNF_uGnxU9-WttWHNKJQ.png" width="1672"></a></p><p class="medium-feed-snippet">Spring Data JPA makes writing database queries surprisingly easy.</p><p class="medium-feed-link"><a href="https://czetsuya.medium.com/specification-pattern-spring-data-jpa-composable-queries-a9e9f9f21b5c?source=rss-f795956d2899------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://czetsuya.medium.com/specification-pattern-spring-data-jpa-composable-queries-a9e9f9f21b5c?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9e9f9f21b5c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 00:19:31 GMT</pubDate>
            <atom:updated>2026-11-17T00:19:31.314Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Dynamic Queries in Spring Data JPA Without Repository Method Explosion]]></title>
            <link>https://czetsuya.medium.com/dynamic-queries-spring-data-jpa-without-repository-method-explosion-d2cfc2777480?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2cfc2777480</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 05:43:12 GMT</pubDate>
            <atom:updated>2026-11-08T05:43:12.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jKtPUXaA8vdNz4J-7EoZg.png" /><figcaption>NERV Persistence cover illustrating dynamic queries using composable JPA Specifications, optional filters, and SQL query generation.</figcaption></figure><p><em>Why composable queries are a better foundation for evolving search APIs.</em></p><p>Spring Data JPA makes persistence remarkably easy to get started with.</p><p>Create an entity. Extend JpaRepository. Declare a few methods. And suddenly, you have a working persistence layer without writing much SQL.</p><p>For many applications, that simplicity is exactly what we need.</p><p>But after working on enterprise applications for years, I’ve noticed a recurring pattern: <strong>repository methods often start multiplying when the business introduces flexible search requirements.</strong></p><p>What begins as a clean repository gradually becomes a collection of methods that differ only in which filters they apply.</p><p>The problem isn’t Spring Data JPA.</p><p>The problem is that we’re trying to represent a dynamic search problem using fixed query definitions.</p><p>And those are two very different things.</p><h3>When a Simple Repository Stops Being Simple</h3><p>Imagine we’re building a customer management application.</p><p>Initially, the requirements are straightforward. We need to find customers by status, country, or customer type.</p><p>Spring Data JPA makes this easy:</p><pre>List&lt;Customer&gt; findByStatus(CustomerStatus status);<br>List&lt;Customer&gt; findByCountry(String country);<br>List&lt;Customer&gt; findByType(CustomerType type);</pre><p>There’s nothing wrong with these methods.</p><p>They’re readable, explicit, and communicate exactly what they do.</p><p>Then the application evolves.</p><p>The product team introduces an advanced customer search screen.</p><p>Users should be able to filter customers by status, country, type, registration date, account manager, and several other attributes.</p><p>More importantly, every filter is optional.</p><p>A user might search by country alone. Another might combine status and registration date. Someone else might apply five filters simultaneously.</p><p>Suddenly, we’re facing a different problem.</p><p>With six independent optional filters, there are potentially 64 combinations. With eight, there are 256.</p><p>Of course, we wouldn’t necessarily implement all those combinations as individual repository methods.</p><p>But that’s precisely the point.</p><p><strong>The number of possible queries grows much faster than the number of actual business operations.</strong></p><p>The application still has one business capability: search customers.</p><p>What changes is the combination of conditions applied to that search.</p><p>Our persistence design should reflect that distinction.</p><h3>The Temptation to Write One Giant Query</h3><p>One common solution is to replace all those derived repository methods with a single JPQL query.</p><pre>@Query(&quot;&quot;&quot;<br>    SELECT c<br>    FROM Customer c<br>    WHERE (:status IS NULL OR c.status = :status)<br>      AND (:country IS NULL OR c.country = :country)<br>      AND (:type IS NULL OR c.type = :type)<br>    &quot;&quot;&quot;)<br>List&lt;Customer&gt; search(<br>    CustomerStatus status,<br>    String country,<br>    CustomerType type<br>);</pre><p>At first glance, this looks like an improvement.</p><p>We now have one method instead of several.</p><p>And for a small number of filters, this can be perfectly reasonable.</p><p>But as the search requirements grow, the query grows with them.</p><p>Additional conditions appear. Date ranges are introduced. Relationships need to be joined. Different operators become necessary.</p><p>Eventually, the query becomes a large expression where every optional parameter influences the resulting SQL.</p><p>There’s also a performance consideration.</p><p>Conditions such as (:status IS NULL OR c.status = :status) may affect how efficiently a database can use indexes, depending on the database engine, parameter values, and execution plan.</p><p>That doesn’t make nullable-parameter JPQL inherently bad.</p><p>It simply means we’ve reduced the number of repository methods without necessarily solving the underlying design problem.</p><p><strong>We’ve consolidated the queries, but we haven’t made the conditions independently composable.</strong></p><h3>Think in Predicates, Not Repository Methods</h3><p>This is where I believe the mental model needs to change.</p><p>Instead of asking:</p><p><em>Which repository method should handle this combination of filters?</em></p><p>We should ask:</p><p><em>Which conditions should be included in this query?</em></p><p>A customer search can be described as a collection of independent predicates:</p><ul><li>Customer has a particular status.</li><li>Customer belongs to a particular country.</li><li>Customer has a particular type.</li><li>Customer registered after a specified date.</li><li>Customer registered before another date.</li></ul><p>Each condition has meaning on its own.</p><p>And each condition can be combined with others.</p><p>Spring Data JPA already provides an abstraction for this: <strong>Specifications</strong>.</p><p>A Specification&lt;T&gt; represents a predicate that can be applied to a JPA query.</p><p>For example:</p><pre>public static Specification&lt;Customer&gt; hasStatus(<br>        CustomerStatus status) {<br>    return (root, query, cb) -&gt;<br>        cb.equal(root.get(&quot;status&quot;), status);<br>}</pre><p>We can define another condition:</p><pre>public static Specification&lt;Customer&gt; hasCountry(<br>        String country) {<br>    return (root, query, cb) -&gt;<br>        cb.equal(root.get(&quot;country&quot;), country);<br>}</pre><p>Neither Specification needs to know anything about the other.</p><p>That’s what makes the approach useful.</p><p>We can compose them:</p><pre>Specification&lt;Customer&gt; specification =<br>    Specification.allOf(<br>        hasStatus(CustomerStatus.ACTIVE),<br>        hasCountry(&quot;PH&quot;)<br>    );</pre><p>And execute them through a repository extending JpaSpecificationExecutor.</p><pre>public interface CustomerRepository<br>        extends JpaRepository&lt;Customer, Long&gt;,<br>                JpaSpecificationExecutor&lt;Customer&gt; {<br>}</pre><p>The repository doesn’t need a new method every time another combination becomes necessary.</p><p>It simply executes the query represented by the composed Specification.</p><h3>Optional Filters Become a Composition Problem</h3><p>Let’s take the idea one step further.</p><p>Suppose our search API receives a criteria object:</p><pre>public record CustomerSearchCriteria(<br>    CustomerStatus status,<br>    String country,<br>    CustomerType type<br>) {<br>}</pre><p>Rather than creating a different repository method for each combination, we can assemble the relevant predicates.</p><pre>public static Specification&lt;Customer&gt; from(<br>        CustomerSearchCriteria criteria) {<br>    List&lt;Specification&lt;Customer&gt;&gt; filters =<br>        new ArrayList&lt;&gt;();<br>    if (criteria.status() != null) {<br>        filters.add(hasStatus(criteria.status()));<br>    }<br>    if (criteria.country() != null<br>            &amp;&amp; !criteria.country().isBlank()) {<br>        filters.add(hasCountry(criteria.country()));<br>    }<br>    if (criteria.type() != null) {<br>        filters.add(hasType(criteria.type()));<br>    }<br>    return Specification.allOf(filters);<br>}</pre><p>The code isn’t particularly complicated.</p><p>But the architectural difference is significant.</p><p>Adding a new filter no longer requires us to consider every existing filter combination.</p><p>We define a new predicate and decide when it should participate in the query.</p><p>The existing predicates remain unchanged.</p><p>This is the kind of extensibility that matters in long-lived applications.</p><p>Not because it eliminates a few lines of code, but because it reduces the number of places affected by a new requirement.</p><h3>Pagination Doesn’t Need to Complicate the Design</h3><p>A production search API almost always needs pagination and sorting.</p><p>Fortunately, Specifications integrate naturally with Spring Data JPA’s pagination support.</p><pre>Page&lt;Customer&gt; customers =<br>    customerRepository.findAll(<br>        specification,<br>        pageable<br>    );</pre><p>That’s one of the things I appreciate about this approach.</p><p>We don’t have to abandon Spring Data JPA’s existing capabilities just because our queries have become more flexible.</p><p>The same repository infrastructure continues to support filtering, pagination, and sorting.</p><p>Of course, a production API still needs sensible limits.</p><p>Unbounded page sizes, arbitrary sort properties, and unstable ordering can create problems regardless of how elegantly the query predicates are composed.</p><p>The abstraction makes queries easier to build.</p><p>It doesn’t remove our responsibility to design the API properly.</p><h3>Reusable Infrastructure Shouldn’t Erase Domain Meaning</h3><p>There’s another architectural question that appears once Specifications become common across multiple services.</p><p>If we’re implementing dynamic search for customers, payments, invoices, subscriptions, and orders, should every service build its own query infrastructure?</p><p>My answer is: <strong>reuse the mechanics, but preserve the domain semantics.</strong></p><p>For example, a customer service might need a predicate called:</p><pre>hasActiveSubscription()</pre><p>A payment service might need:</p><pre>hasUnsettledBalance()</pre><p>These names express business meaning.</p><p>They’re much easier to understand than a generic collection of string-based field names and operators.</p><p>At the same time, both services may need the same underlying technical capabilities: optional filters, operator handling, pagination conventions, sorting validation, and reusable query construction.</p><p>Those are reasonable candidates for shared infrastructure.</p><p>The mistake would be building a universal abstraction so generic that developers can no longer understand what the query actually means.</p><p>I’ve seen this tendency in framework design: we try to eliminate duplication and end up introducing an abstraction that hides too much.</p><p>A good persistence foundation should make common operations easier without turning every query into a configuration puzzle.</p><h3>Where NERV Persistence Fits</h3><p>This separation between reusable infrastructure and domain-specific behavior is part of the thinking behind <strong>NERV Persistence</strong>.</p><p>Spring Data JPA already gives us excellent tools: repositories, Specifications, Criteria API integration, projections, pagination, and sorting.</p><p>I don’t believe a reusable persistence library should attempt to replace those tools.</p><p>Instead, it should complement them.</p><p>The goal is to reduce repeated infrastructure work while keeping application-specific queries explicit and understandable.</p><p>Conceptually, the design looks like this:</p><pre>API / Search Request<br>        |<br>        v<br>Domain Search Criteria<br>        |<br>        v<br>Composable Query Rules<br>        |<br>        v<br>Reusable Persistence Infrastructure<br>        |<br>        v<br>Spring Data JPA / Hibernate<br>        |<br>        v<br>Database</pre><p>This is an architectural illustration, rather than a representation of specific library classes.</p><p>The important boundary is between what belongs to the business domain and what can genuinely be shared across applications.</p><p>For developers interested in the project, NERV Persistence is available on GitHub:</p><p><a href="https://github.com/czetsuyatech/nerv-persistence">https://github.com/czetsuyatech/nerv-persistence</a></p><h3>Composable Doesn’t Automatically Mean Efficient</h3><p>One important lesson is that better Java abstractions don’t guarantee better SQL.</p><p>A Specification can be beautifully composed and still generate an expensive database query.</p><p>Consider filtering customers by status and country while sorting by registration date.</p><p>The performance of that query depends on several factors: table size, data distribution, indexing strategy, and the database’s execution plan.</p><p>None of those concerns disappear because we used Specifications.</p><p>Relationships introduce another layer of complexity.</p><p>A join against a collection can produce multiple rows for the same root entity. That can affect result cardinality, pagination, and count queries.</p><p>For existence checks, an EXISTS subquery may be more appropriate than a direct join.</p><p>Pagination also deserves attention.</p><p>A Page&lt;T&gt; generally needs a total count of matching records. For complicated queries, that count can become surprisingly expensive.</p><p>And dynamic filters should never mean unrestricted access to every entity property.</p><p>A public API still needs explicit rules about which fields can be searched, which operators are allowed, and how much data a client can request.</p><p><strong>Specifications solve query composition. They don’t solve query optimization, authorization, or API governance.</strong></p><p>Those remain separate engineering responsibilities.</p><h3>Not Every Query Needs a Specification</h3><p>I also think it’s important not to turn Specifications into a rule that every repository must follow.</p><p>If a query is simple and fixed, a derived repository method is often the clearest solution.</p><pre>Optional&lt;Customer&gt; findByExternalId(String externalId);</pre><p>There’s no benefit in replacing that with a complicated query abstraction simply for consistency.</p><p>Similarly, complex reporting queries involving aggregation, window functions, or database-specific capabilities may be better expressed using explicit SQL.</p><p>The goal isn’t to eliminate repository methods or SQL.</p><p>It’s to choose an abstraction that matches the nature of the problem.</p><p>Fixed queries are naturally represented by fixed methods.</p><p>Dynamic queries benefit from composable predicates.</p><p>Specialized queries may need specialized implementations.</p><p>Good architecture leaves room for all three.</p><h3>The Real Goal Is Making Change Easier</h3><p>When evaluating persistence abstractions, it’s tempting to focus on how much code they remove.</p><p>But I’ve learned that code reduction alone is a poor measure of architectural quality.</p><p>A framework can reduce hundreds of lines while making the application harder to debug.</p><p>A generic query builder can eliminate repository methods while making business rules difficult to discover.</p><p>A reusable library can standardize infrastructure while introducing unnecessary coupling between services.</p><p>What matters more is how the design behaves when requirements change.</p><p>Can we add a filter without modifying unrelated queries?</p><p>Can another developer understand which conditions are being applied?</p><p>Can we test those conditions independently?</p><p>Can we inspect the generated SQL when performance becomes a problem?</p><p>Can we reuse infrastructure without forcing unrelated domains into the same model?</p><p>Those are the questions worth optimizing for.</p><h3>Final Thoughts</h3><p>Spring Data JPA’s derived repository methods are an excellent feature.</p><p>They make simple database operations concise and readable.</p><p>But as soon as search requirements become optional and combinatorial, we’re dealing with a different problem.</p><p>We’re no longer defining a handful of fixed queries.</p><p>We’re composing queries from independently meaningful conditions.</p><p>Specifications provide a practical way to model that behavior while continuing to use Spring Data JPA’s existing repository infrastructure.</p><p>And when the same technical patterns appear across multiple applications, reusable infrastructure can help reduce duplication without hiding the underlying framework.</p><p>That’s the principle behind the approach we’re exploring with NERV Persistence.</p><p><strong>The best persistence abstraction isn’t the one that produces the fewest repository methods. It’s the one that lets the next requirement arrive without making the existing system harder to understand.</strong></p><p><em>This article is part of the NERV Persistence series, where I explore practical persistence architecture and reusable infrastructure for Java and Spring Boot applications.</em></p><p><strong>NERV Persistence on GitHub:</strong><br><a href="https://github.com/czetsuyatech/nerv-persistence">https://github.com/czetsuyatech/nerv-persistence</a></p><p><strong>Original article on CzetsuyaTech:</strong><br><a href="https://www.czetsuyatech.com/2026/10/dynamic-queries-spring-data-jpa.html">https://www.czetsuyatech.com/2026/10/dynamic-queries-spring-data-jpa.html</a></p><p><em>How do you approach dynamic search in your applications? Do you prefer Spring Data JPA Specifications, QueryDSL, Criteria API, or explicit JPQL?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2cfc2777480" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logs Aren’t an Audit Trail: Debugging Business Data in Production]]></title>
            <link>https://czetsuya.medium.com/logs-arent-an-audit-trail-debugging-business-data-in-production-e6f4d3ccb5a2?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6f4d3ccb5a2</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 01:24:26 GMT</pubDate>
            <atom:updated>2026-11-02T01:24:26.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8ZKnRVdBKHqE6e7zJugFw.png" /><figcaption>Application logs contrasted with a structured audit trail showing account state transitions and revision history.</figcaption></figure><h3>Logs Aren’t an Audit Trail: Debugging Business Data in Production</h3><p><em>Why application logs can tell you an operation succeeded — even when the database transaction was rolled back.</em></p><p>A production support ticket arrives.</p><p>A customer reports that their account was unexpectedly deactivated.</p><p>You open the application, check the database, and confirm that the account is indeed DEACTIVATED.</p><p>Then comes the question that every backend engineer eventually encounters:</p><p><strong>“Why did this happen?”</strong></p><p>You open your observability platform and search for the account ID.</p><p>You find a log message:</p><pre>2026-10-12T09:42:18Z INFO AccountService<br>Account 1042 updated successfully</pre><p>At least something happened.</p><p>But what exactly?</p><p>Was the account previously active? Who initiated the change? Was it an administrator, a scheduled job, or another service?</p><p>And was this the only change, or had the account passed through several states before becoming deactivated?</p><p>The log message doesn’t tell us.</p><p>We could add more logging, of course.</p><p>But that raises a question I’ve encountered repeatedly while building and supporting enterprise applications:</p><p><strong>Should application logs be responsible for preserving the history of our business data?</strong></p><p>I don’t think they should.</p><p>Not because logs are unreliable or unnecessary, but because they were designed to solve a different problem.</p><h3>A Log Message Is Not Proof That Something Happened to the Database</h3><p>Consider a Spring Boot application that deactivates an account.</p><p>The service retrieves the account, changes its status, writes a log message, and performs some additional validation.</p><p>Conceptually:</p><pre>@Transactional<br>public void deactivateAccount(Long accountId) {<br>    Account account = findAccount(accountId);</pre><pre>    account.setStatus(DEACTIVATED);</pre><pre>    log.info(&quot;Account {} deactivated&quot;, accountId);</pre><pre>    validateAdditionalRules(account);<br>}</pre><p>Now imagine that validateAdditionalRules() throws an unchecked exception.</p><p>Spring’s transaction management normally rolls back the database transaction.</p><p>The account remains ACTIVE.</p><p>But the log message has already been written.</p><p>We now have two different representations of what happened:</p><p><strong>Application log</strong></p><pre>09:42:18 Account 1042 deactivated</pre><p><strong>Database</strong></p><pre>Account #1042<br>status = ACTIVE</pre><p>The log isn’t necessarily lying.</p><p>It accurately tells us that execution reached the logging statement.</p><p>But it doesn’t establish that the database transaction committed.</p><p>This is an important distinction.</p><p><strong>An operation being executed is not the same as a business-state change being committed.</strong></p><p>And during production support, confusing those two things can send an investigation in the wrong direction.</p><h3>Why Not Just Log After the Transaction Commits?</h3><p>That’s a reasonable solution to consider.</p><p>Instead of writing the log message inside the transaction, we could write it after a successful commit.</p><p>Spring provides transaction synchronization mechanisms that allow applications to perform work after commit.</p><p>This prevents us from announcing success before the database transaction has completed.</p><p>But it doesn’t solve the entire problem.</p><p>Consider another failure scenario.</p><p>The database transaction commits successfully.</p><p>Before the application can send the log message to the logging platform, the process crashes.</p><p>Now the database contains the change, but the corresponding log message may never arrive.</p><p>We have reversed the original problem.</p><p>Previously, the log existed without the committed database change.</p><p>Now the database change exists without the log.</p><p>This is not a criticism of Spring or any logging framework.</p><p>It’s a consequence of coordinating two separate systems without a shared atomic transaction.</p><p>If preserving the history of business-data changes matters, we need to think carefully about where that history is stored and how it participates in the original transaction.</p><h3>An Audit Trail Has a Different Responsibility</h3><p>Application logs primarily describe execution.</p><p>They tell us which operations ran, which exceptions occurred, and how the application behaved.</p><p>An audit trail has a different purpose.</p><p>It preserves historical information about changes to business entities.</p><p>Consider an account that moves through several states:</p><pre>ACTIVE<br>   ↓<br>SUSPENDED<br>   ↓<br>ACTIVE<br>   ↓<br>DEACTIVATED</pre><p>A normal database query might return:</p><pre>Account #1042<br>status = DEACTIVATED</pre><p>That is the current state.</p><p>But it tells us nothing about the intermediate transitions.</p><p>A useful audit history could show:</p><pre>Oct 12, 09:41<br>ACTIVE → SUSPENDED</pre><pre>Oct 15, 14:20<br>SUSPENDED → ACTIVE</pre><pre>Oct 21, 08:10<br>ACTIVE → DEACTIVATED</pre><p>Now we have a timeline.</p><p>We can see that the account was suspended, reactivated, and eventually deactivated.</p><p>That changes how we investigate the incident.</p><p>Instead of searching through thousands of log entries hoping to discover a relevant event, we can begin with a specific transition and timestamp.</p><p><strong>The audit trail tells us where to look. Logs and traces help us investigate what happened around that moment.</strong></p><p>Neither replaces the other.</p><h3>The Transaction Boundary Matters</h3><p>One reason I appreciate Hibernate Envers is its integration with Hibernate’s persistence lifecycle.</p><p>When an audited entity changes through Hibernate, Envers can persist revision information within the same database transaction as the entity modification.</p><p>Conceptually:</p><pre>BEGIN TRANSACTION<br>    |<br>    +-- Update business entity<br>    |<br>    +-- Persist audit revision<br>    |<br>COMMIT</pre><p>If the transaction rolls back, the associated audit revision rolls back as well.</p><p>This provides a valuable consistency property.</p><p>The entity change and its audit history share the same transaction outcome.</p><p>Of course, there are limitations.</p><p>Envers doesn’t automatically capture arbitrary direct SQL updates outside Hibernate.</p><p>It doesn’t automatically know which user initiated a change unless that information is explicitly captured.</p><p>And it cannot infer the business reason behind every state transition.</p><p>But for audited Hibernate-managed entities, it provides a strong foundation for recording revision history.</p><p>The distinction matters because <strong>an audit trail should describe committed business-data changes, not merely attempted operations.</strong></p><h3>Logs and Audit History Also Have Different Lifecycles</h3><p>There’s another problem that becomes obvious when supporting older production incidents.</p><p>Logs don’t necessarily live forever.</p><p>Most organizations establish retention policies for application logs based on operational needs, storage costs, and security considerations.</p><p>That’s reasonable.</p><p>A high-traffic application may generate millions of diagnostic events every day.</p><p>Keeping all of them indefinitely would be expensive and often unnecessary.</p><p>But consider a support request:</p><blockquote><em>“Can you tell me who changed this account three months ago?”</em></blockquote><p>The relevant application logs may no longer exist.</p><p>That doesn’t necessarily mean the business no longer needs the information.</p><p>Business-data history may have different retention requirements.</p><p>It might need to remain available for operational investigations, internal reviews, or regulatory obligations.</p><p>This doesn’t mean audit records should be stored forever either. Retention, privacy, access control, and deletion requirements still apply.</p><p>The point is that <strong>diagnostic telemetry and business history should not automatically share the same retention policy.</strong></p><p>They serve different purposes.</p><h3>Knowing What Changed Is Not the Same as Knowing Why</h3><p>This is another important limitation of audit history.</p><p>Suppose we retrieve the following revision:</p><pre>Account #1042</pre><pre>status:<br>ACTIVE → SUSPENDED</pre><pre>changedBy:<br>account-service</pre><pre>changedAt:<br>2026-10-12T09:41:13Z</pre><p>We know what changed.</p><p>We know when it changed.</p><p>And we know which recorded service was associated with the revision.</p><p>But do we know why?</p><p>Not necessarily.</p><p>Was the account suspended because of a customer request?</p><p>An administrative action?</p><p>An automated business rule?</p><p>An external integration?</p><p>The audit trail cannot reliably answer those questions unless the application captured the relevant context.</p><p>For example:</p><pre>reasonCode:<br>CUSTOMER_REQUEST</pre><pre>correlationId:<br>c5d8f1e2-7a40-4d9c-8b1e-9f1c02d5a611</pre><p>A reason code can preserve explicitly recorded business intent.</p><p>A correlation identifier can help connect the revision to related logs and distributed traces, assuming that identifier was propagated consistently.</p><p>This is where auditability and observability become particularly valuable together.</p><p>The audit trail establishes the recorded change.</p><p>The logs and traces provide execution context.</p><p>The business metadata helps explain the decision.</p><p><strong>A good production system should preserve evidence, not invent explanations after the fact.</strong></p><h3>Distributed Systems Make This Even More Interesting</h3><p>In a distributed system, a single business operation may cross several components.</p><p>Imagine an account suspension workflow:</p><pre>Account API<br>    |<br>    v<br>Account Service<br>    |<br>    v<br>Database<br>    |<br>    v<br>Transactional Outbox<br>    |<br>    v<br>Message Broker<br>    |<br>    v<br>Notification Service</pre><p>The account is suspended.</p><p>An event is recorded for publication.</p><p>Another service eventually receives the event and sends a notification.</p><p>Now imagine something goes wrong.</p><p>Support might ask:</p><p>Was the account actually suspended?</p><p>Was the event published?</p><p>Did the downstream service process it?</p><p>Was the notification delivered?</p><p>These are four different questions.</p><p>And they require different evidence.</p><p>This is one reason I find the relationship between <strong>NERV Event</strong> and <strong>NERV Audit</strong> interesting.</p><p>NERV Event focuses on reliable asynchronous processing through mechanisms such as transactional outbox, inbox processing, retries, and idempotency.</p><p>Those mechanisms help us understand message delivery and processing.</p><p>NERV Audit focuses on a different concern: the history of changes to business data.</p><p>In a properly designed workflow, the business entity update, audit revision, and outbox record can participate in the same database transaction.</p><p>After commit, the asynchronous event infrastructure takes responsibility for publication and processing according to its configured guarantees.</p><p>The audit trail helps us reconstruct the business-state changes.</p><p>The event-processing records help us reconstruct the asynchronous workflow.</p><p>Neither mechanism replaces the other.</p><p>And when we combine them with logs, metrics, and tracing, we have a much better foundation for investigating production incidents.</p><h3>This Is Why I Built NERV Audit</h3><p>I’ve spent much of my software engineering career building and supporting enterprise Java applications.</p><p>One recurring frustration is that systems often contain plenty of technical information but still make it difficult to answer simple business questions.</p><p>We have logs.</p><p>We have metrics.</p><p>We have traces.</p><p>Sometimes we even have audit tables.</p><p>Yet when someone asks why an entity reached an unexpected state, a developer may still need to manually inspect database records, correlate revisions, and reconstruct the timeline.</p><p>Hibernate Envers already solves an important part of this problem by maintaining entity revision history.</p><p>But capturing revisions and making those revisions useful are two different concerns.</p><p>That’s one of the motivations behind <strong>NERV Audit</strong>, an open-source auditing library built on Hibernate Envers for Spring Boot applications.</p><p>The goal isn’t to replace Envers or reinvent auditing.</p><p>It’s to make historical changes easier to query, inspect, and consume through application-level capabilities.</p><p>Because an audit trail is much more useful when developers and support teams can understand it without manually reconstructing database revisions every time something goes wrong.</p><h3>Building Systems That Can Explain What Happened</h3><p>After working on production systems for years, I’ve become increasingly convinced that auditability should be considered part of operational design.</p><p>Not every entity needs to be audited.</p><p>Not every field should be stored historically.</p><p>And not every business operation needs an elaborate investigation workflow.</p><p>But important business-state changes deserve deliberate treatment.</p><p>When a payment changes status, an account is suspended, or an administrative configuration is modified, we should consider how that decision can be investigated later.</p><p>A useful way to think about it is:</p><p><strong>Logs</strong> help explain what the application was doing.</p><p><strong>Metrics</strong> help explain how the system was behaving.</p><p><strong>Distributed tracing</strong> helps reconstruct execution across services.</p><p><strong>Event-processing records</strong> help reconstruct asynchronous workflows.</p><p><strong>Audit history</strong> helps explain what happened to business data.</p><p>And <strong>business context</strong> helps explain why a decision was made.</p><p>These mechanisms are complementary.</p><p>The challenge is not choosing one over the others.</p><p>It’s understanding which evidence we need and designing the system to preserve it reliably.</p><h3>Final Thoughts</h3><p>Application logs are essential for production support.</p><p>But they are not a substitute for a structured audit trail.</p><p>A log message may describe an operation that eventually rolls back.</p><p>A committed database change may exist even when a corresponding log message was never delivered.</p><p>And even comprehensive logs may not provide a convenient, durable history of an entity’s state transitions.</p><p>That’s why I believe audit history deserves its own place in production architecture.</p><p>Not simply because of compliance.</p><p>But because when something goes wrong, the ability to reconstruct how business data changed can save hours of investigation.</p><p><strong>Logs tell us what the application was doing.</strong></p><p><strong>An audit trail tells us what happened to the data.</strong></p><p>And sometimes, understanding that difference is what turns a difficult production incident into a manageable one.</p><p><em>This is Article #2 in my NERV Audit series, exploring production-ready auditing and the engineering decisions behind it.</em></p><p><strong>Explore the open-source NERV projects:</strong> <a href="https://github.com/czetsuyatech">CzetsuyaTech on GitHub</a></p><p><strong>Read the canonical article:</strong> <a href="https://www.czetsuyatech.com/2026/10/logs-arent-an-audit-trail-debugging-business-data.html">Logs Aren’t an Audit Trail — CzetsuyaTech</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f4d3ccb5a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Production-Ready Exception Handling in Spring Boot: Beyond @RestControllerAdvice]]></title>
            <link>https://czetsuya.medium.com/production-ready-exception-handling-spring-boot-8703d28cdbe7?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/8703d28cdbe7</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 07:41:28 GMT</pubDate>
            <atom:updated>2026-10-22T07:41:28.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pN7bMUidJ0wawpyfqshjMw.png" /><figcaption>Production-ready exception handling in Spring Boot with consistent API errors and reusable NERV Exception infrastructure</figcaption></figure><p>Exception handling is one of those engineering concerns that rarely receives much attention at the beginning of a project.</p><p>You create a Spring Boot application, define a few REST endpoints, and add a global exception handler.</p><p>Everything works.</p><p>Then the application grows.</p><p>More endpoints are introduced. Business rules become more complicated. Services start communicating with other services. Authentication and authorization become important. Eventually, you have several Spring Boot applications, each implementing its own variation of the same exception-handling logic.</p><p>That’s when something seemingly simple becomes an architectural problem.</p><p>While developing <strong>NERV Exception</strong>, an open-source exception-handling library for Java and Spring Boot, I wanted to explore a question:</p><p><strong>What does production-ready exception handling actually mean when applications must communicate failures consistently, securely, and across service boundaries?</strong></p><p>The answer turned out to involve much more than @RestControllerAdvice.</p><h3>The Problem With Exception Handling That Only Works Locally</h3><p>Consider a familiar Spring Boot implementation:</p><pre>@RestControllerAdvice<br>public class GlobalExceptionHandler {</pre><pre>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;String&gt; handle(Exception exception) {<br>        return ResponseEntity<br>                .status(HttpStatus.INTERNAL_SERVER_ERROR)<br>                .body(exception.getMessage());<br>    }<br>}</pre><p>For a small internal application, this might be a reasonable starting point.</p><p>But it makes several assumptions.</p><p>It assumes that every exception represents an internal server failure.</p><p>It assumes that an exception message is appropriate to expose to clients.</p><p>It assumes that clients only need a human-readable explanation.</p><p>And it assumes that the service handling the exception is also the service where the failure originated.</p><p>These assumptions become increasingly difficult to maintain as a system grows.</p><p>A validation failure is not the same as a missing resource. A business conflict is not the same as an unavailable payment provider. And a downstream timeout doesn’t necessarily mean the operation failed.</p><p>Yet poorly designed exception handling can make all these situations look almost identical.</p><p>The first lesson is straightforward:</p><p><strong>Exception handling isn’t just about catching failures. It’s about communicating their meaning.</strong></p><h3>HTTP Status Codes Tell Only Part of the Story</h3><p>HTTP provides useful semantics.</p><p>A 400 response indicates a problem with the request. A 404 indicates that a resource wasn&#39;t found. A 409 represents a conflict. A 503 indicates service unavailability.</p><p>But HTTP statuses cannot describe every application-specific failure.</p><p>Imagine an order service that returns 409 Conflict for three different situations:</p><ul><li>The order has already been processed.</li><li>The payment has already been captured.</li><li>Inventory was reserved by another transaction.</li></ul><p>All three may legitimately produce the same HTTP status.</p><p>But they can require different actions from the consumer.</p><p>A frontend might display a different message for each. Another backend service might need to stop processing in one case but initiate a reconciliation workflow in another.</p><p>If the consumer only sees 409, it must guess what happened.</p><p>Some systems attempt to solve this by parsing exception messages.</p><p>That’s fragile.</p><p>Messages are written for humans. They may change during refactoring, localization, or routine improvements to wording.</p><p>A better approach is to introduce stable application error codes.</p><p>For example:</p><pre>{<br>  &quot;code&quot;: &quot;ORDER_ALREADY_PROCESSED&quot;,<br>  &quot;message&quot;: &quot;This order has already been processed&quot;,<br>  &quot;status&quot;: 409,<br>  &quot;category&quot;: &quot;BUSINESS&quot;,<br>  &quot;retryable&quot;: false<br>}</pre><p>The code identifies the failure.</p><p>The message explains it.</p><p>The HTTP status communicates the transport-level outcome.</p><p>The category provides broader classification.</p><p>And retryability offers guidance about possible recovery.</p><p>These fields serve different purposes. They shouldn’t be treated as interchangeable.</p><p>The example above is illustrative; application-specific codes and categories are defined by the owning application.</p><h3>An Error Response Is a Public API Contract</h3><p>Most engineering teams spend considerable effort designing successful API responses.</p><p>They review DTOs, naming conventions, backward compatibility, and documentation.</p><p>Error responses often receive less scrutiny.</p><p>But consumers depend on them too.</p><p>If a frontend recognizes ORDER_ALREADY_PROCESSED, that error code has effectively become part of the API.</p><p>Renaming it can break consumer behavior, even if the endpoint still returns the same HTTP status and the same JSON structure.</p><p>This leads to a useful design principle:</p><p><strong>Treat error codes with the same care as successful API response fields.</strong></p><p>They should be stable, meaningful, and owned by the application or domain responsible for them.</p><p>A structured error contract can also include information for diagnostics.</p><p>NERV Exception’s response model supports fields such as:</p><pre>{<br>  &quot;code&quot;: &quot;ORDER_ALREADY_PROCESSED&quot;,<br>  &quot;message&quot;: &quot;This order has already been processed&quot;,<br>  &quot;status&quot;: 409,<br>  &quot;retryable&quot;: false,<br>  &quot;category&quot;: &quot;BUSINESS&quot;,<br>  &quot;traceId&quot;: &quot;abc123&quot;,<br>  &quot;spanId&quot;: &quot;def456&quot;,<br>  &quot;path&quot;: &quot;/api/orders/123/process&quot;,<br>  &quot;timestamp&quot;: &quot;2026-10-22T08:30:00Z&quot;,<br>  &quot;origin&quot;: {<br>    &quot;service&quot;: &quot;order-service&quot;,<br>    &quot;instance&quot;: &quot;order-service-1&quot;,<br>    &quot;version&quot;: &quot;1.0.0&quot;,<br>    &quot;environment&quot;: &quot;production&quot;<br>  },<br>  &quot;details&quot;: {}<br>}</pre><p>The example illustrates the supported response shape, not a claim that every field will be populated in every deployment.</p><p>A trace identifier can help connect a client-visible error with internal telemetry. Origin information can identify the service associated with the failure. Structured details can communicate validation information or other safe context.</p><p>But there’s a boundary to respect.</p><p>An error response should help a consumer understand what happened without exposing everything the application knows about the failure.</p><p>That distinction becomes especially important in production.</p><h3>Why Copying Global Exception Handlers Doesn’t Scale</h3><p>Once an organization has several Spring Boot services, a familiar pattern emerges.</p><p>One project contains a reasonably good exception handler.</p><p>A developer copies it into another project.</p><p>The second project adds support for validation errors.</p><p>The third introduces custom business exceptions.</p><p>Another team adds tracing information.</p><p>Someone else changes how internal exception messages are exposed.</p><p>Eventually, every service has a slightly different implementation.</p><p>The duplication isn’t just a maintenance inconvenience.</p><p>It creates inconsistent behavior.</p><p>One service might return a stable application error code. Another might return only an exception message. A third might expose an internal exception cause.</p><p>Clients now need different error-handling logic depending on which service they call.</p><p>This is one reason we built NERV Exception as a reusable library.</p><p>The objective was to centralize common infrastructure concerns while allowing applications to retain ownership of their business failures.</p><p>That distinction is important.</p><p>A shared library can define how errors are represented, converted, and serialized.</p><p>But it shouldn’t need to own every business error that every application might produce.</p><p><strong>Reuse the error-handling mechanism, not the entire business error catalog.</strong></p><h3>The Microservice Boundary Changes Everything</h3><p>Exception handling becomes more interesting when one service calls another.</p><p>Imagine this architecture:</p><pre>API Gateway<br>     |<br>     v<br>Order Service<br>     |<br>     v<br>Payment Service</pre><p>Payment Service returns:</p><pre>{<br>  &quot;code&quot;: &quot;PAYMENT_ALREADY_PROCESSED&quot;,<br>  &quot;message&quot;: &quot;Payment has already been processed&quot;,<br>  &quot;status&quot;: 409,<br>  &quot;category&quot;: &quot;BUSINESS&quot;,<br>  &quot;retryable&quot;: false<br>}</pre><p>Order Service receives the response through an HTTP client.</p><p>Now it has to decide what to do.</p><p>Should it discard the downstream error and replace it with a generic integration failure?</p><p>Should it maintain a local copy of every Payment Service error code?</p><p>Or should it preserve the downstream error even if the code isn’t recognized locally?</p><p>Each approach introduces trade-offs.</p><p>Replacing the error can discard useful information.</p><p>Sharing every business error definition can couple services that should evolve independently.</p><p>Preserving remote errors requires the receiving service to tolerate codes it doesn’t understand.</p><p>While building NERV Exception’s Feign integration, we explored that third approach.</p><p>The library can decode structured downstream errors and represent previously unknown codes using RemoteNervErrorCode.</p><p>This allows a service to preserve meaningful downstream error information without requiring every remote business error to be registered locally.</p><p>However, there’s an important qualification.</p><p>When a downstream code is registered locally, NERV Exception uses the local definition for status, category, and retryability.</p><p>That means the receiving service can reinterpret those aspects of the error.</p><p>And not every field is carried unchanged across the boundary. A regenerated HTTP response can contain the receiving service’s current trace context, request path, and timestamp rather than the original downstream values.</p><p>The lesson is that <strong>a consistent error format does not automatically guarantee transparent error propagation</strong>.</p><p>Service boundaries introduce questions about ownership, authority, and context.</p><p>Those are architectural questions, not merely serialization problems.</p><h3>Retryability Is Not a Promise That Retrying Is Safe</h3><p>One of the more useful fields in a structured error response is retryable.</p><p>But it’s also easy to misunderstand.</p><p>Consider a payment request.</p><p>Order Service sends a payment instruction to Payment Service.</p><p>Payment Service processes the payment successfully, but the response is lost because of a network interruption.</p><p>Order Service sees a timeout.</p><p>Should it retry?</p><p>The failure may be transient, but the operation may already have succeeded.</p><p>Without an idempotency mechanism, retrying could create a duplicate payment.</p><p>This is why retryability must be treated as guidance rather than a complete recovery policy.</p><p>A caller still needs to consider operation idempotency, unknown outcomes, retry limits, backoff, and the effect of repeated requests on downstream dependencies.</p><p>NERV Exception’s Feign integration can classify retryable downstream errors using Feign’s RetryableException.</p><p>But that classification doesn’t automatically configure a retry policy or guarantee that retry attempts will occur.</p><p>Applications remain responsible for retry execution and for deciding what happens when attempts are exhausted.</p><p>The broader lesson is:</p><p><strong>Error classification, retry execution, and business recovery are three different responsibilities.</strong></p><p>A reusable library can help with the first.</p><p>The other two require decisions informed by the application’s business behavior.</p><h3>Production Errors Must Be Useful Without Being Dangerous</h3><p>During development, detailed exception messages are convenient.</p><p>A developer wants to know which database connection failed, which class threw the exception, and what the underlying cause was.</p><p>But exposing that information through a public API can create security risks.</p><p>An internal hostname, SQL error, stack trace, or dependency detail may be useful to an operator but inappropriate for an external consumer.</p><p>A production-oriented design should distinguish between information intended for clients and information intended for internal diagnostics.</p><p>For example, an API might return:</p><pre>{<br>  &quot;code&quot;: &quot;PAYMENT_PROVIDER_UNAVAILABLE&quot;,<br>  &quot;message&quot;: &quot;Payment processing is temporarily unavailable&quot;,<br>  &quot;status&quot;: 503,<br>  &quot;retryable&quot;: true<br>}</pre><p>Meanwhile, internal logs and traces can contain the deeper information required to investigate the failure.</p><p>There was an important implementation lesson here as well.</p><p>In the reviewed NERV Exception 1.4.0 implementation, the Spring Boot starter’s default configuration enables internal message and cause exposure, although stack-trace exposure is disabled by default.</p><p>That means applications exposing public APIs should explicitly review and restrict those settings.</p><p>It’s a reminder that production readiness cannot be judged only by the presence of configuration options.</p><p><strong>What matters is the effective configuration of the deployed application.</strong></p><p>The same principle applies to tracing.</p><p>NERV Exception can use Micrometer tracing context when it is available, but an error-handling library doesn’t automatically create a complete distributed tracing system.</p><p>Error contracts and observability infrastructure complement each other.</p><p>Neither replaces the other.</p><h3>What Building NERV Exception Taught Me</h3><p>Working on reusable exception-handling infrastructure changed how I think about errors in Spring Boot applications.</p><p>At first, the challenge appears to be reducing repetitive code.</p><p>That’s worthwhile, but it isn’t the most important benefit.</p><p>The deeper value comes from making failure behavior consistent across applications.</p><p>A well-designed error contract gives consumers stable identifiers and useful classifications.</p><p>A reusable integration layer helps applications avoid duplicating response conversion logic.</p><p>Structured details make validation failures easier to process.</p><p>Tracing context helps operators connect client-visible failures to internal telemetry.</p><p>And deliberate handling of downstream errors allows microservices to communicate failures without necessarily sharing every business definition.</p><p>But none of these mechanisms eliminates the need for application-level decisions.</p><p>Teams still need to decide which errors are public, how unknown codes are handled, which operations are safe to retry, and what information can cross service boundaries.</p><p>That’s why I don’t think production-ready exception handling should be measured by how many exceptions a library catches.</p><p>It should be measured by whether the resulting behavior is predictable, safe, and useful to the systems consuming it.</p><h3>Final Thoughts</h3><p>A global exception handler is a good starting point.</p><p>But production-ready exception handling requires more than catching exceptions in one place.</p><p>It requires a stable communication contract, meaningful application error codes, safe diagnostic information, and clear responsibilities across service boundaries.</p><p>The most important shift is to stop thinking of exceptions solely as internal programming events.</p><p>Once a failure crosses an API boundary, it becomes part of how systems communicate.</p><p>And like every other form of communication between services, it deserves deliberate design.</p><p><strong>The goal isn’t to make every failure look identical. It’s to make every failure understandable without losing the meaning that makes it different.</strong></p><h3>About NERV Exception</h3><p>NERV Exception is an open-source Java and Spring Boot library focused on consistent error contracts, exception handling, error code resolution, and integrations such as Spring Web and OpenFeign.</p><p>It’s part of the broader NERV engineering ecosystem.</p><p>Explore the projects on <a href="https://github.com/czetsuyatech">GitHub</a>.</p><p>For the canonical technical article, read <strong>“Stop Copying Exception Handlers Between Spring Boot Projects”</strong> on <a href="https://www.czetsuyatech.com/">CzetsuyaTech</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8703d28cdbe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Microservices Need an Error Contract, Not Just Exception Handlers]]></title>
            <link>https://czetsuya.medium.com/microservices-error-contract-spring-boot-280a890b47da?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/280a890b47da</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 03:17:56 GMT</pubDate>
            <atom:updated>2026-10-19T03:17:56.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Umzdg6M1TcfbFl5h0-GVQ.png" /><figcaption>Designing a consistent error contract for Spring Boot microservices using NERV Exception</figcaption></figure><h3>Your Microservices Need an Error Contract, Not Just Exception Handlers</h3><p><em>Why consistent error responses matter more as Spring Boot applications grow into distributed systems.</em></p><p>Exception handling is one of the first things we implement when building a Spring Boot application.</p><p>We create a global exception handler, map exceptions to HTTP status codes, and return a JSON response.</p><p>Something like:</p><pre>{<br>  &quot;message&quot;: &quot;Customer not found&quot;<br>}</pre><p>It works.</p><p>At least until the application becomes part of a larger system.</p><p>Now imagine an architecture with an API gateway, an order service, a payment service, and an inventory service.</p><p>Each service was developed independently. Each team implemented exception handling according to its own requirements.</p><p>One service returns:</p><pre>{<br>  &quot;message&quot;: &quot;Customer not found&quot;<br>}</pre><p>Another returns:</p><pre>{<br>  &quot;error&quot;: &quot;PAYMENT_ALREADY_PROCESSED&quot;,<br>  &quot;status&quot;: 409<br>}</pre><p>And another returns:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2026-10-18T10:30:00Z&quot;,<br>  &quot;status&quot;: 404,<br>  &quot;error&quot;: &quot;Not Found&quot;,<br>  &quot;path&quot;: &quot;/inventory/123&quot;<br>}</pre><p>None of these responses is necessarily wrong.</p><p>But together, they introduce a problem.</p><p><strong>Every service speaks a different language when something fails.</strong></p><p>And that becomes increasingly expensive as the architecture grows.</p><h3>Exception Handling Is an Internal Concern. Error Contracts Are an Architectural Concern.</h3><p>A Java exception describes something that happened inside an application.</p><p>An API error response communicates that failure to another system.</p><p>These are related concerns, but they are not the same thing.</p><p>Consider this exception:</p><pre>throw new IllegalStateException(<br>    &quot;Customer account is disabled&quot;<br>);</pre><p>For the developer, the message may be sufficient.</p><p>But what should another service do with it?</p><p>Should it retry the request?</p><p>Should it tell the user to contact support?</p><p>Should it stop processing the transaction?</p><p>Should it classify the failure as a business rejection or an infrastructure problem?</p><p>A string message doesn’t provide a reliable answer.</p><p>We need something more structured.</p><p>A well-designed error contract should communicate several independent pieces of information:</p><ul><li><strong>Error code:</strong> What specific failure occurred?</li><li><strong>HTTP status:</strong> What was the protocol-level outcome?</li><li><strong>Category:</strong> What kind of failure is this?</li><li><strong>Retryability:</strong> Could repeating the operation be appropriate?</li><li><strong>Origin:</strong> Which service produced the failure?</li><li><strong>Tracing information:</strong> How can we locate the request in our observability system?</li><li><strong>Details:</strong> Is there additional structured context that a consumer can use?</li></ul><p>The important word here is <em>independent</em>.</p><p>These properties should not be inferred from one another without a deliberate policy.</p><p>For example, not every HTTP 500 response is necessarily retryable.</p><p>And not every business error should be classified according to its HTTP status.</p><p>A consistent contract makes these distinctions explicit.</p><h3>HTTP Status Codes Are Not Enough</h3><p>HTTP already provides a standardized way to describe request outcomes.</p><p>We have:</p><ul><li>400 Bad Request</li><li>401 Unauthorized</li><li>403 Forbidden</li><li>404 Not Found</li><li>409 Conflict</li><li>429 Too Many Requests</li><li>500 Internal Server Error</li><li>503 Service Unavailable</li></ul><p>So why introduce application error codes?</p><p>Because HTTP status codes describe broad conditions.</p><p>They don’t describe every business failure.</p><p>Imagine two operations returning HTTP 409:</p><pre>PAYMENT_ALREADY_PROCESSED</pre><pre>ORDER_ALREADY_CANCELLED</pre><p>Both represent conflicts.</p><p>But they may require completely different behavior from the caller.</p><p>For an already-processed payment, the application might need to retrieve the existing transaction.</p><p>For an already-cancelled order, it might need to prevent further processing.</p><p>If the caller only receives HTTP 409, it has insufficient information to distinguish those situations.</p><p>The HTTP status remains useful.</p><p>It just isn’t the entire contract.</p><p><strong>HTTP status tells us the general outcome. Application error codes tell us what actually happened.</strong></p><h3>What a Consistent Error Contract Looks Like</h3><p>While developing NERV Exception, I wanted a reusable way to communicate errors across Spring Boot applications.</p><p>The library’s HTTP response model, NervErrorResponse, contains fields for error identification, classification, tracing, origin, and structured details.</p><p>For example, a conflict response can look like this:</p><pre>{<br>  &quot;code&quot;: &quot;CONFLICT&quot;,<br>  &quot;message&quot;: &quot;Duplicate resource&quot;,<br>  &quot;status&quot;: 409,<br>  &quot;retryable&quot;: false,<br>  &quot;category&quot;: &quot;CLIENT&quot;,<br>  &quot;traceId&quot;: null,<br>  &quot;spanId&quot;: null,<br>  &quot;path&quot;: &quot;/orders&quot;,<br>  &quot;timestamp&quot;: &quot;2026-10-18T00:00:00Z&quot;,<br>  &quot;origin&quot;: {<br>    &quot;service&quot;: &quot;order-service&quot;,<br>    &quot;instance&quot;: &quot;order-service-01&quot;,<br>    &quot;version&quot;: &quot;1.0.0&quot;,<br>    &quot;environment&quot;: &quot;production&quot;<br>  },<br>  &quot;details&quot;: {}<br>}</pre><p>This is an illustrative response using the library’s supported structure. Actual origin values, timestamps, tracing fields, and JSON null handling depend on the application’s environment and configuration.</p><p>Notice something important.</p><p>The error code is CONFLICT, and the category is CLIENT.</p><p>That category is defined by the selected error definition.</p><p>It is not automatically derived from the HTTP status.</p><p>Similarly, retryability is an explicit property of the error definition.</p><p>This matters because it prevents us from relying on oversimplified assumptions such as:</p><blockquote><em>Every server error is retryable.</em></blockquote><p>Or:</p><blockquote><em>Every business error must use the same category.</em></blockquote><p>Those assumptions become problematic once multiple services begin interpreting one another’s failures.</p><h3>The Real Challenge Begins When Errors Cross Service Boundaries</h3><p>Consider this architecture:</p><pre>API Gateway<br>    |<br>    v<br>Order Service<br>    |<br>    +---- Customer Service<br>    |<br>    +---- Payment Service<br>    |<br>    +---- Inventory Service</pre><p>Suppose Order Service calls Payment Service.</p><p>Payment Service rejects the request because the payment has already been processed.</p><p>It returns an application error:</p><pre>{<br>  &quot;code&quot;: &quot;PAYMENT_ALREADY_PROCESSED&quot;,<br>  &quot;message&quot;: &quot;Payment has already been processed&quot;,<br>  &quot;status&quot;: 409,<br>  &quot;retryable&quot;: false,<br>  &quot;category&quot;: &quot;BUSINESS&quot;<br>}</pre><p>This is an illustrative application-defined error.</p><p>Now Order Service receives it.</p><p>What happens next?</p><p>In many applications, the downstream response is converted into a generic HTTP client exception.</p><p>The original error code disappears.</p><p>The category disappears.</p><p>The retryability information disappears.</p><p>And the caller is left with something resembling:</p><pre>FeignException: status 409</pre><p>Technically, the request failed.</p><p>But we lost the information that explained <em>why</em> it failed.</p><p>This is where a consistent error contract becomes more than a formatting decision.</p><p>It becomes a mechanism for preserving meaning across service boundaries.</p><h3>Should Every Microservice Know Every Error Code?</h3><p>One tempting solution is to create a shared library containing every business error code in the system.</p><p>Customer Service defines its errors.</p><p>Payment Service defines its errors.</p><p>Inventory Service defines its errors.</p><p>Then every service imports the same catalog.</p><p>Initially, this appears convenient.</p><p>But consider what happens as the system grows.</p><p>Every time Payment Service introduces a new error code, other services may need to update their shared dependency.</p><p>Even services that don’t understand or care about that payment-specific failure become coupled to its definition.</p><p>This raises an architectural question:</p><p><strong>Should a service need to understand every downstream business error just to preserve it?</strong></p><p>I don’t think it should.</p><p>There is an important distinction between sharing an error contract and sharing business error definitions.</p><p>Services can agree on the structure of an error response without agreeing on every possible error code.</p><p>That distinction influenced the design of NERV Exception’s Feign integration.</p><p>When the decoder encounters a valid NERV error response containing an unknown application code, it can represent that code using RemoteNervErrorCode.</p><p>The receiving service doesn’t need to register every downstream business error.</p><p>For example, it can recognize the structure of:</p><pre>{<br>  &quot;code&quot;: &quot;REMOTE_FAILURE&quot;,<br>  &quot;message&quot;: &quot;Downstream explanation&quot;,<br>  &quot;status&quot;: 422,<br>  &quot;retryable&quot;: false,<br>  &quot;category&quot;: &quot;REMOTE_CATEGORY&quot;<br>}</pre><p>Even if REMOTE_FAILURE doesn&#39;t exist in its local registry.</p><p>The caller may not know the business meaning of that specific code.</p><p>But it can still preserve useful information about the failure.</p><p>That is a significant difference.</p><p><strong>A common error contract should reduce integration complexity without creating unnecessary coupling between business domains.</strong></p><h3>Error Propagation Isn’t Always Lossless</h3><p>There is another subtlety.</p><p>What happens if the receiving service <em>does</em> recognize the downstream error code?</p><p>In NERV Exception, the local registry becomes authoritative for certain properties.</p><p>Specifically, the local definition determines:</p><ul><li>HTTP status</li><li>Error category</li><li>Retryability</li></ul><p>The remote message, origin, and supported details can still be carried by the downstream exception.</p><p>But the original downstream response isn’t necessarily reproduced byte for byte.</p><p>When the receiving service generates its own HTTP response, it can produce a new timestamp, request path, and tracing information.</p><p>This distinction is important.</p><p>The error’s origin and the current request’s execution context are not the same thing.</p><p>For example:</p><pre>Payment Service<br>    |<br>    | Error originated here<br>    v<br>Order Service<br>    |<br>    | Current HTTP response generated here<br>    v<br>API Gateway</pre><p>The original failure may belong to Payment Service.</p><p>But the response being generated belongs to the current request handled by Order Service.</p><p>Those are different pieces of information.</p><p>A well-designed error contract should make that distinction understandable.</p><p>It shouldn’t pretend that every field can be forwarded unchanged through every service.</p><h3>Retryability Is a Signal, Not a Retry Policy</h3><p>This is one of the most important lessons in distributed error handling.</p><p>Consider:</p><pre>{<br>  &quot;code&quot;: &quot;DEPENDENCY_TEMPORARILY_UNAVAILABLE&quot;,<br>  &quot;retryable&quot;: true<br>}</pre><p>The code is illustrative, but the retryability concept is real.</p><p>What does retryable: true actually mean?</p><p>It means the error definition identifies the failure as potentially eligible for retry.</p><p>It does <strong>not</strong> mean that the application will automatically retry.</p><p>It also doesn’t mean that retrying is always safe.</p><p>Imagine a payment request.</p><p>The client sends the request.</p><p>The payment provider processes it.</p><p>But the network connection fails before the response reaches the client.</p><p>Should the client immediately retry?</p><p>Not without considering whether the operation is idempotent.</p><p>Otherwise, it might create a duplicate payment.</p><p>This is why retryability must be considered alongside:</p><ul><li>Idempotency</li><li>Retry limits</li><li>Exponential backoff</li><li>Timeout configuration</li><li>Operation semantics</li><li>Retry exhaustion handling</li></ul><p>NERV Exception’s Feign decoder can represent a retryable downstream error as a Feign RetryableException.</p><p>But actual retry execution depends on the configured Feign retry policy.</p><p>There is also an important boundary: if that retryable wrapper reaches the default generic Spring Web exception handler, the original downstream NERV error is not guaranteed to be reproduced.</p><p>The lesson is straightforward.</p><p><strong>An error contract can tell us whether retrying may be appropriate. It cannot make the operation safe to retry.</strong></p><p>That responsibility belongs to the application architecture.</p><h3>Observability Makes Error Contracts More Useful</h3><p>When a failure occurs in production, knowing the error code is only part of the investigation.</p><p>We also need to understand where the failure originated and how it relates to the request being processed.</p><p>This is where origin and tracing information become useful.</p><p>NERV Exception can include information such as:</p><pre>{<br>  &quot;traceId&quot;: &quot;8f4e1c2a7b3d4e6f&quot;,<br>  &quot;spanId&quot;: &quot;2c9b1a8d4e6f7c3a&quot;,<br>  &quot;origin&quot;: {<br>    &quot;service&quot;: &quot;payment-service&quot;,<br>    &quot;instance&quot;: &quot;payment-service-01&quot;,<br>    &quot;version&quot;: &quot;1.0.0&quot;,<br>    &quot;environment&quot;: &quot;production&quot;<br>  }<br>}</pre><p>These values are illustrative.</p><p>When Micrometer tracing is available, the library can read the current tracing context.</p><p>Without an active trace, the trace and span identifiers may be null.</p><p>This is useful because an API consumer can correlate a failure with application logs and distributed traces.</p><p>But origin and tracing serve different purposes.</p><p>Origin describes the service associated with the error.</p><p>Tracing describes the execution context of the request.</p><p>Neither replaces the other.</p><p>And neither automatically provides a complete history of every service involved.</p><p>For that, we still need proper distributed tracing and observability infrastructure.</p><h3>Error Contracts Also Have Security Implications</h3><p>A consistent error response should make failures easier to understand.</p><p>But it should not expose information that an external consumer shouldn’t see.</p><p>Consider this response:</p><pre>{<br>  &quot;message&quot;: &quot;SQL query failed against internal-db-01&quot;,<br>  &quot;details&quot;: {<br>    &quot;sql&quot;: &quot;SELECT * FROM customer_accounts&quot;,<br>    &quot;exception&quot;: &quot;...&quot;<br>  }<br>}</pre><p>That might be useful in a development environment.</p><p>It is not appropriate for a public API.</p><p>This is why error response configuration matters.</p><p>During the technical review of NERV Exception 1.4.0, we identified an important distinction between its standalone default settings and Spring Boot starter defaults.</p><p>The starter’s defaults enable internal message and exception-cause exposure.</p><p>For public APIs, those settings should be explicitly reviewed and restricted.</p><p>A production-oriented error contract should separate information intended for external consumers from information intended for internal diagnostics.</p><p>The client needs a stable error code and an appropriate message.</p><p>The operator may need a stack trace.</p><p>Those audiences should not automatically receive the same information.</p><p><strong>Consistency should improve observability without compromising security.</strong></p><h3>The Contract Should Evolve Without Breaking Consumers</h3><p>Once an API consumer depends on an error code, that code becomes part of the application’s public behavior.</p><p>Consider:</p><pre>PAYMENT_ALREADY_PROCESSED</pre><p>A frontend might use it to display a particular message.</p><p>Another service might use it to stop a workflow.</p><p>Renaming the code could break those consumers even if the HTTP status remains unchanged.</p><p>The same applies to changing retryability or category semantics.</p><p>These are not merely internal refactorings.</p><p>They can affect application behavior.</p><p>A few principles help:</p><p>Keep published error codes stable.</p><p>Avoid using human-readable messages as identifiers.</p><p>Allow consumers to handle unknown codes gracefully.</p><p>Treat changes to retryability and status mappings as behavioral changes.</p><p>And avoid coupling every service to a single centralized catalog of business errors.</p><p>NERV Exception provides mechanisms for consistent representation and error code resolution.</p><p>It does not automatically enforce a complete schema versioning or compatibility strategy.</p><p>That remains an architectural responsibility.</p><h3>What I Learned Building NERV Exception</h3><p>One of the interesting things about building reusable infrastructure is discovering that the difficult part isn’t necessarily writing the code.</p><p>Creating a global exception handler is straightforward.</p><p>Creating an error response DTO is straightforward.</p><p>Even defining a common error interface is relatively simple.</p><p>The harder questions appear at the boundaries.</p><p>What happens when a downstream service introduces a new error code?</p><p>Should the receiving service preserve the original error or replace it with a local definition?</p><p>Who determines retryability?</p><p>What happens when retries are exhausted?</p><p>Which tracing information belongs to the original failure, and which belongs to the current request?</p><p>How much diagnostic information should an API expose?</p><p>These questions are not solved by adding another @ExceptionHandler.</p><p>They require architectural decisions.</p><p>And those decisions become increasingly important as services evolve independently.</p><p>That’s the problem NERV Exception is intended to address: providing reusable error-handling infrastructure while preserving meaningful distinctions between application failures, transport behavior, and service ownership.</p><p>The library is part of <strong>NERV — Next-Generation Engineering for Runtime Velocity</strong>, an open-source ecosystem of Java and Spring Boot components.</p><p>You can explore the projects on <a href="https://github.com/czetsuyatech">GitHub</a>.</p><h3>Final Thoughts</h3><p>A global exception handler makes error responses consistent within an application.</p><p>An error contract makes failures understandable across applications.</p><p>That difference matters.</p><p>As systems grow, failures become part of the communication between services.</p><p>They influence retry decisions, business workflows, frontend behavior, monitoring, and operational troubleshooting.</p><p>A well-designed error contract should communicate enough information for consumers to respond appropriately without forcing every service to understand every other service’s internal business model.</p><p><strong>The goal isn’t simply to standardize how errors look. It’s to preserve what errors mean.</strong></p><p>And in a distributed system, that distinction makes all the difference.</p><p>This article is part of my NERV Exception series, where I explore the engineering decisions behind production-ready error handling in Spring Boot. You can follow the development of NERV and its open-source libraries on <a href="https://github.com/czetsuyatech">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=280a890b47da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Transaction Boundaries Around Irreversible External Operations]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://czetsuya.medium.com/designing-transaction-boundaries-irreversible-external-operations-92663c6dc644?source=rss-f795956d2899------2"><img src="https://cdn-images-1.medium.com/max/1672/1*SqRoE48SJ02O2i5ERU3VsQ.png" width="1672"></a></p><p class="medium-feed-snippet">The Transaction Committed. The Order Didn&#x2019;t. Or Maybe It Did.</p><p class="medium-feed-link"><a href="https://czetsuya.medium.com/designing-transaction-boundaries-irreversible-external-operations-92663c6dc644?source=rss-f795956d2899------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://czetsuya.medium.com/designing-transaction-boundaries-irreversible-external-operations-92663c6dc644?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/92663c6dc644</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 08:17:13 GMT</pubDate>
            <atom:updated>2026-10-18T08:17:13.702Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A Trading Bot Is Easy. A Trading Engine Is Not]]></title>
            <link>https://czetsuya.medium.com/a-trading-bot-is-easy-a-trading-engine-is-not-73f2428c6711?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/73f2428c6711</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 04:42:23 GMT</pubDate>
            <atom:updated>2026-10-17T04:42:23.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3Pb5zakW5Kd_MpRERomsw.png" /><figcaption>A simple trading bot architecture contrasted with a complex trading engine featuring execution, persistence, and recovery</figcaption></figure><p><em>The unexpected engineering problems hiding behind a simple BUY signal — and how they changed the architecture of NERV Trade.</em></p><p>There’s something satisfying about building your first trading bot.</p><p>You connect to a market-data source, calculate a few indicators, and write some conditions that determine whether to buy or sell.</p><p>Then you run it against historical data.</p><p>Signals appear. Trades are simulated. Profit and loss numbers start moving.</p><p>You change a threshold, run the simulation again, and see what happens.</p><p>It feels like progress.</p><p>And it is.</p><p>But when I started building <strong>NERV Trade</strong>, I eventually discovered that I was solving only a small part of a much larger problem.</p><p>I was teaching software how to make trading decisions.</p><p>I hadn’t yet solved how it should take responsibility for those decisions.</p><p>That distinction would change the architecture of the entire project.</p><h3>It Started With Three Boxes</h3><p>The original idea behind NERV Trade was straightforward.</p><p>Receive market data, analyze it, and generate a trading signal.</p><p>Something like this:</p><pre>Market Data<br>     ↓<br>Analysis<br>     ↓<br>BUY / SELL</pre><p>As a Java backend engineer, this seemed like a manageable problem.</p><p>Market data could be represented using domain objects. Indicators could operate on historical candles. Strategies could evaluate the results and produce decisions.</p><p>The system could be tested.</p><p>It could be extended.</p><p>And eventually, it could connect to a broker.</p><p>At this stage, the interesting questions were mostly about trading.</p><p>Which indicators should we use?</p><p>Should the strategy analyze multiple timeframes?</p><p>How do we avoid generating signals too frequently?</p><p>How do we identify whether the market is trending or ranging?</p><p>Those are legitimate problems.</p><p>But they’re problems about deciding <strong>what we want to do</strong>.</p><p>The moment I started thinking seriously about execution, the questions changed.</p><p>And they became much less comfortable.</p><h3>A BUY Signal Doesn’t Actually Buy Anything</h3><p>Imagine a strategy produces a signal:</p><p><strong>BUY BTC.</strong></p><p>What has happened?</p><p>At first glance, the answer seems obvious.</p><p>The system wants to buy Bitcoin.</p><p>But that isn’t the same as buying Bitcoin.</p><p>A signal is a decision.</p><p>To act on that decision, the application must create an order and submit it to a broker or exchange.</p><p>The broker might accept the order.</p><p>It might reject it.</p><p>It might execute it immediately.</p><p>Or it might execute only part of it.</p><p>Suddenly, what looked like one action becomes several distinct events.</p><pre>Trading Decision<br>       ↓<br>Order Created<br>       ↓<br>Order Submitted<br>       ↓<br>Broker Acknowledgment<br>       ↓<br>Execution<br>       ↓<br>Position Updated</pre><p>And there’s no guarantee that every step will happen immediately — or successfully.</p><p>This was one of the first realizations that changed how I thought about NERV Trade.</p><p>A trading strategy expresses an intention.</p><p>The execution engine must determine what actually happened.</p><p>Those responsibilities shouldn’t be confused.</p><p>Because the moment we treat a decision as though it were already an execution, we lose the ability to represent reality accurately.</p><h3>The Market Doesn’t Promise to Fill Your Entire Order</h3><p>Suppose you submit an order to buy 10 units of an asset.</p><p>In a simple trading simulation, the result might look like this:</p><pre>BUY 10<br>   ↓<br>FILLED 10</pre><p>But a real broker can execute that order in several parts.</p><pre>BUY 10<br>   ↓<br>FILLED 3<br>   ↓<br>FILLED 4<br>   ↓<br>FILLED 3<br>   ↓<br>COMPLETE</pre><p>Now the application must understand that three separate executions belong to the same order.</p><p>It needs to calculate how much was actually purchased, how much remains outstanding, and what each execution cost.</p><p>It also needs to know whether the order is still active.</p><p>An order that has been partially filled and subsequently cancelled is not the same as an order that was never executed.</p><p>Both may be terminal, but their economic consequences are different.</p><p>This is where a simple trading program begins to need something more substantial.</p><p>It needs an execution lifecycle.</p><p>And once it has a lifecycle, it needs rules that prevent the state from becoming inconsistent.</p><p>The trading strategy is no longer the most complicated part of the application.</p><h3>Then I Realized a Position Isn’t Necessarily a Trade</h3><p>Consider another situation.</p><p>Two independent strategies are operating on the same asset.</p><p>Strategy A buys five units.</p><p>Strategy B buys three.</p><p>The account now holds eight units.</p><p>That seems straightforward.</p><p>But what happens when Strategy A decides to exit?</p><p>Should the application sell all eight units?</p><p>Of course not.</p><p>Strategy B still has an active position.</p><p>This exposes a subtle problem with treating the account’s aggregate position as the primary representation of a trade.</p><p>The account knows how much of an asset it holds.</p><p>But that doesn’t automatically tell us which trading decision is responsible for each part of that exposure.</p><p>In NERV Trade, this led to the introduction of <strong>trade intents</strong>.</p><p>A trade intent represents an independently owned trading lifecycle.</p><p>It connects a strategy decision to its orders, executions, exposure, and eventual completion.</p><p>The aggregate position is then derived from those individual lifecycles.</p><p>This was an important architectural decision because it separated two questions that initially appeared identical:</p><p><strong>What does the account hold?</strong></p><p>And:</p><p><strong>Which trading operation owns that exposure?</strong></p><p>Those questions become particularly important when multiple strategies, partial exits, and reversals enter the picture.</p><h3>The Same Execution Arrived Twice</h3><p>Anyone who has worked with distributed systems knows that duplicate events are a fact of life.</p><p>Messages can be redelivered.</p><p>Connections can be interrupted.</p><p>Consumers can restart.</p><p>Reconciliation processes can rediscover information that was already processed.</p><p>Trading infrastructure has similar problems.</p><p>Imagine that an exchange reports an execution:</p><pre>BUY 0.001 BTC<br>Execution ID: 12345</pre><p>NERV Trade receives the execution and updates its internal exposure.</p><p>Everything is correct.</p><p>Then the connection drops.</p><p>Later, the application reconnects and receives the same execution again.</p><p>Or perhaps it discovers the execution while reconciling its records with the exchange.</p><p>If the application processes the event a second time, its internal accounting becomes incorrect.</p><p>The exchange executed 0.001 BTC.</p><p>But the application believes it acquired 0.002 BTC.</p><p>The problem isn’t that the event was delivered twice.</p><p>Duplicate delivery is something a reliable system should anticipate.</p><p>The problem is allowing duplicate delivery to create duplicate economic effects.</p><p>That distinction led NERV Trade toward durable execution identities and idempotent accounting.</p><p>An execution might be observed through several different mechanisms, but it must represent the same underlying economic event.</p><p><strong>The same fill should never become a new fill simply because the application reconnected or restarted.</strong></p><p>This is one of the places where my experience building enterprise Java systems became particularly relevant.</p><p>The problem resembles duplicate payment processing, event-driven workflows, and message-consumer idempotency.</p><p>But in trading, incorrect accounting can directly influence the next financial decision.</p><p>An engine that believes it owns more than it actually does might make an entirely inappropriate trading decision.</p><h3>The Most Dangerous Failure Is the One You Can’t Confirm</h3><p>One of the most interesting problems emerged when considering network failures.</p><p>Imagine that NERV Trade submits a BUY order to an exchange.</p><p>The exchange receives it.</p><p>The order is accepted.</p><p>Then the connection fails before the application receives the response.</p><pre>NERV Trade                 Exchange<br>     |                         |<br>     |------ BUY ORDER -------&gt;|<br>     |                         |<br>     |                    Order Accepted<br>     |                         |<br>     X                         |<br> Connection Lost               |</pre><p>From the application’s perspective, the request failed.</p><p>But the exchange has already accepted the order.</p><p>What should happen next?</p><p>In many backend applications, the instinctive answer is to retry.</p><p>Transient network failures are common, and modern frameworks provide sophisticated retry mechanisms.</p><p>But retries are not automatically safe.</p><p>If NERV Trade submits another order without first establishing what happened to the original, the exchange might accept both.</p><p>The application intended to purchase one quantity.</p><p>It may have accidentally purchased twice as much.</p><p>The uncomfortable truth is that a failed network request does not necessarily mean the operation failed.</p><p>Sometimes, the correct state is simply:</p><p><strong>Unknown.</strong></p><p>And unknown is not the same as rejected.</p><p>This required NERV Trade to preserve uncertain submission states and establish what happened through broker reconciliation.</p><p>Rather than blindly repeating an operation, the engine needs to ask the external system for evidence.</p><p>Did the order exist?</p><p>Was it accepted?</p><p>Was it executed?</p><p>Was it rejected?</p><p>Only then can the engine safely determine what to do next.</p><p>This was another moment when the project began to feel less like a trading bot and more like a distributed transaction system.</p><h3>Then the Application Crashed</h3><p>There’s a particularly uncomfortable question every automated trading system eventually needs to answer.</p><p>What happens when the application stops?</p><p>Not gracefully.</p><p>Not after completing every outstanding operation.</p><p>It simply stops.</p><p>Perhaps the process crashes.</p><p>Perhaps the infrastructure restarts.</p><p>Perhaps a new version is deployed.</p><p>Meanwhile, the broker still exists.</p><p>The orders still exist.</p><p>And the market continues moving.</p><p>When the application starts again, it cannot pretend that everything is new.</p><p>It needs to remember which trades were active, which orders had been submitted, and which executions had already been processed.</p><p>But remembering the latest position isn’t enough.</p><p>The engine also needs to understand how that position was created and which trading lifecycles remain incomplete.</p><p>This is why persistence became more than a convenience in NERV Trade.</p><p>It became part of the correctness model.</p><p>When an execution is accepted, several related pieces of state may need to change.</p><p>The execution must be recorded.</p><p>The order’s accounting must be updated.</p><p>The trade’s exposure must change.</p><p>Cost basis and realized profit or loss may need recalculation.</p><p>The lifecycle may become complete.</p><p>If only some of those changes are committed, the system can become inconsistent.</p><p>For NERV Trade, the solution involved establishing an atomic transaction boundary around accepted execution accounting using PostgreSQL.</p><p>Either the complete economic state transition commits, or none of it does.</p><p>That sounds like ordinary database engineering.</p><p>And in many ways, it is.</p><p>But it becomes much more interesting when those database transactions represent the consequences of actions already performed by an external broker.</p><p>You cannot simply roll back a trade because your application transaction failed.</p><p>The external world has already moved forward.</p><p>Your system must eventually catch up with reality.</p><h3>The Simulator Became an Engineering Tool</h3><p>At this point, connecting to a real exchange might seem like the obvious next step.</p><p>But there was another problem.</p><p>How do you reliably test all these failure scenarios?</p><p>How do you force an order to be partially filled?</p><p>How do you reproduce duplicate execution delivery?</p><p>How do you simulate a crash during execution accounting?</p><p>How do you repeatedly test the same sequence of events without depending on unpredictable exchange behavior?</p><p>This is where the deterministic simulator became essential.</p><p>Initially, a simulator might appear to be a tool for testing trading strategies.</p><p>But for NERV Trade, it became a controlled environment for validating the execution engine itself.</p><p>We could reproduce difficult order lifecycles, inject failures, and verify that the engine maintained its invariants.</p><p>The simulator exercised the same core execution boundaries that would eventually be used by an external broker adapter.</p><p>That gave us confidence in the internal lifecycle before introducing real exchange behavior.</p><p>It also changed how I thought about testing.</p><p>The objective wasn’t simply to prove that the strategy could generate profitable trades.</p><p>It was to prove that the engine could account for trades correctly even when execution didn’t follow the happy path.</p><h3>What We Started Building Was No Longer a Bot</h3><p>Looking back, the architectural evolution is interesting because none of the additional components appeared without a reason.</p><p>The original model was simple:</p><pre>Market Data<br>     ↓<br>Analysis<br>     ↓<br>BUY / SELL</pre><p>But the questions kept accumulating.</p><p>How do we distinguish a decision from an order?</p><p>How do we represent partial fills?</p><p>How do we prevent duplicate executions?</p><p>How do we know which strategy owns a position?</p><p>How do we handle uncertain broker submissions?</p><p>How do we preserve state across restarts?</p><p>How do we reconcile our internal understanding with the exchange?</p><p>Eventually, the architecture became something closer to:</p><pre>Market Data<br>     ↓<br>Multi-Timeframe Analysis<br>     ↓<br>Strategy<br>     ↓<br>Risk<br>     ↓<br>Trade Intent<br>     ↓<br>Order Lifecycle<br>     ↓<br>Broker<br>     ↓<br>Execution Accounting<br>     ↓<br>Durable Persistence<br>     ↓<br>Recovery &amp; Reconciliation</pre><p>That’s a much larger system.</p><p>But complexity wasn’t the goal.</p><p>Every new responsibility was introduced because the previous design couldn’t adequately represent or protect something important.</p><p>And that’s a distinction I think software engineers should be careful about.</p><p>A complicated architecture isn’t necessarily a good architecture.</p><p>A good architecture has clear reasons for its complexity.</p><h3>A Trading Bot Makes Decisions. A Trading Engine Owns Their Consequences.</h3><p>I don’t think there’s a single industry definition that perfectly separates a trading bot from a trading engine.</p><p>For NERV Trade, the distinction became practical.</p><p>A trading bot primarily answers:</p><p><em>What should I trade?</em></p><p>A trading engine must also answer:</p><p><em>What actually happened?</em></p><p><em>What do I currently own?</em></p><p><em>Which strategy owns that exposure?</em></p><p><em>What has already been processed?</em></p><p><em>What remains uncertain?</em></p><p><em>Can I recover after a failure?</em></p><p><em>Does my internal state still agree with the broker?</em></p><p>Those questions eventually became more important to the engineering work than generating another trading signal.</p><p>And they changed how I measured progress.</p><p>Early progress was visible.</p><p>A new indicator.</p><p>A new strategy.</p><p>A better-looking backtest.</p><p>Later, the most important improvements were almost invisible.</p><p>An execution arriving twice changed accounting only once.</p><p>A failed transaction didn’t leave half-committed state.</p><p>An uncertain order wasn’t blindly submitted again.</p><p>A restart didn’t erase the engine’s understanding of its active trades.</p><p>These improvements didn’t produce impressive charts.</p><p>But they made the system more reliable.</p><h3>Before We Could Execute Reliably, We Needed to Think Reliably</h3><p>There’s one part of the story we haven’t explored yet.</p><p>Before worrying about brokers, orders, persistence, or recovery, NERV Trade faced an even more fundamental question.</p><p>Suppose we give the engine the same market data twice.</p><p>Should it produce the same analysis and trading decision?</p><p>The answer seems obvious.</p><p>Of course it should.</p><p>But software doesn’t always behave that way.</p><p>Time-dependent calculations, mutable state, event ordering, candle boundaries, and partially formed market data can all introduce subtle differences.</p><p>If analysis isn’t reproducible, everything built on top of it becomes harder to verify.</p><p>A strategy might produce different decisions during replay.</p><p>A backtest might accidentally use information that wasn’t available at the time.</p><p>A failure might become impossible to reproduce.</p><p>That led to one of the earliest architectural principles behind NERV Trade:</p><p><strong>Determinism.</strong></p><p>Before building an engine that could reliably execute decisions, we needed an engine that could reliably reproduce them.</p><p>And that’s where the next chapter begins.</p><h3>Continuing the NERV Trade Journey</h3><p>This is <strong>Part 2 of the NERV Trade engineering series</strong>, where I document the decisions, failures, and architectural changes involved in building a trading engine using Java and Spring Boot.</p><p>The series isn’t about promising profitable trading strategies.</p><p>It’s about the software engineering challenges involved in building systems that interact with markets, external brokers, and persistent financial state.</p><p><strong>Previous article:</strong> <a href="https://www.czetsuyatech.com/2026/09/i-built-a-trading-engine-in-java.html">I Built a Trading Engine in Java. The Hardest Problems Had Nothing to Do With Trading.</a></p><p><strong>Next article:</strong> <em>Deterministic Trading: Why the Same Market Data Must Produce the Same Decision.</em></p><p>We’ll explore why deterministic analysis matters, how reproducibility affects architecture, and why the same historical market data must produce the same result.</p><h3>About NERV Trade</h3><p>NERV Trade is part of <strong>NERV — Next-Generation Engineering for Runtime Velocity</strong>, my Java and Spring engineering initiative.</p><p>The project explores deterministic market analysis, multi-timeframe strategies, trade lifecycle management, execution accounting, durable persistence, broker integration, and operational safety.</p><p>This article is adapted from the original CzetsuyaTech publication:</p><p><a href="https://www.czetsuyatech.com/2026/10/a-trading-bot-is-easy-trading-engine-is-not.html"><strong>A Trading Bot Is Easy. A Trading Engine Is Not.</strong></a></p><p><em>This series focuses on software engineering and trading infrastructure, not financial advice.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73f2428c6711" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Trading Engine in Java. The Hardest Problems Had Nothing to Do With Trading]]></title>
            <link>https://czetsuya.medium.com/building-a-trading-engine-in-java-beyond-trading-signals-ff03c61c2975?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff03c61c2975</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 04:07:58 GMT</pubDate>
            <atom:updated>2026-10-17T04:07:58.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxvMoPOQhdOdzR4ZIeX8ag.png" /><figcaption>NERV Trade Java trading engine architecture showing market analysis, strategy, risk, execution, and persistence</figcaption></figure><p><em>From BUY and SELL signals to partial fills, distributed systems, database transactions, and surviving application crashes.</em></p><p>I thought building a trading engine would be mostly about trading.</p><p>Market analysis. Technical indicators. Trading strategies. Finding opportunities to buy and sell.</p><p>As a Java developer, I was particularly interested in building a system that could analyze market conditions across multiple timeframes and turn those observations into trading decisions.</p><p>The original idea was straightforward.</p><p>Receive market data. Analyze it. Generate a signal. Execute a trade.</p><p>Something like this:</p><pre>Market Data<br>     ↓<br>Analysis<br>     ↓<br>Strategy<br>     ↓<br>BUY / SELL</pre><p>It seemed like a reasonable starting point.</p><p>And it was.</p><p>But as I continued developing what eventually became <strong>NERV Trade</strong>, I discovered that generating trading signals was only a small part of the engineering challenge.</p><p>The difficult questions had surprisingly little to do with predicting the market.</p><p>They were questions about distributed systems, state management, concurrency, transactions, idempotency, and recovery.</p><p>Questions I’d encountered throughout my career building enterprise Java applications.</p><p>Except this time, the consequences of getting them wrong were different.</p><p>A duplicate event might not just create an incorrect record.</p><p><strong>It could create an incorrect financial position.</strong></p><p>And that changed everything.</p><h3>The First Illusion: A Signal Is a Trade</h3><p>Imagine that a trading strategy analyzes Bitcoin and produces a simple instruction:</p><p><strong>BUY BTC.</strong></p><p>For a basic trading bot, this might be enough.</p><p>The application sends an order to an exchange, receives a response, and moves on.</p><p>But what does BUY actually mean?</p><p>Does it mean the strategy wants to buy?</p><p>Does it mean an order has been created?</p><p>Does it mean the exchange accepted the order?</p><p>Or does it mean Bitcoin was actually purchased?</p><p>These are four different things.</p><p>At first, the distinctions might seem unnecessarily complicated.</p><p>But consider what happens when you submit an order to purchase 10 units of an asset.</p><p>You might expect:</p><pre>BUY 10<br>   ↓<br>FILLED 10</pre><p>Instead, the broker could execute it in several parts.</p><pre>BUY 10<br>   ↓<br>FILLED 3<br>   ↓<br>FILLED 4<br>   ↓<br>FILLED 3<br>   ↓<br>COMPLETE</pre><p>Now your application has to understand that one order produced three executions.</p><p>It must track the quantity already filled, the remaining quantity, the cost of each execution, and the resulting position.</p><p>It must also know whether the order is still active.</p><p>Suddenly, a simple BUY instruction is no longer sufficient to describe what happened.</p><p>This was one of the first important architectural lessons I learned while developing NERV Trade.</p><p><strong>A trading decision is not an order. An order is not an execution. And an execution is not necessarily a completed trade.</strong></p><p>Once I understood that distinction, the architecture began to change.</p><h3>The Second Illusion: A Position Tells You Everything</h3><p>Suppose two independent trading strategies are running.</p><p>Strategy A buys five units of an asset.</p><p>Strategy B buys three.</p><p>The account now holds eight units.</p><pre>Strategy A → BUY 5<br>Strategy B → BUY 3</pre><pre>Aggregate Position → LONG 8</pre><p>If we only look at the account’s aggregate position, everything appears straightforward.</p><p>We own eight units.</p><p>But which strategy owns them?</p><p>What happens if Strategy A decides to exit?</p><p>Should the system sell all eight units?</p><p>Obviously not.</p><p>Strategy B still owns its exposure.</p><p>This raised an important question:</p><p><strong>Should the aggregate position be the primary representation of a trade?</strong></p><p>For NERV Trade, the answer became no.</p><p>Instead, I introduced the concept of a <em>trade intent</em>.</p><p>Each intent represents an independently owned trading lifecycle.</p><p>It connects a strategy decision to its orders, executions, exposure, and eventual completion.</p><p>The account’s aggregate position is then derived from those individual lifecycles.</p><p>This distinction became especially important when handling reversals, partial exits, and multiple strategies operating on the same instrument.</p><p>A position tells you what the account holds.</p><p>It doesn’t necessarily tell you why the account holds it.</p><p>And in an automated trading system, that difference matters.</p><h3>The Third Illusion: Receiving an Event Means Processing It Once</h3><p>As a backend engineer, I was already familiar with duplicate message delivery.</p><p>Anyone who has worked with Kafka, payment systems, or asynchronous APIs knows that events can arrive more than once.</p><p>But trading makes the consequences particularly visible.</p><p>Imagine that an exchange reports an execution:</p><pre>Execution ID: 98765<br>BUY: 0.001 BTC</pre><p>NERV Trade receives the execution and updates its internal exposure.</p><p>So far, everything is correct.</p><p>Then the connection drops.</p><p>The application reconnects.</p><p>Later, reconciliation retrieves the same execution from the exchange.</p><p>Now the engine sees:</p><pre>Execution ID: 98765<br>BUY: 0.001 BTC</pre><p>Again.</p><p>If the application treats this as a new execution, its internal accounting becomes:</p><pre>Actual BTC purchased: 0.001</pre><pre>Internally recorded:   0.002</pre><p>That’s a serious problem.</p><p>The system now believes it owns more than it actually does.</p><p>This is where familiar distributed-systems concepts become essential.</p><p>NERV Trade needed stable execution identities, duplicate detection, and durable idempotency.</p><p>But there was an additional complication.</p><p>An execution could be discovered through different mechanisms:</p><ul><li>A live exchange event</li><li>Reconnection processing</li><li>Broker reconciliation</li><li>Application restart recovery</li></ul><p>All of those paths needed to agree that they were looking at the same execution.</p><p>A new connection must not make an old fill appear new.</p><p>The design principle became:</p><blockquote><em>An execution may be observed multiple times, but its economic effects must be accepted only once.</em></blockquote><p>This is a problem I had encountered in other forms while working with payment processing and event-driven enterprise systems.</p><p>In trading, however, the consequences are immediate and measurable.</p><h3>The Fourth Illusion: A Failed Request Means Nothing Happened</h3><p>This was one of the most interesting problems.</p><p>Imagine that NERV Trade sends an order to an exchange.</p><p>The exchange receives it.</p><p>The order is accepted.</p><p>Then the network connection fails before the exchange can return its response.</p><p>From the application’s perspective, the request failed.</p><p>But from the exchange’s perspective, the order exists.</p><pre>NERV Trade                 Exchange<br>     |                         |<br>     |------ BUY ORDER -------&gt;|<br>     |                         |<br>     |                    Order Accepted<br>     |                         |<br>     X                         |<br> Connection Lost               |</pre><p>What should the application do?</p><p>The instinctive answer in many backend systems is to retry.</p><p>After all, transient failures are common.</p><p>We have retry libraries, exponential backoff, circuit breakers, and resilience frameworks designed to handle them.</p><p>But consider what happens if we blindly retry this order.</p><p>The exchange might accept another order.</p><p>Now we have twice the intended exposure.</p><p>The application attempted to recover from a failure and accidentally created a larger financial position.</p><p>The real problem is that the request outcome is unknown.</p><p><strong>No response does not mean no order.</strong></p><p>This required a different approach.</p><p>Instead of assuming failure and immediately resubmitting, the engine needs to preserve the identity of the original request and reconcile its state with the exchange.</p><p>Did the order exist?</p><p>Was it rejected?</p><p>Was it partially filled?</p><p>Was it completely executed?</p><p>Until those questions are answered, the engine must treat the submission as uncertain.</p><p>This is one of the reasons I became increasingly interested in the similarities between trading systems and payment gateways.</p><p>Both interact with external systems that can perform irreversible actions.</p><p>And both must be extremely careful about retries.</p><h3>Then the Database Became Part of the Trading Problem</h3><p>Eventually, NERV Trade needed to persist its state.</p><p>Initially, that might sound like an ordinary backend requirement.</p><p>Add PostgreSQL.</p><p>Create tables.</p><p>Save orders and executions.</p><p>Restore them when the application restarts.</p><p>But there was a deeper problem.</p><p>Consider what happens when an execution arrives.</p><p>The system may need to update several related pieces of information:</p><pre>Execution received<br>        ↓<br>Record execution identity<br>        ↓<br>Update order accounting<br>        ↓<br>Update trade exposure<br>        ↓<br>Update cost basis<br>        ↓<br>Calculate realized P&amp;L<br>        ↓<br>Update lifecycle<br>        ↓<br>Record journal outcome</pre><p>Now imagine the application crashes halfway through those updates.</p><p>The execution might be recorded, but the position might not be updated.</p><p>Or the position might change while the execution identity is never persisted.</p><p>Either situation is dangerous.</p><p>In the second case, the application might process the same execution again after restarting.</p><p>The solution wasn’t simply to persist more data.</p><p>It was to establish a transaction boundary around the complete economic effect of accepting an execution.</p><p>For NERV Trade, that meant using PostgreSQL transactions to commit execution identity, accounting changes, lifecycle state, and journal outcomes together.</p><p>Either the complete operation succeeds, or it does not commit.</p><p>This was a familiar principle from enterprise application development.</p><p>But implementing it correctly required revisiting how the trading lifecycle managed state.</p><p>One of the important discoveries during development was that certain failure scenarios could leave partially mutated in-memory state.</p><p>That pushed the architecture toward stronger atomicity guarantees.</p><p>It was a reminder that persistence isn’t something you simply add at the end.</p><p><strong>The transaction boundary is part of the domain design.</strong></p><h3>The Application Crashed. The Exchange Didn’t.</h3><p>There’s another uncomfortable reality of automated trading.</p><p>Your application is temporary.</p><p>The exchange is not synchronized with your application’s lifecycle.</p><p>Your application might restart because of a deployment, infrastructure failure, process crash, or maintenance event.</p><p>Meanwhile, orders may remain active.</p><p>Executions may continue.</p><p>Account balances may change.</p><p>When the application comes back, it cannot simply assume that the world is exactly as it was before the restart.</p><p>It must recover its durable state and reconcile unresolved activity.</p><p>That includes understanding which executions were already processed, which orders remain active, and which trading lifecycles are incomplete.</p><p>This is why recovery became a first-class architectural concern in NERV Trade.</p><p>The engine needed to remember not just the latest position, but the sequence of durable facts that explained how it arrived there.</p><p>And when its local understanding was incomplete, it needed to consult the external system rather than guess.</p><h3>Why I Built a Simulator Before Connecting to Binance</h3><p>At this point, you might wonder why I didn’t simply connect the application to an exchange and start testing.</p><p>The reason is that real exchanges are terrible environments for reproducing certain failures.</p><p>How do you reliably force a partial fill?</p><p>How do you reproduce an exact sequence of duplicate executions?</p><p>How do you simulate a crash between two specific accounting operations?</p><p>How do you repeatedly test the same order lifecycle without relying on unpredictable market behavior?</p><p>A deterministic simulator gave NERV Trade a controlled environment for these scenarios.</p><p>It allowed me to test execution behavior independently of a real broker.</p><p>More importantly, it exercised the same core lifecycle concepts that an exchange adapter would eventually use.</p><p>That made the simulator much more than a strategy backtesting tool.</p><p>It became a way to validate the trading engine’s behavior under difficult conditions.</p><p>By the time we introduced the initial Binance Spot Testnet adapter, the engine already had a substantial body of tests covering analysis, lifecycle management, execution accounting, persistence, and recovery.</p><p>At that initial integration milestone, the project had <strong>601 passing tests</strong>.</p><p>That was encouraging.</p><p>But I was careful not to confuse passing tests with proof of real-exchange correctness.</p><p>At that stage, the Binance adapter had been implemented and locally verified, but live Testnet verification had not yet been completed.</p><p>A simulated exchange can demonstrate that your code behaves correctly under the scenarios you’ve modeled.</p><p>It cannot prove that you’ve modeled every relevant behavior of a real exchange.</p><p>That distinction matters.</p><h3>The Architecture Wasn’t Designed All at Once</h3><p>Looking at NERV Trade today, it’s tempting to present the architecture as though it emerged from a single design exercise.</p><p>It didn’t.</p><p>The system evolved as new problems exposed limitations in earlier decisions.</p><p>The journey looked roughly like this:</p><pre>Market Data<br>    ↓<br>Deterministic Analysis<br>    ↓<br>Multi-Timeframe Context<br>    ↓<br>Strategy and Risk<br>    ↓<br>Trade Intent<br>    ↓<br>Order Lifecycle<br>    ↓<br>Execution Accounting<br>    ↓<br>Durable Persistence<br>    ↓<br>Restart Recovery<br>    ↓<br>Broker Integration<br>    ↓<br>Reconciliation</pre><p>Each layer appeared because the previous design needed to answer a question it couldn’t yet answer reliably.</p><p>That progression is what makes the project interesting to me.</p><p>Not because it resulted in a complicated architecture.</p><p>Complexity by itself is not an achievement.</p><p>But because each additional responsibility had a concrete reason to exist.</p><p>The goal was never to build the largest possible trading system.</p><p>It was to build a system whose behavior could be understood, reproduced, and verified.</p><h3>The Most Important Lesson Wasn’t About Trading</h3><p>After working through these problems, I started thinking differently about what makes a trading engine reliable.</p><p>A trading strategy might produce excellent historical results.</p><p>That doesn’t mean the execution engine is correct.</p><p>An exchange might acknowledge an order.</p><p>That doesn’t mean the order has been filled.</p><p>A database transaction might succeed.</p><p>That doesn’t mean the application’s understanding of the exchange is current.</p><p>And hundreds of automated tests might pass.</p><p>That doesn’t mean every real-world integration assumption has been validated.</p><p>These are different dimensions of correctness.</p><p>A serious trading engine has to consider all of them.</p><p>For me, that became the most valuable part of developing NERV Trade.</p><p>The project started as an exploration of trading analysis.</p><p>It gradually became an exploration of reliable software architecture.</p><p>And many of the lessons turned out to apply far beyond trading — to payment systems, event-driven services, distributed workflows, and any application that must preserve correctness while interacting with unreliable external systems.</p><h3>Back to the Beginning</h3><p>There’s a reason I wanted to document this journey rather than simply publish the final architecture.</p><p>NERV Trade didn’t start with trade intents, durable execution identities, PostgreSQL transactions, or broker reconciliation.</p><p>It started with market data and a simple question:</p><p><em>Can we analyze the market and generate useful trading decisions?</em></p><p>Everything that followed emerged from trying to answer increasingly difficult questions about what those decisions meant and how they should be executed.</p><p>That’s the story I want to tell in this series.</p><p>Not just what we built, but why the architecture changed.</p><p>What failed.</p><p>What the tests revealed.</p><p>And what each new problem taught us.</p><p>Because the most interesting part of building a trading engine wasn’t generating the first BUY signal.</p><p><strong>It was discovering how much engineering was required to make that signal mean something reliable.</strong></p><h3>About NERV Trade</h3><p>NERV Trade is part of <strong>NERV — Next-Generation Engineering for Runtime Velocity</strong>, my Java and Spring engineering initiative.</p><p>The project explores deterministic market analysis, trading strategies, execution lifecycle management, broker integration, persistence, recovery, and operational safety.</p><p>This article is adapted from my original CzetsuyaTech post:</p><p><a href="https://www.czetsuyatech.com/2026/09/i-built-a-trading-engine-in-java.html"><strong>I Built a Trading Engine in Java — Here’s What It Took</strong></a></p><p><strong>Next in the series:</strong> <em>A Trading Bot Is Easy. A Trading Engine Is Not.</em></p><p>In the next article, we’ll return to the beginning and examine why the seemingly simple architecture of market data, analysis, and BUY/SELL signals quickly becomes insufficient.</p><p><em>This series explores software engineering and trading infrastructure. It is not financial advice.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff03c61c2975" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auditing Is Easy Until Production: What Hibernate Envers Doesn’t Solve for You]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://czetsuya.medium.com/auditing-is-easy-until-production-hibernate-envers-db7b7db0ee8a?source=rss-f795956d2899------2"><img src="https://cdn-images-1.medium.com/max/1536/1*YnAk3xnPQooXyIfb8eS4lg.png" width="1536"></a></p><p class="medium-feed-snippet">Hibernate Envers can record entity history. Building an audit system you can trust during a production incident requires much more.</p><p class="medium-feed-link"><a href="https://czetsuya.medium.com/auditing-is-easy-until-production-hibernate-envers-db7b7db0ee8a?source=rss-f795956d2899------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://czetsuya.medium.com/auditing-is-easy-until-production-hibernate-envers-db7b7db0ee8a?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/db7b7db0ee8a</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 23:16:04 GMT</pubDate>
            <atom:updated>2026-10-03T23:16:04.788Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Database Tells You What Is. An Audit Trail Tells You What Happened.]]></title>
            <link>https://czetsuya.medium.com/database-tells-you-what-is-audit-trail-tells-you-what-happened-e1d6967e905d?source=rss-f795956d2899------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1d6967e905d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[czetsuya]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 07:03:44 GMT</pubDate>
            <atom:updated>2026-09-30T07:03:44.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Su6_Uh3bVntOed2YSBz2iA.png" /><figcaption>Current state tells us what the data looks like now; audit history shows how it got there.</figcaption></figure><p><em>A production database can show you the current state of your business data. But when something goes wrong, the question you really need to answer is often: How did it get there?</em></p><p>A production support ticket comes in:</p><blockquote><strong><em>“Why is this subscription DEACTIVATED?”</em></strong></blockquote><p>It sounds like a simple question.</p><p>You query the database:</p><pre>id         = 9217<br>status     = DEACTIVATED<br>start_date = 2026-08-15<br>end_date   = 2026-08-30<br>updated_at = 2026-08-30 14:32:17</pre><p>The database answered your query perfectly.</p><p>Unfortunately, it didn’t answer the question.</p><p>You know what the subscription looks like <strong>now</strong>.</p><p>But you still don’t know:</p><ul><li>What was the previous status?</li><li>When did the transition happen?</li><li>Who or what changed it?</li><li>What else changed at the same time?</li><li>Was this a direct transition?</li><li>Or did the entity pass through several states before reaching DEACTIVATED?</li></ul><p>This distinction becomes surprisingly important when supporting production systems.</p><p><strong>The current state of your data is not its history.</strong></p><h3>The Database Isn’t the Problem</h3><p>A typical application table is designed primarily to represent the current state of a business entity.</p><p>Imagine that a subscription moves through three states:</p><pre>ACTIVE → SUSPENDED → DEACTIVATED</pre><p>If the application updates the same row for every transition, eventually the database contains:</p><pre>status = DEACTIVATED</pre><p>That’s not a failure.</p><p>The database is doing exactly what the application asked it to do.</p><p>For normal application processing, the current state is usually what matters.</p><p>But production support often asks a different question.</p><p>Not:</p><blockquote><em>What is the state of this entity?</em></blockquote><p>But:</p><blockquote><strong><em>How did this entity reach this state?</em></strong></blockquote><p>Those questions require different information.</p><h3>So We Search the Logs</h3><p>The natural next step is usually to open whatever observability platform we’re using and search for:</p><pre>subscriptionId=9217</pre><p>Sometimes we get lucky.</p><p>We find the request, follow the execution, identify the operation that changed the entity, and solve the incident.</p><p>Other times, things aren’t so simple.</p><p>The change may have happened days ago.</p><p>The relevant logs may no longer be available.</p><p>Another service may have initiated the operation.</p><p>A scheduled process might have changed the entity.</p><p>An asynchronous message may have triggered it.</p><p>Or we may find hundreds of related log entries and have to reconstruct the sequence manually.</p><p>Logs are indispensable for production support.</p><p>But logs and audit history answer different questions.</p><h3>Execution History vs. Data History</h3><p>Logs primarily describe <strong>application execution</strong>.</p><p>They help answer questions such as:</p><ul><li>Which endpoint was called?</li><li>Which operation executed?</li><li>Which exception occurred?</li><li>What did an external service return?</li><li>Which branch of the application logic ran?</li></ul><p>Distributed tracing adds another dimension by helping us follow an operation across service boundaries.</p><p>Metrics tell us about the behavior and health of the system.</p><p>But sometimes none of those directly answers the question we’re investigating:</p><blockquote><strong><em>What happened to this business entity?</em></strong></blockquote><p>That’s where audit history becomes valuable.</p><h3>Imagine Seeing the Actual Timeline</h3><p>Instead of trying to reconstruct the history from scattered telemetry, imagine opening the entity and seeing:</p><pre>Subscription #9217</pre><pre>2026-08-30 14:32</pre><pre>status<br>SUSPENDED → DEACTIVATED</pre><pre>end_date<br>null → 2026-08-30</pre><pre>changed by:<br>subscription-service<br></pre><pre>2026-08-28 09:17</pre><pre>status<br>ACTIVE → SUSPENDED</pre><pre>changed by:<br>account-service</pre><p>Now we know much more.</p><p>The subscription did not move directly from ACTIVE to DEACTIVATED.</p><p>It was first suspended.</p><p>We know when each transition occurred.</p><p>We know which fields changed together.</p><p>And if the audit metadata captures the appropriate context, we can identify the user, service, or process associated with each revision.</p><p>That doesn’t necessarily tell us <strong>why</strong> the application made the decision.</p><p>But it gives us something extremely valuable:</p><p><strong>a precise place to start investigating.</strong></p><p>Instead of searching through days of telemetry, we can ask:</p><blockquote><em>What caused the subscription to become </em><em>SUSPENDED at 09:17?</em></blockquote><p>And later:</p><blockquote><em>Why did </em><em>subscription-service move it from </em><em>SUSPENDED to </em><em>DEACTIVATED?</em></blockquote><p>Now logs and traces become much more useful because we know exactly what we’re looking for.</p><h3>Audit Trails Aren’t Just for Compliance</h3><p>When developers hear “audit trail,” compliance is often the first thing that comes to mind.</p><p>Who changed the record?</p><p>When was it changed?</p><p>Was the action authorized?</p><p>What did the record look like at a particular point in time?</p><p>Those are important requirements.</p><p>But there’s another reason I think auditability deserves more attention:</p><p><strong>production support.</strong></p><p>A good audit trail can become a debugging tool.</p><p>Think about the different questions our operational tools answer.</p><p><strong>Logs</strong></p><blockquote><em>What was the application doing?</em></blockquote><p><strong>Metrics</strong></p><blockquote><em>How was the system behaving?</em></blockquote><p><strong>Distributed tracing</strong></p><blockquote><em>How did this operation travel through the system?</em></blockquote><p><strong>Audit history</strong></p><blockquote><em>What happened to the business data?</em></blockquote><p>None of these replaces the others.</p><p>Together, however, they give us a much more complete picture of what happened inside a production system.</p><h3>Distributed Systems Make This More Important</h3><p>Modern business operations rarely happen inside a single request.</p><p>Consider something as common as processing a payment.</p><p>The flow might involve:</p><pre>Client<br>  ↓<br>API<br>  ↓<br>Payment Service<br>  ↓<br>Database<br>  ↓<br>Event<br>  ↓<br>Another Service<br>  ↓<br>External Provider</pre><p>Meanwhile, the payment itself may move through several states:</p><pre>PENDING<br>   ↓<br>PROCESSING<br>   ↓<br>AUTHORIZED<br>   ↓<br>COMPLETED</pre><p>Or perhaps:</p><pre>PENDING<br>   ↓<br>PROCESSING<br>   ↓<br>FAILED<br>   ↓<br>RETRYING<br>   ↓<br>COMPLETED</pre><p>Several services, asynchronous events, callbacks, retries, and external systems may participate.</p><p>Hours later, support receives a ticket:</p><blockquote><em>“Why did this payment end up in this state?”</em></blockquote><p>At that point, the original HTTP request may not be the most interesting part of the investigation.</p><p>The <strong>business-state transitions</strong> are.</p><h3>Storing History Isn’t Enough</h3><p>Many applications technically maintain historical information.</p><p>Maybe database triggers capture changes.</p><p>Maybe historical tables exist.</p><p>Maybe the application uses Hibernate Envers.</p><p>But there’s an important difference between:</p><p><strong>having audit data</strong></p><p>and</p><p><strong>having usable audit history.</strong></p><p>If every production investigation requires a developer to open a database client, understand an audit-table schema, correlate revision numbers, and manually compare records, then we’ve stored the history without really turning it into an application capability.</p><p>I’d rather be able to move from something like:</p><pre>Revision 42<br>Revision 43</pre><p>to:</p><pre>status:<br>PENDING → PROCESSING</pre><pre>amount:<br>100.00 → 125.00</pre><pre>changedBy:<br>payment-service</pre><pre>changedAt:<br>2026-09-01T10:31:42Z</pre><p>That’s information a developer can immediately understand.</p><p>More importantly, it’s information that could eventually be exposed through support tools, administrative interfaces, or APIs without requiring direct database access.</p><h3>This Is the Problem Behind NERV Audit</h3><p>I’ve encountered variations of this problem repeatedly while building and supporting enterprise Java applications.</p><p>Hibernate Envers already provides an excellent foundation for maintaining revision history for Hibernate entities.</p><p>But capturing revisions is only one part of the problem.</p><p>Applications still need practical ways to:</p><ul><li>retrieve historical revisions,</li><li>determine what actually changed,</li><li>attach useful revision metadata,</li><li>present field-level changes,</li><li>and expose that history to applications and support tooling.</li></ul><p>Reimplementing those capabilities for every project didn’t make much sense.</p><p>That’s one of the reasons I started building <strong>NERV Audit</strong>.</p><p>NERV Audit is an open-source auditing library for Spring Boot built on Hibernate Envers.</p><p>It doesn’t attempt to replace Envers.</p><p>Instead, it builds on top of it with a simple goal:</p><blockquote><strong><em>Make audit history easier to query, understand, and use in real applications.</em></strong></blockquote><p>This article isn’t meant to be a tutorial for the library, though.</p><p>Before getting into implementation, I want to explore the engineering problems that make this kind of capability useful in the first place.</p><p>Because auditing isn’t interesting simply because we can store old versions of a database row.</p><p>It becomes interesting when something goes wrong in production and that history helps us understand what actually happened.</p><h3>Next: Logs Aren’t an Audit Trail</h3><p>There’s another distinction worth exploring.</p><p>Application logs and audit history are sometimes treated as if they were interchangeable.</p><p>They’re not.</p><p>They have different lifecycles, different purposes, and different guarantees.</p><p>In the next article in this NERV Audit series, I’ll look at why production systems often need both.</p><p><strong>The database tells you what is.</strong></p><p><strong>An audit trail tells you what happened.</strong></p><p>And when you’re debugging business data in production, that difference can save a lot of investigation time.</p><p><em>NERV Audit is part of the open-source NERV ecosystem — reusable Java and Spring components built around problems encountered in production systems.</em></p><p><strong>GitHub:</strong> NERV Audit<br><strong>More NERV engineering articles:</strong> CzetsuyaTech</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1d6967e905d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>