<?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"><channel><title><![CDATA[Wallace Espindola | Solution Architect]]></title><description><![CDATA[Hands-on articles on Java, Spring Boot, Python, databases, security, legacy modernization and spec-driven development, each with a GitHub repo you can run.]]></description><link>https://wallaceespindola.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 01 Dec 2026 01:37:32 GMT</lastBuildDate><atom:link href="https://wallaceespindola.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Is Markdown becoming a programming language? Spec-driven development with AI]]></title><description><![CDATA[In spec-driven development with AI, the Markdown spec becomes the file that matters most: AI builds from it and reviews check against it.]]></description><link>https://wallaceespindola.hashnode.dev/is-markdown-becoming-a-programming-language-spec-driven-development-with-ai</link><guid isPermaLink="true">https://wallaceespindola.hashnode.dev/is-markdown-becoming-a-programming-language-spec-driven-development-with-ai</guid><category><![CDATA[AI]]></category><category><![CDATA[programming]]></category><category><![CDATA[markdown]]></category><category><![CDATA[Spec-Driven-Development]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Wallace Espindola]]></dc:creator><pubDate>Mon, 30 Nov 2026 23:03:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64aebca99b6f7761817ead2f/7511e0e4-b80d-41c0-9106-daca175171b6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><em>In an AI-assisted project, the most important file may not be a <code>.java</code>, <code>.ts</code> or <code>.py</code> file at all. It may be a <code>.md</code> file.</em></p>
</blockquote>
<p>The rise of AI coding assistants has changed how many of us write software.</p>
<p>Instead of manually implementing every class, endpoint, or component, we're increasingly describing <strong>what</strong> we want and letting AI generate <strong>how</strong> it's built.</p>
<p>This raises an interesting question:</p>
<blockquote>
<p><strong>If AI writes the code, what becomes the primary artifact of software engineering?</strong></p>
</blockquote>
<p>I believe the answer is <strong>the specification</strong>.</p>
<p>More specifically, I think we're moving toward a world where structured Markdown specifications become the interface between humans and AI, while source code becomes an implementation artifact.</p>
<p>This idea is commonly referred to as <strong>Spec-Driven Development (SDD)</strong>.</p>
<hr />
<h2>The Problem With Today's AI Development</h2>
<p>Most developers have experienced something like this:</p>
<pre><code class="language-plaintext">You:
Build me a user authentication system.

AI:
...generates code...

You:
Actually, I wanted JWT.

AI:
...rewrites...

You:
It also needs OAuth.

AI:
...rewrites...

You:
And multi-tenancy...

AI:
...rewrites again...
</code></pre>
<p>The AI isn't failing.</p>
<p>It's guessing.</p>
<p>Every new prompt adds context that should have existed from the beginning.</p>
<p>This is often called <em>vibe coding</em>, iteratively steering an AI toward the desired result through conversation.</p>
<p>It works surprisingly well for prototypes.</p>
<p>It doesn't scale well for complex systems.</p>
<hr />
<h2>Enter Spec-Driven Development</h2>
<p>Instead of conversations becoming the source of truth, the specification becomes the source of truth.</p>
<p>Rather than repeatedly telling the AI what you meant, you define the system once.</p>
<pre><code class="language-text">Idea
  ↓
Specification
  ↓
Architecture
  ↓
Implementation Plan
  ↓
Tasks
  ↓
Tests
  ↓
Code
  ↓
Validation
</code></pre>
<p>Every AI agent now works from the same shared understanding.</p>
<hr />
<h2>Why Markdown?</h2>
<p>Markdown is surprisingly powerful.</p>
<p>It is:</p>
<ul>
<li>readable by humans</li>
<li>version-controlled</li>
<li>diff-friendly</li>
<li>simple enough for product teams</li>
<li>structured enough for AI agents</li>
</ul>
<p>A project could look something like this:</p>
<pre><code class="language-plaintext">specs/
├── constitution.md
├── product-spec.md
├── domain-model.md
├── api-spec.md
├── security.md
├── ux-spec.md
├── acceptance-tests.md
├── implementation-plan.md
└── tasks.md
</code></pre>
<p>(Or maybe just one PRD.md -- Product Requirements Document -- is enough for you.)</p>
<p>None of these files execute.</p>
<p>Yet together they describe almost everything needed to build the software.</p>
<hr />
<h2>The Specification Becomes the Control Plane</h2>
<p>Instead of writing prompts like:</p>
<blockquote>
<p>"Create a billing API."</p>
</blockquote>
<p>You define:</p>
<ul>
<li>business objectives</li>
<li>user roles</li>
<li>domain entities</li>
<li>API contracts</li>
<li>validation rules</li>
<li>security requirements</li>
<li>performance targets</li>
<li>acceptance criteria</li>
<li>edge cases</li>
</ul>
<p>The AI now has context before writing a single line of code.</p>
<p>Less guessing.</p>
<p>More engineering.</p>
<hr />
<h2>AI Agents Become Specialists</h2>
<p>One aspect of SDD that excites me is how naturally it supports multiple AI agents working together.</p>
<p>For example:</p>
<pre><code class="language-plaintext">                 Specification
                        │
        ┌───────────────┼───────────────┐
        │               │               │
        ▼               ▼               ▼
   Planner Agent   Coding Agent   Test Agent
        │               │               │
        └───────────────┼───────────────┘
                        ▼
                Human Review
                        │
                        ▼
             Updated Specification
</code></pre>
<p>Instead of one giant conversation with a single assistant, each agent has a focused responsibility.</p>
<p>The specification becomes the shared contract between them.</p>
<hr />
<h2>This Changes the Role of Software Engineers</h2>
<p>Some people worry AI will replace software engineers.</p>
<p>I think it's changing what we optimize for.</p>
<p>The most valuable engineers may become those who excel at:</p>
<ul>
<li>system design</li>
<li>architecture</li>
<li>domain modeling</li>
<li>product thinking</li>
<li>writing precise specifications</li>
<li>reviewing AI-generated implementations</li>
<li>defining quality standards</li>
</ul>
<p>In other words:</p>
<p>We spend less time telling computers <em>how</em> to do something.</p>
<p>We spend more time defining <em>what should exist</em>.</p>
<hr />
<h2>This Doesn't Replace Programming Languages</h2>
<p>Java isn't disappearing.</p>
<p>Neither are Python, Go, Rust, TypeScript, or C#.</p>
<p>Code still matters.</p>
<p>Performance still matters.</p>
<p>Architecture still matters.</p>
<p>Human judgment still matters.</p>
<p>The difference is that code may no longer be the highest-level artifact.</p>
<p>Specifications may become the foundation from which everything else is derived.</p>
<hr />
<h2>Challenges</h2>
<p>Like every engineering approach, SDD has trade-offs.</p>
<p>Good specifications take time to write.</p>
<p>Bad specifications produce bad implementations.</p>
<p>Not every project needs this level of rigor.</p>
<p>And AI-generated code still requires review, testing, and validation.</p>
<p>Spec-Driven Development isn't about removing engineers from the process.</p>
<p>It's about giving AI enough context to become a better engineering partner.</p>
<hr />
<h2>Final Thoughts</h2>
<p>I don't think Markdown is literally becoming a programming language.</p>
<p>But I do think it's becoming something equally important:</p>
<p><strong>the language through which humans communicate software intent to AI.</strong></p>
<p>That might sound like a subtle distinction.</p>
<p>I don't think it is.</p>
<p>It changes where engineering effort is invested, how teams collaborate, and what becomes the long-term source of truth in a codebase.</p>
<p>As AI continues to improve, I expect we'll spend less time writing implementation and more time writing intent.</p>
<p>And that intent will increasingly live in structured specifications.</p>
<p>Perhaps the first file we'll create in a new project won't be:</p>
<pre><code class="language-python">main.py
</code></pre>
<p>or</p>
<pre><code class="language-java">App.java
</code></pre>
<p>It might simply be:</p>
<pre><code class="language-markdown">product-spec.md
</code></pre>
<hr />
<h2>References</h2>
<ul>
<li><p>Martin Fowler, <em>Exploring GenAI: Spec-Driven Development</em>: <a href="https://martinfowler.com/articles/exploring-gen-ai/sdd-3-tools.html">https://martinfowler.com/articles/exploring-gen-ai/sdd-3-tools.html</a></p>
</li>
<li><p>GitHub Spec Kit: <a href="https://github.com/github/spec-kit">https://github.com/github/spec-kit</a></p>
</li>
<li><p>Spec Kit Documentation: <a href="https://github.com/github/spec-kit/blob/main/spec-driven.md">https://github.com/github/spec-kit/blob/main/spec-driven.md</a></p>
</li>
<li><p>Kiro Documentation: <a href="https://kiro.dev/docs/specs/">https://kiro.dev/docs/specs/</a></p>
</li>
<li><p>Heeki Park, <em>Using Spec-Driven Development with Claude Code</em>: <a href="https://medium.com/@heekipark">https://medium.com/@heekipark</a></p>
</li>
<li><p>CJ Roth, <em>Building an Elite Engineering Culture</em>: <a href="https://www.cjroth.com/blog/2026-02-18-building-an-elite-engineering-culture">https://www.cjroth.com/blog/2026-02-18-building-an-elite-engineering-culture</a></p>
</li>
</ul>
<hr />
<h2>What do you think?</h2>
<p>Are we moving toward <strong>spec-first engineering</strong>, or do you think code will always remain the primary source of truth?</p>
<p>I'd love to hear how you're using AI in your development workflow.</p>
<hr />
<p><strong>About the author</strong></p>
<p><strong>Wallace Espindola</strong></p>
<p>Senior Software Engineer | Solution Architect | AI Enthusiast</p>
<ul>
<li>💼 LinkedIn: <a href="https://www.linkedin.com/in/wallaceespindola/">https://www.linkedin.com/in/wallaceespindola/</a></li>
<li>💻 GitHub: <a href="https://github.com/wallaceespindola">https://github.com/wallaceespindola</a></li>
<li>🌐 Website: <a href="https://wtechitsolutions.com">https://wtechitsolutions.com</a></li>
</ul>
<p>Pick one small feature and write its spec in Markdown before any code. Then let the AI build from it and see how much of the review turns into checking the spec instead of the code.</p>
]]></content:encoded></item><item><title><![CDATA[Use AI to understand legacy systems before you rewrite them]]></title><description><![CDATA[AI is most useful in legacy modernization when it helps teams understand old systems and their business rules, not when it rewrites code faster.]]></description><link>https://wallaceespindola.hashnode.dev/use-ai-to-understand-legacy-systems-before-you-rewrite-them</link><guid isPermaLink="true">https://wallaceespindola.hashnode.dev/use-ai-to-understand-legacy-systems-before-you-rewrite-them</guid><category><![CDATA[AI]]></category><category><![CDATA[legacy]]></category><category><![CDATA[modernization]]></category><category><![CDATA[architecture]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Wallace Espindola]]></dc:creator><pubDate>Mon, 30 Nov 2026 23:00:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64aebca99b6f7761817ead2f/b4743f34-28ed-45b4-9b7d-7fda8e53b57b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>TL;DR:</strong> the best use of AI in legacy modernization is not rewriting old code faster. It is understanding it better, so you can modernize safely and design a stronger architecture for what comes next.</p>
<p>When developers hear <strong>legacy modernization</strong>, the conversation often jumps immediately to technology:</p>
<ul>
<li>Which framework should replace the old one?</li>
<li>Should we move to microservices?</li>
<li>Should we migrate everything to the cloud?</li>
<li>Can AI convert the codebase for us?</li>
</ul>
<p>I think that starts the discussion too late.</p>
<p>Before rewriting anything, we should understand what the legacy system actually does.</p>
<hr />
<h2>Legacy code contains business knowledge</h2>
<p>A 15 or 20 year-old application contains more than outdated syntax.</p>
<p>It may contain business rules that were never documented, edge cases discovered through years of production incidents, integration behavior other applications depend on and workarounds nobody remembers introducing.</p>
<p>Deleting that code without understanding it can mean deleting business knowledge.</p>
<p>AI makes this discovery process much easier.</p>
<p>It can help:</p>
<ul>
<li>Explain unfamiliar code</li>
<li>Trace dependencies</li>
<li>Identify duplicated business rules</li>
<li>Analyze database access</li>
<li>Document integrations</li>
<li>Find potentially unused components</li>
<li>Generate tests around current behavior</li>
</ul>
<p>The first deliverable of modernization should therefore not necessarily be new code.</p>
<p>It should be:</p>
<p><strong>A map of the existing system.</strong></p>
<h2>Code conversion is not modernization</h2>
<p>Suppose AI converts an old application into a new language successfully.</p>
<ul>
<li>Compilation passes.</li>
<li>Tests pass.</li>
<li>The application runs.</li>
</ul>
<p>Have we modernized it? Maybe not.</p>
<p>If we preserved the same tight coupling, shared database, unclear domain boundaries and problematic dependencies, we have simply moved technical debt into a newer stack.</p>
<p>We created:</p>
<p><strong>A modern implementation of an outdated architecture.</strong></p>
<p>The problem is not whether AI can generate the replacement code.</p>
<p>Increasingly, it can.</p>
<p>The difficult question is:</p>
<p><strong>What architecture should that code implement?</strong></p>
<h2>Find business boundaries first</h2>
<p>Legacy modules frequently represent historical technical boundaries rather than real business boundaries.</p>
<p>Imagine a module named:</p>
<p><code>CustomerManagement</code></p>
<p>Inside it we might discover:</p>
<pre><code class="language-text">- Customer onboarding
- Customer identity
- Contracts
- Preferences
- Notifications
- Billing integration
</code></pre>
<p>These capabilities may not belong together in the future architecture.</p>
<ul>
<li><p>Some may need independent scaling.</p>
</li>
<li><p>Some may have stronger security requirements.</p>
</li>
<li><p>Some may change frequently while others remain stable.</p>
</li>
<li><p>Some may belong to completely different teams.</p>
</li>
</ul>
<p>AI can help discover these relationships by analyzing code, APIs (Application Programming Interfaces), databases and terminology.</p>
<p>But it should support architectural discovery, not replace architectural judgment.</p>
<hr />
<h2>Migrate incrementally</h2>
<p>I am also skeptical of Big Bang rewrites.</p>
<p>While the replacement is being built, the legacy application usually keeps changing.</p>
<ol>
<li><p>New features arrive.</p>
</li>
<li><p>Regulations change.</p>
</li>
<li><p>Bugs get fixed.</p>
</li>
<li><p>Integrations evolve.</p>
</li>
<li><p>The new platform then spends months trying to catch a moving target.</p>
</li>
</ol>
<p>A safer approach is usually incremental modernization.</p>
<p>The Strangler Fig Pattern is one example:</p>
<pre><code class="language-text">Legacy System
      ↓
Legacy + Modern Capabilities
      ↓
Mostly Modern + Remaining Legacy
      ↓
Modern Platform
</code></pre>
<p>New functionality gradually surrounds and replaces the old implementation.</p>
<p>Instead of one huge migration event, modernization becomes a sequence of smaller architectural decisions.</p>
<hr />
<h2>Use tests as the contract</h2>
<p>AI can be particularly valuable here.</p>
<p>Before replacing a component, generate characterization tests around existing behavior.</p>
<p>Then compare the new implementation against those tests.</p>
<p>A simplified workflow becomes:</p>
<pre><code class="language-text">Existing behavior
      ↓
Automated tests
      ↓
Modern implementation
      ↓
Behavior comparison
      ↓
Migration
</code></pre>
<p>For critical workloads, go further.</p>
<p>Use:</p>
<ul>
<li>Shadow traffic</li>
<li>Feature flags</li>
<li>Parallel execution</li>
<li>Output comparison</li>
<li>Controlled rollouts</li>
<li>Observability</li>
</ul>
<p>The objective is evidence, not confidence.</p>
<p>Instead of:</p>
<blockquote>
<p>“The rewrite looks correct.”</p>
</blockquote>
<p>we want:</p>
<blockquote>
<p>“The modern implementation has been validated against real legacy behavior.”</p>
</blockquote>
<hr />
<h2>Don't default to microservices</h2>
<p>Another modernization trap:</p>
<pre><code class="language-text">Legacy Monolith → Microservices → Success
</code></pre>
<p>Distributed systems introduce their own complexity: networking, observability, data consistency, deployment coordination and operational overhead.</p>
<p>A modular monolith may be a much better modernization target for many applications.</p>
<p>Extract a service when you actually need independent:</p>
<ul>
<li>Ownership</li>
<li>Scaling</li>
<li>Deployment</li>
<li>Reliability</li>
<li>Lifecycle</li>
</ul>
<p>Not because the word <em>microservice</em> appears on the target architecture diagram.</p>
<hr />
<h2>Data is usually the hard part</h2>
<p>Application code can be replaced relatively quickly.</p>
<p>Data cannot.</p>
<p>A legacy database may simultaneously support applications, reports, integrations and historical processes.</p>
<p>Modernization therefore requires explicit decisions about:</p>
<p><strong>Who owns the data?</strong></p>
<p><strong>What is the source of truth?</strong></p>
<p><strong>Do we migrate or synchronize?</strong></p>
<p><strong>Can old and new applications write simultaneously?</strong></p>
<p><strong>How do we validate migrated records?</strong></p>
<p>AI can help analyze schemas and generate migration logic.</p>
<p>It cannot make unclear data ownership disappear.</p>
<hr />
<h2>The real opportunity</h2>
<p>AI changes the economics of modernization.</p>
<p>Understanding code becomes cheaper.</p>
<p>Generating documentation becomes cheaper.</p>
<p>Creating tests becomes faster.</p>
<p>Repetitive transformation work becomes faster.</p>
<p>That allows engineers to spend more time on what matters:</p>
<p><strong>architecture, business understanding, validation, security and system design.</strong></p>
<p>So I don't think the future of legacy modernization is:</p>
<pre><code class="language-text">Old Code → AI → New Code
</code></pre>
<p>I think it is closer to:</p>
<pre><code class="language-text">Legacy Knowledge
      ↓
AI-Assisted Understanding
      ↓
Architecture Decisions
      ↓
Incremental Transformation
      ↓
Modern Platform
</code></pre>
<p>AI should not help us reproduce the past faster.</p>
<p><strong>It should help us understand the past well enough to design something better.</strong></p>
<hr />
<p>##Further Reading</p>
<p>If you're interested in exploring legacy modernization, incremental architecture and AI-assisted software engineering further, these are excellent resources:</p>
<p><a href="https://martinfowler.com/articles/2024-strangler-fig-rewrite.html">Martin Fowler - Strangler Fig Application / Rewriting Strangler Fig</a>: A foundational perspective on gradually replacing legacy systems instead of relying on risky Big Bang rewrites.</p>
<p><a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/strangler-fig.html">AWS (Amazon Web Services) Prescriptive Guidance - Strangler Fig Pattern</a>: Practical architectural guidance for incrementally decomposing and modernizing legacy applications.</p>
<p><a href="https://learn.microsoft.com/en-us/azure/app-modernization-guidance/">Microsoft Learn - Application Modernization Guidance for Azure</a>: A comprehensive modernization framework covering assessment, planning, modernization strategies, cloud adoption and AI opportunities.</p>
<p><a href="https://learn.microsoft.com/en-us/azure/app-modernization-guidance/plan/the-6-rs-of-application-modernization">Microsoft Learn - The 6 Rs of Application Modernization</a>: A useful decision framework covering Rehost, Replatform, Refactor, Rebuild, Retire and Retain.</p>
<p><a href="https://docs.github.com/en/copilot/tutorials/modernize-legacy-code">GitHub Documentation - Modernizing Legacy Code with GitHub Copilot</a>: A practical example of using AI to understand legacy code, map data flows, generate tests and progressively modernize an application.</p>
<p><a href="https://www.ibm.com/think/topics/generative-ai-for-application-modernization">IBM - Generative AI for Application Modernization</a>: An overview of how Generative AI can accelerate application assessment, transformation and modernization programs.</p>
<hr />
<p>##About the Author</p>
<p><strong>Wallace Espindola</strong> is a Senior Software Engineer | Solution Architect | AI &amp; Cloud Enthusiast. Passionate about tech.</p>
<p>💼 <a href="https://www.linkedin.com/in/wallaceespindola">Wallace's LinkedIn</a></p>
<p>💻 <a href="https://github.com/wallaceespindola">Wallace's GitHub</a></p>
<p>Before your next modernization plan, ask AI to explain one module and its business rules, then check the answer with the people who know the system. That conversation is worth more than any generated rewrite.</p>
]]></content:encoded></item><item><title><![CDATA[Share Copilot capacity without sharing accounts: the TASK.md handoff]]></title><description><![CDATA[A TASK.md handoff lets a team share GitHub Copilot capacity across per-user limits without sharing accounts or breaking the contract.]]></description><link>https://wallaceespindola.hashnode.dev/share-copilot-capacity-without-sharing-accounts-the-task-md-handoff</link><guid isPermaLink="true">https://wallaceespindola.hashnode.dev/share-copilot-capacity-without-sharing-accounts-the-task-md-handoff</guid><category><![CDATA[github copilot]]></category><category><![CDATA[AI]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Git]]></category><category><![CDATA[markdown]]></category><dc:creator><![CDATA[Wallace Espindola]]></dc:creator><pubDate>Mon, 30 Nov 2026 22:59:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64aebca99b6f7761817ead2f/5f5df5ee-5f25-4685-bbf2-a77bd46564d8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most teams get Copilot through a company contract, and each developer works against a personal limit per billing period. Usage is never even: one developer runs out early while another barely touches their allowance. Sharing accounts is not an option, but sharing the work is.</p>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/33ohpjpqe6wrfpyuzqfu.png" alt="Illustrative bar chart of per-developer Copilot credit use in one billing period: two developers hit the limit early, three have credits left over, and one has no license" /></p>
<p>A limit belongs to one user, so the leftover credits do nothing for the colleague who ran out. That's capacity the company already paid for, sitting idle. If you route work to the people who still have credits, you get more out of the same contract without buying extra seats. (If your org pools credits with no per-user caps, the credit argument is weaker, but the teammate with no license still needs a way in.)</p>
<p>The informal fix is a chat message: "can you run this through Copilot for me?" It sort of works, once. The context is half in your head, the delegate spends credits on clarifying questions, and everything Copilot learned disappears with the conversation.</p>
<p>So I wrote down a process for doing it properly. The owner of the work writes a Markdown task spec, commits it to the repo, and a teammate with spare Copilot capacity implements it. Nobody transfers tokens or shares a login, and the repo carries the context.</p>
<p>The full proposal and example files are here: <a href="https://github.com/wallaceespindola/share-tokens-using-spec-driven-dev">share-tokens-using-spec-driven-dev on GitHub</a>. This article covers the hands-on part: the files you add to a repo and how a task moves through them.</p>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/t65743e4y8ijnzao38hk.png" alt="The delegation loop in three stages: the owner writes the task spec and a reviewer checks it against the definition of ready, the delegate implements with Copilot while the owner validates and updates the spec on issues, then the owner opens the PR through the same CI/CD and quality gates" /></p>
<h2>This is spec-driven development, with a team around it</h2>
<p>If you've used <a href="https://github.com/github/spec-kit">GitHub Spec Kit</a>, the shape will look familiar. Spec-driven development makes the spec the source of truth and treats the AI as the one who implements it. This process keeps that idea and splits the steps between people:</p>
<table>
<thead>
<tr>
<th>Spec Kit step</th>
<th>Who does it here</th>
</tr>
</thead>
<tbody><tr>
<td><code>/speckit-constitution</code> (once per project)</td>
<td>Team standards in <code>/docs</code> plus <code>.github/copilot-instructions.md</code></td>
</tr>
<tr>
<td><code>/speckit-specify</code></td>
<td>Owner writes up the business requirements</td>
</tr>
<tr>
<td><code>/speckit-plan</code>, <code>/speckit-tasks</code></td>
<td>The approved <code>TASK-NNN.md</code> file</td>
</tr>
<tr>
<td><code>/speckit-implement</code></td>
<td>Delegate's Copilot session</td>
</tr>
<tr>
<td><code>/speckit-converge</code></td>
<td>Owner's validation loop, repeated until the work is accepted</td>
</tr>
</tbody></table>
<p>You don't need Spec Kit to run this. Plain Markdown files work fine. If you want the toolkit, it supports Copilot:</p>
<pre><code class="language-bash">uv tool install specify-cli
specify init my-project --integration copilot
</code></pre>
<p>In Spec Kit, you repeat implement and converge until converge reports "Converged". Here, the owner's validation plays that role.</p>
<h2>The one rule: nobody shares credentials</h2>
<p>Writing a good spec and validating the result cost zero AI credits. Implementation is where Copilot saves the most time. So the split is:</p>
<ul>
<li>The <strong>owner</strong> does the thinking and the checking: writes the task, validates the result, makes the final commit and opens the PR.</li>
<li>The <strong>delegate</strong> spends credits on the one part that benefits most: implementation, tests and docs.</li>
<li>A <strong>reviewer</strong> (architect, tech lead or another developer) approves the task before anyone spends a credit.</li>
</ul>
<p>Upstream of all three, the business side (a product owner or analyst) writes the requirements and acceptance criteria, ideally in the existing <code>docs/specs</code>.</p>
<p>The owner stays responsible for what gets merged, and the delegate never needs access they don't already have. Delegated code goes through the same review, CI/CD and quality gates as any other change.</p>
<p>Here is the whole flow, one swimlane per role:</p>
<p><img src="https://raw.githubusercontent.com/wallaceespindola/share-tokens-using-spec-driven-dev/main/docs/articles/devto/diagrams/delegation-flow.png" alt="Delegation flow across Business, Owner, Reviewer, Delegate, CI/CD and Team, with a send-back loop at review and an iteration loop at validation" /></p>
<p>There are two loops in there. A task the reviewer rejects goes back to the owner before any credits are spent. A result that fails validation goes back to the delegate, but only after the owner fixes the task file, because a retry against the same spec will usually produce the same mistake.</p>
<h2>The repo layout</h2>
<p>Everything lives in the repository. A Copilot conversation is gone when the session ends, while the files stay in git history.</p>
<pre><code class="language-text">.github/
  copilot-instructions.md          # loaded into Copilot requests in this repo
  instructions/
    tests.instructions.md          # path-specific rules (applyTo glob)
  prompts/
    implement-task.prompt.md       # the shared /implement-task prompt
  agents/
    ready-check.agent.md           # optional: reviewer persona
docs/
  ARCHITECTURE.md
  CODING_GUIDE.md
  TESTING_GUIDE.md
  specs/report-generation/design.md
  backlog/
    TASK-042-order-summary-report.md
AGENTS.md                          # same guidance for other coding agents
</code></pre>
<p>Per GitHub's docs, repository instructions go in <code>.github/copilot-instructions.md</code>, path-specific ones in <code>.github/instructions/*.instructions.md</code>, custom agents in <code>.github/agents/*.agent.md</code> and skills in <code>.github/skills/&lt;name&gt;/SKILL.md</code>. Prompt files live in <code>.github/prompts/</code> as <code>*.prompt.md</code> and are documented by VS Code. Support differs between IDEs and the cloud agent, so check the docs for the surface your delegates use.</p>
<h2>Step 1: the task file</h2>
<p>One file per task, named <code>docs/backlog/TASK-NNN-short-slug.md</code>. <code>NNN</code> is zero-padded and never reused. Each task also gets a GitHub issue labeled <code>ai-delegation</code> that links the file, so the issue board shows what is waiting and who picked up what.</p>
<p>Here is the example from the repo, <code>TASK-042-order-summary-report.md</code>:</p>
<pre><code class="language-markdown"># TASK-042: Generate order summary report

Status: Draft | Approved | In progress | In validation | Done
Owner: &lt;name&gt;
Reviewer: &lt;name&gt;
Delegate: &lt;name&gt;
Issue: &lt;link&gt;

## Objective
Generate the order summary report from normalized order records.

## Tech stack
- Java 25, Spring Boot, PostgreSQL
- Kafka where required

## Expected behavior
1. Load the report configuration.
2. Retrieve the eligible orders.
3. Generate the report.
4. Store the delivery metadata.

## Architecture constraints
- Follow ../ARCHITECTURE.md and ../CODING_GUIDE.md.
- Do not bypass the defined service boundaries.

## Acceptance criteria
- [ ] The report is generated for all eligible orders.
- [ ] The job can be restarted after a failure.
- [ ] A failed run is recorded.
- [ ] Unit tests cover the new code.
- [ ] Integration tests cover the end-to-end flow.

## Out of scope
- File transport
- Customer notification

## References
- ../TESTING_GUIDE.md
- ../specs/report-generation/design.md

## Implementation notes
Filled in by the delegate at handback.
- Changed:
- Decisions:
- Open questions:
</code></pre>
<p>A few sections pull more weight than they look like they should:</p>
<ul>
<li><strong>Out of scope</strong> keeps Copilot from wandering. Without it, "generate the report" can easily turn into "generate and email the report".</li>
<li><strong>References</strong> point at real files. The design doc for TASK-042 already describes the <code>report_run</code> table and the restart rule (skip a completed run with the same configuration and period), so the task doesn't repeat it.</li>
<li><strong>Implementation notes</strong> is empty on purpose. The delegate fills it in at handback (more on that below).</li>
</ul>
<h2>Step 2: the definition of ready</h2>
<p>Copilot burns credits fastest when it has to guess. The reviewer approves a task only when every box is ticked:</p>
<pre><code class="language-markdown">- [ ] The objective fits in one or two sentences.
- [ ] Each expected behavior is a concrete step, not a wish.
- [ ] Each acceptance criterion can be checked by a test or a visible result.
- [ ] Out of scope is listed.
- [ ] Every referenced doc exists and is current.
- [ ] Input and output examples are included where the format matters.
- [ ] No secrets, credentials or production data.
- [ ] Small enough for one session (a PR one person can review in under an hour).
</code></pre>
<p>The last item is the easiest one to skip. If the task won't fit in one reviewable PR, split it into TASK-043 and TASK-044 before anyone starts.</p>
<p>Not everything is worth delegating, either. Every delegated task pays for a spec, a review, a handoff and a validation. That overhead pays off for new endpoints, services or jobs with a clear spec, test suites for existing code, mechanical refactors across many files, and boilerplate like DTOs, mappers and migrations. Keep one-line fixes, exploratory design work and live incidents with the owner.</p>
<p>If you want help with the review, a custom agent can run the checklist. A minimal <code>.github/agents/ready-check.agent.md</code>:</p>
<pre><code class="language-markdown">---
name: ready-check
description: Checks a TASK-NNN.md file against the definition of ready before credits are spent.
---
You review task files in docs/backlog/. Do not edit code.
For the given task, check each item of the definition of ready in
docs/spec/PRD-copilot-capacity-sharing.md section 8.
Report each item as PASS or FAIL with one line of reasoning,
then list the questions the owner must answer before approval.
</code></pre>
<p><code>description</code> is the only required frontmatter field for a custom agent. The human reviewer still makes the call; the agent just catches the obvious gaps.</p>
<h2>Step 3: repository instructions</h2>
<p><code>.github/copilot-instructions.md</code> holds the conventions every request should know about, so no delegate has to re-explain them in chat:</p>
<pre><code class="language-markdown"># Copilot instructions

## Stack
Java 25, Spring Boot, Maven, PostgreSQL. Kafka only where a task says so.

## Read before changing code
- docs/ARCHITECTURE.md: service boundaries and layering (api -&gt; service -&gt; repository/client)
- docs/CODING_GUIDE.md: records for DTOs, constructor injection, 120-char lines
- docs/TESTING_GUIDE.md: JUnit 5 + Mockito, Testcontainers for integration tests

## Rules
- A layer never calls the layer above it. No business logic in controllers.
- Schema changes go through versioned migrations, never manual DDL.
- No hardcoded secrets or environment-specific values.
- Every acceptance criterion in a task maps to at least one test.
- When working from docs/backlog/TASK-*.md, stay inside its "Out of scope" limits.
</code></pre>
<p>Keep it short. It rides along with every request in the repo, so each line you add is context you pay for again and again. Rules that only matter for tests or migrations go into a path-specific file with an <code>applyTo</code> glob:</p>
<pre><code class="language-markdown">---
applyTo: "src/test/**"
---
Use JUnit 5 and Mockito. Integration tests use a real PostgreSQL via Testcontainers.
Name tests after the behavior: shouldSkipCompletedRunForSamePeriod().
Never retry a flaky test until it passes; fix it or remove it.
</code></pre>
<h2>Step 4: the shared implement-task prompt</h2>
<p>This is the file that makes every delegate run tasks the same way. Save it as <code>.github/prompts/implement-task.prompt.md</code>:</p>
<pre><code class="language-markdown">---
description: Implement a TASK-NNN.md file from docs/backlog end to end
agent: agent
argument-hint: Path to the task file, e.g. docs/backlog/TASK-042-order-summary-report.md
---
You are implementing the task in ${input:task:docs/backlog/TASK-NNN-slug.md}.

1. Read the task file and every document listed under References.
   Read .github/copilot-instructions.md conventions as binding.
2. If Status is not "Approved", stop and say so.
3. Produce a short plan: files to create or change, tests per acceptance
   criterion. Wait for my confirmation before editing.
4. Implement the plan. Respect "Architecture constraints" and "Out of scope".
5. Run the full test suite (mvn verify). Fix failures until all tests pass.
   If you fail twice on the same error, stop and explain instead of retrying.
6. Fill in "Implementation notes" in the task file:
   - Changed: files and what changed
   - Decisions: choices not dictated by the task, with reasons
   - Open questions: anything the owner must decide
7. Set Status to "In validation". Do not commit or open a PR.
</code></pre>
<p>The delegate types <code>/implement-task</code> in Copilot Chat, passes the task path, and gets the same plan-first, test-gated run every time. Step 3 makes Copilot stop after the plan, because a wrong plan caught early costs one request while a wrong implementation costs many. Step 7 keeps the commit and the PR with the owner, who is still responsible for the change.</p>
<p><code>${input:...}</code> is the prompt-file syntax for asking the user for a value, and <code>agent: agent</code> runs the prompt in agent mode so Copilot can edit files and run the build.</p>
<h2>Step 5: the handback</h2>
<p>When the delegate is done, the task file explains what happened. A filled-in section might look like this (illustrative, not from a real run):</p>
<pre><code class="language-markdown">## Implementation notes
- Changed: ReportJob, ReportRunRepository, V7__report_run.sql migration,
  ReportJobTest, ReportJobIT (Testcontainers).
- Decisions: Restart check queries report_run by configuration and period
  in SQL, per CODING_GUIDE ("filter in SQL, not in Java").
- Open questions: Should a run stuck in STARTED for more than a day count
  as failed? The design doc does not say.
</code></pre>
<p>Then the owner validates: JUnit, functional or simulation tests, the affected screens. Small issues they fix themselves. Anything bigger means updating the task file (usually that open question becomes a new acceptance criterion) and sending it back for another iteration. When it's clean, the owner commits, links the task file in the PR, and CI/CD runs its usual gates.</p>
<p>The task's <code>Status</code> line tracks all of this, and only one state spends credits:</p>
<p><img src="https://raw.githubusercontent.com/wallaceespindola/share-tokens-using-spec-driven-dev/main/docs/articles/devto/diagrams/task-lifecycle.png" alt="Task status lifecycle: Draft, Approved, In progress, In validation, Done, with send-back and iteration loops" /></p>
<p>Last step: anything worth keeping from the implementation notes (a decision, a gotcha) moves into <code>/docs</code>. If it only exists in a Copilot conversation, the next delegate won't see it.</p>
<h2>Making the delegate's credits last</h2>
<p>For background: GitHub <a href="https://github.blog/news-insights/company-news/github-copilot-is-moving-to-usage-based-billing/">announced that Copilot plans move to usage-based billing from June 1, 2026</a>, with a monthly allotment of GitHub AI Credits consumed by tokens at each model's listed rate. Code completions don't draw on credits. Agent work does. That's why session hygiene matters:</p>
<ul>
<li>One task per session, started fresh. Long sessions drag old context into every new request.</li>
<li>Reference files, don't paste them. Use <code>#file</code> or Markdown links in the prompt instead of copying code into chat.</li>
<li>Plan before editing. The <code>implement-task</code> prompt enforces this.</li>
<li>Use a cheaper model for routine steps (boilerplate, renames, simple tests) and a stronger one only for the hard parts. Model rates change, so check the current pricing in GitHub's docs rather than trusting a number in a blog post, including this one.</li>
<li>When Copilot loops, stop and fix the task. Retrying the same prompt over and over is an expensive way to find out the spec was ambiguous.</li>
</ul>
<p>The same habits help owners stretch their own small allowance.</p>
<h2>The cloud agent route</h2>
<p>Instead of working in the IDE, a delegate can assign the task's GitHub issue to the Copilot cloud agent, which works in the background and opens a draft PR. The owner then validates that draft PR exactly like a local handback. Two things to know before you do this. Per GitHub's docs, cloud agent sessions also use GitHub Actions minutes, shared with the rest of the account's workflows. And which allowance the AI usage counts against depends on how your organization bills Copilot, so check your billing setup before you count on it landing on the delegate's credits and not the owner's.</p>
<h2>Public tools worth installing</h2>
<p>All public, all installed in the repo so every delegate gets the same setup:</p>
<ul>
<li><a href="https://github.com/github/spec-kit">GitHub Spec Kit</a>. The owner can draft the spec and plan with it before turning them into a task file (mapping above).</li>
<li><a href="https://github.com/github/awesome-copilot">awesome-copilot</a>. Community instructions, prompts, custom agents and skills, including Java, Spring Boot and JUnit ones. Copy what fits rather than writing from scratch.</li>
<li><a href="https://github.com/anthropics/skills">anthropics/skills</a> and <a href="https://github.com/addyosmani/agent-skills">addyosmani/agent-skills</a>. Skills in the open Agent Skills format (spec-driven development, TDD, code review). Drop them into <code>.github/skills/&lt;name&gt;/SKILL.md</code>.</li>
<li><a href="https://github.com/github/github-mcp-server">GitHub MCP server</a>. Lets Copilot read the task's issue, linked PRs and CI results.</li>
<li><a href="https://github.com/upstash/context7">Context7</a>. Current library docs, so Copilot doesn't write against an outdated Spring Boot API.</li>
<li><a href="https://github.com/microsoft/playwright-mcp">Playwright MCP</a>. Drives the UI to check screens, which helps the delegate before handback and the owner during validation.</li>
<li>Copilot code review, for an automated first pass on the PR before the human review.</li>
</ul>
<h2>Things that will trip you up</h2>
<p><strong>Secrets in task files.</strong> A task file is committed and read by people and models. Use synthetic examples, never production data or credentials. The definition of ready has a checkbox for this; don't skip it.</p>
<p><strong>Stale references.</strong> If <code>design.md</code> describes last quarter's schema, Copilot will happily implement last quarter's schema. That is why "every referenced doc exists and is current" sits in the checklist.</p>
<p><strong>Too many iterations.</strong> If a task needs more than two round trips, it usually wasn't ready. Look at the template and the review before blaming the delegate.</p>
<p><strong>Company policy.</strong> Use Copilot inside your organization's approved AI settings (public code filtering, content exclusions). This process doesn't grant anyone access they didn't already have, and it shouldn't be used to route around policy.</p>
<h2>Recap</h2>
<ul>
<li>The owner writes <code>TASK-NNN.md</code>, a reviewer approves it against the definition of ready, and only then does a delegate spend credits.</li>
<li>A shared <code>implement-task.prompt.md</code> and <code>.github/copilot-instructions.md</code> mean every delegate runs a task the same way.</li>
<li>The delegate hands back passing tests plus filled-in implementation notes. The owner validates, commits and opens the PR.</li>
<li>No tokens, accounts or licenses move between people. Only the task file does.</li>
</ul>
<h2>Try it yourself</h2>
<p>Clone <a href="https://github.com/wallaceespindola/share-tokens-using-spec-driven-dev">the repo</a>, copy <code>docs/backlog/TASK-042-order-summary-report.md</code> as your template, add the prompt file and instructions above to <code>.github/</code>, and run one small task through the loop with a teammate. The full process, including what to measure per sprint (tasks merged, iterations per task, queue length), is in <code>docs/spec/PRD-copilot-capacity-sharing.md</code>.</p>
<p>How does your team handle uneven Copilot capacity today? Chat messages, pairing, or something more structured? I'd like to hear in the comments.</p>
<p>Try the TASK.md handoff on one feature this week. If the person with spare capacity can pick it up without a call, the format is doing its job.</p>
<p><strong>Examples repository:</strong> every example in this article (the PRD, the TASK-042 task spec, the team guides, the Copilot instructions, the prompt file and the diagrams) is in <a href="https://github.com/wallaceespindola/share-tokens-using-spec-driven-dev">https://github.com/wallaceespindola/share-tokens-using-spec-driven-dev</a>.</p>
<p>Need more tech insights?</p>
<p>Check out my GitHub, LinkedIn, and Speaker Deck.</p>
<p>Happy coding!</p>
<p>Wallace Espindola, Solution Architect</p>
<ul>
<li>GitHub: <a href="https://github.com/wallaceespindola/">https://github.com/wallaceespindola/</a></li>
<li>LinkedIn: <a href="https://www.linkedin.com/in/wallaceespindola/">https://www.linkedin.com/in/wallaceespindola/</a></li>
<li>Speaker Deck: <a href="https://speakerdeck.com/wallacese">https://speakerdeck.com/wallacese</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Strangler fig around a COBOL core: patterns that keep the mainframe honest]]></title><description><![CDATA[Strangler fig, anti-corruption layer and parallel run around a COBOL banking core, so modern Java takes over one operation at a time.]]></description><link>https://wallaceespindola.hashnode.dev/strangler-fig-around-a-cobol-core-patterns-that-keep-the-mainframe-honest</link><guid isPermaLink="true">https://wallaceespindola.hashnode.dev/strangler-fig-around-a-cobol-core-patterns-that-keep-the-mainframe-honest</guid><category><![CDATA[Java]]></category><category><![CDATA[architecture]]></category><category><![CDATA[legacy]]></category><category><![CDATA[COBOL]]></category><category><![CDATA[Microservices]]></category><dc:creator><![CDATA[Wallace Espindola]]></dc:creator><pubDate>Mon, 30 Nov 2026 22:57:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64aebca99b6f7761817ead2f/920cede1-d56f-41e0-b08c-bda23b0be810.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Picture a bank with its ledger on a COBOL core and a mobile team that needs a modern account inquiry API. A big-bang rewrite is off the table, so someone puts a facade in front of the mainframe and names the pattern: Strangler Fig. Route one operation at a time to new code and let the old system shrink.</p>
<p>That's the right starting point, and <a href="https://martinfowler.com/bliki/StranglerFigApplication.html">Martin Fowler's Strangler Fig Application page</a> explains it well. The trouble starts the day after the facade goes in. The new service has to read packed decimals out of copybook records. It has to know whether a balance is posted or only memo-posted. It has to prove it computes the same interest as the old code before anyone flips a route. And once it publishes events, it has to survive the broker delivering the same event twice.</p>
<p>That work falls to the patterns you add around the facade. This article covers the hands-on part: the Java code for three of those patterns (an anti-corruption layer, a parallel run with mismatch classification and a transactional outbox with an idempotent consumer), plus the read side you put next to them. Everything comes from a small Java 25 module in <a href="https://github.com/wallaceespindola/legacy-modernization-patterns">legacy-modernization-patterns on GitHub</a>, with no Spring and no database, so you can run it on a laptop in seconds.</p>
<p>If you want the "why" behind not rewriting legacy systems blind, I wrote about that earlier in <a href="https://dev.to/wallaceespindola/stop-rewriting-legacy-systems-use-ai-to-understand-them-first-21ba">Stop rewriting legacy systems, use AI to understand them first</a>. This one stays close to the code.</p>
<h2>The pattern map</h2>
<p>Here's where each pattern sits around the facade, and which package in the repo implements it:</p>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/3dn6u94now4yll7vnvzp.png" alt="Pattern map in three rows: routing, where clients call a strangler facade that sends shadow and canary traffic to a parallel run; the modern path, where the parallel run hands the modern result to the modern service, which writes to an outbox table in the same transaction and a relay publishes to an event bus read by an idempotent consumer; and the legacy path, where the facade sends legacy calls to the ACL in front of the COBOL core" /></p>
<p>The facade is the interception point. It starts as a pure pass-through (100% of traffic to legacy, no behavior change), and you only flip a route after the patterns below have done their job. Rolling back means changing a route, with no deployment involved.</p>
<p>The module is organized by pattern:</p>
<table>
<thead>
<tr>
<th>Package</th>
<th>Pattern</th>
<th>Main class</th>
</tr>
</thead>
<tbody><tr>
<td><code>acl</code></td>
<td>Anti-Corruption Layer</td>
<td><code>AccountTranslator</code></td>
</tr>
<tr>
<td><code>interest</code></td>
<td>Branch by Abstraction, Parallel Run</td>
<td><code>InterestCalculatorToggle</code>, <code>ParallelRun</code></td>
</tr>
<tr>
<td><code>outbox</code></td>
<td>Transactional Outbox, Idempotent Consumer</td>
<td><code>OutboxRelay</code>, <code>IdempotentConsumer</code></td>
</tr>
<tr>
<td><code>posting</code></td>
<td>Safe financial writes (unknown outcome)</td>
<td><code>SafePostingClient</code></td>
</tr>
</tbody></table>
<p>I'll skip <code>posting</code> here. It deserves its own article, and the repo has it if you're curious.</p>
<h2>Step 1: the anti-corruption layer</h2>
<p>The ACL is the boundary between the legacy world and your domain model. On a mainframe that means a few concrete jobs: EBCDIC to UTF-8, packed decimal (COMP-3) to <code>BigDecimal</code>, fixed-width copybook records to typed objects and legacy return codes to domain outcomes. The example record in the repo is 20 bytes: a 10-byte account ID, a 1-byte type flag, a 7-byte COMP-3 balance and a 2-byte return code. The ID, flag and return code are EBCDIC text (code page <code>IBM037</code>); the balance is COMP-3.</p>
<h3>Decoding COMP-3</h3>
<p>Packed decimal stores two digits per byte, one per nibble, and puts the sign in the last nibble: <code>C</code> or <code>F</code> for positive, <code>D</code> for negative. So the bytes <code>01 23 45 6C</code> with scale 2 are <code>1234.56</code>. Here's the decoder from <code>examples/account-modernization/src/main/java/com/wallaceespindola/modernization/acl/PackedDecimal.java</code>, trimmed to the main method and the sign check:</p>
<pre><code class="language-java">public static BigDecimal decode(byte[] bytes, int scale) {
    if (bytes == null || bytes.length == 0) {
        throw new IllegalArgumentException("Empty packed decimal");
    }
    BigInteger digits = BigInteger.ZERO;
    int last = bytes.length - 1;
    for (int i = 0; i &lt;= last; i++) {
        digits = append(digits, bytes[i] &gt;&gt; 4 &amp; 0xF);
        if (i &lt; last) {
            digits = append(digits, bytes[i] &amp; 0xF);
        }
    }
    boolean negative = isNegative(bytes[last] &amp; 0xF);
    return new BigDecimal(negative ? digits.negate() : digits, scale);
}

private static boolean isNegative(int signNibble) {
    return switch (signNibble) {
        case SIGN_POSITIVE_C, SIGN_POSITIVE_F -&gt; false;
        case SIGN_NEGATIVE -&gt; true;
        default -&gt; throw new IllegalArgumentException("Invalid packed sign nibble: " + signNibble);
    };
}
</code></pre>
<p>Two details matter. The high nibble of the last byte is a digit, the low nibble is the sign, which is why the loop skips the low nibble only on the last byte. And anything unexpected (a digit nibble above 9, an unknown sign) throws (the digit check lives in <code>append</code>, omitted above). You don't want a corrupt record to quietly become a balance of zero. <code>LegacyAccountRecord.parse</code> catches that exception and rethrows it as a <code>LegacyTechnicalException</code>, so callers see one kind of legacy failure.</p>
<h3>Semantic translation</h3>
<p>Once the bytes are decoded, you still have to decode the meaning. On many cores, the same balance field can hold a ledger (posted) balance or a memo-posted (pending) one, depending on a record type flag. If that flag leaks into your API, every consumer has to learn what <code>'M'</code> means, and you've just copied the legacy model into the new system.</p>
<p>Here's the translator from <code>examples/account-modernization/src/main/java/com/wallaceespindola/modernization/acl/AccountTranslator.java</code>, trimmed to the two methods:</p>
<pre><code class="language-java">public AccountLookup translate(byte[] raw) {
    LegacyAccountRecord record = LegacyAccountRecord.parse(raw);
    return switch (record.returnCode()) {
        case OK -&gt; new Found(new AccountBalance(record.accountId(), record.balance(), typeOf(record.typeFlag())));
        case NOT_FOUND -&gt; new NotFound(record.accountId());
        case BLOCKED -&gt; new Blocked(record.accountId());
        default -&gt; throw new LegacyTechnicalException("Legacy return code " + record.returnCode());
    };
}

private static BalanceType typeOf(char flag) {
    return switch (flag) {
        case LEDGER_FLAG -&gt; BalanceType.POSTED;
        case MEMO_POSTED_FLAG -&gt; BalanceType.PENDING;
        default -&gt; throw new LegacyTechnicalException("Unknown record type flag " + flag);
    };
}
</code></pre>
<p>Return codes <code>"00"</code>, <code>"04"</code> and <code>"08"</code> become <code>Found</code>, <code>NotFound</code> and <code>Blocked</code>, three records of a sealed <code>AccountLookup</code> interface, so the compiler makes callers handle each case. Flags <code>'L'</code> and <code>'M'</code> become <code>BalanceType.POSTED</code> and <code>BalanceType.PENDING</code>. Nothing named <code>typeFlag</code> or <code>returnCode</code> leaves the <code>acl</code> package.</p>
<p>A few rules I'd hold the ACL to:</p>
<ul>
<li><strong>One ACL per bounded context:</strong> an account ACL, not a "mainframe ACL" that every team adds to.</li>
<li><strong>Translation only:</strong> no business rules. Once it starts deciding things, it's a new monolith with extra latency.</li>
<li><strong>Retire it with the legacy capability:</strong> an ACL with no legacy system behind it is dead weight.</li>
</ul>
<h2>Step 2: the read side, pending and posted</h2>
<p>The first capability most teams move is account inquiry, because reads are low risk and high volume. The usual shape is change data capture (CDC) from the legacy store into a read model, with the ledger staying the system of record. That's CQRS without event sourcing: the mainframe ledger is already the write model.</p>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/vb48vc56hkbo0m7730ds.png" alt="Read-side flow in two rows: the facade sends balance reads to the account inquiry service while CDC lag is within its SLO, and falls back to a legacy call through the ACL to the COBOL ledger when it isn't; below, the ledger memo-posts during the day and hard-posts at end of day, and CDC feeds a translation step into the read model with pending and posted balances, which the inquiry service reads" /></p>
<p>The repo doesn't ship a CDC pipeline (it would need a database and a broker), but the ACL above is exactly what the translation step needs. Raw CDC records are legacy-shaped. If you write them straight into the read model, the new model inherits the old schema, flags included. So run them through the same kind of translation, and store <code>POSTED</code> and <code>PENDING</code> as separate, explicit values.</p>
<p>Many cores memo-post during the day and hard-post in the end-of-day batch, and CDC sees both. If the read model has one "balance" column, customers will watch their balance jump around at night. With pending and posted modeled explicitly, the UI can show both and nothing surprises anyone.</p>
<p>Two more things to put in place before you route reads to the new service:</p>
<ul>
<li><strong>A lag SLO with a fallback route:</strong> if CDC falls behind, the facade sends balance reads back to legacy through the ACL. That keeps the step reversible.</li>
<li><strong>Per-key ordering and dedup:</strong> partition by account ID, and drop duplicates by source log position.</li>
</ul>
<h2>Step 3: the parallel run</h2>
<p>Before the facade sends real customers to new logic, you want evidence that the new logic agrees with the old one. A parallel run computes both, compares them, records the result and serves the legacy answer. The repo does this for monthly interest, behind a Branch by Abstraction toggle with three modes: <code>LEGACY</code>, <code>SHADOW</code> and <code>MODERN</code>.</p>
<p>The two calculators disagree on purpose. The legacy one uses 30/360, truncates the intermediate result to four decimals, then rounds half-up (COBOL <code>ROUNDED</code>). The modern one uses actual days over 365 and rounds half-even. Those are exactly the differences that show up in real parallel runs: rounding mode, day-count convention and intermediate truncation.</p>
<p>Here's the core of <code>examples/account-modernization/src/main/java/com/wallaceespindola/modernization/interest/ParallelRun.java</code>, trimmed to the two methods that matter:</p>
<pre><code class="language-java">@Override
public BigDecimal monthlyInterest(BigDecimal balance, BigDecimal annualRate, YearMonth month) {
    BigDecimal legacyResult = legacy.monthlyInterest(balance, annualRate, month);
    BigDecimal modernResult = modern.monthlyInterest(balance, annualRate, month);
    BigDecimal difference = modernResult.subtract(legacyResult).abs();
    comparisons.add(new Comparison(balance, annualRate, month, legacyResult, modernResult, difference,
            classify(difference, month)));
    return legacyResult;
}

private MismatchCategory classify(BigDecimal difference, YearMonth month) {
    if (difference.signum() == 0) {
        return MismatchCategory.MATCH;
    }
    if (difference.compareTo(ONE_CENT) &lt;= 0) {
        return MismatchCategory.ROUNDING;
    }
    if (difference.compareTo(tolerance) &lt;= 0) {
        return MismatchCategory.WITHIN_TOLERANCE;
    }
    boolean oddMonthLength = month.lengthOfMonth() != DAYS_IN_LEGACY_MONTH;
    return oddMonthLength ? MismatchCategory.DAY_COUNT : MismatchCategory.UNEXPLAINED;
}
</code></pre>
<p>The last line of <code>monthlyInterest</code> is the important one: it always returns <code>legacyResult</code>. So shadow mode has no customer-visible effect. (In a real system you'd also stub notification and payment adapters on the shadow path, and enforce that in configuration.)</p>
<p>The classification is what makes the output usable. A raw list of mismatches turns into a spreadsheet nobody reads. Buckets turn it into a triage conversation: rounding noise, within tolerance, a known day-count difference or something a human has to look at. With a balance of 1000 at 5% in January, the tests show legacy at <code>4.17</code> and modern at <code>4.25</code>. The difference of <code>0.08</code> is above the one-cent tolerance, and January has 31 days, so it lands in <code>DAY_COUNT</code>, not <code>UNEXPLAINED</code>. <code>ParallelRunReport</code> then counts comparisons per category.</p>
<p>The classifier is a heuristic, and the Javadoc in the repo says so. In a real run you'd grow the categories as you explain differences (business date vs system date, time zones), and only <code>UNEXPLAINED</code> should block a cutover. Once the counts look right, the rollout goes shadow, then canary (a small segment gets the modern result while legacy is still computed and compared), then full cutover with legacy kept warm for a rollback window.</p>
<h2>Step 4: the outbox and the idempotent consumer</h2>
<p>When the new service starts owning business events (a notification, a fraud signal), it needs to change its own state and publish an event without the two drifting apart. Writing to the database and then calling the broker is a dual write, and a crash between the two loses the event or publishes one for a change that never committed.</p>
<p>The transactional outbox fixes that: the state change and an outbox row commit in one local transaction, and a relay publishes outbox rows later. The repo models the transaction with <code>InMemoryUnitOfWork</code>, which commits ledger rows and outbox rows together or not at all. The relay, from <code>examples/account-modernization/src/main/java/com/wallaceespindola/modernization/outbox/OutboxRelay.java</code>, trimmed to its one method:</p>
<pre><code class="language-java">public int relayOnce() {
    int sent = 0;
    for (OutboxEvent event : store.unpublished()) {
        try {
            publisher.publish(event);
        } catch (RuntimeException e) {
            LOG.log(Level.WARNING, "Publish failed for {0}, will retry: {1}", event.eventId(), e.getMessage());
            break;
        }
        store.markPublished(event.eventId());
        sent++;
    }
    return sent;
}
</code></pre>
<p>It stops at the first failure to keep the order, and it marks an event as published only after the broker accepted it. That second rule means a crash after <code>publish</code> and before <code>markPublished</code> sends the event again on the next run. Delivery is at-least-once, and there's no way around that on the producer side.</p>
<p>So the consumer has to make duplicates harmless. Here's <code>examples/account-modernization/src/main/java/com/wallaceespindola/modernization/outbox/IdempotentConsumer.java</code>, trimmed to the method:</p>
<pre><code class="language-java">public synchronized boolean accept(OutboxEvent event) {
    if (inbox.contains(event.eventId())) {
        return false;
    }
    handler.accept(event);
    inbox.add(event.eventId());
    return true;
}
</code></pre>
<p>The inbox is a set of processed event IDs. A redelivered event returns <code>false</code> and the handler never runs twice. In production, the inbox is a table keyed by event ID, and you insert into it in the same transaction as the consumer's own state change. Otherwise you've moved the dual-write problem from the producer to the consumer.</p>
<p>On the mainframe side, the same idea exists: write the event to a Db2 outbox table, or put it on MQ, inside the same CICS unit of work as the business update. For the relay you can poll, as the example does, or tail the outbox table with CDC, which avoids polling load and keeps commit order.</p>
<h2>Things that will trip you up</h2>
<p><strong>A leaky ACL.</strong> If a legacy field name, a return code or a record shape shows up in a new API or event, the ACL has a hole. Review contracts for it the same way you review for secrets.</p>
<p><strong>Rounding that isn't a bug.</strong> COBOL <code>ROUNDED</code> is half-up by default, while Java's <code>BigDecimal</code> needs an explicit <code>RoundingMode</code>. Plenty of "mismatches" in a parallel run come from this one line, so classify them as a group instead of chasing them one by one.</p>
<p><strong>Shadow traffic with side effects.</strong> A shadow path that sends a real notification or books a real entry is worse than no parallel run. Stub every adapter with a side effect, and enforce it in configuration so it doesn't depend on someone catching it in review.</p>
<p><strong>A consumer that is "mostly" idempotent.</strong> An inbox that is updated after the handler commits, in a separate transaction, will process a duplicate eventually. Write the inbox row in the same transaction as the handler's changes.</p>
<p><strong>The perpetual strangler.</strong> Facades, ACLs, CDC pipelines and parallel-run harnesses are transitional architecture. Each one needs a removal date, or you end up running and paying for both stacks indefinitely. <a href="https://martinfowler.com/articles/patterns-legacy-displacement/">Patterns of Legacy Displacement</a> by Ian Cartwright, Rob Horn and James Lewis calls this out well.</p>
<h2>Where it doesn't pay off</h2>
<p>This toolkit has a cost: you build, run and later delete everything in it. If the legacy capability is small enough to replace in one well-tested release, coexistence may cost more than the cutover. If it's stable, cheap to run and not blocking anyone, retaining it behind an API is a good outcome. And if there's no interception point at all (no API, queue or data boundary), the facade has nowhere to go, so you start with event interception or encapsulation first. There's no adoption data here. Choose the patterns per capability, and add each one only where it solves a problem you actually have.</p>
<h2>Recap</h2>
<ul>
<li>The strangler facade decides where traffic goes. It starts as a pass-through and every flip is a routing change you can undo.</li>
<li>The ACL decodes COMP-3 and EBCDIC, but its real job is semantics: return codes become domain outcomes, flags become <code>POSTED</code> and <code>PENDING</code>.</li>
<li>The read side keeps pending and posted apart, has a lag SLO and falls back to legacy when it's behind.</li>
<li>The parallel run serves the legacy answer, compares and classifies, so you triage categories instead of rows.</li>
<li>The outbox gives you at-least-once publishing without dual writes, and the idempotent consumer makes the "at least" part safe.</li>
</ul>
<h2>Try it yourself</h2>
<p>You need Java 25 and Maven. Clone <a href="https://github.com/wallaceespindola/legacy-modernization-patterns">the repo</a> and run the build:</p>
<pre><code class="language-bash">cd examples/account-modernization &amp;&amp; mvn verify
</code></pre>
<p>All 36 tests should pass in a few seconds. Good places to start reading are <code>PackedDecimalTest</code> (the byte-level examples), <code>ParallelRunTest</code> (the classification cases, including the <code>4.17</code> vs <code>4.25</code> one) and <code>OutboxTest</code> (a broker that fails, then recovers and gets the same event again). Then pass a tolerance of <code>0.10</code> to <code>ParallelRun</code> and rerun the January case: the <code>0.08</code> <code>DAY_COUNT</code> gap becomes <code>WITHIN_TOLERANCE</code>. The pattern catalog behind the code, including the phases and exit criteria, is in <a href="https://github.com/wallaceespindola/legacy-modernization-patterns/blob/main/docs/legacy-modernization-patterns-context.md">docs/legacy-modernization-patterns-context.md</a>.</p>
<p>Which of these patterns did your team find hardest to get right around a legacy core: the ACL, the parallel run or the outbox? I'd like to hear in the comments.</p>
<p>Start with one read-only operation, run it in parallel against the core and compare every response. When the differences reach zero and stay there, route it, then pick the next one.</p>
<p><strong>Examples repository:</strong> <a href="https://github.com/wallaceespindola/legacy-modernization-patterns">https://github.com/wallaceespindola/legacy-modernization-patterns</a></p>
<p>Need more tech insights?</p>
<p>Check out my GitHub, LinkedIn, and Speaker Deck.</p>
<p>Happy coding!</p>
<p>Wallace Espindola, Solution Architect</p>
<ul>
<li>GitHub: <a href="https://github.com/wallaceespindola/">https://github.com/wallaceespindola/</a></li>
<li>LinkedIn: <a href="https://www.linkedin.com/in/wallaceespindola/">https://www.linkedin.com/in/wallaceespindola/</a></li>
<li>Speaker Deck: <a href="https://speakerdeck.com/wallacese">https://speakerdeck.com/wallacese</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Before you port that COBOL to Java, write characterization tests]]></title><description><![CDATA[Characterization tests pin down what a COBOL interest calculation really does, so the Java port can be proven equal before it replaces the mainframe.]]></description><link>https://wallaceespindola.hashnode.dev/before-you-port-that-cobol-to-java-write-characterization-tests</link><guid isPermaLink="true">https://wallaceespindola.hashnode.dev/before-you-port-that-cobol-to-java-write-characterization-tests</guid><category><![CDATA[COBOL]]></category><category><![CDATA[Java]]></category><category><![CDATA[Testing]]></category><category><![CDATA[legacy]]></category><category><![CDATA[banking]]></category><dc:creator><![CDATA[Wallace Espindola]]></dc:creator><pubDate>Mon, 30 Nov 2026 22:54:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64aebca99b6f7761817ead2f/dd3285a7-7bc8-447a-ad49-c36ba3bbbfcd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Moving a bank's monthly interest calculation off the mainframe sounds small. The COBOL program is short, the logic looks like one line of arithmetic, and someone will say it can be ported in an afternoon. They are right that the port compiles in an afternoon, and the unit tests written for it will pass. Whether it matches what the mainframe really does is another question.</p>
<p>That cent sums up the trouble with legacy banking code. The rules live in the code rather than in a document, and the code carries semantics (truncation, packed decimal, implied decimal points) that a reasonable-looking Java port changes without anyone noticing. So before you port anything, you pin down what the legacy system actually does and make it the judge.</p>
<p>This article covers the hands-on part: the files you read, the files you add and the commands you run to put one COBOL rule under characterization tests, port it to Java 25 and prove the port is equivalent. Everything is in the companion repo, <a href="https://github.com/wallaceespindola/banking-modernization-with-ai">banking-modernization-with-ai on GitHub</a>. The COBOL in there is illustrative (it isn't compiled), and the Java module is real and runs with <code>make test</code>.</p>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/jeobgvulrj0vbrjk99ih.png" alt="The modernization loop in three stages: understand the legacy estate by discovering it and extracting rules, prove and move by characterizing, modernizing one slice and verifying it, then cut over and decommission, with breaks going back to the rules" /></p>
<p>The diagram is the whole loop the repo describes. This article lives in the middle of it: extract one rule, characterize it, port it, verify it.</p>
<h2>What's in the repo</h2>
<p>These are the files you'll touch, in the order you'll touch them:</p>
<pre><code class="language-text">examples/cobol/
  ACCTREC.cpy                       # account record layout (copybook)
  INTCALC.cbl                       # monthly interest, rule BR-INT-001
docs/templates/
  rule-catalog-entry.md             # catalog template + BR-INT-001 entry
examples/java/src/main/java/com/wtechitsolutions/bankingmodernization/
  PackedDecimal.java                # COMP-3 decoder
  InterestRule.java                 # legacy-equivalent port + naive port
  Reconciler.java                   # zero-tolerance, per-account compare
examples/java/src/test/
  java/.../InterestRuleGoldenMasterTest.java
  resources/golden/monthly-interest.csv
</code></pre>
<p>You need Java 25 and Maven for the Java part. Nothing else.</p>
<h2>Step 1: read the copybook before the program</h2>
<p>Start with the copybook, not the program. In COBOL, the copybook is the data contract, and it's usually shared. The header comment in <code>ACCTREC.cpy</code> says it plainly: changing it is an interface change for every program that <code>COPY</code>s it. Here are the fields that matter for interest:</p>
<pre><code class="language-cobol">       01  ACCT-REC.
           05  ACCT-ID                 PIC X(8).
           05  ACCT-STATUS             PIC X(1).
               88  ACCT-ACTIVE                   VALUE 'A'.
               88  ACCT-CLOSED                   VALUE 'C'.
           05  ACCT-BALANCE            PIC S9(11)V99 COMP-3.
           05  ACCT-ANNUAL-RATE        PIC S9(3)V99  COMP-3.
           05  ACCT-OPEN-DATE          PIC 9(7).
      *        Julian date CCYYDDD
</code></pre>
<p>Three things in there will bite a naive port. <code>S9(11)V99</code> means signed, eleven integer digits and two decimals, but the <code>V</code> is an implied decimal point: it isn't stored anywhere in the bytes. <code>COMP-3</code> means packed decimal, so you can't read the field as text. And the open date is a Julian <code>CCYYDDD</code>, which isn't used by this rule but will be by the next one. (The 88-levels are named conditions, so <code>IF ACCT-ACTIVE</code> in the program means <code>ACCT-STATUS = 'A'</code>.)</p>
<p>Now the program. The rule itself is one statement in paragraph <code>2000-CALC-INTEREST</code> of <code>INTCALC.cbl</code>:</p>
<pre><code class="language-cobol">       2000-CALC-INTEREST.
           IF ACCT-ACTIVE
      *        No ROUNDED phrase: the result is truncated to two decimals.
               COMPUTE WS-MONTHLY-INT =
                   ACCT-BALANCE * ACCT-ANNUAL-RATE / 1200
           ELSE
               MOVE ZERO TO WS-MONTHLY-INT
           END-IF.
</code></pre>
<p>The detail you're looking for is what's missing. There's no <code>ROUNDED</code> phrase on the <code>COMPUTE</code>, so COBOL truncates the result to the two decimals of the receiving field <code>WS-MONTHLY-INT PIC S9(11)V99</code>. Truncation goes toward zero, which matters for negative balances. A real legacy program wouldn't have that helpful comment, which is why you read the statement and not the comments.</p>
<h2>Step 2: decode COMP-3 into BigDecimal</h2>
<p>You can't compare legacy and modern results until you can read the legacy data. Packed decimal stores two digits per byte, one per nibble, and the last nibble is the sign: <code>C</code> for positive, <code>D</code> for negative, <code>F</code> for unsigned. The scale isn't in the bytes at all. It comes from the <code>PIC</code> clause, so <code>PIC S9(3)V99 COMP-3</code> has scale 2 and the value +123.45 is stored as <code>12 34 5C</code>.</p>
<p>Here is the decoder, trimmed from <code>PackedDecimal.java</code> in the repo:</p>
<pre><code class="language-java">public static BigDecimal decode(byte[] field, int scale) {
    if (field == null || field.length == 0) {
        throw new IllegalArgumentException("Packed decimal field is empty");
    }
    StringBuilder digits = new StringBuilder(field.length * 2);
    for (int i = 0; i &lt; field.length; i++) {
        int high = (field[i] &gt;&gt; 4) &amp; 0x0F;
        int low = field[i] &amp; 0x0F;
        digits.append(digit(high, i));
        if (i &lt; field.length - 1) {
            digits.append(digit(low, i));
        } else {
            return signed(new BigInteger(digits.toString()), low).movePointLeft(scale).setScale(scale);
        }
    }
    throw new IllegalStateException("unreachable");
}
</code></pre>
<p>Two choices in there are deliberate. The caller passes the scale, because only the copybook knows it. And the decoder throws on a digit nibble above 9 or an unknown sign nibble instead of guessing, because a corrupt field should stop a migration run, not turn into a plausible number. <code>PackedDecimalTest</code> covers positive, negative, unsigned (<code>05 0F</code> with scale 2 is <code>0.50</code>) and both invalid cases.</p>
<h2>Step 3: write the rule catalog entry</h2>
<p>Before any Java, write down the rule in a form a domain expert can confirm. The repo has a template in <code>docs/templates/rule-catalog-entry.md</code> and a filled-in entry for this rule. Trimmed from the repo:</p>
<pre><code class="language-markdown">## BR-INT-001: Monthly interest accrual

- Status: validated
- Capability: Interest accrual
- Source: `examples/cobol/INTCALC.cbl`, paragraph `2000-CALC-INTEREST`; copybook `examples/cobol/ACCTREC.cpy`
- Plain-language rule: for an active account, monthly interest is the balance times the annual rate in percent, divided by 1200. Closed accounts accrue nothing.
- Inputs: `ACCT-BALANCE PIC S9(11)V99 COMP-3`, `ACCT-ANNUAL-RATE PIC S9(3)V99 COMP-3`, `ACCT-STATUS PIC X(1)`
- Output: `WS-MONTHLY-INT PIC S9(11)V99 COMP-3`
- Arithmetic: no `ROUNDED` phrase, so the result is truncated toward zero to two decimals. Intermediate precision depends on compiler options and is pinned by the characterization tests.
- Edge cases: negative balances (overdraft interest, truncated toward zero), zero balance, sub-cent results, maximum balance
- Characterization tests: `examples/java/src/test/java/com/wtechitsolutions/bankingmodernization/InterestRuleGoldenMasterTest.java`, data in `examples/java/src/test/resources/golden/monthly-interest.csv`
- Modern implementation: `examples/java/src/main/java/com/wtechitsolutions/bankingmodernization/InterestRule.java`
</code></pre>
<p>The Arithmetic line is the one that saves you. It turns "the code divides by 1200" into "the code truncates toward zero to two decimals", which is a statement someone can agree or disagree with. The Edge cases line drives the test data in the next step.</p>
<p>This is also where AI is most useful in the workflow. An assistant can read the program and draft this entry quickly, with the source link and paragraph or line range. It can't approve it. The template keeps a status field (candidate, in review, validated, rejected) and an "Approved by" field for a reason: AI proposes, a named domain expert signs off, and the entry isn't done until it links to the tests that prove the port matches.</p>
<h2>Step 4: capture the golden master</h2>
<p>A golden master (or characterization test, in Michael Feathers' terms from <a href="https://www.oreilly.com/library/view/working-effectively-with/0131177052/">Working Effectively with Legacy Code</a>) records what the legacy system outputs for a set of inputs, without judging whether it's right. The legacy system is the test oracle, and it outranks the spec, the model and your own reading of the code.</p>
<p>In a real migration you'd run the legacy batch against representative and edge-case inputs (masked, never raw production data) and save the outputs. The repo can't do that, so its CSV is an illustrative fixture worked out by hand from the COBOL semantics, not captured from a real bank. Here it is, <code>src/test/resources/golden/monthly-interest.csv</code>:</p>
<pre><code class="language-csv">account,balance,annual_rate_percent,legacy_monthly_interest
ACC-0001,1000.00,5.00,4.16
ACC-0002,2500.00,3.75,7.81
ACC-0003,1234.56,2.50,2.57
ACC-0004,999999.99,4.10,3416.66
ACC-0005,0.01,5.00,0.00
ACC-0006,-150.00,18.00,-2.25
ACC-0007,-100.00,19.99,-1.66
ACC-0008,0.00,7.25,0.00
</code></pre>
<p>Most rows map to an edge case from the catalog entry: a sub-cent result (<code>ACC-0005</code>), a zero balance (<code>ACC-0008</code>), a large balance (<code>ACC-0004</code>) and two overdrafts (<code>ACC-0006</code>, <code>ACC-0007</code>). The others (<code>ACC-0001</code>, <code>ACC-0002</code>, <code>ACC-0003</code>) are baseline cases. Look at <code>ACC-0001</code>: 1000.00 times 5.00 divided by 1200 is 4.1666..., and truncation makes the legacy answer 4.16 where rounding would give 4.17.</p>
<h2>Step 5: port the rule with the right RoundingMode</h2>
<p>Now you write Java. Money is <code>BigDecimal</code> with an explicit scale and an explicit <code>RoundingMode</code>, never <code>double</code>. <code>InterestRule.java</code> holds two versions of the rule on purpose:</p>
<pre><code class="language-java">/** Legacy-equivalent result: truncation toward zero, like COBOL without {@code ROUNDED}. */
public static BigDecimal monthlyInterest(BigDecimal balance, BigDecimal annualRatePercent) {
    // One division on an exact product. If the compiler used a smaller intermediate precision
    // (ARITH option), pin that from the characterization tests before changing this line.
    return balance.multiply(annualRatePercent).divide(MONTHS_TIMES_PERCENT, MONEY_SCALE, RoundingMode.DOWN);
}

/** The port a reviewer would accept at first glance: banker's rounding. Kept to show the break. */
public static BigDecimal monthlyInterestNaivePort(BigDecimal balance, BigDecimal annualRatePercent) {
    return balance.multiply(annualRatePercent).divide(MONTHS_TIMES_PERCENT, MONEY_SCALE, RoundingMode.HALF_EVEN);
}
</code></pre>
<p><code>RoundingMode.DOWN</code> in Java rounds toward zero, which matches COBOL truncation for both positive and negative values. (<code>FLOOR</code> would not: it turns -1.6658... into -1.67.) <code>MONTHS_TIMES_PERCENT</code> is <code>1200</code> and <code>MONEY_SCALE</code> is <code>2</code>, so the scale of the receiving field is explicit in the code, just like the <code>PIC</code> clause.</p>
<p>The naive port uses <code>HALF_EVEN</code>, banker's rounding. It isn't a silly choice. It reads as more "correct" than truncation, and a reviewer could easily approve it, which is why the repo keeps it.</p>
<h2>Step 6: reconcile against the golden master</h2>
<p>A test that compares one value at a time tells you a row failed. A reconciler tells you which accounts broke, by how much and whether the totals agree. That's the shape of the report a business owner will read: <code>Reconciler.Report</code> carries the breaks plus <code>legacyTotal</code> and <code>modernTotal</code>, and it only counts as equivalent when there are no breaks and the totals match. <code>Reconciler.java</code> compares legacy and modern results per account with zero tolerance. The core loop, trimmed from the repo:</p>
<pre><code class="language-java">for (String account : accounts) {
    BigDecimal l = legacy.get(account);
    BigDecimal m = modern.get(account);
    if (l == null) {
        breaks.add(new Break(account, null, m, "missing in legacy"));
    } else if (m == null) {
        breaks.add(new Break(account, l, null, "missing in modern"));
    } else if (l.compareTo(m) != 0) {
        breaks.add(new Break(account, l, m, "amount differs by " + m.subtract(l).toPlainString()));
    }
}
</code></pre>
<p>It uses <code>compareTo</code>, not <code>equals</code>, because <code>BigDecimal.equals</code> treats <code>10.0</code> and <code>10.00</code> as different. An account present on only one side is a break too. A missing record is a worse problem than a wrong cent.</p>
<p>The golden-master test ties it together. Trimmed from <code>InterestRuleGoldenMasterTest.java</code>:</p>
<pre><code class="language-java">@ParameterizedTest(name = "{0}: {1} at {2}% -&gt; {3}")
@CsvFileSource(resources = GOLDEN, numLinesToSkip = 1)
void matchesLegacyOutputToTheCent(String account, BigDecimal balance, BigDecimal rate, BigDecimal expected) {
    assertEquals(expected, InterestRule.monthlyInterest(balance, rate), account);
}

@Test
void portReconcilesWithLegacyRun() {
    Reconciler.Report report = reconcileAgainstGolden(InterestRule::monthlyInterest);

    assertTrue(report.equivalent(), () -&gt; "Breaks: " + report.breaks());
}

@Test
void naivePortWithBankersRoundingProducesBreaks() {
    Reconciler.Report report = reconcileAgainstGolden(InterestRule::monthlyInterestNaivePort);

    assertFalse(report.equivalent());
    assertEquals(List.of("ACC-0001", "ACC-0004", "ACC-0007"), report.breaks().stream().map(Reconciler.Break::accountId).toList());
}
</code></pre>
<p>The parameterized test runs once per CSV row, so each account shows up by name in the test report. The other two tests run the whole file through the reconciler, once with the real port and once with the naive one.</p>
<p>Here's the loop those tests implement:</p>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/yy5ut54v5012ads4o6fl.png" alt="Golden-master loop: the legacy batch run produces the golden master CSV, which feeds the reconciler its expected values; the BR-INT-001 catalog entry is ported to InterestRule.java with RoundingMode.DOWN, the reconciler checks it with zero tolerance per account, equivalent results let the slice move on, and a dashed arrow sends breaks back to the catalog entry" /></p>
<p>Follow the dotted arrow when the reconciler reports a break. You don't patch the Java until the numbers match. You go back to the catalog entry, find out which rule you misunderstood, get it confirmed and then fix the port.</p>
<h2>Step 7: run it and watch the naive port fail</h2>
<p>From the repo root:</p>
<pre><code class="language-bash">make test
</code></pre>
<p>That runs <code>mvn -q test</code> in <code>examples/java</code>, so it's quiet when everything passes. Run Maven without <code>-q</code> to see the counts. Trimmed Surefire output:</p>
<pre><code class="language-bash">cd examples/java &amp;&amp; mvn test
</code></pre>
<pre><code class="language-text">[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, ... in com.wtechitsolutions.bankingmodernization.PackedDecimalTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, ... in com.wtechitsolutions.bankingmodernization.ReconcilerTest
[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, ... in com.wtechitsolutions.bankingmodernization.InterestRuleGoldenMasterTest
[INFO] Tests run: 17, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
</code></pre>
<p>All 17 pass, and one of them passes because the naive port fails. With <code>HALF_EVEN</code>, three of the eight accounts break:</p>
<table>
<thead>
<tr>
<th>Account</th>
<th>Legacy</th>
<th>Naive port</th>
</tr>
</thead>
<tbody><tr>
<td>ACC-0001</td>
<td>4.16</td>
<td>4.17</td>
</tr>
<tr>
<td>ACC-0004</td>
<td>3416.66</td>
<td>3416.67</td>
</tr>
<tr>
<td>ACC-0007</td>
<td>-1.66</td>
<td>-1.67</td>
</tr>
</tbody></table>
<p>Each break is one cent, on a fixture of eight rows. Across a real portfolio and a monthly cycle, that's the kind of difference that turns up in a ledger reconciliation weeks after go-live, when it's much harder to explain. If you want to see it fail in the other direction, change <code>RoundingMode.DOWN</code> to <code>HALF_EVEN</code> in <code>monthlyInterest</code> and run the tests again: <code>matchesLegacyOutputToTheCent</code> and <code>portReconcilesWithLegacyRun</code> go red with the same three accounts.</p>
<h2>Things that will trip you up</h2>
<p><strong>Intermediate precision.</strong> The Java port computes the exact product and does one division. A COBOL compiler can carry a different intermediate precision depending on its options (the comment in the repo calls it the <code>ARITH</code> option). The catalog entry says that precision is pinned by the characterization tests, and the comment in <code>InterestRule</code> says the same: if real legacy outputs disagree with the exact calculation, the golden master wins and you change the Java to match.</p>
<p><strong>Hand-made golden data.</strong> The repo's CSV was worked out by hand, which is fine for showing the technique and not fine for a migration. In real work the golden master comes from running the legacy system, on masked inputs, and it covers month-end and the edge cases the domain expert names.</p>
<p><strong>Copybooks beyond this one.</strong> <code>ACCTREC.cpy</code> is deliberately simple. Real ones bring <code>REDEFINES</code>, <code>OCCURS DEPENDING ON</code>, signed zoned decimal and EBCDIC collation that sorts differently from ASCII. Each one needs its own decoder and its own tests before you trust a comparison.</p>
<p><strong>Equals on BigDecimal.</strong> Using <code>equals</code> instead of <code>compareTo</code> is an easy way to make a reconciler report breaks that aren't there. <code>ReconcilerTest.equalAmountsWithDifferentScaleAreNotABreak</code> is there to keep it honest.</p>
<h2>What it costs and what it misses</h2>
<p>Characterization tests cost something: you need access to the legacy system to run it, masked test data, a domain expert's time for the catalog entry and someone who can read COBOL well enough to spot a missing <code>ROUNDED</code>. For one rule that's manageable. Across a whole estate it's a large share of the work, so plan for it.</p>
<p>They also don't tell you the legacy behavior is right. A golden master pins what the system does, bugs included. If the expert looks at the overdraft rows and says "that was never intended", you've found a business decision, and someone has to own the change.</p>
<p>And they don't cover everything. A per-record golden master won't catch batch semantics like checkpoint and restart, cut-off times or "exactly once per business date". Those need record-and-replay, parallel runs over at least one full business cycle and reconciliation at the account and general-ledger level, which the <a href="https://github.com/wallaceespindola/banking-modernization-with-ai/blob/main/docs/banking-modernization-with-ai-context.md">context file in the repo</a> lays out in its testing section. For a rule that will be retired instead of ported, skip all of this.</p>
<h2>Recap</h2>
<ul>
<li>Read the copybook first. <code>PIC S9(11)V99 COMP-3</code> tells you the sign, the scale and the storage format, none of which are in the bytes as text.</li>
<li>Decode <code>COMP-3</code> with the scale from the <code>PIC</code> clause, and fail loudly on bad nibbles.</li>
<li>Write the rule catalog entry before the code, with the arithmetic spelled out. AI can draft it, an expert approves it.</li>
<li>Capture the golden master from the legacy system and treat it as the oracle.</li>
<li>Port with <code>BigDecimal</code> and the <code>RoundingMode</code> the legacy code implies: <code>DOWN</code> for COBOL without <code>ROUNDED</code>.</li>
<li>Reconcile per account with zero tolerance, and send breaks back to the catalog entry.</li>
</ul>
<h2>Try it yourself</h2>
<p>Clone <a href="https://github.com/wallaceespindola/banking-modernization-with-ai">the repo</a>, run <code>make test</code>, then flip the <code>RoundingMode</code> in <code>InterestRule.monthlyInterest</code> and watch the reconciler name the three accounts. After that, add a row to <code>monthly-interest.csv</code> for a case the fixture doesn't cover (a closed account, or the maximum balance <code>PIC S9(11)V99</code> allows), work out the legacy answer from the COBOL semantics and see whether the port agrees.</p>
<p>Which COBOL arithmetic detail has caught you out in a port, rounding, intermediate precision or something in a copybook? I'd like to hear in the comments.</p>
<p>Pin the old behavior down before you change anything. Once the golden master is in place, the port stops being a matter of opinion and becomes a test that either passes or tells you exactly which account differs.</p>
<p><strong>Examples repository:</strong> every example in this article (the <code>ACCTREC</code> copybook, the <code>INTCALC</code> program, the BR-INT-001 catalog entry, the COMP-3 decoder, the interest rule and its naive port, the reconciler, the golden-master test and CSV and the diagrams) is in <a href="https://github.com/wallaceespindola/banking-modernization-with-ai">https://github.com/wallaceespindola/banking-modernization-with-ai</a>.</p>
<p>Need more tech insights?  </p>
<p>Check out my GitHub, LinkedIn, and Speaker Deck.</p>
<p>Happy coding!</p>
<p>Wallace Espindola, Solution Architect</p>
<p>GitHub: <a href="https://github.com/wallaceespindola/">https://github.com/wallaceespindola/</a></p>
<p>LinkedIn: <a href="https://www.linkedin.com/in/wallaceespindola/">https://www.linkedin.com/in/wallaceespindola/</a></p>
<p>Speaker Deck: <a href="https://speakerdeck.com/wallacese">https://speakerdeck.com/wallacese</a></p>
]]></content:encoded></item><item><title><![CDATA[Flyway or Liquibase? I built the same schema with both and diffed it]]></title><description><![CDATA[Flyway vs Liquibase compared by building one schema with both tools on two databases and diffing the results, not trusting feature tables.]]></description><link>https://wallaceespindola.hashnode.dev/flyway-or-liquibase-i-built-the-same-schema-with-both-and-diffed-it</link><guid isPermaLink="true">https://wallaceespindola.hashnode.dev/flyway-or-liquibase-i-built-the-same-schema-with-both-and-diffed-it</guid><category><![CDATA[Java]]></category><category><![CDATA[spring-boot]]></category><category><![CDATA[database]]></category><category><![CDATA[Devops]]></category><category><![CDATA[flyway]]></category><dc:creator><![CDATA[Wallace Espindola]]></dc:creator><pubDate>Mon, 30 Nov 2026 22:48:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64aebca99b6f7761817ead2f/c55db6dd-4eaa-4bab-b1db-12cfb4c5df58.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Flyway vs Liquibase comparisons usually come as feature tables, and most of them agree on the headline: Flyway is simpler, Liquibase does rollback. What they leave out are the details you only see once both tools run inside a real application, such as which one records how long a migration took, which one records who wrote it, and how you read that history back at runtime.</p>
<p>So I built the comparison as code. One Spring Boot application, two H2 databases, the same logical schema written once for each engine, and an endpoint that reads both schemas back from <code>INFORMATION_SCHEMA</code> and reports whether they match. The full project is here: <a href="https://github.com/wallaceespindola/flyway-vs-liquibase-db-migrations">flyway-vs-liquibase-db-migrations on GitHub</a>.</p>
<p>This article covers the hands-on part: the files you add for each engine, how they are wired without auto-configuration, and the commands to check the result yourself. Every snippet is copied from the repo, trimmed where noted.</p>
<h2>What you are building</h2>
<p>The stack is Java 25, Spring Boot 4.1.2, plain JDBC and Maven. The engine versions come from the Spring Boot BOM rather than from pinned properties, so both tools are on whatever Spring Boot itself tests: Flyway 12.4.0, Liquibase 5.0.4 and H2 2.4.240.</p>
<p><img src="https://raw.githubusercontent.com/wallaceespindola/flyway-vs-liquibase-db-migrations/db37e3c/docs/articles/devto/diagrams/two-engines-overview.png" alt="Two H2 databases side by side: FlywayConfig migrates ./data/flywaydb from the six scripts in db/migration, LiquibaseConfig migrates ./data/liquibasedb from the master changelog, and ComparisonService reads both through INFORMATION_SCHEMA to answer GET /api/v1/comparison" /></p>
<p>The rule the whole project rests on: <code>./data/flywaydb</code> belongs to Flyway, <code>./data/liquibasedb</code> belongs to Liquibase, and neither engine ever touches the other's database. Share a single database between them and whichever engine runs second sees a schema that already exists, which makes the diff worthless.</p>
<h2>Step 1: turn off DataSource auto-configuration</h2>
<p>Spring Boot is happy to configure one <code>DataSource</code> and one migration engine for you. Two of each is where that stops being helpful, and hiding the bootstrap would also hide half of what the comparison is about. So <code>application.yml</code> excludes the auto-configuration and declares two datasource blocks under a custom <code>app</code> prefix (trimmed):</p>
<pre><code class="language-yaml">spring:
  autoconfigure:
    exclude:
      - org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration

app:
  datasource:
    flyway:
      url: jdbc:h2:file:./data/flywaydb;DB_CLOSE_DELAY=-1;AUTO_SERVER=TRUE;NON_KEYWORDS=VALUE
      driver-class-name: org.h2.Driver
      username: sa
      password: ""
    liquibase:
      url: jdbc:h2:file:./data/liquibasedb;DB_CLOSE_DELAY=-1;AUTO_SERVER=TRUE;NON_KEYWORDS=VALUE
      driver-class-name: org.h2.Driver
      username: sa
      password: ""
  migration:
    flyway:
      locations: classpath:db/migration
      baseline-on-migrate: true
    liquibase:
      change-log: classpath:db/changelog/db.changelog-master.yaml
      contexts: demo
      default-schema: PUBLIC
</code></pre>
<p>If you are coming from Spring Boot 3, note the package in that exclude. Spring Boot 4 split auto-configuration into modules, so <code>DataSourceAutoConfiguration</code> and <code>DataSourceProperties</code> now live in <code>org.springframework.boot.jdbc.autoconfigure</code>. The H2 console moved too: it needs the <code>spring-boot-h2console</code> dependency on the classpath.</p>
<h2>Step 2: wire each engine yourself</h2>
<p>Each engine gets its own <code>@Configuration</code> class that builds a <code>DataSourceProperties</code>, a <code>DataSource</code>, the engine and a <code>JdbcTemplate</code>. Here's the Flyway bean from <code>FlywayConfig</code> (trimmed to the engine itself):</p>
<pre><code class="language-java">@Bean(name = "flyway", initMethod = "migrate")
public Flyway flyway(@Qualifier(DATA_SOURCE) DataSource dataSource) {
    log.info("Configuring Flyway with locations={} baselineOnMigrate={}", locations, baselineOnMigrate);
    return Flyway.configure()
            .dataSource(dataSource)
            .locations(locations)
            .baselineOnMigrate(baselineOnMigrate)
            .validateOnMigrate(true)
            .cleanDisabled(true)
            .load();
}
</code></pre>
<p>And the Liquibase counterpart from <code>LiquibaseConfig</code>:</p>
<pre><code class="language-java">@Bean("liquibase")
public SpringLiquibase liquibase(@Qualifier(DATA_SOURCE) DataSource dataSource) {
    log.info("Configuring Liquibase with changeLog={} contexts={}", changeLog, contexts);
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog(changeLog);
    liquibase.setContexts(contexts);
    liquibase.setDefaultSchema(defaultSchema);
    liquibase.setDropFirst(false);
    liquibase.setShouldRun(true);
    return liquibase;
}
</code></pre>
<p>Flyway needs a <code>DataSource</code> and a location. Liquibase also wants a changelog entry point, contexts and a default schema. Those extra setters are what make contexts and per-environment filtering possible later on.</p>
<p>Both engines migrate during bean initialization: Flyway through <code>initMethod = "migrate"</code>, <code>SpringLiquibase</code> in <code>afterPropertiesSet()</code>. That creates a trap. A <code>JdbcTemplate</code> built on the same <code>DataSource</code> can be created before the migration has run, and the first query hits an empty database. The fix is one annotation per side:</p>
<pre><code class="language-java">@Bean(JDBC_TEMPLATE)
@Primary
@DependsOn("flyway")
public JdbcTemplate flywayJdbcTemplate(@Qualifier(DATA_SOURCE) DataSource dataSource) {
    return new JdbcTemplate(dataSource);
}
</code></pre>
<p><code>liquibaseJdbcTemplate</code> does the same with <code>@DependsOn("liquibase")</code>. With two beans of every JDBC type in the context, <code>@Qualifier</code> stops being optional. The repo keeps the bean names as constants (<code>FlywayConfig.JDBC_TEMPLATE</code>, <code>LiquibaseConfig.JDBC_TEMPLATE</code>) so the qualifier strings aren't copied around as literals, and the Flyway side is <code>@Primary</code>.</p>
<h2>Step 3: add the migration files, in pairs</h2>
<p>Every Flyway migration has a deliberate Liquibase counterpart. Each pair makes the same business change, written the way that tool expects.</p>
<p><img src="https://raw.githubusercontent.com/wallaceespindola/flyway-vs-liquibase-db-migrations/db37e3c/docs/articles/devto/diagrams/paired-migrations.png" alt="Paired migrations: Flyway V1 to V5 plus the repeatable R__ catalog view on the left, Liquibase changesets 001 to 006 on the right, with V5 mapping to two changesets, 005 and 005b, which is why Flyway applies 6 and Liquibase applies 7" /></p>
<p>On the Flyway side you drop SQL files into <code>src/main/resources/db/migration</code> and the filename does the rest. <code>V1__create_category_table.sql</code> is plain H2 SQL (header comment trimmed):</p>
<pre><code class="language-sql">CREATE TABLE category
(
    id          BIGINT AUTO_INCREMENT PRIMARY KEY,
    name        VARCHAR(100) NOT NULL,
    description VARCHAR(500),
    created_at  TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT uk_category_name UNIQUE (name)
);

CREATE INDEX idx_category_name ON category (name);
</code></pre>
<p>Liquibase doesn't scan for files. You write a master changelog that includes each one, in order (header comment trimmed):</p>
<pre><code class="language-yaml">databaseChangeLog:
  - include:
      file: db/changelog/changes/001-create-category-table.xml
  - include:
      file: db/changelog/changes/002-create-product-table.yaml
  - include:
      file: db/changelog/changes/003-seed-reference-data.sql
  - include:
      file: db/changelog/changes/004-add-product-audit-table.xml
  - include:
      file: db/changelog/changes/005-add-product-active-flag.xml
  - include:
      file: db/changelog/changes/006-product-catalog-view.xml
</code></pre>
<p>The includes mix XML, YAML and Liquibase's formatted SQL on purpose, to show all three work in one changelog. The YAML changeset 002 also shows the escape hatch: check constraints have no portable Liquibase tag, so that changeset drops to a <code>sql</code> change for them.</p>
<p>Look closely at V4 and 004. <code>V4__add_product_audit_table.sql</code> creates an audit table and has no way back. Its header comment says reverting means writing a new forward migration. The Liquibase changeset adds a precondition and a rollback (trimmed to the parts that matter):</p>
<pre><code class="language-xml">&lt;changeSet id="004-add-product-audit-table" author="wallaceespindola" context="demo"&gt;
    &lt;!-- Schema order matters: preConditions must precede comment and the change tags. --&gt;
    &lt;preConditions onFail="MARK_RAN" onFailMessage="product table missing, skipping audit table"&gt;
        &lt;tableExists tableName="product"/&gt;
    &lt;/preConditions&gt;

    &lt;comment&gt;Add the product audit trail, guarded by a precondition&lt;/comment&gt;

    &lt;createTable tableName="product_audit"&gt;
        &lt;column name="id" type="BIGINT" autoIncrement="true"&gt;
            &lt;constraints primaryKey="true" primaryKeyName="pk_product_audit" nullable="false"/&gt;
        &lt;/column&gt;
        &lt;column name="product_id" type="BIGINT"&gt;
            &lt;constraints nullable="false" foreignKeyName="fk_product_audit_product"
                         references="product(id)"/&gt;
        &lt;/column&gt;
    &lt;/createTable&gt;

    &lt;rollback&gt;
        &lt;dropIndex tableName="product_audit" indexName="idx_product_audit_product"/&gt;
        &lt;dropTable tableName="product_audit"/&gt;
    &lt;/rollback&gt;
&lt;/changeSet&gt;
</code></pre>
<p>That comment inside the changeset is there because the ordering cost me a debug cycle. Liquibase validates the XML against its schema, and if <code>&lt;preConditions&gt;</code> comes after <code>&lt;comment&gt;</code>, the changelog fails to parse at startup.</p>
<p>The last pair is the view. Flyway's <code>R__product_catalog_view.sql</code> is a repeatable migration: no version, re-applied whenever its checksum changes. Liquibase gets the same behavior from an attribute, <code>runOnChange="true"</code> on changeset 006, so the rule lives in the changeset instead of the filename.</p>
<h2>Step 4: run it</h2>
<p>You need Java 25 and Maven 3.9 or newer. H2 is embedded, so there's nothing else to install:</p>
<pre><code class="language-bash">git clone https://github.com/wallaceespindola/flyway-vs-liquibase-db-migrations.git
cd flyway-vs-liquibase-db-migrations
./start.sh
</code></pre>
<p><code>start.sh</code> builds the jar if needed, starts the app in the background and waits for the health check. Use <code>./start.sh --clean</code> to delete both databases first and watch every migration run from scratch, <code>./stop.sh</code> to shut down, and <code>make help</code> for the Makefile equivalents. Swagger UI is at <code>http://localhost:8080/swagger-ui.html</code> and the H2 console at <code>/h2-console</code>.</p>
<p>Then ask for the comparison:</p>
<pre><code class="language-bash">curl -s http://localhost:8080/api/v1/comparison | jq
</code></pre>
<p>Here's what I got on a clean start, trimmed for length (timestamps and timings will differ on your machine):</p>
<pre><code class="language-json">{
  "success": true,
  "message": "Both engines produced an equivalent business schema",
  "data": {
    "flyway": {
      "engine": "FLYWAY",
      "historyTable": "flyway_schema_history",
      "appliedCount": 6,
      "pendingCount": 0,
      "upToDate": true,
      "migrations": [
        {
          "identifier": "V1",
          "description": "create category table",
          "author": "n/a",
          "checksum": "-1250524602",
          "executionTimeMs": 5,
          "status": "Success"
        }
      ]
    },
    "liquibase": {
      "engine": "LIQUIBASE",
      "historyTable": "DATABASECHANGELOG",
      "appliedCount": 7,
      "pendingCount": 0,
      "upToDate": true,
      "migrations": [
        {
          "identifier": "001-create-category-table::wallaceespindola",
          "description": "Create the category reference table",
          "author": "wallaceespindola",
          "checksum": "9:0d75bd8afd86057e8d2484d044a2f1ca",
          "executionTimeMs": null,
          "status": "EXECUTED"
        }
      ]
    },
    "schemasEquivalent": true,
    "schemaDifferences": [],
    "featureMatrix": [
      {
        "feature": "Execution timing recorded",
        "flyway": "Yes, per migration, in milliseconds",
        "liquibase": "No per-changeset duration is persisted",
        "edge": "FLYWAY"
      }
    ]
  },
  "timestamp": "2026-11-17T23:45:16.296765Z"
}
</code></pre>
<p>Three things to look at. <code>schemasEquivalent: true</code> with an empty <code>schemaDifferences</code> means both engines produced the same tables, columns and views. The applied counts are 6 and 7, because V5 adds the <code>active</code> column and backfills it in one script while Liquibase splits that into <code>005</code> (the column, labeled <code>schema-evolution</code>) and <code>005b</code> (the backfill, labeled <code>data-backfill</code>), each with its own rollback. And the history rows differ in shape: Flyway has a duration but no author, Liquibase has an author but <code>executionTimeMs: null</code>.</p>
<p>The null is kept in the JSON on purpose (Jackson is configured to include nulls). Liquibase does log "ran successfully in 3ms" for each changeset at startup, but it doesn't write that duration to <code>DATABASECHANGELOG</code>, so there's nothing to read back later.</p>
<h2>Step 5: read the history back from inside the app</h2>
<p>This is where the two implementations of <code>MigrationHistoryProvider</code> look nothing alike. <code>FlywayHistoryService</code> asks Flyway (trimmed):</p>
<pre><code class="language-java">MigrationInfo[] all = flyway.info().all();
log.debug("Flyway reported {} known migrations", all.length);

List&lt;AppliedMigration&gt; applied = Arrays.stream(all)
        .filter(info -&gt; info.getInstalledOn() != null)
        .map(FlywayHistoryService::toAppliedMigration)
        .sorted(Comparator.comparing(AppliedMigration::appliedAt))
        .toList();
</code></pre>
<p><code>flyway.info()</code> returns applied and pending migrations as objects, ordered, with state and checksum, and it comes straight from the bean the app already has. Liquibase does have a status API (<code>getChangeSetStatuses()</code> and <code>listUnrunChangeSets()</code> on the <code>Liquibase</code> class), but it needs an instance built from the changelog plus an open database connection. <code>SpringLiquibase</code> runs the update at startup and doesn't hand you that object, so <code>LiquibaseHistoryService</code> queries the bookkeeping table directly:</p>
<pre><code class="language-java">private static final String HISTORY_QUERY =
        """
        SELECT ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, EXECTYPE,
               MD5SUM, DESCRIPTION, COMMENTS, CONTEXTS, LABELS, DEPLOYMENT_ID
        FROM DATABASECHANGELOG
        ORDER BY ORDEREXECUTED
        """;
</code></pre>
<p>I kept both shapes instead of hiding them behind something clever. The SQL route is the finding: with the Spring integration, the table is the easiest interface on the Liquibase side. In exchange, that table carries author, contexts, labels and deployment id, none of which exist in <code>flyway_schema_history</code>.</p>
<p>A few more endpoints if you want to poke around:</p>
<pre><code class="language-bash">curl -s http://localhost:8080/api/v1/migrations/liquibase | jq '.data.migrations[].identifier'
curl -s http://localhost:8080/api/v1/migrations/flyway/schema | jq
curl -s http://localhost:8080/api/v1/catalog/liquibase | jq
curl -s http://localhost:8080/api/v1/comparison/features | jq
</code></pre>
<p>The last one returns the 18-row feature matrix on its own.</p>
<h2>Troubleshooting</h2>
<p><strong>Flyway warns about H2:</strong> Flyway 12.4.0 logs that H2 2.4.240 is newer than the version it was verified with (2.3.232). Everything works. I left both versions to the Spring Boot BOM rather than pinning one, because pinning takes the project off the set Spring Boot tests together.</p>
<p><strong>Liquibase fails to parse the changelog:</strong> check element order inside the changeset. <code>&lt;preConditions&gt;</code> goes before <code>&lt;comment&gt;</code> and before any change tags.</p>
<p><strong>Queries hit empty tables:</strong> a <code>JdbcTemplate</code> is missing its <code>@DependsOn</code> on the engine bean.</p>
<p><strong>The diff reports index differences:</strong> it won't, by design. <code>ComparisonService.diff()</code> compares tables, views and columns and ignores indexes, because H2 generates names for constraint-backing indexes and those names differ between the two engines. Counting them would report noise as drift.</p>
<p><strong>You added a migration and a test failed:</strong> you added it to one side only. The integration test asserts <code>schemasEquivalent</code> and the exact applied counts, so a new <code>V6</code> needs its <code>007</code> changeset, and the 6 and 7 in the tests move together.</p>
<h2>Licensing, before you pick one</h2>
<p>The rollback in changeset 004 is free, but check what "free" means now. With <a href="https://docs.liquibase.com/community/release-notes/5-0">Liquibase 5.0</a>, Liquibase Community moved from Apache 2.0 to the <a href="https://www.liquibase.com/blog/liquibase-community-for-the-future-fsl">Functional Source License</a> (FSL-1.1-ALv2), which converts to Apache 2.0 after two years. Liquibase's own FAQ calls it source available, not OSI open source, and contributors now sign a CLA. The commercial product, <a href="https://www.liquibase.com/5-0-launch">formerly Pro</a>, is now Liquibase Secure. Whether that matters depends on how you use and distribute it, so ask whoever signs off on licenses before you standardize on it.</p>
<p>On the Flyway side, undo migrations aren't in Community. Per Redgate's <a href="https://documentation.red-gate.com/fd/feature-summary-165740620.html">feature summary</a> they're a paid-edition feature (Enterprise can also generate undo scripts for you). In Community, reverting means a new forward migration, which is exactly what the V4 comment says.</p>
<h2>Recap</h2>
<ul>
<li>Two databases, one per engine, so neither tool ever sees the other's tables.</li>
<li>Explicit <code>FlywayConfig</code> and <code>LiquibaseConfig</code>, DataSource auto-configuration excluded, <code>@DependsOn</code> so nothing queries an unmigrated database.</li>
<li>Paired migration files: V1 to V5 plus <code>R__</code> against 001 to 006 plus <code>005b</code>, which is why the counts are 6 and 7.</li>
<li><code>GET /api/v1/comparison</code> returns <code>schemasEquivalent: true</code>, and the project's 86 tests (98.8% line coverage, 80% JaCoCo gate) keep it that way.</li>
<li>History reads differ: <code>flyway.info()</code> against a <code>SELECT</code> on <code>DATABASECHANGELOG</code>.</li>
</ul>
<h2>Try it yourself</h2>
<p>Clone <a href="https://github.com/wallaceespindola/flyway-vs-liquibase-db-migrations">the repo</a>, run <code>./start.sh --clean</code>, and open <code>http://localhost:8080/</code> for the dashboard or curl the comparison endpoint. Then break it on purpose: add a column in a new <code>V6</code> without the Liquibase counterpart, restart, and watch <code>schemaDifferences</code> fill up.</p>
<p>Which of the two does your team run today, and has the rollback or the licensing question actually changed a decision for you? I'd like to hear in the comments.</p>
<p>If you are choosing between the two, clone the repo, run both migrations and look at the diff yourself. The schema will match; the history tables, rollback story and licensing are where your decision really lives.</p>
<p><strong>Examples repository:</strong> the Spring Boot application, both sets of migration files, the comparison endpoints, the tests and the diagrams from this article are all in <a href="https://github.com/wallaceespindola/flyway-vs-liquibase-db-migrations">https://github.com/wallaceespindola/flyway-vs-liquibase-db-migrations</a>.</p>
<p>Need more tech insights?</p>
<p>Check out my GitHub, LinkedIn, and Speaker Deck.</p>
<p>Happy coding!</p>
<p>Wallace Espindola, Solution Architect</p>
<ul>
<li>GitHub: <a href="https://github.com/wallaceespindola/">https://github.com/wallaceespindola/</a></li>
<li>LinkedIn: <a href="https://www.linkedin.com/in/wallaceespindola/">https://www.linkedin.com/in/wallaceespindola/</a></li>
<li>Speaker Deck: <a href="https://speakerdeck.com/wallacese">https://speakerdeck.com/wallacese</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Is your JVM exposed to Java4Shell? Three checks and a patch plan]]></title><description><![CDATA[Check if your JVM is exposed to Java4Shell (CVE-2026-114938) in minutes: CPU flag, full Java version and JIT flags, then patch Docker and Kubernetes.]]></description><link>https://wallaceespindola.hashnode.dev/is-your-jvm-exposed-to-java4shell-three-checks-and-a-patch-plan</link><guid isPermaLink="true">https://wallaceespindola.hashnode.dev/is-your-jvm-exposed-to-java4shell-three-checks-and-a-patch-plan</guid><category><![CDATA[Java]]></category><category><![CDATA[Security]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[jvm]]></category><dc:creator><![CDATA[Wallace Espindola]]></dc:creator><pubDate>Mon, 30 Nov 2026 22:37:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64aebca99b6f7761817ead2f/646fa49a-a1da-4019-9905-66756e482dea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Java4Shell (CVE-2026-114938) was disclosed on 17 November 2026, and on most teams the first useful question is not how the exploit works but whether a given JVM is exposed right now. You can answer that per host in a few minutes by looking at three things: the CPU, the full Java version and two JIT flags. If one of the three says no, the JVM is not exposed today, although it still needs the patch.</p>
<p>This article covers the hands-on part. You check one box, then you fix it: the shell commands, the small checker in the companion repo (run it once, or run it as a service and read the JSON), the Docker images before and after, the Kubernetes mitigation patch and node affinity, and finally the patch itself. Everything quoted here lives in <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved">the examples repository</a>.</p>
<h2>What you are looking for</h2>
<p>The flaw is heap memory corruption in HotSpot's AVX-512 Base64 decode intrinsic, the code behind <code>java.util.Base64.Decoder</code>. It was disclosed by <a href="https://calif.io/java4shell">Calif</a> on the same day Oracle shipped its <a href="https://www.oracle.com/security-alerts/cspunov2026.html">November 2026 Critical Security Patch Update</a> and the <a href="https://openjdk.org/groups/vulnerability/advisories/">OpenJDK Vulnerability Group</a> published its advisory.</p>
<p>On CPUs with AVX-512 VBMI, HotSpot swaps the pure-Java decode loop for a hand-written vectorized stub. For specially malformed input, that stub writes past the end of the output buffer before Java's normal validation rejects the string. Published analyses put the overrun at roughly 62 to 64 bytes. Java's memory safety applies to bytecode, not to JIT-generated native stubs, so the write corrupts adjacent heap memory.</p>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/2osqy0uzr24aevzyzkur.png" alt="Attack flow: a malformed Base64 string reaches the AVX-512 VBMI decode stub, causing an out-of-bounds heap write that leads to a JVM crash or, with heap grooming, potential remote code execution" /></p>
<p>Two things make this different from Log4Shell for the person doing the checking. The bug is in the runtime, not a library, so a fully updated Maven or Gradle build can still be vulnerable and dependency-only (SCA) scanners won't see it. And it depends on hardware: the same container image can be exposed on one node pool and safe on another.</p>
<h2>Check one box: three questions per JVM</h2>
<p>The vulnerable stub is selected only when all of these hold, per the <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/docs/java4shell-context.md">context doc in the repo</a> and the analyses it cites:</p>
<ol>
<li>An x86-64 CPU with <strong>AVX-512 VBMI</strong> (the <code>avx512vbmi</code> CPU flag).</li>
<li>An affected JDK build: OpenJDK 17.0.6 and later, 21, 25 and 27 before their fix releases, or the Oracle Java 8 Enterprise Performance Pack.</li>
<li>HotSpot running with <code>UseAVX=3</code> and <code>UseBASE64Intrinsics=true</code>, which are the defaults on such CPUs.</li>
</ol>
<p>Standard Java 8 and 11 are not affected. Neither is ARM64 (Graviton, Apple Silicon, Ampere) or x86-64 without VBMI. On the Intel side, Ice Lake, Sapphire Rapids, Emerald Rapids and Granite Rapids have VBMI. Skylake-SP and Cascade Lake have AVX-512 without VBMI, so they are not exposed. On AMD, Zen 4 and newer are exposed, Zen 3 and older are not.</p>
<p>Here is the triage flow I'd follow for each Java process:</p>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/5099d7wk053fh8bciizv.png" alt="Triage flowchart: check for avx512vbmi on an x86-64 CPU, then an unpatched affected JDK, then UseAVX=3 and UseBASE64Intrinsics=true, then whether untrusted Base64 is reachable before authentication, ending in not exposed, mitigated, high or critical" /></p>
<p>The last question in the flow is about your code, not the box. Base64 decoding sits on many pre-authentication paths (HTTP Basic <code>Authorization</code> headers, JWT parsing, SAML and OIDC payloads, cookies, webhook signatures), so a login page in front of the app is no protection if the decode happens before the credential check.</p>
<h3>The commands</h3>
<p>Run these against the production runtime on the production host, not on a laptop. These come straight from the repo's context doc:</p>
<pre><code class="language-bash"># 1. CPU: does the host expose AVX-512 VBMI? (Linux)
grep -o -m1 'avx512vbmi' /proc/cpuinfo || echo "no avx512vbmi: not exposed"

# 2. Runtime version (full four-part version matters)
java -version
docker run --rm --entrypoint java my-app:latest -version

# 3. Effective JIT flags of the exact binary the app uses
java -XX:+PrintFlagsFinal -version | grep -E 'UseAVX|UseBASE64Intrinsics'

# 4. Flags of an already running JVM
jcmd &lt;pid&gt; VM.flags -all | grep -E 'UseAVX|UseBASE64Intrinsics'
</code></pre>
<p>Step 2 is where people slip. The fix lives in the fourth version number: <code>21.0.13</code> is still vulnerable, <code>21.0.13.1</code> is not. Dashboards, regexes and scanners that keep only three components will report both as the same build. The <a href="https://dev.to/ianwieds/the-java4shell-fix-lives-in-the-fourth-version-number-3p26">DEV Community post on the fourth version number</a> covers that trap in detail.</p>
<p>If you'd rather not type all of that, the repo wraps the host part in <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/examples/detect/check-host.sh"><code>examples/detect/check-host.sh</code></a>:</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# Quick Java4Shell (CVE-2026-114938) triage for one Linux host and one java binary.
# Usage: examples/detect/check-host.sh [/path/to/java]
set -uo pipefail
JAVA="${1:-java}"

if grep -qw avx512vbmi /proc/cpuinfo 2&gt;/dev/null; then
  echo "CPU: avx512vbmi present"
else
  echo "CPU: no avx512vbmi (or not Linux x86-64): not exposed on this host"
fi

echo "Runtime: $("$JAVA" -version 2&gt;&amp;1 | head -1)"
"$JAVA" -XX:+PrintFlagsFinal -version 2&gt;/dev/null | grep -E '\b(UseAVX|UseBASE64Intrinsics)\b'
</code></pre>
<p>Pass the path to the exact <code>java</code> binary your application starts with. Servers often have more than one JDK installed, and the one on the <code>PATH</code> is not always the one in the service unit.</p>
<h2>The checker: one file, one verdict</h2>
<p>The shell script prints facts and leaves the conclusion to you. <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/examples/detect/Java4ShellCheck.java"><code>examples/detect/Java4ShellCheck.java</code></a> goes one step further: it inspects the JVM it runs in and returns a verdict. It is a single file with no dependencies, so you can launch it with <code>java</code> directly.</p>
<p>The decision is a few lines, trimmed from the repo:</p>
<pre><code class="language-java">    static Verdict verdict(String arch, Optional&lt;Boolean&gt; vbmi, boolean affected, int useAvx, boolean b64) {
        boolean x86 = arch.equals("amd64") || arch.equals("x86_64");
        if (!x86 || !affected || useAvx &lt; 3 || !b64) {
            return Verdict.NOT_EXPOSED;
        }
        return vbmi.map(has -&gt; has ? Verdict.EXPOSED : Verdict.NOT_EXPOSED).orElse(Verdict.UNKNOWN);
    }
</code></pre>
<p>Any single "no" ends the check. Only when the architecture, the build and both flags line up does the CPU flag decide, and if <code>/proc/cpuinfo</code> can't be read the answer is <code>UNKNOWN</code> instead of a guess. The flag values come from <code>HotSpotDiagnosticMXBean</code>, so they reflect what the running JVM uses, including anything set through <code>JAVA_TOOL_OPTIONS</code>.</p>
<p>The version check compares all four components against the first fixed release of each line (also trimmed from the repo):</p>
<pre><code class="language-java">        int[] fixed = switch (v.feature()) {
            case 17 -&gt; new int[] {17, 0, 21, 1};
            case 21 -&gt; new int[] {21, 0, 13, 1};
            case 25 -&gt; new int[] {25, 0, 5, 1};
            case 27 -&gt; new int[] {27, 0, 1, 1};
            default -&gt; null;
        };
</code></pre>
<p>Those are the upstream and Oracle numbers. More on vendor numbering in the limits section below.</p>
<h3>Run it once</h3>
<p>From the repo root:</p>
<pre><code class="language-bash">make check-jvm   # java examples/detect/Java4ShellCheck.java
make self-test   # the built-in checks
</code></pre>
<p>The exit code is the verdict: 0 not exposed, 1 exposed, 2 unknown. That makes it usable as a gate in a CI job or a startup script. Here is the real output on my Apple Silicon laptop:</p>
<pre><code class="language-text">javaVersion          25.0.5+9-LTS
javaVendor           Amazon.com Inc.
osArch               aarch64
avx512vbmi           unknown
useAvx               0
useBase64Intrinsics  true
affectedBuild        true
verdict              NOT_EXPOSED
</code></pre>
<p>This is a useful example because it looks scary at first glance. <code>affectedBuild</code> is <code>true</code> (25.0.5 is below 25.0.5.1), and <code>useBase64Intrinsics</code> is <code>true</code>. But the architecture is <code>aarch64</code>, so the AVX-512 path doesn't exist here. <code>UseAVX</code> isn't even a flag on ARM64, which is why it reads <code>0</code>, and there is no <code>/proc/cpuinfo</code> on macOS, hence <code>unknown</code>. Not exposed on this box, and still due for the patch on the normal cadence.</p>
<h3>Run it as a service</h3>
<p>Sometimes you want to ask a host from the outside, or keep a check endpoint next to other health probes. The checker has a <code>--serve</code> mode with <code>GET /health</code> and <code>GET /check</code>, and the repo wraps it in <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/scripts/run.sh"><code>scripts/run.sh</code></a> and <code>scripts/kill.sh</code>:</p>
<pre><code class="language-bash">make run     # scripts/run.sh 8080, starts service in background
make status  # curl -s localhost:8080/check
make kill    # scripts/kill.sh
</code></pre>
<p><code>run.sh</code> writes a PID file and a log under <code>.run/</code>, and refuses to start a second copy. The <code>/check</code> response is the same report as JSON, plus a <code>timestamp</code>:</p>
<pre><code class="language-json">{"javaVersion":"25.0.5+9-LTS","javaVendor":"Amazon.com Inc.","osArch":"aarch64","avx512vbmi":"unknown","useAvx":"0","useBase64Intrinsics":"true","affectedBuild":"true","verdict":"NOT_EXPOSED","timestamp":"2026-11-27T22:51:48.200959Z"}
</code></pre>
<p>Read it left to right, the way the triage diagram reads top to bottom. <code>osArch</code> and <code>avx512vbmi</code> answer the CPU question, <code>javaVersion</code> and <code>affectedBuild</code> the build question, <code>useAvx</code> and <code>useBase64Intrinsics</code> the flags question, and <code>verdict</code> combines them. All values are strings, so compare <code>"EXPOSED"</code>, not a boolean.</p>
<p>There is also a <code>Dockerfile</code> and <code>docker-compose.yml</code> for the service (<code>make docker-build</code>, <code>make docker-up</code>). Keep in mind what that container measures: the Temurin 25 JRE inside the checker's image, on whatever CPU the container lands on. That is a good way to probe a node's CPU, but it says nothing about your application's JDK. For that, run the checker with the same <code>java</code> binary and the same <code>JAVA_TOOL_OPTIONS</code> as the application.</p>
<p><img src="https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/510la87z72kd8hqw5xvn.jpg" alt="Server rack with rows of blinking green status lights in a data center" /></p>
<p><em>Photo by <a href="https://unsplash.com/@fslfsl">Domaintechnik</a> on <a href="https://unsplash.com/photos/VHmBX7FnXw0">Unsplash</a></em></p>
<h2>Then fix it: Docker before and after</h2>
<p>Here is the vulnerable image from <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/examples/docker/Dockerfile.vulnerable"><code>examples/docker/Dockerfile.vulnerable</code></a>:</p>
<pre><code class="language-dockerfile"># Vulnerable: 21.0.13 predates the 21.0.13.1 fix for CVE-2026-114938.
FROM eclipse-temurin:21.0.13-jre
WORKDIR /app
COPY target/application.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
</code></pre>
<p>Nothing in it looks wrong. The tag is pinned and specific, and it is still one patch release short.</p>
<p>If the patched base image isn't available yet, or your rollout takes longer than you'd like, the mitigation turns off the Base64 intrinsic. From <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/examples/docker/Dockerfile.mitigated"><code>examples/docker/Dockerfile.mitigated</code></a>:</p>
<pre><code class="language-dockerfile"># Temporary mitigation until the patched image ships. Merge with any JAVA_TOOL_OPTIONS you already set.
FROM eclipse-temurin:21.0.13-jre
ENV JAVA_TOOL_OPTIONS="-XX:-UseBASE64Intrinsics"
WORKDIR /app
COPY target/application.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
</code></pre>
<p>Read the comment on the first line. <code>JAVA_TOOL_OPTIONS</code> overrides any existing value, so if your image already sets memory or GC options there, merge them instead of replacing them. <code>-XX:UseAVX=2</code> also closes the hole, but it disables every AVX-512 code path, not just Base64, and costs more. And don't rely on <code>-XX:DisableIntrinsic=_base64_decodeBlock</code> on its own, because analyses warned it does not reliably cover the vulnerable path.</p>
<p>The fix is a new base image. From <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/examples/docker/Dockerfile.patched"><code>examples/docker/Dockerfile.patched</code></a>:</p>
<pre><code class="language-dockerfile"># Patched: pin the fixed release by digest once you have verified it reports 21.0.13.1 or the vendor equivalent.
FROM eclipse-temurin:21-jre@sha256:&lt;verified-digest-of-patched-image&gt;
WORKDIR /app
COPY target/application.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
</code></pre>
<p>Then rebuild without the cache and check what actually ended up inside:</p>
<pre><code class="language-bash">docker build --pull --no-cache -t my-app:patched .
docker run --rm --entrypoint java my-app:patched -version   # expect 21.0.13.1 or the vendor equivalent
</code></pre>
<p>A floating tag such as <code>21-jre</code> only helps if it is re-pulled, and <code>--pull</code> forces that. The digest makes the fix reproducible, and Renovate or Dependabot can propose digest bumps from there. This is a patch-level update, so no business logic changes and no Java major-version migration.</p>
<h2>Kubernetes: mitigate in place, or move off the exposed nodes</h2>
<p>In a cluster the CPU check has to run on the node, not inside a build container. With <a href="https://kubernetes-sigs.github.io/node-feature-discovery/">Node Feature Discovery</a> installed, nodes carry CPU feature labels, and <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/examples/kubernetes/inventory.sh"><code>examples/kubernetes/inventory.sh</code></a> lists the VBMI nodes plus the Java version in each running pod (trimmed from the repo):</p>
<pre><code class="language-bash">echo "Nodes advertising AVX-512 VBMI:"
kubectl get nodes -l feature.node.kubernetes.io/cpu-cpuid.AVX512VBMI=true -o name

echo
echo "Java runtime per pod:"
kubectl get pods -A --field-selector=status.phase=Running \
  -o jsonpath='{range .items[*]}{.metadata.namespace}{" "}{.metadata.name}{" "}{.spec.nodeName}{"\n"}{end}' |
while read -r ns pod node; do
  version="$(kubectl exec -n "$ns" "$pod" -- java -version 2&gt;&amp;1 | head -1)"
  echo "$ns/$pod on $node: ${version:-no java}"
done
</code></pre>
<p>It assumes <code>java</code> is on the <code>PATH</code> and pods are single-container, so treat it as a quick look. For a whole fleet, an image scanner or runtime inventory does the job better.</p>
<p>For the exposed workloads, you have two short-term options. The first is the same flag as in Docker, applied as a strategic-merge patch from <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/examples/kubernetes/mitigation.yaml"><code>examples/kubernetes/mitigation.yaml</code></a>:</p>
<pre><code class="language-yaml"># Strategic-merge patch: disable the Base64 intrinsic until the patched image is deployed.
# kubectl patch deployment my-app --patch-file examples/kubernetes/mitigation.yaml
spec:
  template:
    spec:
      containers:
        - name: my-app
          env:
            - name: JAVA_TOOL_OPTIONS
              value: "-XX:-UseBASE64Intrinsics"
</code></pre>
<p>The container <code>name</code> must match your deployment's container, because that is how the merge finds it. Patching the pod template triggers a rollout, so the pods restart with the flag. Confirm it took effect with <code>jcmd &lt;pid&gt; VM.flags</code> inside a pod, or with the checker's <code>useBase64Intrinsics</code> field. Some products (Jira, Keycloak, Jenkins) keep their own JVM options files, so follow their guidance: <a href="https://github.com/keycloak/keycloak/issues/55293">Keycloak issue #55293</a> and the <a href="https://www.jenkins.io/blog/2026/11/18/mitigating-java4shell/">Jenkins blog post</a>.</p>
<p>The second option is to keep the workload off VBMI nodes altogether, from <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved/blob/main/examples/kubernetes/avoid-vbmi-nodes.yaml"><code>examples/kubernetes/avoid-vbmi-nodes.yaml</code></a>:</p>
<pre><code class="language-yaml"># Strategic-merge patch: keep a workload off nodes that advertise AVX-512 VBMI (needs Node Feature Discovery).
# kubectl patch deployment my-app --patch-file examples/kubernetes/avoid-vbmi-nodes.yaml
spec:
  template:
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: feature.node.kubernetes.io/cpu-cpuid.AVX512VBMI
                    operator: DoesNotExist
</code></pre>
<p>This uses the hardware condition as the control, since the vulnerable stub is never selected without VBMI. Scheduling exposed workloads onto ARM64 or non-VBMI node pools is a valid containment step. Watch the <code>DoesNotExist</code> operator, though. If Node Feature Discovery isn't running, no node has the label, every node matches and the patch does nothing. And if all your nodes are VBMI nodes, the pods go <code>Pending</code>. Check the label output from <code>inventory.sh</code> before you rely on it.</p>
<h2>Then patch: the fixed versions</h2>
<p>Both mitigations only buy time, and the ticket closes when the patched build is running. Minimum fixed versions, in Oracle and OpenJDK numbering:</p>
<table>
<thead>
<tr>
<th>Java line</th>
<th>Minimum fixed</th>
</tr>
</thead>
<tbody><tr>
<td>8 Performance Pack</td>
<td>8u513-perf</td>
</tr>
<tr>
<td>17</td>
<td>17.0.21.1</td>
</tr>
<tr>
<td>21</td>
<td>21.0.13.1</td>
</tr>
<tr>
<td>25</td>
<td>25.0.5.1</td>
</tr>
<tr>
<td>27</td>
<td>27.0.1.1</td>
</tr>
</tbody></table>
<p>Java 11 isn't affected, but 11.0.33.1 ships other fixes from the same patch update, so patch it anyway. Every HotSpot-based distribution inherits the bug (Eclipse Temurin, Amazon Corretto, Azul Zulu, Red Hat build of OpenJDK, Microsoft Build of OpenJDK, distro packages), and each one uses its own build numbers and timelines. In the first days after disclosure, several vendors had trackers open without fixed builds. Check your vendor's advisory for the exact package version.</p>
<p>After the rollout:</p>
<ol>
<li>Re-run the checker or <code>java -version</code> against the running pods, not just the image tags.</li>
<li>Remove the <code>JAVA_TOOL_OPTIONS</code> mitigation and the node affinity patch, so you get the intrinsic's performance back.</li>
<li>Look at the crash history from before the patch: <code>hs_err_pid*.log</code>, <code>SIGSEGV</code> and container restarts with exit code 134 or 139 on AVX-512 nodes. Repeated crashes there may indicate probing.</li>
</ol>
<h2>Trade-offs and limits</h2>
<p>A few things to keep in mind before you call it done:</p>
<ul>
<li><strong>The mitigation costs performance:</strong> expect slower Base64 decoding, which matters for JWT-heavy gateways and upload services. Measure it. <code>-XX:UseAVX=2</code> affects every vectorized intrinsic and costs more than the targeted flag.</li>
<li><strong>RCE is contested, the crash isn't:</strong> Calif demonstrated RCE in lab conditions. Independent reproductions confirmed the heap overflow but described reliable RCE as hard, since it depends on heap layout, GC, JIT state and the code path. <a href="https://www.ox.security/blog/java4shell-cve-2026-114938-rce-risk/">OX Security</a> estimated that fewer than 0.12% of JVMs are at realistic risk of RCE. A crash is easy, so treat every exposed instance as at least DoS-vulnerable.</li>
<li><strong>The severity score depends on who you ask:</strong> Calif rates it 9.2 Critical (CVSS 4.0), while Oracle's November patch update lists a top Java SE score of 8.1 (CVSS 3.1). No in-the-wild exploitation had been reported as of 19 November 2026.</li>
<li><strong>Vendor numbering differs:</strong> the checker hard-codes the upstream fix versions. A vendor build that carries the fix under another number can show up as affected, or the other way around, so the vendor advisory wins over the checker.</li>
<li><strong>The checker has blind spots:</strong> it reads <code>/proc/cpuinfo</code>, so outside Linux it reports <code>UNKNOWN</code> on x86-64. It uses <code>Runtime.version()</code> and single-file launch, so it can't run on Java 8, which means the 8 Performance Pack needs a manual version check against 8u513-perf.</li>
<li><strong>A WAF is not a fix:</strong> gateway rules that reject malformed or oversized Base64 reduce noise but can be bypassed.</li>
</ul>
<p>So the order of work stays the same: check, mitigate where the box says exposed, patch, then remove the mitigation.</p>
<h2>Recap</h2>
<p>You can answer "is this JVM exposed" with three checks: <code>avx512vbmi</code> on an x86-64 CPU, a four-part version below the fix release, and <code>UseAVX=3</code> with <code>UseBASE64Intrinsics=true</code>. The repo's checker does the same in one command, with an exit code for scripts and a JSON endpoint for everything else. If the answer is yes, <code>-XX:-UseBASE64Intrinsics</code> or a node affinity rule buys you time, and a rebuilt image on the fixed JDK closes it. For the wider picture, the <a href="https://securitylabs.datadoghq.com/articles/java4shell-remote-code-execution-in-openjdk-cve-2026-114938/">Datadog Security Labs</a> and <a href="https://eclypsium.com/blog/java4shell-patch-java-check-the-processor/">Eclypsium</a> write-ups are good next reads.</p>
<p>How are you tracking the fourth version number across your fleet? I'd like to hear in the comments.</p>
<p>Run the three checks on one host today, then wire the checker into the pipeline so every new image answers the question on its own. When the next runtime CVE arrives, you will already know where to look.</p>
<p><strong>Examples repository:</strong> every example in this article (the Java4Shell checker, the run scripts, the Docker and Kubernetes examples and the diagrams) is in <a href="https://github.com/wallaceespindola/java4shell-explained-and-solved">https://github.com/wallaceespindola/java4shell-explained-and-solved</a>.</p>
<p>Need more tech insights?</p>
<p>Check out my GitHub, LinkedIn, and Speaker Deck.</p>
<p>Happy coding!</p>
<p>Wallace Espindola, Solution Architect</p>
<ul>
<li>GitHub: <a href="https://github.com/wallaceespindola/">https://github.com/wallaceespindola/</a></li>
<li>LinkedIn: <a href="https://www.linkedin.com/in/wallaceespindola/">https://www.linkedin.com/in/wallaceespindola/</a></li>
<li>Speaker Deck: <a href="https://speakerdeck.com/wallacese">https://speakerdeck.com/wallacese</a></li>
</ul>
]]></content:encoded></item></channel></rss>