<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tetsuya Wakita on Medium]]></title>
        <description><![CDATA[Stories by Tetsuya Wakita on Medium]]></description>
        <link>https://medium.com/@wakita181009?source=rss-62f89bf3179e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4bp21Hww3XjblYAZNEDGGg.jpeg</url>
            <title>Stories by Tetsuya Wakita on Medium</title>
            <link>https://medium.com/@wakita181009?source=rss-62f89bf3179e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:53:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wakita181009/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Rewrote python-dateutil in Rust — Even a Naive Port Is Up to 94x Faster]]></title>
            <link>https://medium.com/@wakita181009/i-rewrote-python-dateutil-in-rust-even-a-naive-port-is-up-to-94x-faster-404f13b08336?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/404f13b08336</guid>
            <category><![CDATA[dateutil]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[maturin]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 08:53:39 GMT</pubDate>
            <atom:updated>2026-04-08T18:02:53.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmPLqH-tI9TR-fNcD_mRRQ.png" /></figure><blockquote><strong><em>TL;DR</em></strong><em> — </em><em>pip install python-dateutil-rs, change one import, get 5x-94x faster date parsing, recurrence rules, and timezone lookups. It&#39;s a line-by-line Rust port via PyO3 - no code changes required. </em><a href="https://github.com/wakita181009/dateutil-rs"><em>GitHub</em></a><em> | </em><a href="https://pypi.org/project/python-dateutil-rs/"><em>PyPI</em></a></blockquote><h3>python-dateutil Is Everywhere — and It’s Pure Python</h3><p><a href="https://dateutil.readthedocs.io/en/stable/">python-dateutil</a> is one of the most depended-on packages in the Python ecosystem. With <strong>300M+ monthly downloads on PyPI</strong>, it powers date parsing, relative deltas, recurrence rules, and timezone handling across countless applications.</p><p>But it’s written in pure Python. For hot paths — parsing thousands of ISO timestamps in a data pipeline, expanding recurring calendar events, computing relative dates in a loop — that means leaving significant performance on the table.</p><p>What if you could make it up to 94x faster without changing a single line of your application code?</p><pre>pip install python-dateutil-rs</pre><p>That’s python-dateutil-rs - a Rust-backed drop-in replacement I built using PyO3 and maturin. Same API, same behavior, dramatically faster.</p><p>And here’s the thing: <strong>this is a naive, line-by-line port</strong>. The Rust code mirrors the original Python logic almost 1:1, with no Rust-specific optimizations yet. The speedups come purely from Rust’s compiled nature — no dynamic dispatch, minimal GC pressure, no interpreter overhead.</p><h3>The Approach: Module-by-Module Rewrite via PyO3</h3><p>A full rewrite of a battle-tested library is risky. Instead, I took an <strong>incremental approach</strong>: rewrite each module in Rust independently, validate against the original test suite (~13,000 lines of tests, all passing), and ship value at every step.</p><p>The architecture uses <a href="https://github.com/PyO3/maturin">maturin</a>’s mixed layout — a Rust extension module and Python wrapper live in the same package:</p><pre>dateutil_rs (Python package)<br> ├── _native (Rust extension via PyO3/maturin) ← all modules<br> └── Python wrappers ← API compatibility layer</pre><p>Every module is now implemented in Rust: parser, relativedelta, rrule, tz, easter, utils, and weekday constants. The Python layer handles API compatibility — for example, serializing custom parserinfo lookup tables and forwarding them to the Rust parser:</p><pre>from dateutil_rs._native import isoparse<br>from dateutil_rs._native import parse as _parse_rs<br><br>def parse(timestr, parserinfo=None, **kwargs):<br>    if parserinfo is not None:<br>        # Serialize custom lookup tables → forward to Rust<br>        config = parserinfo._to_rust_config()<br>        return _parse_rs(timestr, parserinfo_config=config, **kwargs)<br>    return _parse_rs(timestr, **kwargs)</pre><p>The API is identical to python-dateutil - just change the import:</p><pre># Before (python-dateutil)<br>from dateutil.parser import parse<br>from dateutil.relativedelta import relativedelta<br>from dateutil.rrule import rrule, MONTHLY<br>from dateutil.tz import gettz, tzutc<br><br># After (python-dateutil-rs) — same code<br>from dateutil_rs.parser import parse<br>from dateutil_rs.relativedelta import relativedelta<br>from dateutil_rs.rrule import rrule, MONTHLY<br>from dateutil_rs.tz import gettz, tzutc</pre><h3>Benchmark Results</h3><p>All benchmarks: Python 3.13, macOS Apple Silicon M3 (arm64), Rust 1.86 stable, release build (--release), measured with pytest-benchmark. Compared against python-dateutil 2.9.0.</p><h3>At a Glance</h3><pre>Module          Speedup Range     Highlight<br>─────────────────────────────────────────────────────────<br>Timezone        1.7x – 94.3x     Batch gettz() with cache: 94.3x<br>ISO Parser      5.1x – 23.5x     With microseconds: 23.5x<br>RRule           3.1x – 20.0x     rrulestr with dtstart: 20.0x<br>RelativeDelta   4.9x – 18.7x     Multiply by scalar: 18.7x<br>General Parser  1.3x – 3.5x      Fuzzy parsing: 3.5x<br>Easter          3.2x – 6.2x      1000 years batch: 6.2x</pre><blockquote><strong><em>Note on the 94.3x headline number</em></strong><em>: The timezone benchmark includes a Rust-side </em><em>RwLock&lt;HashMap&gt; cache (similar to python-dateutil&#39;s </em><em>_TzFactory). Without caching, pure timezone operations still see 1.7x-3.8x speedups. The most representative single-operation speedup is </em><strong><em>23.5x</em></strong><em> on ISO parsing.</em></blockquote><h3>ISO Parsing — Up to 23.5x Faster</h3><pre>Benchmark            python-dateutil    dateutil-rs    Speedup<br>──────────────────────────────────────────────────────────────<br>Date only                  0.81 µs       0.08 µs       10.7x<br>Datetime                   2.06 µs       0.10 µs       20.9x<br>Datetime + TZ              3.11 µs       0.61 µs        5.1x<br>With microseconds          2.67 µs       0.11 µs       23.5x<br>7 various formats         23.10 µs       3.10 µs        7.4x</pre><h3>RelativeDelta — Up to 18.7x Faster</h3><pre>Benchmark            python-dateutil    dateutil-rs    Speedup<br>──────────────────────────────────────────────────────────────<br>Create simple              0.94 µs       0.19 µs        4.9x<br>Add months                 1.62 µs       0.13 µs       12.7x<br>Subtract                   3.03 µs       0.18 µs       16.5x<br>Multiply by scalar         1.49 µs       0.08 µs       18.7x<br>Sequential add ×12        19.41 µs       1.70 µs       11.4x<br>Month-end overflow         1.74 µs       0.13 µs       13.3x</pre><h3>RRule (Recurrence Rules) — Up to 20x Faster</h3><pre>Benchmark            python-dateutil    dateutil-rs    Speedup<br>──────────────────────────────────────────────────────────────<br>Weekly ×52               105.33 µs      34.44 µs        3.1x<br>Monthly ×120             448.46 µs     114.12 µs        3.9x<br>Yearly ×100            2,144.58 µs     235.02 µs        9.1x<br>rrulestr simple            3.14 µs       0.53 µs        6.0x<br>rrulestr complex           6.60 µs       0.90 µs        7.4x<br>rrulestr with dtstart     15.61 µs       0.78 µs       20.0x</pre><h3>Timezone — Up to 94.3x Faster (Cache-Inclusive)</h3><pre>Benchmark            python-dateutil    dateutil-rs    Speedup<br>──────────────────────────────────────────────────────────────<br>gettz various (×10)      714.93 µs       7.59 µs       94.3x<br>gettz offset              20.20 µs       5.26 µs        3.8x<br>resolve_imaginary          6.54 µs       3.19 µs        2.0x<br>datetime_exists            3.15 µs       1.62 µs        1.9x<br>convert chain              6.74 µs       4.08 µs        1.7x</pre><p>The 94.3x speedup on batch gettz() comes from a process-global RwLock&lt;HashMap&gt; cache - similar to python-dateutil&#39;s _TzFactory, but with Rust&#39;s near-zero-cost Arc clone for cached timezone objects. Even without the cache hit, individual timezone operations see 1.7x-3.8x improvements from compiled execution alone.</p><h3>Easter — Up to 6.2x Faster</h3><pre>Benchmark            python-dateutil    dateutil-rs    Speedup<br>──────────────────────────────────────────────────────────────<br>Single call                0.51 µs       0.13 µs        3.9x<br>1000 years               437.88 µs      70.46 µs        6.2x</pre><h3>Why Is It Fast? It’s Just Rust Being Rust</h3><p>Here’s the surprising part: <strong>the Rust code is a faithful, almost line-by-line translation of the Python source</strong>. I didn’t design clever algorithms or exploit Rust-specific data structures. The speedups come from the fundamental differences between compiled and interpreted execution.</p><p>Profiling revealed that Python’s overhead isn’t in any single place — it’s <strong>everywhere</strong>. Every function call, every attribute access, every integer comparison, every object allocation pays an interpreter tax. In a tight loop, these micro-costs compound dramatically. That’s why even a naive port sees 5x-94x improvements on batch operations.</p><p>Let’s look at three modules to see exactly where the performance comes from:</p><h3>isoparse: Byte-Level Parsing (23.5x)</h3><p>The original isoparser in Python uses string slicing and int() conversion. The Rust version does the same logic - but on byte arrays instead of Python strings:</p><pre>fn parse_isodate_common(&amp;self, dt_str: &amp;[u8]) -&gt; Result&lt;([i32; 3], usize), String&gt; {<br>    let mut c = [1i32; 3]; // [year, month, day]<br><br>    // Year: parse 4 ASCII bytes directly<br>    c[0] = parse_int(&amp;dt_str[..4])?;<br>    let mut pos = 4;<br><br>    let has_sep = dt_str[pos] == b&#39;-&#39;;<br>    if has_sep { pos += 1; }<br><br>    // Month: 2 bytes<br>    c[1] = parse_int(&amp;dt_str[pos..pos + 2])?;<br>    pos += 2;<br><br>    // Day: 2 bytes<br>    // ...<br>}</pre><p>Same algorithm as the Python version. No string allocation, no regex, no dynamic dispatch — just the inherent overhead of interpretation removed. The parse_int helper converts ASCII bytes to integers with a multiply-and-add loop. For a microsecond field like 123456, this is dramatically faster than Python&#39;s int(&quot;123456&quot;).</p><p>Result: &quot;2024-01-15T10:30:00.123456+09:00&quot; goes from 2.67 µs to 0.11 µs.</p><h3>RelativeDelta: Fixed Struct vs Dynamic Attributes (18.7x)</h3><p>Python’s relativedelta stores fields as instance attributes with getattr/ setattr patterns. The Rust version uses a fixed struct - same fields, same logic:</p><pre>pub struct RelativeDelta {<br>    // Relative (plural) fields — offsets<br>    years: i32,<br>    months: i32,<br>    days: f64,<br>    hours: f64,<br>    minutes: f64,<br>    seconds: f64,<br>    microseconds: f64,<br>    // Absolute (singular) fields — &quot;set to this value&quot;<br>    year: Option&lt;i32&gt;,<br>    month: Option&lt;i32&gt;,<br>    day: Option&lt;i32&gt;,<br>    // ...<br>}</pre><p>Multiplication is just multiplying each field — no dictionary lookups, no attribute resolution, no type coercion overhead. Same algorithm, 18.7x faster.</p><h3>RRule: Same Algorithm, Less Overhead (9.1x-20x)</h3><p>Recurrence rules (RFC 5545) are the most complex module — they expand patterns like “every 3rd Tuesday of the month” into concrete dates. The Rust implementation follows the same expansion algorithm as python-dateutil:</p><ul><li>Stack-allocated date arithmetic via chrono instead of Python datetime objects</li><li>No per-iteration object allocation or GC pressure</li><li>Integer comparisons instead of Python object protocol (__lt__, __eq__)</li></ul><p>For yearly rules over 100 occurrences, the overhead compounds: 2,144 µs → 235 µs. For rrulestr parsing, the gap is even wider - 20x faster because string-to-rule conversion involves heavy tokenization that benefits enormously from compiled execution.</p><h3>What’s Next: v1 — Actually Optimized Rust</h3><p>Everything above is <strong>v0</strong> — a compatibility-first port that proves Rust’s floor is Python’s ceiling. The Rust code deliberately mirrors Python’s logic to ensure behavioral fidelity against 13,000 lines of inherited tests.</p><p><strong>v1</strong> is where things get interesting. It will be a clean Rust-native implementation with real optimizations:</p><pre>Optimization              Technique                          Target Impact<br>──────────────────────────────────────────────────────────────────────────────<br>Zero-copy parsing         &amp;str slices instead of             Parser: 5x–50x<br>                          String clones<br>Compile-time hash maps    phf perfect hash for               Parser: faster<br>                          weekday/month lookup               tokenization<br>Buffer reuse              Pre-allocated buffers              RRule: 5x–15x<br>                          cleared across iterations<br>Minimal allocations       SmallVec, stack buffers,           All modules<br>                          arena patterns<br>Streamlined API           Drop rarely-used features          Smaller,<br>                          (fuzzy parse, POSIX tz)            faster core</pre><p>v1 will ship as:</p><ul><li>dateutil on <strong>crates.io</strong> — pure Rust crate, no PyO3 dependency</li><li>dateutil on <strong>PyPI</strong> — thin PyO3 binding layer wrapping the Rust core</li></ul><p>The v0 → v1 migration path:</p><pre>v0.x: faithful python-dateutil port (current — 1.3x–94x faster)<br>v1.x: Rust-optimized core (target — 5x–100x faster)</pre><p>If a naive port already delivers up to 94x speedups, imagine what happens when the Rust code is actually written like Rust.</p><h3>What I Learned Building This</h3><h3>PyO3 Is Remarkably Ergonomic</h3><p>PyO3’s derive macros make exposing Rust types to Python straightforward:</p><pre>#[pyclass(name = &quot;relativedelta&quot;)]<br>pub struct RelativeDelta { /* ... */ }<br><br>#[pymethods]<br>impl RelativeDelta {<br>    #[new]<br>    fn new(/* 15+ optional kwargs */) -&gt; Self { /* ... */ }<br><br>    fn __add__(&amp;self, other: &amp;Bound&lt;&#39;_, PyAny&gt;) -&gt; PyResult&lt;PyObject&gt; {<br>        // Handle datetime + relativedelta<br>    }<br>}</pre><p>The trickiest part was datetime ↔ chrono conversion. PyO3&#39;s chrono feature handles the basics, but timezone-aware datetimes require careful handling of the Python tzinfo protocol.</p><h3>A Faithful Port Is a Valid Strategy</h3><p>The instinct when rewriting in Rust is to redesign everything. I resisted that. By keeping the logic 1:1 with Python, I could validate correctness against the original test suite — and still ship massive speedups. The optimization pass (v1) comes later, built on a foundation that is already proven correct.</p><h3>Where the Overhead Actually Is</h3><p>The takeaway is clear: CPython’s per-operation overhead is small in isolation, but it compounds multiplicatively in loops. A date parser that touches 10 fields per call, called 10,000 times, pays the interpreter tax 100,000 times. Rust pays it zero times.</p><h3>Try It</h3><pre>pip install python-dateutil-rs</pre><ul><li><strong>GitHub</strong>: <a href="https://github.com/wakita181009/dateutil-rs">wakita181009/dateutil-rs</a></li><li><strong>PyPI</strong>: <a href="https://pypi.org/project/python-dateutil-rs/">python-dateutil-rs</a></li><li><strong>Python</strong>: 3.10–3.14 on Linux and macOS (Windows support planned)</li></ul><p>The project is open source (MIT). If your application use Ws python-dateutil, switching is a one-line import change. v0 is stable, fully tested, and API-compatible. v1 — the Rust-optimized core with zero-copy parsing and phf hash maps — is coming.</p><p>The numbers speak for themselves. And once zero-copy parsing and arena allocation land in v1, they’re about to get a lot bigger.</p><p><em>Originally published at </em><a href="https://dev.to/wakita181009/i-rewrote-python-dateutil-in-rust-even-a-naive-port-is-up-to-94x-faster-4n4e"><em>https://dev.to</em></a><em> on April 8, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=404f13b08336" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zod vs Typia vs AJV — I Built a Build Plugin That Makes Zod 60x Faster With Zero Code Changes]]></title>
            <link>https://medium.com/@wakita181009/zod-vs-typia-vs-ajv-i-built-a-build-plugin-that-makes-zod-60x-faster-with-zero-code-changes-b2ca4b133523?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ca4b133523</guid>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 17:40:29 GMT</pubDate>
            <atom:updated>2026-03-29T18:03:20.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FldB4e4XdwT1lfMV.png" /></figure><p>When I first released Zod AOT, it required wrapping every schema with compile():</p><pre>import { compile } from &quot;zod-aot&quot;;<br><br>const UserSchema = compile(<br>  z.object({<br>    name: z.string().min(1),<br>    email: z.email(),<br>  })<br>);ty</pre><p>The #1 feedback was: <strong>“I don’t want to change my code.”</strong></p><p>Fair. So I removed that requirement. Zod AOT now has an autoDiscover mode - a Vite plugin that finds your Zod schemas at build time, compiles them into optimized validators, and replaces them in-place. Your schema files stay pure Zod. No imports from zod-aot. No wrappers. Just this:</p><pre>// vite.config.ts<br>import zodAot from &quot;zod-aot/vite&quot;;<br><br>export default defineConfig({<br>  plugins: [zodAot({ autoDiscover: true })],<br>});</pre><p>That’s it. Every exported Zod schema in your project gets AOT-compiled at build time.</p><p>I also added Typia and AJV to the benchmarks, built a two-phase “Fast Path” validator, and shipped a diagnostic CLI. Here’s what changed.</p><h3>autoDiscover: How It Works</h3><p>The challenge is detecting Zod schemas without any marker in the source code. There’s no compile() call, no special import - just plain Zod:</p><pre>// src/schemas.ts — plain Zod, no Zod AOT import<br>import { z } from &quot;zod&quot;;<br><br>export const CreateUserSchema = z.object({<br>  name: z.string().min(1).max(100),<br>  email: z.email(),<br>  age: z.number().int().min(0).max(150),<br>  role: z.enum([&quot;admin&quot;, &quot;editor&quot;, &quot;viewer&quot;]),<br>});<br><br>export const UpdateUserSchema = z.object({<br>  name: z.string().min(1).max(100).optional(),<br>  email: z.email().optional(),<br>  age: z.number().int().min(0).max(150).optional(),<br>  role: z.enum([&quot;admin&quot;, &quot;editor&quot;, &quot;viewer&quot;]).optional(),<br>});</pre><p>The plugin detects and compiles these in four steps:</p><h3>Step 1: Regex Pre-filter</h3><p>Before doing any work, the plugin checks if the file contains a runtime Zod import:</p><pre>import { z } from &quot;zod&quot;   ✓  (runtime — schema definitions)<br>import type { z } from &quot;zod&quot;  ✗  (type-only — skip)</pre><p>Files without a runtime Zod import are skipped entirely. This keeps build times fast — most files in your project aren’t schema files.</p><h3>Step 2: Execute and Inspect Exports</h3><p>The plugin loads the source file at build time using <a href="https://github.com/unjs/jiti">jiti</a> and inspects each export:</p><pre>function isZodSchema(value: unknown): boolean {<br>  if (typeof value !== &quot;object&quot; || value === null || !(&quot;_zod&quot; in value))<br>    return false;<br>  const zod = (value as Record&lt;string, unknown&gt;)[&quot;_zod&quot;];<br>  return typeof zod === &quot;object&quot; &amp;&amp; zod !== null &amp;&amp; &quot;def&quot; in zod;<br>}</pre><p>Every Zod schema has a _zod.def structure - this is the internal definition that describes the schema&#39;s type, checks, and children. If an export has this marker, it&#39;s a Zod schema.</p><h3>Step 3: Compile to Optimized Validators</h3><p>Each discovered schema goes through the Zod AOT compilation pipeline:</p><pre>Zod Schema → Extract IR → Generate Code → Wrap in IIFE</pre><p>The pipeline walks the schema tree, extracts an intermediate representation, and generates flat, inlined validation code — the same process as before, but triggered automatically.</p><h3>Step 4: AST-Based Source Replacement</h3><p>The plugin uses <a href="https://github.com/acornjs/acorn">acorn</a> to parse expression boundaries in the source code:</p><pre>// Before (source)<br>export const CreateUserSchema = z.object({ ... });<br><br>// After (build output)<br>export const CreateUserSchema = /* @__PURE__ */ (() =&gt; {<br>  // ... generated validation code ...<br>  var __w = Object.create(originalSchema);<br>  __w.parse = function(input) { /* optimized */ };<br>  __w.safeParse = __validate;<br>  __w.schema = originalSchema;<br>  return __w;<br>})();</pre><p>The Object.create(originalSchema) is key - it preserves the full Zod API. Your compiled schema still has .shape, .keyof(), .pick(), .merge(), and everything else. Framework code that inspects schema metadata (like tRPC or React Hook Form resolvers) continues to work.</p><h3>Build Output</h3><p>With verbose: true, you see what happened:</p><pre>[zod-aot] Auto-discovering: src/schemas.ts (4 Zod exports found)<br>[zod-aot]   ✓ CreateUserSchema<br>[zod-aot]   ✓ UpdateUserSchema<br>[zod-aot]   ✓ ListUsersSchema<br>[zod-aot]   ✓ UserIdSchema<br>[zod-aot] Build summary: 4/4 schemas optimized across 1 file(s)</pre><h3>Scoping</h3><p>Not every file should be auto-discovered — you probably don’t want to execute test fixtures or files with side effects at build time. Use include and exclude:</p><pre>zodAot({<br>  autoDiscover: true,<br>  include: [&quot;src/schemas&quot;],<br>  exclude: [&quot;test&quot;, &quot;mock&quot;],<br>});</pre><h3>Two-Phase Validation: The Fast Path</h3><p>The prior version of Zod AOT generated error-collecting validators — they always created an issues array and tracked every validation failure. That’s necessary for error reporting, but it’s overhead when the input is valid.</p><p>In production, <strong>most inputs are valid</strong>. So I added a Fast Path.</p><h3>Phase 1: Boolean Expression Chain</h3><p>For valid inputs, the entire schema is validated with a single boolean expression:</p><pre>// Generated Fast Path for CreateUserSchema<br>typeof input===&quot;object&quot;&amp;&amp;input!==null&amp;&amp;!Array.isArray(input)&amp;&amp;<br>typeof input.name===&quot;string&quot;&amp;&amp;input.name.length&gt;=1&amp;&amp;input.name.length&lt;=100&amp;&amp;<br>typeof input.email===&quot;string&quot;&amp;&amp;__re0.test(input.email)&amp;&amp;<br>typeof input.age===&quot;number&quot;&amp;&amp;!Number.isNaN(input.age)&amp;&amp;<br>  Number.isSafeInteger(input.age)&amp;&amp;input.age&gt;=0&amp;&amp;input.age&lt;=150&amp;&amp;<br>(input.role===&quot;admin&quot;||input.role===&quot;editor&quot;||input.role===&quot;viewer&quot;)</pre><p>If this evaluates to true, the function returns { success: true, data: input } immediately.</p><p><strong>Zero allocations.</strong> No issues array. No error objects. No path arrays. Just a boolean chain that short-circuits on the first failure.</p><p>Regex patterns and enum Sets are pre-compiled in a preamble:</p><pre>var __re0 = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;<br>// Small enums (≤3 values) use inline === checks instead of Set.has()</pre><h3>Phase 2: Error-Collecting Path (Slow Path)</h3><p>If the Fast Path fails — meaning the input has at least one issue — the full error-collecting validator runs. This creates the standard { success: false, error: { issues: [...] } } response with codes, paths, and messages.</p><p>The key insight: <strong>the Slow Path only runs when it’s actually needed.</strong> For hot API endpoints where 95%+ of requests pass validation, the Fast Path is all that executes.</p><h3>Fast Path Eligibility</h3><p>Not every schema qualifies for a Fast Path. Schemas with .transform(), .refine(), .default(), .coerce(), or .catch() are ineligible because they need to modify the input or run opaque functions. The check command (see below) tells you which schemas qualify.</p><h3>The 5-Way Benchmark</h3><p>I added <a href="https://github.com/samchon/typia">Typia</a> and <a href="https://github.com/ajv-validator/ajv">AJV</a> to the benchmark suite. All five validators parse the same data with equivalent schemas:</p><ul><li><strong>Zod v3</strong>: Interpreter model, walks schema tree on every call</li><li><strong>Zod v4</strong>: New architecture with JIT object compilation via new Function()</li><li><strong>Zod AOT</strong>: Build-time compilation with two-phase validation</li><li><strong>Typia</strong>: Compile-time code generation via TypeScript transformer</li><li><strong>AJV</strong>: JSON Schema validator with ahead-of-time compilation</li></ul><p>Environment: Node.js v22, Apple M-series, Vitest bench, 1M+ iterations with warmup.</p><h3>Full Results</h3><pre>Schema                      Zod v3   Zod v4   Zod AOT   Typia    AJV<br>──────────────────────────────────────────────────────────────────────<br>String min/max               8.3M     5.6M    10.6M*   10.5M    8.8M<br>Enum                         7.6M     9.3M    10.2M    10.8M*  10.7M<br>Medium object (valid)        1.3M     1.7M     5.2M     7.0M*   4.8M<br>Medium object (invalid)      365K      63K      471K     2.1M    4.7M*<br>Large object — 100 items     8.6K    11.6K     627K     808K*    89K<br>Discriminated union (3)      2.3M     3.0M    10.2M    10.6M*   5.4M<br>Recursive tree — 121 nodes    23K     103K      733K     1.4M*   251K<br>Set (20 items)               980K     461K     7.6M*      —        —<br>Map (20 entries)             479K     235K     5.1M*      —        —<br>Event log (mixed types)      263K     473K     4.5M*      —        —<br>Partial fallback — 50 items   18K      30K      238K*      —        —</pre><p><em>ops/sec — higher is better. “-” = type not supported by the library.</em> <strong>What the numbers tell us:</strong></p><p><strong>Primitives</strong> — All AOT approaches converge around ~10.5M ops/sec. This is the V8 ceiling for simple type checks. No meaningful difference between Zod AOT, Typia, and AJV.</p><p><strong>Objects</strong> — Typia leads (1.3x over Zod AOT on medium, 1.2x on large). But the gap narrows as objects grow — the Fast Path’s single boolean chain scales well. AJV collapses on large objects (9x slower than Typia at 100 items). Zod v4 is 3–54x slower than both.</p><p><strong>Invalid inputs</strong> — AJV dominates the error path (4.7M ops/s) with minimal error construction. Zod v4 is slowest at 63K due to rich structured errors. In practice, most production inputs are valid — the Fast Path handles those.</p><p><strong>Collections (Set/Map)</strong> — Zod AOT’s exclusive territory. Typia doesn’t validate Set or Map contents. AJV doesn’t support JS-native types. Zod AOT is <strong>16–22x faster</strong> than Zod v4 here.</p><p><strong>Recursive</strong> — Typia leads 1.9x over Zod AOT on deep trees. Zod AOT currently uses z.lazy() fallback for recursive references - improving this is on the roadmap.</p><p><strong>Partial fallback</strong> — Schemas with .transform() can&#39;t be fully AOT-compiled, but Zod AOT compiles everything it can and delegates the rest to Zod. Even partial compilation delivers <strong>2.6-8x</strong> over Zod v4.</p><h3>The Scoreboard</h3><pre>Category                  Winner                    Runner-up<br>──────────────────────────────────────────────────────────────────────<br>Primitives                Tie (all AOT ≈ 10.5M)     —<br>Objects (valid)           Typia                     Zod AOT (within 1.2x)<br>Objects (invalid)         AJV                       Typia<br>Collections (Set/Map)     Zod AOT                   (only competitor)<br>Discriminated unions      Tie (Typia ≈ Zod AOT)     —<br>Recursive                 Typia                     Zod AOT (1.9x gap)<br>Partial compilation       Zod AOT                   (only competitor)</pre><p>Zod AOT sits in a unique position: <strong>near-Typia performance with full Zod API compatibility.</strong> You don’t need type-level tags, a different schema DSL, or JSON Schema. You keep z.object(), z.email(), .transform(), .refine() - and the build plugin handles the rest.</p><h3>The check Command: Know Your Coverage</h3><p>Not sure what percentage of your schemas will be compiled? Run check:</p><pre>npx zod-aot check src/schemas.ts</pre><pre>validateUser — 100% compiled (8/8 nodes) | Fast Path: eligible<br>  └─ ✓ object<br>     ├─ ✓ string .name<br>     ├─ ✓ string .email<br>     ├─ ✓ number .age<br>     ├─ ✓ enum .role<br>     ├─ ✓ boolean .isActive<br>     ├─ ✓ array .tags<br>     │  └─ ✓ string .tags[]<br>     └─ ✓ nullable .bio<br>        └─ ✓ string .bio<br><br>validateOrder — 80% compiled (4/5 nodes) | Fast Path: ineligible<br>  └─ ✓ object<br>     ├─ ✓ string .orderId<br>     ├─ ✓ number .amount<br>     ├─ ✓ enum .currency<br>     └─ ✗ fallback .slug (transform)<br>           hint: Extract transform into a separate post-processing step</pre><p>Each schema gets a tree view showing:</p><ul><li>Which nodes are fully compiled (✓) vs falling back to Zod (✗)</li><li>Compilation coverage percentage</li><li>Fast Path eligibility</li><li>Actionable hints for improving coverage</li></ul><h3>CI Integration</h3><pre># Fail if compilation coverage drops below 80%<br>npx zod-aot check src/schemas/ --fail-under 80 --json</pre><p>The --json flag outputs structured data for CI pipelines:</p><pre>{<br>  &quot;exportName&quot;: &quot;validateOrder&quot;,<br>  &quot;coverage&quot;: { &quot;total&quot;: 5, &quot;compilable&quot;: 4, &quot;percent&quot;: 80 },<br>  &quot;fastPath&quot;: { &quot;eligible&quot;: false, &quot;blocker&quot;: &quot;fallback (transform)&quot; },<br>  &quot;fallbacks&quot;: [{<br>    &quot;reason&quot;: &quot;transform&quot;,<br>    &quot;path&quot;: &quot;.slug&quot;,<br>    &quot;hint&quot;: &quot;Extract transform into a separate post-processing step&quot;<br>  }]<br>}</pre><h3>Framework Integration</h3><p>autoDiscover works at the build layer — framework code doesn’t know or care:</p><p><strong>tRPC</strong>: Schemas auto-compiled, router unchanged.</p><pre>// router.ts — no changes needed<br>const appRouter = router({<br>  createUser: publicProcedure<br>    .input(CreateUserSchema)  // ← this is now AOT-compiled<br>    .mutation(({ input }) =&gt; db.users.create(input)),<br>});</pre><p><strong>Hono</strong>: Middleware validation auto-optimized.</p><pre>app.post(&quot;/users&quot;, zValidator(&quot;json&quot;, CreateUserSchema), (c) =&gt; {<br>  // CreateUserSchema is AOT-compiled at build time<br>  const data = c.req.valid(&quot;json&quot;);<br>});</pre><p><strong>React Hook Form</strong>: Resolver schemas auto-compiled.</p><pre>const { register } = useForm({<br>  resolver: zodResolver(CreateUserSchema), // AOT-compiled<br>});</pre><p>The Object.create() wrapper ensures that framework code reading .shape, .keyof(), or other Zod metadata still works - the compiled schema inherits from the original.</p><h3>What I Learned from the Competition</h3><p><strong>Typia</strong> is the performance king for objects and recursive structures. Its compile-time TypeScript transformer generates monolithic validation functions with zero runtime overhead. But:</p><ul><li>It requires type-level tags (tags.MinLength&lt;3&gt;) instead of method chaining - a different mental model</li><li>It doesn’t validate Set or Map contents</li><li>No bigint support</li><li>No .transform() or .refine() - it&#39;s a validator, not a parser</li></ul><p><strong>AJV</strong> has the best error-path performance and the broadest ecosystem (JSON Schema is a standard). But:</p><ul><li>JSON Schema doesn’t support JavaScript-native types (Set, Map)</li><li>Verbose schema definitions — no chaining, no composition</li><li>No transforms or pipes — declarative validation only</li></ul><p><strong>Zod AOT</strong> fills the gap: Zod’s composable API, near-Typia performance, full JavaScript type support, and partial compilation for schemas that mix validation with transformation.</p><h3>Get Started</h3><pre>npm install zod-aot zod@^4</pre><pre>// vite.config.ts — that&#39;s the entire setup<br>import zodAot from &quot;zod-aot/vite&quot;;<br><br>export default defineConfig({<br>  plugins: [zodAot({ autoDiscover: true })],<br>});</pre><p>Your existing Zod schemas are now AOT-compiled. No code changes.</p><p>Also works with webpack, esbuild, Rollup, Rolldown, rspack, and Bun via <a href="https://github.com/unjs/unplugin">unplugin</a>.</p><ul><li><strong>GitHub</strong>: <a href="https://github.com/wakita181009/zod-aot">github.com/wakita181009/zod-aot</a></li><li><strong>npm</strong>: <a href="https://www.npmjs.com/package/zod-aot">zod-aot</a></li></ul><h3>Methodology</h3><p>All benchmarks use safeParse() on pre-created schema instances, measured with Vitest bench (1M+ iterations, with warmup). Numbers are steady-state throughput - JIT is already compiled after the first call. Typia uses createValidate&lt;T&gt;(). AJV uses ajv.compile(schema). Invalid-input benchmarks use all-fields-invalid payloads to stress the error path.</p><ul><li><strong>Environment</strong>: Node.js v22, Apple M-series</li><li><strong>Libraries</strong>: Zod v3.24, Zod v4, Zod AOT 0.14, Typia 12, AJV 8</li><li><strong>Raw data</strong>: <a href="https://github.com/wakita181009/zod-aot/tree/main/benchmarks">benchmarks/</a> in the zod-aot repo</li></ul><p><em>Originally published at </em><a href="https://dev.to/wakita181009/zod-vs-typia-vs-ajv-i-built-a-vite-plugin-that-makes-zod-60x-faster-with-zero-code-changes-1poc"><em>https://dev.to</em></a><em> on March 29, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ca4b133523" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Is Zod v4 Fast — and Where Is Its Ceiling?]]></title>
            <link>https://medium.com/@wakita181009/why-is-zod-v4-fast-and-where-is-its-ceiling-edf0f1524079?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf0f1524079</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[aot]]></category>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 20:49:06 GMT</pubDate>
            <atom:updated>2026-03-19T21:32:52.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KBbjTlIu14stV5lV.png" /></figure><p>Zod v4 is faster than v3. But almost nobody knows <em>why</em>. It’s not just a cleaner codebase or smaller bundle — Zod v4 has a JIT-like code generator that builds specialized validation functions at runtime using new Function(). It&#39;s hidden inside a class called $ZodObjectJIT, and unless you read the source, you&#39;d never know it was there.</p><p>I read the internals to understand how v4’s performance works, benchmarked every schema type, and used what I learned to build an AOT compiler that extends the same idea to build time. Here’s everything I found.</p><p><strong>What the benchmarks show:</strong></p><ul><li>v4’s JIT targets <strong>object schemas</strong> — delivering 1.3–4.5x over v3 for objects and recursive structures</li><li>For other types (primitives with checks, collections), v4 traded raw throughput for a richer architecture (better errors, async support, modular checks)</li><li>AOT compilation extends the JIT principle to <strong>all schema types</strong>: 3–60x faster than v4</li></ul><h3>Zod v3: The Interpreter Model</h3><p>Every time you call .parse() in Zod v3, the same thing happens: the entire schema tree gets walked at runtime. Each node dispatches based on type — string, number, object, array — and the traversal recurses until it hits the leaves.</p><pre>// Simplified: what Zod v3 does on every .parse() call<br>function parse(schema, data) {<br>  switch (schema._def.typeName) {<br>    case &quot;ZodString&quot;:  return parseString(schema._def, data);<br>    case &quot;ZodNumber&quot;:  return parseNumber(schema._def, data);<br>    case &quot;ZodObject&quot;:  return parseObject(schema._def, data); // recurses into each property<br>    case &quot;ZodArray&quot;:   return parseArray(schema._def, data);  // recurses into each element<br>    // ...<br>  }<br>}</pre><p>This is an interpreter. The schema is a data structure, and Zod walks it every time. For a simple z.string(), the overhead is negligible. For a nested object with 100 items, you&#39;re traversing hundreds of nodes on every single call.</p><p>The schema never changes. But Zod re-discovers its structure every time.</p><h3>Zod v4: A New Architecture</h3><p>Zod v4 introduced a fundamentally different internal architecture. Every schema now has a _zod object with two key functions:</p><ul><li><strong>_zod.parse</strong>: The type-specific validation logic (type check, structural validation)</li><li><strong>_zod.run</strong>: Orchestrates parse + runs checks (.min(), .max(), .email(), etc.)</li></ul><pre>.parse(data) → _zod.run({ value, issues }, ctx) → _zod.parse(payload, ctx) → runChecks()</pre><p>When a schema has no checks, Zod v4 optimizes by making _zod.run point directly to _zod.parse — skipping the check orchestration entirely.</p><p>The new architecture also brought real improvements beyond performance: structured error objects with full path tracking, first-class async support, modular check pipelines, and globalConfig for runtime tuning. These features have a small cost in the hot path — a deliberate trade-off that makes Zod v4 far more capable than v3.</p><p>But the most interesting optimization is hidden deeper.</p><h3>The Hidden JIT: $ZodObjectJIT</h3><h3>The Doc Class: Runtime Code Generation</h3><p>Deep inside Zod v4’s source (schemas.js), there&#39;s a class called Doc. It doesn&#39;t validate data. It generates JavaScript code as strings and compiles them into functions using new Function():</p><pre>// From zod/v4/core/doc.js — a runtime code generator<br>export class Doc {<br>  constructor(args) {<br>    this.content = [];<br>    this.args = args;<br>  }<br><br>  write(code) {<br>    // Accumulates lines of JavaScript source code<br>    this.content.push(code);<br>  }<br><br>  compile() {<br>    const F = Function;<br>    // new Function(&quot;arg1&quot;, &quot;arg2&quot;, &quot;...code...&quot;) → executable function<br>    return new F(...this.args, this.content.join(&quot;\n&quot;));<br>  }<br>}</pre><p>This is runtime code generation: it builds JavaScript source as strings and compiles it with new Function() for reuse on later parses. Strictly speaking, this isn&#39;t a full optimizing JIT like V8 or HotSpot — but it plays a similar role: specialize once, reuse many times.</p><h3>How $ZodObjectJIT Works</h3><p>$ZodObjectJIT wraps the standard $ZodObject parser. On the first .parse() call, it generates a specialized validation function for that specific object shape:</p><pre>// From zod/v4/core/schemas.js — simplified<br>export const $ZodObjectJIT = core.$constructor(&quot;$ZodObjectJIT&quot;, (inst, def) =&gt; {<br>  $ZodObject.init(inst, def);<br>  const superParse = inst._zod.parse;  // Save the original<br><br>  const generateFastpass = (shape) =&gt; {<br>    const doc = new Doc([&quot;shape&quot;, &quot;payload&quot;, &quot;ctx&quot;]);<br>    doc.write(`const input = payload.value;`);<br>    doc.write(`const newResult = {};`);<br><br>    for (const key of Object.keys(shape)) {<br>      // Generate inline validation code for each property<br>      doc.write(`const r_${key} = shape[&quot;${key}&quot;]._zod.run(<br>        { value: input[&quot;${key}&quot;], issues: [] }, ctx);`);<br>      doc.write(`if (r_${key}.issues.length) { /* merge issues */ }`);<br>      doc.write(`newResult[&quot;${key}&quot;] = r_${key}.value;`);<br>    }<br><br>    doc.write(`payload.value = newResult;`);<br>    doc.write(`return payload;`);<br>    return doc.compile();  // → new Function(...)<br>  };<br><br>  let fastpass;  // Cached compiled function<br><br>  inst._zod.parse = (payload, ctx) =&gt; {<br>    if (jit &amp;&amp; fastEnabled &amp;&amp; ctx?.async === false &amp;&amp; ctx.jitless !== true) {<br>      if (!fastpass) fastpass = generateFastpass(def.shape);  // First call only<br>      return fastpass(shape, payload, ctx);<br>    }<br>    return superParse(payload, ctx);  // Fallback<br>  };<br>});</pre><p>On the first parse call:</p><ol><li>Iterates over the object shape</li><li>Generates JavaScript code that validates each property inline</li><li>Compiles it with new Function()</li><li>Caches the compiled function in fastpass</li></ol><p>Every subsequent call skips the code generation and executes the cached function directly.</p><h3>Environment Detection</h3><p>Before the JIT path kicks in, Zod v4 checks whether the runtime allows new Function():</p><pre>const jit = !core.globalConfig.jitless;<br>const fastEnabled = jit &amp;&amp; allowsEval.value;</pre><pre>// From zod/v4/core/util.js<br>export const allowsEval = cached(() =&gt; {<br>  if (typeof navigator !== &quot;undefined&quot; &amp;&amp;<br>      navigator?.userAgent?.includes(&quot;Cloudflare&quot;)) {<br>    return false;  // Cloudflare Workers blocks eval<br>  }<br>  try {<br>    const F = Function;<br>    new F(&quot;&quot;);<br>    return true;<br>  } catch (_) {<br>    return false;  // CSP-restricted environments<br>  }<br>});</pre><p>If new Function() is blocked — Cloudflare Workers, strict CSP headers, or jitless mode — Zod v4 gracefully falls back to the standard parse path. The validation result is identical; only the execution speed differs.</p><h3>What JIT Covers (and What It Doesn’t)</h3><p>$ZodObjectJIT targets the most impactful case: <strong>object schemas</strong>. Objects are by far the most common complex schema in real applications — every API request body, every form, every database row.</p><p>But it’s specifically scoped to objects:</p><ul><li>z.string().min(1).email() — uses the standard check pipeline</li><li>z.number().int().positive() — uses the standard check pipeline</li><li>z.array(z.string()) — standard parse (though nested objects inside get JIT)</li><li>z.set(), z.map(), z.record() — standard parse</li><li>z.discriminatedUnion() — has its own separate optimization (a Map lookup table)</li></ul><p>The generated code also still calls shape[key]._zod.run() for each property — it delegates to child schemas at runtime. The JIT eliminates the object-level dispatch overhead, but the per-property traversal remains.</p><h3>Benchmarks: Where JIT Helps</h3><p>I benchmarked Zod v3, Zod v4, and Zod AOT across every schema type. The results show exactly where the JIT makes a difference.</p><h3>Objects and Recursive Structures: JIT Territory</h3><pre>| Schema                    | Zod v3     | Zod v4     | Zod AOT    | v3 → v4          | v4 → AOT  |<br>|-                          |-           |-           |-           |-                 |-          |<br>| Medium object (valid)     | 1.3M ops/s | 1.6M ops/s | 5.5M ops/s | **1.31x faster** | 3.31x     |<br>| Large object (10 items)   | 81K        | 113K       | 4.0M       | **1.39x faster** | **35.8x** |<br>| Large object (100 items)  | 8.9K       | 12.0K      | 725K       | **1.35x faster** | **60.6x** |<br>| Recursive tree (7 nodes)  | 420K       | 1.5M       | 6.4M       | **3.69x faster** | 4.15x     |<br>| Recursive tree (121 nodes)| 23K        | 105K       | 739K       | **4.49x faster** | 7.05x     |<br>| Discriminated union (3)   | 2.4M       | 2.9M       | 10.1M      | **1.18x faster** | 3.54x     |</pre><p>This is where v4 shines. For valid object inputs, the JIT fast path delivers 1.3–1.4x over v3. For recursive structures — where each level hits an object schema — the JIT compounds: 3.7–4.5x over v3.</p><h3>Primitives: Architecture Trade-off Visible</h3><pre>| Schema           | Zod v3   | Zod v4   | Zod AOT  | v3 → v4       | v4 → AOT |<br>|-                 |-         |-         |-         |-              |-         |<br>| Simple string    | 8.5M     | 9.6M     | 11.0M    | 1.13x faster  | 1.15x    |<br>| String min/max   | 8.0M     | 5.8M     | 10.3M    | 0.73x         | 1.78x    |<br>| Number int+pos   | 7.9M     | 5.7M     | 11.0M    | 0.73x         | 1.93x    |<br>| Enum             | 7.3M     | 9.2M     | 10.4M    | 1.26x faster  | 1.13x    |<br>| Bigint min/max   | 7.5M     | 5.4M     | 10.2M    | 0.72x         | 1.89x    |</pre><p>For primitives with checks, v4’s modular check pipeline (separate check objects, runChecks orchestration) adds overhead compared to v3&#39;s simpler inline approach. This is the cost of v4&#39;s new features — structured errors, conditional checks via when, and the ability to compose check pipelines. The JIT doesn&#39;t apply here since these aren&#39;t object schemas.</p><p>At ~6M ops/s, this is still extremely fast for any real application. The difference only shows up in micro-benchmarks.</p><h3>Collections: No JIT (Yet)</h3><pre>| Schema             | Zod v3   | Zod v4   | Zod AOT  | v3 → v4       | v4 → AOT |<br>|-                   |-         |-         |-         |-              |-         |<br>| Tuple              | 3.9M     | 4.4M     | 10.4M    | 1.12x faster  | 2.38x    |<br>| Record (5 keys)    | 2.3M     | 1.6M     | 5.4M     | 0.69x         | 3.51x    |<br>| Set (5 items)      | 2.7M     | 1.5M     | 9.8M     | 0.58x         | 6.35x    |<br>| Set (20 items)     | 964K     | 464K     | 7.7M     | 0.48x         | 16.5x    |<br>| Map (5 entries)    | 1.5M     | 954K     | 8.5M     | 0.62x         | 8.96x    |<br>| Map (20 entries)   | 489K     | 239K     | 5.2M     | 0.49x         | 21.6x    |</pre><p>Collections (Set, Map, Record) go through the new internal pipeline without JIT assistance. The throughput difference vs v3 reflects the richer v4 architecture, not a regression — v4 does more work per element (payload construction, issue path tracking, async readiness).</p><p>This is where AOT makes the biggest relative difference: 16–22x for 20-item collections, since AOT can eliminate the per-element overhead entirely.</p><h3>Invalid Inputs: Error Construction Dominates</h3><pre>| Schema                             | Zod v3   | Zod v4   | Zod AOT  | v3 → v4  | v4 → AOT |<br>|-                                   |-         |-         |-         |-         |-         |<br>| Medium object (all-fields-invalid) | 381K     | 62K      | 476K     | 0.16x    | 7.64x    |</pre><p>The most dramatic difference is on invalid inputs. This benchmark uses an all-fields-invalid payload to stress-test the error path. v4’s error construction is significantly richer than v3’s — detailed issue objects with codes, paths, metadata, and i18n support. That richness has a cost in throughput benchmarks.</p><p>In real workloads where most inputs are valid, this gap is much smaller. And when inputs <em>are</em> invalid, v4’s structured errors make debugging far easier — that’s a worthwhile trade-off.</p><h3>Real-World Schemas</h3><pre>| Schema                    | Zod v3   | Zod v4   | Zod AOT  | v3 → v4       | v4 → AOT  |<br>|-                          |-         |-         |-         |-              |-          |<br>| Event log (mixed types)   | 265K     | 472K     | 4.5M     | 1.78x faster  | **9.55x** |<br>| Partial fallback (object) | 797K     | 1.4M     | 3.4M     | 1.77x faster  | 2.43x     |<br>| Partial fallback (50 arr) | 18K      | 29K      | 252K     | 1.61x faster  | **8.69x** |</pre><p>Real-world schemas mix objects, discriminated unions, tuples, and records. Here v4’s JIT contributes meaningfully: 1.6–1.8x over v3. AOT extends this further: 2.4–9.6x over v4.</p><p>The “partial fallback” rows show schemas with .transform() — fields that can&#39;t be AOT-compiled. zod-aot falls back to Zod for those fields while compiling the rest. Even partial compilation delivers 2.4-8.7x over v4.</p><h3>From JIT to AOT: Taking It Further</h3><p>v4’s JIT gave me the idea for zod-aot. The insight is the same: <strong>schemas are static, so validation can be specialized ahead of time</strong>. The JIT does this at runtime for objects. AOT does it at build time for everything.</p><p>Here’s the same schema, side by side:</p><pre>const UserSchema = z.object({<br>  name: z.string().min(1).max(100),<br>  email: z.string().email(),<br>  age: z.number().int().positive(),<br>});</pre><p><strong>Zod v4 JIT output</strong> (generated at runtime via new Function):</p><pre>const input = payload.value;<br>const newResult = {};<br><br>// Each property still delegates to the child schema&#39;s _zod.run()<br>const r_name = shape[&quot;name&quot;]._zod.run({ value: input[&quot;name&quot;], issues: [] }, ctx);<br>if (r_name.issues.length) {<br>  payload.issues = payload.issues.concat(<br>    r_name.issues.map(iss =&gt; ({ ...iss, path: [&quot;name&quot;, ...(iss.path || [])] }))<br>  );<br>}<br>newResult[&quot;name&quot;] = r_name.value;<br><br>const r_email = shape[&quot;email&quot;]._zod.run({ value: input[&quot;email&quot;], issues: [] }, ctx);<br>// ... same pattern for each property<br><br>payload.value = newResult;<br>return payload;</pre><p>The JIT eliminates the object-level dispatch loop. But each property still calls _zod.run() → _zod.parse() → runChecks(). The per-property overhead remains.</p><p><strong>Zod AOT output</strong> (generated at build time):</p><pre>function safeParse_User(input) {<br>  var __issues = [];<br>  if (typeof input !== &quot;object&quot; || input === null || Array.isArray(input)) {<br>    __issues.push({ code: &quot;invalid_type&quot;, expected: &quot;object&quot;, path: [] });<br>  } else {<br>    // Fully inlined — no function calls, no delegation<br>    if (typeof input[&quot;name&quot;] !== &quot;string&quot;) {<br>      __issues.push({ code: &quot;invalid_type&quot;, expected: &quot;string&quot;, path: [&quot;name&quot;] });<br>    } else if (input[&quot;name&quot;].length &lt; 1) {<br>      __issues.push({ code: &quot;too_small&quot;, minimum: 1, path: [&quot;name&quot;] });<br>    } else if (input[&quot;name&quot;].length &gt; 100) {<br>      __issues.push({ code: &quot;too_big&quot;, maximum: 100, path: [&quot;name&quot;] });<br>    }<br>    if (typeof input[&quot;email&quot;] !== &quot;string&quot;) {<br>      __issues.push({ code: &quot;invalid_type&quot;, expected: &quot;string&quot;, path: [&quot;email&quot;] });<br>    } else if (!__re_email.test(input[&quot;email&quot;])) {<br>      __issues.push({ code: &quot;invalid_format&quot;, format: &quot;email&quot;, path: [&quot;email&quot;] });<br>    }<br>    if (typeof input[&quot;age&quot;] !== &quot;number&quot; || Number.isNaN(input[&quot;age&quot;])) {<br>      __issues.push({ code: &quot;invalid_type&quot;, expected: &quot;number&quot;, path: [&quot;age&quot;] });<br>    } else if (!Number.isSafeInteger(input[&quot;age&quot;])) {<br>      __issues.push({ code: &quot;invalid_type&quot;, expected: &quot;int&quot;, path: [&quot;age&quot;] });<br>    } else if (input[&quot;age&quot;] &lt; 0) {<br>      __issues.push({ code: &quot;too_small&quot;, minimum: 0, path: [&quot;age&quot;] });<br>    }<br>  }<br>  if (__issues.length &gt; 0) return { success: false, error: { issues: __issues } };<br>  return { success: true, data: input };<br>}</pre><p>No schema objects. No _zod.run() calls. No check pipeline. Flat, inlined validation with zero dispatch overhead.</p><pre>|                      | Zod v4 JIT                        | Zod AOT                            |<br>|-                     |-                                  |-                                   |<br>| **When compiled**    | First `.parse()` call             | Build time                         |<br>| **Scope**            | Object-level dispatch only        | Full schema tree, all types        |<br>| **Per-property cost**| `_zod.run()` + checks pipeline    | Inlined type checks                |<br>| **Environment**      | Requires `new Function()`         | Works everywhere (no eval)         |<br>| **Cold start**       | First parse pays compilation cost | Zero — function exists at startup  |</pre><h3>Where AOT Matters Most</h3><p>In a long-running Node.js server, v4’s JIT warms up on the first request and stays fast. AOT’s advantage is smaller here.</p><p>But in environments where JIT can’t help:</p><ul><li><strong>Cloudflare Workers / strict CSP</strong>: new Function() is blocked. Zod v4 falls back to the standard parse path. AOT works everywhere — no eval needed.</li><li><strong>Serverless with frequent cold starts</strong>: Every new Lambda/Edge instance pays the JIT compilation cost. AOT has zero cold-start penalty.</li><li><strong>Collection-heavy validation</strong>: Set, Map, and Record schemas don’t benefit from JIT. AOT delivers 16–22x for these.</li><li><strong>High-throughput APIs</strong>: When you’re validating complex nested objects at &gt;10K requests/sec, AOT’s 35–60x improvement over v4 is the difference between needing 1 server and needing 60.</li></ul><h3>Trade-offs</h3><p>AOT isn’t free:</p><ul><li><strong>.transform(), </strong><strong>.refine(), </strong><strong>.superRefine()</strong> contain opaque functions that can&#39;t be compiled ahead of time. zod-aot falls back to Zod for these fields (partial compilation still helps, but the benefit is proportional to how much of your schema is compilable).</li><li><strong>Build integration required</strong> — a bundler plugin (Vite, webpack, esbuild) or CLI step. It’s 4 lines of config, but not zero.</li><li><strong>Generated code adds to bundle size</strong> — for most schemas this is smaller than Zod itself, but it’s a factor.</li><li><strong>Static schemas only</strong> — if you construct schemas dynamically at runtime, AOT can’t help.</li></ul><h3>When to Use What</h3><pre>| Scenario                                  | Recommendation   | Why                                      |<br>|-                                          |-                 |-                                         |<br>| Prototyping / small schemas               | Zod v4 as-is     | JIT is invisible, zero setup             |<br>| Long-running API server                   | Zod v4 is likely sufficient | JIT warms up on first request   |<br>| Cloudflare Workers / strict CSP           | **zod-aot**      | JIT is disabled — AOT works everywhere   |<br>| Serverless with frequent cold starts      | **zod-aot**      | Zero cold-start compilation cost         |<br>| Complex nested objects at high throughput | **zod-aot**      | 35-60x over v4                           |<br>| Set/Map/Record heavy validation           | **zod-aot**      | JIT doesn&#39;t cover these, AOT does        |<br>| Schemas dominated by `.transform()`       | Zod v4           | AOT can&#39;t compile opaque functions       |</pre><h3>Try Zod AOT</h3><pre>npm install zod-aot zod@^4</pre><pre>import { z } from &quot;zod&quot;;<br>import { compile } from &quot;zod-aot&quot;;<br><br>// Wrap with compile() — same API, AOT-compiled in production<br>const UserSchema = compile(<br>  z.object({<br>    name: z.string().min(1).max(100),<br>    email: z.string().email(),<br>    age: z.number().int().positive(),<br>  })<br>);<br><br>// .parse(), .safeParse(), .is() — all work as expected<br>const user = UserSchema.parse(data);</pre><p>Add the Vite plugin (4 lines):</p><pre>// vite.config.ts<br>import zodAot from &quot;zod-aot/vite&quot;;<br><br>export default defineConfig({<br>  plugins: [zodAot()],<br>});</pre><p>In development, compile() passes through to Zod. In production builds, the plugin replaces it with generated validation code. Zero code changes to your schemas.</p><ul><li><strong>GitHub</strong>: <a href="https://github.com/wakita181009/zod-aot">github.com/wakita181009/zod-aot</a></li><li><strong>npm</strong>: <a href="https://www.npmjs.com/package/zod-aot">zod-aot</a></li></ul><h3>Methodology</h3><p>All benchmarks use safeParse() on pre-created schema instances, measured with Vitest bench (1M+ iterations per case, with warmup). Zod v4 object benchmarks report steady-state throughput — the JIT fast path is already compiled after the first call. Invalid-input benchmarks use all-fields-invalid payloads to stress the error path. Async paths are excluded.</p><ul><li><strong>Environment</strong>: Node.js v22, Apple M-series</li><li><strong>Libraries</strong>: Zod v3.24, Zod v4.3, Zod AOT latest</li><li><strong>Raw data</strong>: <a href="https://github.com/wakita181009/zod-aot/tree/main/benchmarks">benchmarks/</a> in the zod-aot repo</li></ul><p><em>Originally published at </em><a href="https://dev.to/wakita181009/why-is-zod-v4-fast-and-where-is-its-ceiling-280l"><em>https://dev.to</em></a><em> on March 19, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edf0f1524079" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Google Apps Script with Any Bundler: Vite, Rollup, esbuild, webpack, and Bun]]></title>
            <link>https://medium.com/@wakita181009/build-google-apps-script-with-any-bundler-vite-rollup-esbuild-webpack-and-bun-f41918ecac4f?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f41918ecac4f</guid>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 16:38:15 GMT</pubDate>
            <atom:updated>2026-03-19T16:41:52.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ezFltANR5uTvNIhVW3JNg.png" /></figure><p><em>Google Apps Script projects shouldn’t be tied to one bundler.</em></p><p><em>So I rebuilt my Vite-only plugin into a universal plugin for Vite, Rollup, webpack, esbuild, and Bun — and added a scaffolding CLI on top.</em></p><h3>The problem with modern bundlers in Google Apps Script</h3><p>If you’ve ever deployed a GAS project only to find that doGet was silently removed by tree-shaking - or that export keywords broke the Apps Script runtime - you know the pain.</p><p>Google Apps Script has a slightly awkward relationship with modern JavaScript tooling.</p><p>Bundlers like Vite, Rollup, webpack, and esbuild are great at optimizing modules. But GAS expects certain functions — doGet, doPost, onOpen, installable triggers, menu handlers - to exist in the global scope with stable names.</p><p>That creates a few recurring problems:</p><ul><li>export is convenient in source code, but GAS doesn&#39;t want it in the final bundle</li><li>tree-shaking can remove entry points that are only referenced by the Apps Script runtime</li><li>appsscript.json has to be copied into the output alongside the bundle</li></ul><p>Here’s what the plugin actually does to your output:</p><pre>// Your source:<br>export function doGet(e) {<br>  return HtmlService.createHtmlOutput(&quot;Hello&quot;);<br>}<br><br>// Without plugin — bundler may wrap, rename, or tree-shake:<br>// doGet is gone or unreachable<br><br>// With @gas-plugin/unplugin — export stripped, global preserved:<br>function doGet(e) {<br>  return HtmlService.createHtmlOutput(&quot;Hello&quot;);<br>}</pre><p>In my previous post, I introduced <strong>gas-vite-plugin</strong>, a small Vite plugin that handled exactly that.</p><p>It worked well — but only for Vite.</p><p>If your team used Rollup, webpack, or esbuild, you had to solve the same problem a different way.</p><p>So I rebuilt it as a universal plugin.</p><h3>What changed</h3><p>The project is now <strong>@gas-plugin</strong> — a monorepo with two packages:</p><pre>| Package                  | What it does                                                         |<br>| -------------------------|----------------------------------------------------------------------|<br>| @gas-plugin/unplugin     | Universal bundler plugin for Vite, Rollup, webpack, esbuild, and Bun |<br>| @gas-plugin/cli          | Scaffolding CLI for new GAS projects                                 |</pre><p>The original <strong>gas-vite-plugin</strong> still exists as a deprecated compatibility package, but the main path going forward is @gas-plugin/unplugin.</p><h3>Why I rebuilt it with unplugin</h3><p>I could have maintained separate plugins for each bundler.</p><p>That would have meant duplicating the same logic across multiple packages: transform exported entry points, preserve GAS globals, and copy the manifest into the output directory.</p><p>Instead, I used <strong>unplugin</strong>, which lets you implement the plugin once and expose adapters for multiple bundlers. For this kind of narrowly focused build-time behavior, that’s a much better fit than maintaining five independent implementations.</p><p>The result is simple:</p><ul><li>same plugin behavior</li><li>same options</li><li>different import path per bundler</li></ul><p>That means the GAS-specific parts stay consistent even if your build tool changes.</p><h3>@gas-plugin/unplugin: one plugin, any bundler</h3><p>Here’s the same plugin working across different bundlers.</p><h3>Vite</h3><pre>import gasPlugin from &quot;@gas-plugin/unplugin/vite&quot;;<br>import { defineConfig } from &quot;vite&quot;;<br><br>export default defineConfig({<br>  plugins: [gasPlugin()],<br>  build: {<br>    lib: {<br>      entry: &quot;src/main.ts&quot;,<br>      formats: [&quot;es&quot;],<br>      fileName: () =&gt; &quot;Code.js&quot;,<br>    },<br>  },<br>});</pre><h3>Rollup</h3><pre>import gasPlugin from &quot;@gas-plugin/unplugin/rollup&quot;;<br><br>export default {<br>  input: &quot;src/main.ts&quot;,<br>  output: { dir: &quot;dist&quot;, format: &quot;es&quot; },<br>  plugins: [gasPlugin()],<br>};</pre><h3>esbuild</h3><pre>import gasPlugin from &quot;@gas-plugin/unplugin/esbuild&quot;;<br>import { build } from &quot;esbuild&quot;;<br><br>await build({<br>  entryPoints: [&quot;src/main.ts&quot;],<br>  outdir: &quot;dist&quot;,<br>  bundle: true,<br>  format: &quot;esm&quot;,<br>  plugins: [gasPlugin()],<br>});</pre><h3>webpack</h3><pre>import gasPlugin from &quot;@gas-plugin/unplugin/webpack&quot;;<br><br>export default {<br>  entry: &quot;./src/main.ts&quot;,<br>  output: { path: new URL(&quot;./dist&quot;, import.meta.url).pathname },<br>  plugins: [gasPlugin()],<br>};</pre><h3>Bun</h3><pre>import gasPlugin from &quot;@gas-plugin/unplugin/bun&quot;;<br><br>await Bun.build({<br>  entrypoints: [&quot;src/main.ts&quot;],<br>  outdir: &quot;dist&quot;,<br>  plugins: [gasPlugin()],<br>});</pre><p>The options are the same everywhere:</p><pre>gasPlugin({<br>  manifest: &quot;appsscript.json&quot;,<br>  include: [&quot;src/**/*.html&quot;],<br>  globals: [&quot;processData&quot;],<br>  autoGlobals: true,<br>});</pre><h3>How autoGlobals and globals work</h3><p>By default, bundlers may tree-shake or rename your GAS entry points like doGet or onOpen - because nothing in your code imports them.</p><ul><li><strong>autoGlobals: true</strong> scans your source for exported functions and automatically exposes them as global declarations in the output. This is the simplest way to make sure your GAS entry points survive the build.</li><li><strong>globals: [&quot;processData&quot;]</strong> lets you manually specify additional functions that should be preserved as globals - useful for installable triggers or menu callbacks that aren&#39;t exported from the entry point.</li></ul><p>You can use both together: autoGlobals handles the common case, and globals covers edge cases.</p><p>That consistency is the main goal: you shouldn’t have to rethink your GAS build setup just because you prefer one bundler over another.</p><h3>@gas-plugin/cli: scaffold a project in seconds</h3><p>I also added a CLI so you can start a new project without wiring everything manually.</p><pre>npx @gas-plugin/cli create</pre><p>You’ll get interactive prompts for:</p><ul><li>project name</li><li>template</li><li>bundler</li><li>optional clasp configuration</li><li>optional Script ID</li></ul><p>Example:</p><pre>◆  Project name<br>│  my-gas-app<br>│<br>◆  Template<br>│  ● basic — Spreadsheet automation (onOpen, triggers)<br>│  ○ webapp — Web app (doGet/doPost + HTML client)<br>│<br>◆  Bundler<br>│  ● vite<br>│  ○ rollup<br>│  ○ esbuild<br>│  ○ webpack<br>│  ○ bun<br>│<br>◆  Include clasp configuration?<br>│  Yes<br>│<br>◆  Script ID (optional)<br>│  1BxTjDm...</pre><p>And if you prefer automation-friendly setup, you can skip prompts entirely:</p><pre>npx @gas-plugin/cli create my-gas-app \<br>  --template webapp \<br>  --bundler vite \<br>  --clasp \<br>  --script-id YOUR_SCRIPT_ID</pre><p>The generated project is intentionally minimal:</p><pre>my-gas-app/<br>├── src/<br>│   ├── index.ts<br>│   ├── utils.ts<br>│   └── client.html       # webapp template only<br>├── package.json<br>├── appsscript.json<br>├── tsconfig.json<br>├── biome.json<br>├── vite.config.ts        # or rollup/esbuild/webpack config<br>├── .clasp.json           # when --clasp<br>├── .claspignore<br>└── .gitignore</pre><p>Then:</p><pre>npm run build<br>npx clasp push</pre><p>That gives you the basics you actually need, without forcing a larger opinionated toolchain on every project.</p><h3>Why this exists when google/aside already exists</h3><p>Google already provides <a href="https://github.com/google/aside"><strong>@google/aside</strong></a>, and it’s a legitimate option.</p><p>So this project is <strong>not</strong> trying to replace it outright.</p><p>The difference is scope.</p><h3>google/aside is a batteries-included starter</h3><p>It gives you a more opinionated setup out of the box.</p><h3>@gas-plugin is a smaller, composable alternative</h3><p>It focuses on two things:</p><ul><li>making bundled output work cleanly for GAS</li><li>letting you choose your own bundler and surrounding toolchain</li></ul><p>Here’s the practical difference:</p><pre>|                             | `google/aside`                             | `@gas-plugin`                                                  |<br>| --------------------------- | -------------------------------------------| ---------------------------------------------------------------|<br>| **Bundler choice**          | Primarily Rollup-based setup               | Vite, Rollup, esbuild, webpack, Bun                            |<br>| **`export` handling**       | You work within the template&#39;s conventions | `export` is stripped at build time for GAS output              |<br>| **Tree-shaking protection** | Side-effect import pattern                 | `autoGlobals` can preserve exported entry points automatically |<br>| **Scaffolding style**       | More batteries included                    | Minimal scaffold, bring your own tools                         |<br>| **Templates**               | Opinionated starter                        | `basic` and `webapp`                                           |</pre><p>So the real distinction is:</p><ul><li>choose <strong>google/aside</strong> if you want a fuller default setup</li><li>choose <strong>@gas-plugin</strong> if you want a lighter, bundler-agnostic foundation</li></ul><h3>Migration from gas-vite-plugin</h3><p>If you’re already using the old package, migration is intentionally small:</p><pre>- import gasPlugin from &quot;gas-vite-plugin&quot;;<br>+ import gasPlugin from &quot;@gas-plugin/unplugin/vite&quot;;</pre><pre>npm uninstall gas-vite-plugin<br>npm install -D @gas-plugin/unplugin</pre><p>Same idea, same behavior — just no longer tied to Vite alone.</p><h3>Why I think this matters</h3><p>GAS is still incredibly useful for internal tools, automations, lightweight web apps, and spreadsheet-driven workflows.</p><p>But the tooling ecosystem has often pushed developers into one of two extremes:</p><ul><li>stay close to vanilla Apps Script and give up modern build ergonomics</li><li>adopt a very specific template and toolchain</li></ul><p>I wanted something in between:</p><ul><li>modern TypeScript workflow</li><li>support for the bundler you already use</li><li>minimal GAS-specific friction</li><li>no unnecessary lock-in</li></ul><p>That’s what @gas-plugin is trying to be.</p><p>If you’ve tried it, I’d love to hear which bundler you’re using and whether anything felt off. Issues and PRs are welcome on <a href="https://github.com/wakita181009/gas-plugin">GitHub</a>.</p><h3>Links</h3><ul><li><a href="https://github.com/wakita181009/gas-plugin"><strong>GitHub</strong></a> — source, examples, issues</li><li><a href="https://www.npmjs.com/package/@gas-plugin/unplugin"><strong>@gas-plugin/unplugin</strong></a></li><li><a href="https://www.npmjs.com/package/@gas-plugin/cli"><strong>@gas-plugin/cli</strong></a></li></ul><p><em>Originally published at </em><a href="https://dev.to/wakita181009/build-google-apps-script-with-any-bundler-vite-rollup-esbuild-webpack-and-bun-2e73"><em>https://dev.to</em></a><em> on March 14, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f41918ecac4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Made an LLM Add Features to Its Own Code — Classic Spring Boot vs Clean Architecture]]></title>
            <link>https://medium.com/@wakita181009/i-made-an-llm-add-features-to-its-own-code-classic-spring-boot-vs-clean-architecture-a4f30fe51334?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f30fe51334</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 17:59:00 GMT</pubDate>
            <atom:updated>2026-03-11T14:39:29.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DSgMPljQMnkOxHOp.png" /></figure><p><em>In Part 0, both implementations worked. In Part 1, the LLM modified its own code — and the results challenged my assumptions about both architectures.</em></p><h3>Phase 1: feature addition</h3><p>In <a href="https://dev.to/wakita181009/i-made-an-llm-build-the-same-app-twice-classic-spring-boot-vs-clean-architecture-9hl">Part 0</a>, I had Claude Code generate two complete SaaS billing systems from scratch — one in classic Spring Boot, one in Clean Architecture with Arrow-kt. Both worked. Both had ~89% coverage. The structural differences were visible but untested.</p><p>Phase 1 tests what happens next. I gave the LLM three new feature specs and pointed it at the Phase 0 codebase:</p><ul><li><strong>Add-ons</strong> — flat-rate and per-seat billing types, attached to subscriptions with proration on mid-cycle changes</li><li><strong>Seat management</strong> — per-seat pricing with minimum/maximum constraints, prorated charges on seat count changes</li><li><strong>Credit notes</strong> — full and partial refunds, with two application methods (refund to payment method or account credit)</li></ul><p>Same orchestrator agent. Same process. The only difference: this time, the LLM read existing code before writing new code.</p><p>I expected Clean to scale cleanly and Classic to degrade predictably. The actual results were messier — and more interesting.</p><h3>Generation time: the gap disappeared</h3><p>This is the most surprising number in the entire experiment.</p><p>In Phase 0, Clean took 1.75x longer — the orchestrator had to coordinate 6 agents across 5 modules with strict dependency ordering, generating 115 files from a detailed layer sketch. Classic’s simpler pipeline finished in half the time.</p><p>In Phase 1, they’re 23 seconds apart. The existing codebase became the context. The LLM didn’t need the layer sketch to figure out where files go — it could read the project structure and follow the patterns already established. The upfront cost of Clean’s architecture was paid in Phase 0. Phase 1 spent it.</p><h3>Classic: the LLM learned from its own code</h3><h3>The most interesting finding</h3><p>In Phase 0, the LLM created one SubscriptionService with 457 lines and 9 responsibilities. I expected Phase 1 to make it worse - to stuff add-on logic, seat management, and credit notes into the same class.</p><p>Instead, the LLM created three new services:</p><p>The LLM saw the existing 457-line service and chose not to add to it. It created separate services for separate domains. This is genuine adaptation — the Phase 0 code taught the LLM that this project uses one service per domain concept.</p><p>This matters. Nobody added a rule saying “create separate services.” Nobody modified the .claude/ context. The LLM read the existing codebase and adapted its behavior. The implication is significant: <strong>good existing code can guide an LLM even without explicit architectural constraints.</strong> Classic&#39;s Phase 0 output, despite its flaws, was good enough to teach the LLM better decomposition in Phase 1.</p><h3>What didn’t improve</h3><p><strong>SubscriptionService still grew.</strong> Despite decomposition into new services, SubscriptionService went from 457 to 635 lines. The processRenewal() method absorbed per-seat pricing calculations, add-on charge aggregation, and account credit application:</p><pre>// classic/service/SubscriptionService.kt — processRenewal() grew to include:<br>// - Per-seat plan charge calculation<br>// - Add-on charge iteration and line item generation<br>// - Account credit balance application<br>// - 9 original responsibilities + 3 new ones</pre><p>The new services handle creation and modification of add-ons, seats, and credit notes. But renewal — the operation that touches everything — still lives in SubscriptionService. The LLM couldn&#39;t extract it because the method depends on repositories from all three new domains.</p><p><strong>Proration logic is duplicated.</strong> The same day-ratio calculation appears in SeatService.updateSeatCount(), AddOnService.attachAddOn(), and SubscriptionService.processRenewal():</p><p>Each service calculates proration independently. The LLM generated each method in isolation and didn’t refactor common logic afterward. (Note: as we’ll see, clean has the same problem — the LLM duplicates cross-cutting calculations regardless of architecture.)</p><p><strong>Exception explosion.</strong> Phase 0 had 8 exception types. Phase 1 added 13 more:</p><p>Each exception is a flat class extending ServiceException. There&#39;s no hierarchy grouping add-on errors separate from seat errors. When a controller catches ServiceException, it handles all 21 types through the same GlobalExceptionHandler - the HTTP status code is embedded in each exception, which works, but provides no compile-time guarantee that all cases are handled.</p><h3>Clean: use cases added like Lego blocks</h3><h3>The structure held</h3><p>Phase 1 added exactly 4 new use cases:</p><p>Each use case has its own sealed error type. AttachAddOnError has 12 variants. UpdateSeatCountError has 11 variants. The compiler enforces exhaustive handling at every call site.</p><p>New domain models ( AddOn, SubscriptionAddOn, CreditNote) follow the same value object pattern. New ports ( AddOnQueryPort, SubscriptionAddOnCommandQueryPort, CreditNoteCommandQueryPort) maintain the dependency direction. New infrastructure adapters implement the ports. The existing code didn&#39;t need to change its structure to accommodate new features - new features slotted into the existing structure.</p><h3>Where clean showed cracks</h3><p><strong>The backward-compatibility hack.</strong> ProcessRenewalUseCase needed to incorporate add-on charges into renewal invoices. The LLM&#39;s solution:</p><p>Optional dependencies with ?.let null checks. This is a code smell in Clean Architecture - a use case should declare all its dependencies explicitly. The LLM chose backward compatibility over correctness, probably because the existing tests for ProcessRenewalUseCase don&#39;t provide add-on ports. Breaking those tests would mean rewriting them, which the LLM avoided.</p><p><strong>Proration duplication — the same problem as classic.</strong> Phase 0’s PlanChangeUseCase delegates to a ProrationDomainService in the domain layer. But the Phase 1 use cases ( AttachAddOnUseCase, DetachAddOnUseCase, UpdateSeatCountUseCase) all calculate proration inline - the same totalDays / daysRemaining pattern, duplicated across four use cases. The LLM didn&#39;t reuse the existing domain service. Use case isolation, which prevents god services, also prevents the LLM from seeing shared logic across use cases. Architecture constrains bloat but doesn&#39;t prevent duplication.</p><p><strong>252-line use case.</strong> UpdateSeatCountUseCaseImpl handles both seat increases (charge proration) and seat decreases (credit issuance), including per-seat add-on proration for both directions. At 252 lines, it&#39;s the largest use case - still smaller than classic&#39;s SubscriptionService, but pushing the boundary of &quot;one use case, one responsibility.&quot;</p><h3>The numbers: Phase 0 → Phase 1</h3><h3>Code volume</h3><p><em>Phase 0 line counts covered production source only. Phase 1 includes production + test breakdown. jOOQ generated code (in </em><em>build/) is excluded from all counts.</em></p><p>Both codebases roughly doubled in file count. The largest file metric is not a full maintainability measure, but it’s a useful proxy for <em>responsibility concentration</em> — how much logic the LLM packs into a single place. Classic’s largest file grew 39% (457 → 635). Clean’s grew 110% but from a much lower base (120 → 252, still below the size where single-file comprehension starts to get harder).</p><h3>Test results</h3><p>Test counts are almost identical (291 vs 288). The LLM generated comprehensive tests for both architectures. In this setup, Clean’s warm build time rose from 3s to 8s, likely reflecting the growing overhead of a larger multi-module Gradle build.</p><h3>Coverage</h3><p>Classic’s line coverage improved from 89.7% to 94.6%. The new services (AddOnService, SeatService, CreditNoteService) are well-tested — possibly because the LLM generated them fresh with tests, rather than modifying existing code.</p><p>Clean’s branch coverage at 64.7% deserves honest scrutiny. One-third of all branch paths are untested. The sealed interface error types define variants like Internal(cause: String) and Domain(error: DomainError) that no test exercises. In Part 0, I argued that clean&#39;s uncovered paths are &quot;named and enumerable&quot; - you can grep for them. That&#39;s true. But Phase 1 reveals the practical cost: <strong>the LLM defines exhaustive error types because the type system demands it, then doesn&#39;t write exhaustive tests because nothing demands that.</strong> The architecture pays the definition cost but doesn&#39;t automatically collect the testing benefit. The types exist as compile-time documentation, not runtime guarantees - unless someone (human or LLM) writes the tests to match.</p><h3>What Phase 1 reveals that Phase 0 couldn’t</h3><h3>Patterns across both architectures</h3><p><strong>1. Existing code is the strongest context.</strong> In classic, the LLM read a 457-line god service and decided <em>not</em> to make it worse — it created three new services unprompted. In clean, it followed the existing use case pattern without needing the layer sketch. The .claude/ rules and agent configurations matter most in Phase 0. By Phase 1, the codebase itself teaches the LLM what to do. This also explains the generation time convergence.</p><p><strong>2. Architecture constrains structure but not duplication.</strong> Both implementations duplicated proration logic — classic across three services, clean across four use cases. Phase 0’s PlanChangeUseCase delegates to a ProrationDomainService, but Phase 1&#39;s new use cases all calculate proration inline. The LLM didn&#39;t reuse the existing domain service. It generates each unit independently and doesn&#39;t refactor across boundaries - whether those boundaries are services or use cases.</p><p><strong>3. Type safety without test safety is incomplete.</strong> Clean’s branch coverage dropped to 64.7%. The type system demanded exhaustive error definitions; the LLM complied. But nothing demanded exhaustive tests, and the LLM didn’t write them. Meanwhile, classic’s processRenewal() grew from 9 to 12 responsibilities (457 → 635 lines) because there&#39;s no mechanism to prevent a method from becoming the integration point for the entire domain. Clean constrains bloat structurally; classic relies on the LLM making good local decisions - which it sometimes does (new services) and sometimes doesn&#39;t (growing processRenewal). But neither architecture made the LLM write better tests.</p><h3>What the data suggests — and what it doesn’t</h3><h3>What the numbers show</h3><p>Two phases of data show clear patterns:</p><p><strong>Generation time converged.</strong> Phase 0: 1.75x gap. Phase 1: 1.01x gap. Existing code as context reduced Clean’s coordination overhead and increased Classic’s reading time. Whether this trend continues, stabilizes, or reverses at Phase N is unknown — we have two data points, not a curve.</p><p><strong>Classic’s largest file grew; Clean’s stayed bounded.</strong> 457 → 635 lines vs 120 → 252 lines. Classic’s growth came from processRenewal() absorbing cross-domain logic. Clean&#39;s growth came from a complex use case (seat + add-on proration), but each use case remains independent. The <em>mechanism</em> differs: Classic grows by accretion in existing files; Clean grows by adding new files.</p><p><strong>Duplication is architecture-independent.</strong> Both implementations duplicated proration logic across multiple locations. The LLM doesn’t refactor across boundaries — whether those boundaries are services (classic) or use cases (clean). This is arguably the most important finding: <strong>the LLM’s weakest capability is recognizing shared logic across independently generated code units.</strong></p><p><strong>The LLM adapts to existing code patterns.</strong> Classic’s self-decomposition into new services was unprompted. Clean’s consistent use case structure was self-reinforcing. Existing code is a stronger guide than configuration files.</p><h3>The trade-off table</h3><h3>A hypothesis, not a conclusion</h3><p>Two data points don’t make a trend. But they suggest a hypothesis worth testing:</p><p><strong>Architecture may function as a scaling constraint on LLM-generated code.</strong> Clean’s explicit boundaries prevent the <em>structural</em> problems that compound over time (god services, file bloat, implicit dependencies). Classic’s flexibility allows the LLM to adapt (new services), but also allows it to accumulate debt (growing integration points, flat error hierarchies).</p><p>However, architecture does <em>not</em> solve the LLM’s core limitation — <strong>cross-boundary refactoring.</strong> Both implementations duplicated proration logic. Both missed opportunities to extract shared abstractions. Clean’s sealed types went untested at the same rate as Classic’s exception paths. The LLM fills each container correctly but doesn’t optimize across containers.</p><p>The question for a real project isn’t “which architecture should I pick?” It’s a compound question:</p><ul><li><strong>How often will features be added?</strong> More features favor explicit boundaries.</li><li><strong>How much do features interact?</strong> More interaction creates cross-cutting concerns that stress any architecture.</li><li><strong>What is the team’s tolerance for boilerplate?</strong> In this experiment, Clean carried a roughly 2.5x file-count overhead.</li><li><strong>What is the LLM’s role?</strong> If the LLM generates initial code and humans maintain it, Classic’s familiarity wins. If the LLM generates and extends code continuously, Clean’s self-documenting structure wins.</li></ul><p><strong>Architecture is not a prompt. It’s the shape of the container the LLM fills — and the shape determines what compounds and what stays constant as the codebase grows.</strong></p><p>The full source is on GitHub: <a href="https://github.com/wakita181009/clean-architecture-kotlin-in-practice/tree/main/classic">classic/</a> | <a href="https://github.com/wakita181009/clean-architecture-kotlin-in-practice/tree/main/clean">clean/</a></p><p><em>Originally published at </em><a href="https://dev.to/wakita181009/i-made-an-llm-add-features-to-its-own-code-classic-spring-boot-vs-clean-architecture-l6l"><em>https://dev.to</em></a><em> on March 9, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f30fe51334" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Made an LLM Build the Same App Twice — Classic Spring Boot vs Clean Architecture]]></title>
            <link>https://medium.com/@wakita181009/i-made-an-llm-build-the-same-app-twice-classic-spring-boot-vs-clean-architecture-4f29f063e0d2?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f29f063e0d2</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 17:08:11 GMT</pubDate>
            <atom:updated>2026-03-11T14:31:12.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7qJ6TkI2avMD92tf.png" /></figure><p><em>I gave Claude Code identical business requirements with two different architectural contexts. The generated code told me more about architecture’s value than any textbook could.</em></p><h3>The experiment</h3><p>I set up a controlled experiment in two phases:</p><ul><li><strong>Phase 0 — Full-scratch generation.</strong> Give the LLM a spec and an empty project. It builds everything from zero. This tests how architecture shapes greenfield code.</li><li><strong>Phase 1 — Feature addition.</strong> Give the LLM an existing codebase (the Phase 0 output) and a new feature spec. It reads, modifies, and extends. This tests how architecture holds up under change.</li></ul><p>Same business domain for both: a SaaS subscription billing system. The spec covers plan management with tiered pricing (free / starter / professional / enterprise), the full subscription lifecycle (trial → active → paused → canceled → expired), usage-based metering with per-plan limits, proration calculations on mid-cycle plan changes, invoice generation with line items and discount application, and payment processing with retry logic and grace periods.</p><p>Same spec files. Two different architectural contexts.</p><ul><li><strong>Classic</strong>: single-module Spring Boot, layered architecture (controller → service → repository → model), JPA, JUnit 5, exception-based error handling</li><li><strong>Clean</strong>: 5-module Clean Architecture, Arrow-kt Either, CQRS, jOOQ, Kotest, sealed interface error types</li></ul><p>This article covers Phase 0. The orchestrator agent read the specs, produced a layer sketch, and spawned implementer agents to generate every file from zero. No human edits. No iterative refinement. The only difference was the .claude/ directory - the architectural context the LLM received.</p><h3>What “context” means for an LLM</h3><p>Most discussions about AI-generated code focus on the prompt. But for a codebase-scale task, the prompt is the least important input. What matters is the <strong>context</strong> — the accumulated knowledge the LLM has access to when making decisions.</p><p>For classic:</p><pre>classic/.claude/<br>├── CLAUDE.md            # Architecture rules, package conventions<br>├── rules/               # 3 files: JPA patterns, Spring patterns, testing<br>├── agents/              # 5 agents: orchestrator, entity, service, api, tester<br>├── skills/              # TDD patterns<br>├── specs/               # 4 spec files (shared)<br>└── layer-sketch.md      # 45 files to create</pre><p>For clean:</p><pre>clean/.claude/<br>├── CLAUDE.md            # Layer rules, CQRS structure, forbidden imports<br>├── rules/               # 2 files: Arrow Either style, test conventions<br>├── agents/              # 6 agents: orchestrator, domain, app, infra, presentation, tester<br>├── skills/              # 5 skills: CA patterns, FP patterns, Arrow-kt, jOOQ, TDD<br>├── specs/               # 4 spec files (shared)<br>└── layer-sketch.md      # 115 files to create</pre><p>But the difference isn’t just the .claude/ directory. The clean project also requires <strong>infrastructure that exists before the LLM starts generating</strong>: a multi-module Gradle setup with dependency constraints between modules, custom detekt rules ( ForbiddenLayerImportRule, NoThrowOutsidePresentationRule), jOOQ code generation from DDL, and Kover coverage thresholds. Classic needs none of this - a single build.gradle.kts with Spring Boot starters is enough.</p><p>The classic context teaches the LLM <strong>how to write code</strong> — JPA annotation patterns, @Transactional placement, exception hierarchy design. The clean context teaches the LLM <strong>where code cannot go</strong> - forbidden imports per layer, mandatory Either return types, whitelist-based constraints - backed by tooling that enforces those boundaries at build time.</p><p>This is the fundamental difference. Classic gives guidelines. Clean gives boundaries with teeth.</p><h3>The generated code: classic</h3><p>The LLM produced 33 source files in a single module. Here’s what it did well and where it broke down.</p><h3>What the LLM got right</h3><p><strong>Rich domain models.</strong> The Money class handles currency-safe arithmetic with operator overloading. SubscriptionStatus and InvoiceStatus implement state machine transitions with canTransitionTo() guards. These patterns came directly from the spec + the jpa-kotlin.md rule file.</p><p><strong>Exception hierarchy.</strong> The LLM created a ServiceException base class with HTTP status codes and a GlobalExceptionHandler that maps each exception type to the correct response. Clean, predictable, consistent.</p><h3>Where classic broke down</h3><p><strong>The 457-line service.</strong> SubscriptionService handles creation, plan changes, pauses, resumes, cancellations, renewals, and discount management - all in one class. The LLM followed the most common Spring Boot pattern it&#39;s seen: one service per entity.</p><p>Nobody told the LLM to create one service with nine responsibilities. But nobody told it not to, either. The classic context defines a service/ package and lists SubscriptionService as the class to create. The LLM filled it with everything subscription-related - because that&#39;s the statistical norm in Spring Boot codebases.</p><p><strong>Hardcoded discount resolution — in the wrong place.</strong> The spec mentions discount codes but doesn’t specify a database lookup. Both implementations hardcoded the same &quot;WELCOME20&quot; string. The difference is <em>where</em>.</p><p>In classic, the hardcode lives inside SubscriptionService as a private method:</p><p>In clean, the same hardcode lives in DiscountRepositoryImpl in the infrastructure layer, behind a DiscountCodePort interface:</p><p>Both are stubs. But when the time comes to replace the hardcode with a database lookup, classic requires modifying SubscriptionService - the 457-line class that owns all subscription logic. Clean requires modifying only the infrastructure adapter. The use case never knows the difference, because it depends on DiscountCodePort, not the concrete implementation. The layer sketch defined this port upfront; the LLM didn&#39;t choose it - the architecture did.</p><p><strong>Invoice generation duplicated.</strong> The changePlan() method and processRenewal() method both construct Invoice objects with line items. The logic is nearly identical. The LLM generated each method independently, and since there&#39;s no factory pattern in the context, it copy-pasted the construction logic.</p><h3>The generated code: clean</h3><p>The LLM produced 80+ source files across 5 modules. The same spec, but a fundamentally different result.</p><h3>The architecture constrained the output</h3><p><strong>One use case, one file.</strong> The clean context defines 8 command use cases and 3 query use cases — each as a separate interface and implementation. The LLM couldn’t create a 457-line service because the structure doesn’t have a place for one.</p><p>The largest use case is 120 lines. The structure made bloat physically impossible.</p><p><strong>Either forced exhaustive error handling.</strong> Every use case returns Either&lt;SpecificError, T&gt;. The LLM couldn&#39;t skip error cases because the sealed interface makes the compiler enforce exhaustiveness:</p><p>In classic, the LLM defined 8 exception types. In clean, it defined 50+ error variants across sealed interfaces. Not because the LLM tried harder — but because the type system demanded it.</p><p><strong>Ports prevented infrastructure leakage.</strong> The PlanQueryPort is defined in the application layer. The LLM couldn&#39;t import JPA or jOOQ in the use case because the module boundary prevents it. The adapter pattern isn&#39;t a recommendation - it&#39;s the only way to access external systems.</p><h3>Where clean showed overhead</h3><p><strong>115 files for the same business logic.</strong> The clean version has 2.5x more files than classic. Many are thin — a sealed interface with two variants, a port interface with one method, a DTO with five fields. But they exist, and each one had to be generated, placed in the correct module, and wired together.</p><p><strong>Value object ceremony.</strong> Every ID type requires a smart constructor returning Either:</p><p>There are 10 value object types. Classic uses Long directly. The type safety is real, but so is the boilerplate.</p><h3>The numbers</h3><h3>Generation time</h3><p>Clean took 1.75x longer to generate. The orchestrator coordinates 6 agents across 5 modules with dependency ordering — domain must finish before application, application before infrastructure and presentation. Classic’s 4-agent pipeline runs in a simpler sequence with fewer handoffs. The multi-module coordination, larger layer sketch (115 files vs 45), and the additional Arrow-kt/CQRS patterns all add up.</p><h3>Code volume</h3><h3>Test results</h3><p>The build time difference disappears once the Gradle daemon is warm — compilation is the bottleneck, not test execution. Clean’s tests actually execute faster (1.7s vs 2.2s) despite having more tests, because domain and application tests run without Spring context startup.</p><h3>Layer-by-layer test performance</h3><p><strong>Classic:</strong> <strong>Clean:</strong></p><p>Two things stand out. First, clean’s presentation tests don’t use @WebMvcTest - they instantiate the controller directly and call methods. The 1.1s is pure Kotest/MockK initialization overhead, not Spring. Second, the Kotest runner adds ~0.9s of startup per module for the first test class. After initialization, subsequent test classes run at ~15ms each.</p><h3>Coverage</h3><p><strong>Classic by layer:</strong> <strong>Clean by module:</strong></p><p>Coverage numbers are nearly identical — but they measure different things.</p><p>Classic’s 89.7% means “89.7% of lines were reached.” The missing 10.3% includes exception paths that were never thrown in tests. Those paths exist as throw statements - invisible to the type system, easy to forget in tests.</p><p>Clean’s 87.7% means “87.7% of typed error paths were exercised.” The missing 12.3% is visible in the code — it’s sealed interface variants like Internal(cause: String) that tests didn&#39;t trigger. The untested paths are <strong>named</strong> and <strong>enumerated</strong>. You can grep for them.</p><h3>What the experiment actually shows</h3><p>Both implementations are functionally equivalent. They handle the same subscription lifecycle — creation, plan changes, pauses, resumes, cancellations, renewals, usage metering, and payment processing. Both compile, both pass tests, both have ~89% coverage. <strong>There is no meaningful difference in what the code does.</strong></p><p>The difference is in how the code is shaped.</p><h3>Classic: the LLM’s strengths and blind spots</h3><p>Classic plays to the LLM’s greatest advantage: <strong>the sheer volume of training data for conventional patterns.</strong> Spring Boot is the most common Kotlin/JVM web framework. The LLM has seen millions of @Service + @Repository + @RestController examples. The result is concise, idiomatic code that any Spring developer would recognize immediately.</p><p>The model layer is genuinely good. Money with operator overloading, SubscriptionStatus with canTransitionTo() guards, Invoice with state machine transitions - these are clean, well-structured patterns that benefit from the LLM&#39;s deep familiarity with the ecosystem.</p><p>But the same statistical bias that makes the LLM good at conventional patterns makes it prone to conventional mistakes:</p><ul><li><strong>Service bloat.</strong> SubscriptionService at 457 lines with 9 responsibilities. The LLM follows the &quot;one service per entity&quot; norm - the pattern it&#39;s seen most often - even when the complexity demands decomposition.</li><li><strong>Code duplication.</strong> Invoice construction logic appears in both changePlan() and processRenewal(). The LLM generates each method independently. Without an explicit Factory pattern in the context, it doesn&#39;t extract shared logic.</li><li><strong>Shortest-path solutions.</strong> Hardcoded discount resolution instead of a repository lookup. When the spec is underspecified, the LLM takes the minimal implementation — not the extensible one.</li></ul><p>These aren’t bugs. The code works. But they’re the kind of structural problems that compound over time as features are added.</p><h3>Clean: boundaries prevent problems, at a cost</h3><p>Clean architecture constrains the LLM’s output through structure rather than instruction. The result is code with clear dependency direction, no bloated classes, and exhaustive error handling — but significantly more of it.</p><p><strong>What boundaries buy you:</strong></p><ul><li><strong>No bloat possible.</strong> The layer sketch defines 8 command use cases as separate files. The LLM can’t merge them into a god service because there’s no single file to put it in. The largest use case is 120 lines.</li><li><strong>Explicit dependencies.</strong> Every external system access goes through a Port interface defined in the application layer. The LLM can’t accidentally couple a use case to jOOQ or JPA — the module boundary prevents the import.</li><li><strong>Exhaustive error handling.</strong> Sealed interfaces with Either force the LLM to define and handle every error variant. Classic has 8 exception types; clean has 50+ error variants. The compiler enforces this, not the prompt.</li></ul><p><strong>What boundaries cost you:</strong></p><ul><li><strong>2.5x more code.</strong> 1,225 lines across 80+ files vs 787 lines across 33 files. Many clean files are thin wrappers — a port interface with one method, a sealed interface with two variants — but they all need to be generated, placed correctly, and wired together.</li><li><strong>Longer generation time.</strong> The clean orchestrator must coordinate 6 agents across 5 modules with dependency ordering (domain → application → infrastructure | presentation). Classic’s orchestrator runs 4 agents in a simpler pipeline. The multi-module coordination overhead is real.</li><li><strong>Higher context investment.</strong> 24 configuration files vs 19. The additional skills (Arrow-kt patterns, CA layer rules, FP patterns) and the detailed layer sketch are necessary to produce correct output — but they represent upfront work before the first feature ships.</li></ul><h3>The core observation</h3><p>The LLM doesn’t “understand” architecture. It follows the path of least resistance within the constraints it’s given.</p><p>With classic constraints, the path of least resistance is the <strong>statistically dominant pattern</strong> — concise, idiomatic, and immediately readable, but carrying the same structural debts (god services, code duplication) that the average Spring Boot project accumulates over time.</p><p>With clean constraints, the path of least resistance is the <strong>structurally enforced pattern</strong> — no bloat, exhaustive error handling, explicit dependencies, but at the cost of 1.75x generation time and 2.5x more files.</p><p>The LLM didn’t write better or worse code in either case. It filled the container it was given.</p><p><strong>Architecture is not a prompt. It’s the shape of the container the LLM fills.</strong></p><p>But this is Phase 0 — greenfield generation. Both codebases work. Both have high coverage. The structural differences are visible but haven’t been tested under pressure. The real question is what happens when the LLM modifies existing code — when the 457-line service needs a tenth responsibility, when the duplicated invoice logic needs a third variant.</p><p>The full source is on GitHub: <a href="https://github.com/wakita181009/clean-architecture-kotlin-in-practice/tree/main/classic">classic/</a> | <a href="https://github.com/wakita181009/clean-architecture-kotlin-in-practice/tree/main/clean">clean/</a></p><p><em>Originally published at </em><a href="https://dev.to/wakita181009/i-made-an-llm-build-the-same-app-twice-classic-spring-boot-vs-clean-architecture-9hl"><em>https://dev.to</em></a><em> on March 9, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f29f063e0d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Made Zod 64x Faster by Compiling Schemas at Build Time]]></title>
            <link>https://medium.com/@wakita181009/i-made-zod-64x-faster-by-compiling-schemas-at-build-time-be5de452b5e9?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5de452b5e9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[aot]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 15:19:06 GMT</pubDate>
            <atom:updated>2026-03-04T15:19:06.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFu1914kGz28xNDwXnAcSQ.png" /></figure><p>Zod v4 is fast. But what if you could skip schema traversal entirely? I built a compiler that turns your Zod schemas into plain JavaScript validation functions at build time — and it’s 2–64x faster.</p><h3>The Problem: Runtime Schema Traversal Is Inherently Slow</h3><p>Zod is everywhere. With over 100 million weekly npm downloads, it’s the de facto standard for runtime validation in TypeScript. The API is beautiful — you define a schema, and you get both runtime validation and static types for free.</p><p>But that elegance has a cost.</p><p>Every time you call .parse(), Zod walks the entire schema tree at runtime. It checks each node type, applies constraints, collects errors, and constructs the result. For a simple z.string(), the overhead is negligible. But for a nested object with arrays, unions, and dozens of fields? That tree walk adds up fast.</p><pre>// Every .parse() call traverses this entire tree — every time<br>const UserSchema = z.object({<br>  id: z.string().uuid(),<br>  name: z.string().min(1).max(100),<br>  email: z.string().email(),<br>  role: z.enum([&quot;admin&quot;, &quot;user&quot;, &quot;viewer&quot;]),<br>  preferences: z.object({<br>    theme: z.enum([&quot;light&quot;, &quot;dark&quot;]),<br>    notifications: z.boolean(),<br>    language: z.string().length(2),<br>  }),<br>  tags: z.array(z.string()).max(20),<br>});<br><br>// This traverses ~15 schema nodes on every single call<br>UserSchema.parse(data);</pre><p>This matters in real production scenarios:</p><ul><li><strong>API servers</strong> validating every incoming request body</li><li><strong>Edge functions</strong> where cold-start budgets are measured in milliseconds</li><li><strong>Form validation</strong> running on every keystroke on mobile devices</li></ul><p>The schema never changes. But Zod re-discovers its structure on every single parse call.</p><h3>The Insight: Schemas Are Static — Validation Can Be Compiled</h3><p>Here’s the key observation: most Zod schemas are defined once at module scope and never change at runtime. The tree walk produces the same sequence of operations every time. It’s pure overhead.</p><p>This is exactly the problem compilers solve — move repeated work from runtime to build time.</p><p>What if instead of walking a schema tree at runtime, you could generate a plain function that does the exact same validation — but with zero traversal overhead?</p><pre>// What Zod does at runtime (simplified):<br>function parse(schema, data) {<br>  switch (schema.type) {<br>    case &quot;object&quot;: return parseObject(schema, data);<br>    case &quot;string&quot;: return parseString(schema, data);<br>    case &quot;array&quot;:  return parseArray(schema, data);<br>    // ... recursive traversal continues<br>  }<br>}<br><br>// What AOT compilation produces:<br>function validateUser(data) {<br>  if (typeof data !== &quot;object&quot; || data === null) return error(&quot;Expected object&quot;);<br>  if (typeof data.id !== &quot;string&quot;) return error(&quot;Expected string&quot;);<br>  if (!UUID_REGEX.test(data.id)) return error(&quot;Invalid uuid&quot;);<br>  if (typeof data.name !== &quot;string&quot;) return error(&quot;Expected string&quot;);<br>  if (data.name.length &lt; 1) return error(&quot;String must contain at least 1 character(s)&quot;);<br>  // ... flat, linear, no traversal<br>}</pre><p>The second function does the same thing, but there’s no schema tree to walk. No type switches. No recursive calls. Just straight-line validation code.</p><h3>Introducing zod-aot</h3><p>That’s what zod-aot does. It reads your Zod schemas at build time, compiles them into optimized validation functions, and replaces the runtime parsing with generated code.</p><h3>Installation</h3><pre>npm install zod-aot zod@^4</pre><h3>Usage — wrap with compile()</h3><pre>import { z } from &quot;zod&quot;;<br>import { compile } from &quot;zod-aot&quot;;<br><br>const UserSchema = compile(<br>  z.object({<br>    id: z.string().uuid(),<br>    name: z.string().min(1).max(100),<br>    email: z.string().email(),<br>    role: z.enum([&quot;admin&quot;, &quot;user&quot;, &quot;viewer&quot;]),<br>  })<br>);<br><br>// Same API — .parse(), .safeParse(), .is()<br>const user = UserSchema.parse(data);</pre><p>In development, compile() passes through to Zod as-is. In production builds, the bundler plugin replaces it with the generated validation function. Zero code changes to your existing schemas.</p><h3>Build integration</h3><p><strong>Vite</strong> (4 lines):</p><pre>// vite.config.ts<br>import { zodAot } from &quot;zod-aot/vite&quot;;<br><br>export default defineConfig({<br>  plugins: [zodAot()],<br>});</pre><p><strong>CLI</strong> for non-bundler workflows:</p><pre>npx zod-aot generate src/ -o dist/</pre><p>The compiled validators expose the same interface: .parse() throws on invalid input, .safeParse() returns a result object, and .is() acts as a type guard.</p><h3>Transform and Refine: Partial Compilation</h3><p>Here’s where it gets interesting. Not everything in a Zod schema can be compiled ahead of time.</p><p>Zod’s .transform(), .refine(), .superRefine(), and z.custom() accept arbitrary JavaScript functions. These are opaque at build time — there&#39;s no way to statically analyze what (val) =&gt; val.toUpperCase() does without executing it.</p><p>So zod-aot doesn&#39;t try to compile them. Instead, it uses <strong>partial compilation</strong>.</p><pre>const ProfileSchema = compile(<br>  z.object({<br>    name: z.string().min(1),                          // ✅ AOT compiled<br>    email: z.string().email(),                         // ✅ AOT compiled<br>    age: z.number().int().min(0).max(150),             // ✅ AOT compiled<br>    bio: z.string().transform((s) =&gt; s.trim()),        // ⚠️ Falls back to Zod<br>    score: z.number().refine((n) =&gt; isPrime(n)),       // ⚠️ Falls back to Zod<br>  })<br>);</pre><p>In this schema, 3 out of 5 fields get full AOT compilation. The remaining 2 delegate to Zod at runtime — only for those specific fields. The compiler decides this automatically at extraction time. No annotations, no configuration, no manual intervention.</p><blockquote><strong><em>This is the key design decision</em></strong><em>: compile what you can, fall back gracefully for the rest. A schema that’s 80% compilable still gets 80% of the performance benefit.</em></blockquote><p>This means you never have to worry about whether your schema is “compatible” with zod-aot. Every Zod v4 schema works. The question is only how much of it gets compiled.</p><h3>Benchmark Results</h3><p>Theory is nice. Let’s see actual numbers.</p><p>I benchmarked zod-aot compiled validators against Zod v4&#39;s native .parse() across a range of schema complexities. Each benchmark runs 100,000 iterations with warmup, using performance.now() for timing.</p><pre>Schema                              |   Zod v4   | zod-aot    | Speedup<br>------------------------------------|------------|------------|---------<br>Simple string (z.string().email())  | 1.2M ops/s | 2.1M ops/s |  ~1.8x<br>Medium object (valid input)         | 480K ops/s | 2.4M ops/s |  ~5x<br>Medium object (invalid input)       | 210K ops/s | 4.8M ops/s |  ~23x<br>Large nested object (100 items)     | 12K  ops/s | 780K ops/s |  ~64x<br>Discriminated union (5 variants)    | 320K ops/s | 3.2M ops/s |  ~10x</pre><p>The pattern is clear: <strong>the larger and more complex the schema, the greater the AOT benefit</strong>.</p><p>For a simple string validation, the overhead of Zod’s runtime traversal is minimal — you’re only walking one or two nodes. The speedup is modest.</p><p>But for a large nested object with 100 array items, each containing multiple validated fields, Zod has to traverse hundreds of schema nodes on every parse call. The AOT-compiled version does the same validation with flat, inlined code — no tree to walk. That’s where the 64x gap comes from.</p><p>The invalid input case is particularly interesting. The compiled validator hits the first failing check and returns immediately. Zod’s runtime has more overhead even for early exits because of the error collection and traversal machinery.</p><blockquote><strong><em>Key takeaway</em></strong><em>: If your hot-path schemas are simple primitives, Zod v4 is already fast enough. If you’re validating complex nested objects at high throughput, AOT compilation delivers an order-of-magnitude improvement.</em></blockquote><h3>Comparison and Trade-offs</h3><h3>How zod-aot compares to alternatives</h3><p><strong>vs Typia</strong> (~76M ops/s): Typia is faster because it compiles directly from TypeScript types using a compiler plugin. But it requires you to define validation as TypeScript types — not Zod schemas. If your codebase already uses Zod, migrating to Typia means rewriting every schema.</p><p><strong>vs AJV standalone</strong>: AJV compiles JSON Schema into validation functions — conceptually the same approach as zod-aot. But AJV operates in the JSON Schema ecosystem. If you’re using Zod, you’d need to convert schemas to JSON Schema first, losing Zod-specific features.</p><p><strong>vs Zod v4 native</strong>: zod-aot is complementary, not competitive. It builds on Zod v4 and uses its internals. You keep writing Zod schemas — zod-aot just makes them faster in production.</p><p><strong>zod-aot’s niche</strong>: zero migration cost for existing Zod users. You keep your schemas, your types, your ecosystem integrations with tRPC/React Hook Form/Next.js. You just add compile() and a build plugin.</p><h3>Honest trade-offs</h3><p>Nothing is free. Here’s what you should know:</p><ul><li><strong>Build-time extraction</strong>: zod-aot runs your schema code once at build time to extract the schema structure. If your schemas have side effects at definition time, this could cause issues.</li><li><strong>transform/</strong><strong>refine-heavy schemas</strong> get minimal benefit. If most of your validation logic lives in custom functions, AOT compilation can&#39;t help much.</li><li><strong>Bundle size</strong>: generated validators are standalone JavaScript — no Zod dependency at runtime, but the generated code itself adds to your bundle. For most schemas this is smaller than Zod itself.</li><li><strong>Zod v4 only</strong>: zod-aot depends on Zod v4’s internal schema representation (_zod.def). It does not support Zod v3.</li></ul><h3>Try It Out</h3><p>zod-aot is open source under the MIT license.</p><ul><li><strong>GitHub</strong>: <a href="https://github.com/wakita181009/zod-aot">https://github.com/wakita181009/zod-aot</a></li><li><strong>npm</strong>: <a href="https://www.npmjs.com/package/zod-aot">zod-aot</a></li></ul><p>What’s next:</p><ul><li>Broader schema type coverage (recursive types, branded types)</li><li>Incremental build caching for large codebases</li><li>Source map support for debugging compiled validators</li></ul><p>If you’re using Zod in a performance-sensitive context, give it a try. Star the repo if you find it useful, and file issues for anything that doesn’t work. PRs are always welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5de452b5e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enforcing Clean Architecture on AI-Generated Kotlin with Custom Detekt Rules]]></title>
            <link>https://medium.com/@wakita181009/llm-generated-code-keeps-breaking-clean-architecture-how-i-enforce-it-at-build-time-with-detekt-d6e86019a4f0?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e86019a4f0</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 05:38:34 GMT</pubDate>
            <atom:updated>2026-03-03T05:56:42.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULJzHgqsPckVK1kbbJtZ5Q.png" /></figure><p><em>How custom detekt rules, specialized AI agents, and specification-driven development keep Clean Architecture intact — even when an LLM writes the code.</em></p><h3>The moment an LLM broke the architecture</h3><p>I asked an AI coding assistant to add a new use case to the application layer. It wrote the code in under a minute. It also added @Service to the class, imported org.springframework.stereotype.Service, and threw an IllegalArgumentException for invalid input.</p><p>Three architecture rules broken in a single generation.</p><p>LLMs are fast. They’re also statistically inclined to produce the most common pattern they’ve seen — and in the Kotlin ecosystem, that’s Spring annotations on everything, exceptions for error handling, and no concept of layer boundaries. Your architecture documentation might say “no Spring in application layer.” The LLM has seen 100,000 Spring Boot examples that do exactly the opposite.</p><p>In <a href="https://medium.com/@wakita181009/clean-architecture-in-kotlin-no-exceptions-no-magic-no-compromise-d17310fb9cd0">the previous parts of this series</a>, I built a Clean Architecture in Kotlin with Gradle module boundaries, Arrow-kt Either error handling, and CQRS — all enforced at compile time. Those guarantees held because humans followed the rules. Now the developer is an LLM. The question becomes: <strong>how do you make the architecture enforce itself on code the LLM generates?</strong></p><h3>Custom detekt rules: architecture as static analysis</h3><p>Gradle modules prevent cross-layer dependencies — domain can&#39;t import from infrastructure because the dependency doesn&#39;t exist. But within the allowed imports, an LLM can still break the architecture in two fundamental ways:</p><ol><li><strong>Importing forbidden libraries</strong> into pure layers (Spring annotations in domain/application)</li><li><strong>Throwing exceptions</strong> instead of returning Either&lt;Error, T&gt;</li></ol><p>Both are valid Kotlin. Both compile. Both violate the architecture. Gradle can’t catch them. So I wrote two custom detekt rules that can.</p><h3>Rule 1: ForbiddenLayerImportRule — whitelist-based import enforcement</h3><p>Instead of blacklisting specific imports (which the LLM can always find creative alternatives for), this rule whitelists what’s allowed. Anything not on the list is rejected.</p><pre>class ForbiddenLayerImportRule(config: Config) : Rule(config, &quot;...&quot;) {<br><br>    private val commonAllowedPrefixes = listOf(<br>        &quot;kotlin.&quot;, &quot;java.&quot;,<br>        &quot;arrow.core.&quot;, &quot;arrow.fx.coroutines.&quot;,<br>        &quot;kotlinx.coroutines.&quot;, &quot;org.slf4j.&quot;,<br>    )<br><br>    override fun visitImportDirective(importDirective: KtImportDirective) {<br>        super.visitImportDirective(importDirective)<br><br>        val file = importDirective.containingKtFile<br>        if (file.virtualFilePath.contains(&quot;/test/&quot;)) return<br><br>        val packageName = file.packageFqName.asString()<br>        val importPath = importDirective.importedFqName?.asString() ?: return<br><br>        val layer = packageName.removePrefix(&quot;$projectBase.&quot;).substringBefore(&quot;.&quot;)<br>        val layerOwnPackages = when (layer) {<br>            &quot;domain&quot; -&gt; listOf(&quot;$projectBase.domain.&quot;)<br>            &quot;application&quot; -&gt; listOf(&quot;$projectBase.domain.&quot;, &quot;$projectBase.application.&quot;)<br>            else -&gt; return  // only enforce on domain and application<br>        }<br><br>        val allowed = commonAllowedPrefixes + layerOwnPackages<br>        if (allowed.none { importPath.startsWith(it) }) {<br>            report(Finding(<br>                Entity.from(importDirective),<br>                &quot;Import &#39;$importPath&#39; is not allowed in $layer layer.&quot;,<br>            ))<br>        }<br>    }<br>}</pre><p>The logic is deliberate:</p><ul><li><strong>Domain layer</strong>: can only import Kotlin stdlib, Arrow-kt, coroutines, SLF4J, and its own packages</li><li><strong>Application layer</strong>: the same, plus domain layer packages</li><li><strong>Test files</strong>: skipped — tests can import whatever they need (MockK, Kotest, etc.)</li><li><strong>Other layers</strong>: not enforced — infrastructure and presentation have legitimate framework needs</li></ul><p>When an LLM generates import org.springframework.stereotype.Service in a use case class, detekt fails the build with a clear message: <em>&quot;Import &#39;org.springframework.stereotype.Service&#39; is not allowed in application layer.&quot;</em> The LLM can read that message and fix its own output.</p><p>Why whitelist instead of blacklist? Because I can’t anticipate every library an LLM might try to import. The whitelist is short and complete: Kotlin, Arrow, coroutines, SLF4J, and own-layer packages. Everything else is denied by default.</p><h3>Rule 2: NoThrowOutsidePresentationRule — enforcing Either for all errors</h3><p>In <a href="https://medium.com/@wakita181009/clean-architecture-in-kotlin-no-exceptions-no-magic-no-compromise-d17310fb9cd0">Part 1</a>, every fallible operation returns Either&lt;XxxError, T&gt;. No exceptions. The return type is the complete error specification.</p><p>LLMs don’t naturally write this way. They reach for throw IllegalArgumentException(&quot;invalid input&quot;) because that&#39;s what most Kotlin code does.</p><pre>class NoThrowOutsidePresentationRule(config: Config) : Rule(config, &quot;...&quot;) {<br><br>    private val forbiddenLayers = setOf(&quot;domain&quot;, &quot;application&quot;, &quot;infrastructure&quot;)<br><br>    override fun visitThrowExpression(expression: KtThrowExpression) {<br>        super.visitThrowExpression(expression)<br><br>        val file = expression.containingKtFile<br>        if (file.virtualFilePath.contains(&quot;/test/&quot;)) return<br><br>        val packageName = file.packageFqName.asString()<br>        val layer = packageName.removePrefix(&quot;$projectBase.&quot;).substringBefore(&quot;.&quot;)<br>        if (layer in forbiddenLayers) {<br>            report(Finding(<br>                Entity.from(expression),<br>                &quot;throw detected in &#39;$packageName&#39;. Use Either&lt;XxxError, T&gt; instead.&quot;,<br>            ))<br>        }<br>    }<br>}</pre><p>Three layers are covered: domain, application, and infrastructure. The only layer where throw is permitted is presentation — because Spring&#39;s exception handler infrastructure (ResponseStatusException, GraphQLException) requires it.</p><p>Together, these two rules turn architecture guidelines into compiler-level enforcement. The LLM writes code, the Kotlin compiler checks types, and detekt checks architecture. Violations are build errors, not code review comments.</p><h3>From documentation to specification: SDD for LLMs</h3><p><a href="https://medium.com/@wakita181009/your-tests-are-slow-because-your-architecture-has-no-seams-5cd3bcaf738b">Part 2</a> introduced the idea that the application module is a direct translation of the product spec. Tests validate the implementation matches the spec. That workflow was manual — an engineer reads the requirements, writes the interfaces, then writes the tests.</p><p>For LLM-driven development, the spec needs to be machine-readable. Not a PDF. Not a Confluence page. A structured markdown file in the repository that an agent can parse directly.</p><h3>The spec template</h3><p>Every feature starts with a spec file in .claude/specs/:</p><pre># Feature Spec: [Feature Name]<br><br>## 1. Context<br>[Why this feature exists. Business problem.]<br><br>## 2. Domain Model Changes<br>### New Value Objects<br>- `OrderId` (@JvmInline value class): Long, must be positive<br>  - Invalid: `OrderError.InvalidId(value)` -&gt; &quot;Invalid order ID: $value&quot;<br><br>### Domain Errors<br>sealed interface OrderError : DomainError:<br>| Variant      | When                  | Message format              |<br>|--------------|-----------------------|-----------------------------|<br>| InvalidId    | ID &lt;= 0               | &quot;Invalid order ID: $value&quot;  |<br>| NotFound     | No record for this ID | &quot;Order not found: $id&quot;      |<br><br>## 3. Use Cases<br>### UC-1: Find Order by ID<br>Input: id (Long)<br>Happy path: validate -&gt; find -&gt; return Order<br>Error cases:<br>| Error              | Application Error Type           | HTTP |<br>|--------------------|----------------------------------|------|<br>| Invalid ID         | OrderFindByIdError.InvalidId     | 400  |<br>| Not found          | OrderFindByIdError.NotFound      | 404  |<br><br>## 4. Presentation<br>| Method | Path            | Success | Errors    |<br>|--------|-----------------|---------|-----------|<br>| GET    | /api/orders/{id}| 200     | 400, 404  |</pre><p>The spec is structured enough for an LLM to extract: which value objects to create, what validation rules they have, what error types to define, what use cases to implement, and what HTTP status codes to return. Every field maps directly to a Clean Architecture construct.</p><p>This is the key connection from Part 2: <em>the spec-to-code mapping that was implicit in the engineer’s head is now explicit in a file.</em> The LLM doesn’t need to interpret requirements — it reads a table and generates the corresponding Kotlin class.</p><h3>Specialized agents: one agent per layer</h3><p>Here’s the central design insight: <strong>each agent should know only the rules of its own layer.</strong></p><p>A domain-implementer agent that knows about Spring is an agent that might use Spring. An infrastructure-implementer that knows about domain logic is an agent that might put logic in the wrong place. The same principle that separates layers in the code separates agents in the pipeline.</p><h3>The agent architecture</h3><pre>orchestrator (opus)<br>  ├── spec-writer (sonnet)      -&gt; writes .claude/specs/[feature].md<br>  ├── test-designer (sonnet)    -&gt; designs test cases from spec<br>  ├── tester (sonnet)           -&gt; writes failing tests (RED)<br>  ├── domain-implementer (sonnet)<br>  ├── app-implementer (sonnet)<br>  ├── infra-implementer (sonnet)<br>  ├── presentation-implementer (sonnet)<br>  └── reviewer / linter / security-checker (parallel QA)</pre><p>Each agent is a markdown file with explicit constraints. Here’s the opening of the domain-implementer:</p><pre># Domain Implementer Agent<br><br>You implement the domain layer: entities, value objects, error types,<br>and repository interfaces.<br><br>## Constraints — STRICTLY ENFORCED<br>- **NO** Spring annotations (@Component, @Repository, @Service)<br>- **NO** JooQ, R2DBC, JDBC imports<br>- **NO** `throw` statements (use Either / raise() / ensure())<br>- **ONLY** allowed: Kotlin stdlib, Arrow-kt, SLF4J</pre><p>The constraints mirror the detekt rules — but at the prompt level. The agent is told what it cannot do before it writes a single line. If it still violates, detekt catches it at build time.</p><h3>Skills as domain knowledge</h3><p>Each agent references skills — structured knowledge about specific patterns:</p><p>SkillWhat it containsca-kotlinLayer rules, module dependencies, what each layer can importfp-kotlinImmutability patterns, Either chaining, sealed error hierarchiestdd-kotlinTest patterns per layer, MockK/Kotest conventions, property-based testingsdd-specSpec template, how to extract domain constructs from requirementsarrow-ktArrow-kt specific patterns: either { }, .bind(), mapLeftjooq-ddljOOQ DSL patterns, DDL codegen, reactive Mono/Flux usage</p><p>The domain-implementer loads ca-kotlin and fp-kotlin. The infra-implementer loads ca-kotlin and jooq-ddl. The tester loads tdd-kotlin. Each agent gets the knowledge relevant to its layer — no more, no less.</p><h3>Model selection: right model for the right task</h3><p>Not all tasks need the same model. The orchestrator — which coordinates the entire pipeline, decides when to retry, and synthesizes results — runs on Opus (highest reasoning capability). The implementers and spec-writer run on Sonnet (faster, cheaper, sufficient for structured generation).</p><p>This isn’t just cost optimization. It’s about matching capability to task complexity. Writing a value object from a spec is pattern-matching. Deciding whether to re-run the implementation phase after a test failure is judgment.</p><h3>The pipeline: from spec to shipped</h3><p>Here’s what a complete implementation cycle looks like using slash commands:</p><pre>/spec order-api        -&gt; spec-writer creates .claude/specs/order-api.md<br>/spec-review order-api -&gt; spec-reviewer validates completeness<br>/test-design order-api -&gt; test-designer creates test plan from spec<br>/impl order-api        -&gt; orchestrator runs the full pipeline<br>/qa                    -&gt; QA pipeline: build + lint + security + review</pre><p>The /impl command is where the interesting engineering happens. It has to respect the dependency graph between layers while maximizing parallelism.</p><h3>The dependency-aware parallelization</h3><pre>Phase 1 (sequential):  spec read -&gt; domain-implementer -&gt; app-implementer<br>Phase 2 (parallel):    infra-implementer | presentation-implementer | test-implementer<br>Phase 3 (parallel):    builder | linter | security-checker<br>Phase 4 (sequential):  code-reviewer -&gt; documenter</pre><p>Domain must complete before application — use cases depend on domain entities, value objects, and repository interfaces. Application must complete before infrastructure, presentation, and tests — all three consume the use case interfaces but don’t depend on each other.</p><p>This maps directly to the Clean Architecture dependency graph. The implementation order follows the dependency direction: domain -&gt; application -&gt; (infrastructure | presentation | tests). The architecture that makes code modular also makes the build pipeline parallelizable.</p><h3>What the orchestrator actually does</h3><p>The orchestrator is the only agent that doesn’t write code. It reads the spec, creates a layer sketch (mapping spec elements to Kotlin classes), spawns agents in the correct order, reads test results, and decides whether to retry.</p><pre>### Phase 0 — Analyze<br>- Read the spec<br>- Extract and output a Layer Sketch:<br>  - Domain entity (fields + types)<br>  - Value objects (backing type + validation)<br>  - Repository interface (method signatures)<br>  - Use cases (interface name + execute signature)<br>- List every file to create before spawning any agent<br><br>### Phase 1 — Red (tester first, alone)<br>Spawn only the tester agent. Wait for completion.<br><br>### Phase 2 — Green (implementer reads tests)<br>Spawn implementer alone. Wait for completion.<br><br>### Phase 3 — Verify + Review (parallel)<br>Spawn reviewer, linter, security-checker simultaneously.<br>Run: ./gradlew test koverVerify detekt<br><br>### Phase 4 — Synthesize<br>If tests are red, re-spawn implementer with failure output.<br>Cap iterations at 3.</pre><p>The “red -&gt; green -&gt; verify” loop is the SDD + TDD workflow from <a href="https://dev.to/wakita181009/your-tests-are-slow-because-your-architecture-has-no-seams-499o">Part 2</a> — automated. Tests are written before implementation. Implementation is written to pass the tests. The architecture rules are checked after every cycle. The orchestrator doesn’t trust the implementer — it verifies.</p><h3>Hooks: the last line of defense</h3><p>Claude Code supports hooks — shell commands that trigger on specific events. Two hooks close the loop between the LLM and the architecture rules:</p><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;PostToolUse&quot;: [<br>      {<br>        &quot;matcher&quot;: &quot;Write|Edit&quot;,<br>        &quot;hooks&quot;: [{<br>          &quot;type&quot;: &quot;command&quot;,<br>          &quot;command&quot;: &quot;cd $CLAUDE_PROJECT_DIR &amp;&amp; ./gradlew ktlintFormat 2&gt;&amp;1 | tail -60&quot;,<br>          &quot;timeout&quot;: 30<br>        }]<br>      }<br>    ],<br>    &quot;Stop&quot;: [<br>      {<br>        &quot;hooks&quot;: [{<br>          &quot;type&quot;: &quot;command&quot;,<br>          &quot;command&quot;: &quot;cd $CLAUDE_PROJECT_DIR &amp;&amp; ./gradlew detekt 2&gt;&amp;1 | tail -60&quot;,<br>          &quot;timeout&quot;: 120<br>        }]<br>      }<br>    ]<br>  }<br>}</pre><p><strong>PostToolUse on Write/Edit</strong>: Every time the LLM creates or modifies a file, ktlint auto-formats it. No style drift. No formatting discussions. The code matches the project style before the LLM’s next turn.</p><p><strong>Stop</strong>: When the LLM finishes its work, detekt runs automatically. If the custom rules detect a throw in the domain layer or a Spring import in the application layer, the violation is surfaced immediately. The LLM sees the failure output and can self-correct.</p><p>This creates a feedback loop: write -&gt; auto-format -&gt; continue -&gt; finish -&gt; architecture check -&gt; fix if violated. The LLM operates within the enforcement boundary in real time.</p><p>In <a href="https://medium.com/@wakita181009/clean-architecture-in-practice-swapping-database-clients-and-adding-graphql-in-kotlin-a145b0f87934">Part 3</a>, I proved that swapping the database changed zero files in domain or application. In <a href="https://medium.com/@wakita181009/cqrs-with-clean-architecture-in-kotlin-separating-read-and-write-paths-for-better-performance-cf8758cfad72">Part 4</a>, CQRS actually <em>simplified</em> the domain by removing read responsibilities that didn’t belong there. Hooks guarantee those architectural properties hold not just for those one-time changes — but for every code change an LLM makes, continuously.</p><h3>The enforcement stack</h3><p>Here’s the complete picture of how architecture rules are enforced across the stack:</p><p>LayerMechanismWhat it preventsGradle modulesCompile-time dependency graphdomain importing from infrastructureForbiddenLayerImportRuleAST-level import whitelistSpring/JPA/framework imports in pure layersNoThrowOutsidePresentationRuleAST-level throw detectionExceptions in domain/application/infrastructureKover 80% thresholdLine coverage gateUntested error pathsAgent constraintsPrompt-level rulesAgent writing code outside its layerSkillsDomain knowledge injectionAgent using wrong patterns for its layerPostToolUse hookAuto-format on every writeStyle driftStop hookDetekt on every completionArchitecture violations in final output</p><p>Each layer catches what the layer above might miss. The agent prompt says “no throw.” If the LLM ignores it, detekt catches it. If detekt isn’t run, Kover might catch the untested exception path. Defense in depth — the same principle that makes Clean Architecture resilient makes the LLM pipeline resilient.</p><h3>The honest tradeoffs</h3><p>This setup has real costs:</p><p><strong>Initial investment is high.</strong> 18 agent definitions, 7 skills, 6 commands, 2 custom detekt rules, and a hook configuration. That’s a significant upfront cost before a single feature is implemented through the pipeline.</p><p><strong>Agent definitions need maintenance.</strong> When the project’s patterns evolve — say, migrating from jOOQ to Exposed — every agent and skill that references jOOQ needs updating. The knowledge isn’t centralized in one place; it’s distributed across agent prompts and skill files.</p><p><strong>Model costs add up.</strong> Running an Opus orchestrator that spawns multiple Sonnet agents per feature isn’t cheap. For a solo developer on a side project, the cost-per-feature may not justify the automation. For a team shipping multiple features per sprint, the math changes.</p><p><strong>The pipeline is only as good as the spec.</strong> An ambiguous or incomplete spec produces ambiguous or incomplete code. The automation amplifies whatever you feed it. Garbage spec, garbage implementation — faster.</p><h3>What makes the cost worth it</h3><p>The payoff is in the second feature, not the first. Once the agents, skills, and rules exist, adding a new feature follows the same path: write a spec, run /impl, review the output. The architectural guarantees from Parts 1-4 are maintained automatically. No code review needed to catch Spring imports in the domain layer. No manual checks for exception-based error handling. The pipeline enforces what the architecture demands.</p><p>For teams with multiple engineers (including AI agents) contributing to the same codebase, the enforcement stack is the difference between architecture that degrades over time and architecture that holds.</p><h3>What this series built</h3><p>Five articles. One architecture. Database migration, new protocols, CQRS optimization, LLM-generated code — each article applied a different pressure. The architecture held every time. Not because engineers were careful, but because the constraints were structural.</p><p>Clean Architecture was designed to make software maintainable by humans. It turns out the same constraints — explicit dependencies, typed errors, pure layers — are exactly what LLMs need to write code safely. The architecture didn’t change. The developer did.</p><p>The full source is on GitHub: <a href="https://github.com/wakita181009/clean-architecture-kotlin/tree/v4">https://github.com/wakita181009/clean-architecture-kotlin/tree/v4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e86019a4f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CQRS with Clean Architecture in Kotlin: Separating Read and Write Paths for Better Performance]]></title>
            <link>https://medium.com/@wakita181009/cqrs-with-clean-architecture-in-kotlin-separating-read-and-write-paths-for-better-performance-cf8758cfad72?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf8758cfad72</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 22:00:39 GMT</pubDate>
            <atom:updated>2026-03-01T22:05:10.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EXV0uOSv1DAOIPsg-6iXw.png" /></figure><p><em>How CQRS inside Clean Architecture gave reads a fast path while keeping writes honest</em></p><h3>The read path is doing work it doesn’t need to</h3><p>In <a href="https://medium.com/@wakita181009/clean-architecture-in-practice-swapping-database-clients-and-adding-graphql-in-kotlin-a145b0f87934">Part 3</a>,<br>I swapped Spring Data R2DBC for jOOQ and added GraphQL alongside REST. The domain and application layers: zero files<br>changed.</p><p>But something bothered me about the read path. When a client calls GET /api/github-repos, here&#39;s what happens:</p><ol><li>The controller calls gitHubRepoListUseCase.execute(pageNumber, pageSize)</li><li>The use case validates pagination parameters</li><li>The repository queries the database</li><li>The database rows are mapped into <strong>domain entities</strong> — constructing GitHubRepoId, GitHubOwner, GitHubRepoName value objects with full validation</li><li>The domain entities are mapped into REST response DTOs</li><li>The DTOs are serialized to JSON</li></ol><p>Steps 4 and 5 are pure overhead. The client asked for a list of repos. The read path doesn’t modify anything, doesn’t<br>enforce business invariants, doesn’t trigger side effects. It just needs data — but it’s constructing fully validated<br>domain objects, only to immediately unwrap them into flat DTOs.</p><p>Writes are different. When a client calls POST /api/github-repos, domain validation matters. The GitHubRepoId must<br>be positive. The GitHubOwner must not be blank. The GitHubRepoName must not be blank. Those invariants protect the<br>system&#39;s integrity. The domain model earns its keep on the write path.</p><p>This is the core insight behind CQRS: <strong>reads and writes have fundamentally different needs.</strong> Forcing them through the<br>same model means one path is always doing unnecessary work.</p><h3>What CQRS changes in Clean Architecture</h3><p>CQRS — Command Query Responsibility Segregation — separates the read model from the write model. In its simplest form (<br>no event sourcing, no separate databases), it means:</p><ul><li><strong>Commands</strong> (writes) go through the full domain model: validation, invariants, business rules</li><li><strong>Queries</strong> (reads) bypass the domain and return DTOs directly from the database</li></ul><p>The application layer splits into two sub-packages:</p><pre>application/<br>├── command/                    # Write path<br>│   ├── dto/github/<br>│   │   └── GitHubRepoDto.kt<br>│   ├── error/github/<br>│   │   └── GitHubRepoSaveError.kt<br>│   └── usecase/github/<br>│       ├── GitHubRepoSaveUseCase.kt<br>│       └── GitHubRepoSaveUseCaseImpl.kt<br>│<br>└── query/                      # Read path<br>    ├── dto/<br>    │   ├── PageDto.kt<br>    │   └── github/<br>    │       └── GitHubRepoQueryDto.kt<br>    ├── error/github/<br>    │   ├── GitHubRepoFindByIdQueryError.kt<br>    │   └── GitHubRepoListQueryError.kt<br>    ├── repository/github/<br>    │   └── GitHubRepoQueryRepository.kt<br>    └── usecase/github/<br>        ├── GitHubRepoFindByIdQueryUseCase.kt<br>        ├── GitHubRepoFindByIdQueryUseCaseImpl.kt<br>        ├── GitHubRepoListQueryUseCase.kt<br>        └── GitHubRepoListQueryUseCaseImpl.kt</pre><p>Separate DTOs, separate errors, separate repository interfaces. The write path and read path don’t share<br>application-layer types. They share domain value objects for input validation — and nothing else.</p><h3>The command side: unchanged domain flow</h3><p>The write path keeps the full domain-driven approach from Parts 1–3. The save use case validates input by constructing<br>domain entities:</p><pre>class GitHubRepoSaveUseCaseImpl(<br>    private val gitHubRepoRepository: GitHubRepoRepository,<br>) : GitHubRepoSaveUseCase {<br>    override suspend fun execute(dto: GitHubRepoDto): Either&lt;GitHubRepoSaveError, GitHubRepo&gt; =<br>        either {<br>            val repo = dto.toDomain().mapLeft(GitHubRepoSaveError::ValidationFailed).bind()<br>            gitHubRepoRepository<br>                .save(repo)<br>                .mapLeft(GitHubRepoSaveError::SaveFailed)<br>                .bind()<br>        }<br>}</pre><p>dto.toDomain() constructs every value object — GitHubRepoId.of(id), GitHubOwner.of(owner),<br>GitHubRepoName.of(name) — each returning Either. If any validation fails, the chain short-circuits with<br>ValidationFailed. If the repository call fails, it short-circuits with SaveFailed.</p><p>The domain repository interface is now write-only:</p><pre>interface GitHubRepoRepository {<br>    suspend fun save(repo: GitHubRepo): Either&lt;GitHubError, GitHubRepo&gt;<br>}</pre><p>In Parts 1–3, this interface also had findById and list. Those methods are gone — reads no longer flow through the<br>domain. The domain repository does one thing: persist validated domain entities.</p><h3>The query side: DTOs all the way</h3><p>Here’s the read path. No domain entities. No value object construction on the output path:</p><pre>class GitHubRepoListQueryUseCaseImpl(<br>    private val queryRepository: GitHubRepoQueryRepository,<br>) : GitHubRepoListQueryUseCase {<br>    override suspend fun execute(<br>        pageNumber: Int,<br>        pageSize: Int,<br>    ): Either&lt;GitHubRepoListQueryError, PageDto&lt;GitHubRepoQueryDto&gt;&gt; =<br>        either {<br>            val validPageNumber =<br>                PageNumber<br>                    .of(pageNumber)<br>                    .mapLeft(GitHubRepoListQueryError::InvalidPageNumber)<br>                    .bind()<br>            val validPageSize =<br>                PageSize<br>                    .of(pageSize)<br>                    .mapLeft(GitHubRepoListQueryError::InvalidPageSize)<br>                    .bind()<br>            val limit = validPageSize.value<br>            val offset = (validPageNumber.value - 1) * validPageSize.value<br>            queryRepository.list(limit, offset).bind()<br>        }<br>}</pre><p>The return type tells the story: Either&lt;GitHubRepoListQueryError, PageDto&lt;GitHubRepoQueryDto&gt;&gt;. Not<br>Page&lt;GitHubRepo&gt;. The query returns a PageDto of GitHubRepoQueryDto — a flat data class with no domain types:</p><pre>data class GitHubRepoQueryDto(<br>    val id: Long,<br>    val owner: String,<br>    val name: String,<br>    val fullName: String,<br>    val description: String?,<br>    val language: String?,<br>    val stargazersCount: Int,<br>    val forksCount: Int,<br>    val isPrivate: Boolean,<br>    val createdAt: OffsetDateTime,<br>    val updatedAt: OffsetDateTime,<br>)</pre><p>Plain types. Long, String, Int, Boolean. No GitHubRepoId, no GitHubOwner, no GitHubRepoName. The DTO is a<br>direct projection of the database row — no domain construction overhead.</p><h3>The query repository: why it lives in the application layer</h3><p>In <a href="https://medium.com/@wakita181009/clean-architecture-in-kotlin-no-exceptions-no-magic-no-compromise-d17310fb9cd0">Part 1</a>, the<br>repository interface was defined in the domain layer — because the domain needs to express what persistence operations<br>it requires. That’s still true for writes. GitHubRepoRepository.save() takes a domain entity and returns a domain<br>entity.</p><p>But the query repository is different:</p><pre>interface GitHubRepoQueryRepository {<br>    suspend fun findById(id: Long): Either&lt;GitHubRepoFindByIdQueryError, GitHubRepoQueryDto&gt;<br><br>    suspend fun list(<br>        limit: Int,<br>        offset: Int,<br>    ): Either&lt;GitHubRepoListQueryError, PageDto&lt;GitHubRepoQueryDto&gt;&gt;<br>}</pre><p>Two things stand out. First, the error types are the full sealed interfaces (GitHubRepoFindByIdQueryError,<br>GitHubRepoListQueryError), not just FetchFailed. The infrastructure implementation is responsible for resolving &quot;not<br>found&quot; — it queries the database and knows whether a row exists. The application layer handles input validation (<br>InvalidId). Each layer raises the errors within its scope.</p><p>Second, this interface lives in application/query/repository/, not domain/repository/. The reason is structural: it<br>takes primitives (Long, Int) and returns application-layer DTOs (GitHubRepoQueryDto, PageDto). It has no domain<br>types in its signature. Placing it in the domain layer would force the domain to know about GitHubRepoQueryDto — an<br>application-layer concept. That breaks the dependency rule.</p><p>The query repository is an application-layer port. Infrastructure implements it. The domain doesn’t know it exists.</p><h3>Pragmatic validation: reusing domain value objects</h3><p>The query side doesn’t construct domain entities — but it does reuse domain value objects for <strong>input validation</strong>. Look<br>at GitHubRepoFindByIdQueryUseCaseImpl:</p><pre>class GitHubRepoFindByIdQueryUseCaseImpl(<br>    private val queryRepository: GitHubRepoQueryRepository,<br>) : GitHubRepoFindByIdQueryUseCase {<br>    override suspend fun execute(id: Long): Either&lt;GitHubRepoFindByIdQueryError, GitHubRepoQueryDto&gt; =<br>        either {<br>            val repoId = GitHubRepoId.of(id).mapLeft(GitHubRepoFindByIdQueryError::InvalidId).bind()<br>            queryRepository.findById(repoId.value).bind()<br>        }<br>}</pre><p>GitHubRepoId.of(id) is a domain value object. The query uses it to validate that the ID is positive — the same rule<br>the write path enforces. But after validation, it extracts .value and passes the raw Long to the query repository.<br>The domain entity GitHubRepo is never constructed.</p><p>This is pragmatic CQRS. Domain validation rules (positive IDs, page size limits) are universal — they apply to reads and<br>writes equally. Duplicating that logic would be worse than reusing it. But domain <em>entities</em> — the full aggregate with<br>all its fields validated and wrapped — are only needed when writing.</p><p>The same pattern applies to pagination. PageNumber.of() and PageSize.of() enforce business constraints (minimum 1,<br>maximum 100). The query converts them to limit and offset — database concepts — and the query repository takes those<br>primitives directly.</p><h3>Infrastructure: two repositories, one database</h3><p>Both repositories read from and write to the same github_repo table. The split is logical, not physical.</p><p>The query repository implementation maps database records directly to DTOs:</p><pre>@Repository<br>class GitHubRepoQueryRepositoryImpl(<br>    private val dsl: DSLContext,<br>) : GitHubRepoQueryRepository {<br>    override suspend fun findById(id: Long): Either&lt;GitHubRepoFindByIdQueryError, GitHubRepoQueryDto&gt; =<br>        either {<br>            val dto =<br>                Either<br>                    .catch {<br>                        Mono<br>                            .from(<br>                                dsl<br>                                    .selectFrom(GITHUB_REPO)<br>                                    .where(GITHUB_REPO.ID.eq(id)),<br>                            ).map { it.toQueryDto() }<br>                            .awaitSingleOrNull()<br>                    }.mapLeft { GitHubRepoFindByIdQueryError.FetchFailed(it.message ?: &quot;Unknown error&quot;) }<br>                    .bind()<br><br>            ensureNotNull(dto) { GitHubRepoFindByIdQueryError.NotFound(id) }<br>        }</pre><p>it.toQueryDto() maps a jOOQ GithubRepoRecord to GitHubRepoQueryDto. No domain entity involved. The database row<br>becomes a DTO in a single step. ensureNotNull from Arrow-kt handles the &quot;not found&quot; case — if the query returns<br>null, it raises NotFound directly. The application layer doesn&#39;t need to check for null; the infrastructure resolves<br>it.</p><p>Compare this with the write repository, which maps to a full domain entity through toDomain() — constructing value<br>objects, enforcing invariants. Two implementations of the same table, each optimized for its path.</p><h3>Presentation: same pattern, different types</h3><p>The controller now injects queries and commands as separate dependencies:</p><pre>@RestController<br>@RequestMapping(&quot;/api/github-repos&quot;)<br>class GitHubRepoController(<br>    private val gitHubRepoListQueryUseCase: GitHubRepoListQueryUseCase,<br>    private val gitHubRepoFindByIdQueryUseCase: GitHubRepoFindByIdQueryUseCase,<br>    private val gitHubRepoSaveUseCase: GitHubRepoSaveUseCase,<br>) {</pre><p>Read endpoints call queries. The write endpoint calls the command use case. The Either.fold pattern is identical:</p><pre>@GetMapping(&quot;/{id}&quot;)<br>suspend fun findById(@PathVariable id: Long): ResponseEntity&lt;*&gt; =<br>    gitHubRepoFindByIdQueryUseCase.execute(id).fold(<br>        ifLeft = { error -&gt;<br>            when (error) {<br>                is GitHubRepoFindByIdQueryError.InvalidId -&gt;<br>                    ResponseEntity.badRequest().body(ErrorResponse(error.message))<br>                is GitHubRepoFindByIdQueryError.NotFound -&gt;<br>                    ResponseEntity.notFound().build&lt;Nothing&gt;()<br>                is GitHubRepoFindByIdQueryError.FetchFailed -&gt; {<br>                    logger.error(&quot;Failed to fetch GitHub repo (id=$id): ${error.message}&quot;)<br>                    ResponseEntity.internalServerError().body(ErrorResponse(&quot;Internal server error&quot;))<br>                }<br>            }<br>        },<br>        ifRight = { dto -&gt;<br>            ResponseEntity.ok(GitHubRepoResponse.fromQueryDto(dto))<br>        },<br>    )</pre><p>The response DTO now has two factory methods: fromDomain() for commands (unwrapping value objects) and<br>fromQueryDto() for queries (direct field copy):</p><pre>companion object {<br>    fun fromDomain(repo: GitHubRepo) =<br>        GitHubRepoResponse(<br>            id = repo.id.value,      // unwrap value object<br>            owner = repo.owner.value,<br>            // ...<br>        )<br><br>    fun fromQueryDto(dto: GitHubRepoQueryDto) =<br>        GitHubRepoResponse(<br>            id = dto.id,             // already a Long<br>            owner = dto.owner,<br>            // ...<br>        )<br>}</pre><p>The same split applies to GraphQL. The mapper has GitHubRepoQueryDto.toGraphQL() for reads and<br>DomainGitHubRepo.toGraphQL() for writes. Different source types, same destination type. The presentation layer adapts<br>both paths to its protocol without knowing which path the data took to get there.</p><h3>Tests: the specification still holds</h3><p>Query tests mock the query repository. Command tests mock the domain repository. Each side has its own test fixtures:</p><pre>class GitHubRepoListQueryUseCaseImplTest {<br>    private val queryRepository = mockk&lt;GitHubRepoQueryRepository&gt;()<br>    private val queryUseCase = GitHubRepoListQueryUseCaseImpl(queryRepository)<br><br>    @Test<br>    fun `execute returns Right with page when parameters are valid`() =<br>        runTest {<br>            val page = PageDto(totalCount = 1, items = listOf(sampleQueryDto()))<br>            coEvery { queryRepository.list(offset = 0, limit = 20) } returns Either.Right(page)<br>            queryUseCase.execute(1, 20).shouldBeRight(page)<br>        }<br><br>    @Test<br>    fun `execute returns Left InvalidPageNumber when pageNumber is 0`() =<br>        runTest {<br>            val error = queryUseCase.execute(0, 20).shouldBeLeft()<br>            error shouldBe GitHubRepoListQueryError.InvalidPageNumber(PageNumberError.BelowMinimum(0))<br>        }<br><br>    @Test<br>    fun `execute calculates correct offset for page 2`() =<br>        runTest {<br>            val page = PageDto(totalCount = 30, items = listOf(sampleQueryDto()))<br>            coEvery { queryRepository.list(offset = 20, limit = 20) } returns Either.Right(page)<br>            queryUseCase.execute(2, 20).shouldBeRight(page)<br>        }<br>}</pre><p>Note the offset test. Page 2 with size 20 should produce offset = 20. This calculation —<br>(pageNumber - 1) * pageSize — happens in the query use case, not the repository. The repository receives limit and<br>offset as primitives. The business logic of pagination lives in the application layer; the database execution lives in<br>infrastructure.</p><p>The command tests are unchanged<br>from <a href="https://dev.to/wakita181009/your-tests-are-slow-because-your-architecture-has-no-seams-499o">Part 2</a>:</p><pre>class GitHubRepoSaveUseCaseImplTest {<br>    private val repository = mockk&lt;GitHubRepoRepository&gt;()<br>    private val useCase = GitHubRepoSaveUseCaseImpl(repository)<br><br>    @Test<br>    fun `execute returns Left ValidationFailed when dto has invalid id`() =<br>        runTest {<br>            val dto = sampleDto().copy(id = 0L)<br>            val error = useCase.execute(dto).shouldBeLeft()<br>            error shouldBe GitHubRepoSaveError.ValidationFailed(GitHubError.InvalidId(0L))<br>        }<br>}</pre><p>Domain validation on the write path. DTO projection on the read path. Each test verifies the right behavior for its side<br>of the split.</p><h3>The honest tradeoff</h3><p>CQRS adds types. Specifically:</p><p>Before (unified)After (CQRS)1 repository interface2 repository interfaces1 DTO type2 DTO types (command + query)3 use cases, 1 error hierarchy per use case1 command + 2 queries, separate error hierarchies1 infrastructure implementation2 infrastructure implementations</p><p>That’s roughly double the application-layer surface area for the same feature set. For a project with one entity, this<br>feels like overkill. For a project with dozens of entities, where read and write patterns diverge significantly — <br>different fields projected, different joins, different caching strategies — the separation pays for itself.</p><p>The key question is: <strong>will your read and write patterns diverge?</strong> If yes, CQRS gives you the seam to evolve them<br>independently. If no — if every read returns exactly the same shape as the domain entity — the unified model from Parts<br>1–3 is simpler and sufficient.</p><p>In this project, the divergence is modest. But the architecture is now ready for it to grow. Adding a search query that<br>joins across tables, a dashboard aggregation that returns computed fields, or a denormalized read model for high-traffic<br>endpoints — none of these will touch the command side or the domain.</p><p>The full source is on GitHub: <a href="https://github.com/wakita181009/clean-architecture-kotlin/tree/v3">https://github.com/wakita181009/clean-architecture-kotlin/tree/v3</a></p><ul><li><a href="https://medium.com/@wakita181009/clean-architecture-in-kotlin-no-exceptions-no-magic-no-compromise-d17310fb9cd0"><em>Part 1: Clean Architecture in Kotlin with Spring Boot: Gradle Modules + Arrow-kt in Practice→</em></a></li><li><a href="https://medium.com/@wakita181009/your-tests-are-slow-because-your-architecture-has-no-seams-5cd3bcaf738b"><em>Part 2: </em>Why Your Kotlin Tests Are Slow: How Clean Architecture Enables Sub-Second Unit Testing<em>→</em></a></li><li><a href="https://medium.com/@wakita181009/clean-architecture-in-kotlin-no-exceptions-no-magic-no-compromise-d17310fb9cd0"><em>Part 3: Clean Architecture in Practice: Swapping Database Clients and Adding GraphQL in Kotlin→</em></a></li><li><a href="https://medium.com/@wakita181009/cqrs-with-clean-architecture-in-kotlin-separating-read-and-write-paths-for-better-performance-cf8758cfad72"><em>Part 4: CQRS with Clean Architecture in Kotlin: Separating Read and Write Paths for Better Performance→</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf8758cfad72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture in Practice: Swapping Database Clients and Adding GraphQL in Kotlin]]></title>
            <link>https://medium.com/@wakita181009/clean-architecture-in-practice-swapping-database-clients-and-adding-graphql-in-kotlin-a145b0f87934?source=rss-62f89bf3179e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a145b0f87934</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jooq]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Tetsuya Wakita]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 16:06:52 GMT</pubDate>
            <atom:updated>2026-03-01T22:04:51.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1H_6dbiD5uCS2fkhnHHemQ.png" /></figure><p><em>How Clean Architecture delivered on its promise — infrastructure and presentation changed completely, domain and application stayed identical.</em></p><h3>The claim every architecture post makes</h3><p>Every Clean Architecture tutorial promises the same thing: swap your database, change your API protocol, and the business logic stays untouched.</p><p>Most tutorials stop there. They show the diagram, explain the dependency rule, and leave you to wonder whether it actually holds when you try it.</p><p>This article is the proof of concept.</p><p>Starting from the project in <a href="https://dev.to/wakita181009/clean-architecture-in-kotlin-no-exceptions-no-magic-no-compromise-5ha1">Part 1</a> — a Spring Boot API backed by Spring Data R2DBC — I made two changes:</p><ol><li><strong>Infrastructure</strong>: replaced Spring Data R2DBC with <a href="https://www.jooq.org/"><strong>jOOQ</strong></a> for type-safe SQL</li><li><strong>Presentation</strong>: added a <strong>GraphQL API</strong> using <a href="https://netflix.github.io/dgs/">Netflix DGS</a> alongside the existing REST endpoints</li></ol><p>Here’s the git diff for the domain module: nothing. For the application module: nothing. Every use case, every domain entity, every value object, every error type — unchanged.</p><p>Let’s walk through what actually changed, and why everything else didn’t need to.</p><h3>What we’re changing and why</h3><p>The original infrastructure layer used Spring Data R2DBC with a generated entity class and a Spring repository interface. It worked — but the mapping was manual and the queries were limited to what Spring Data’s derived query methods could express.</p><p>jOOQ generates a type-safe DSL from the database schema. Instead of r2dbcRepository.findById(id), you write dsl.selectFrom(GITHUB_REPO).where(GITHUB_REPO.ID.eq(id)). The table name and column names are compile-time constants. A typo in a column name is a build error.</p><p>For the API layer, GraphQL offers something REST doesn’t: clients specify exactly the fields they need. Adding it shouldn’t change anything about how the business logic works — it’s just a new way to receive requests and send responses.</p><h3>Infrastructure: replacing Spring Data with jOOQ</h3><h3>Configuration</h3><p>The jOOQ setup lives in infrastructure — the only module that knows about databases:</p><pre>@Configuration<br>@EnableTransactionManagement<br>class JooqConfig(<br>    private val cfi: ConnectionFactory,<br>) {<br>    @Bean<br>    fun dsl(): DSLContext =<br>        DSL.using(<br>            DSL<br>                .using(cfi)<br>                .configuration()<br>                .derive(<br>                    Settings()<br>                        .withRenderQuotedNames(RenderQuotedNames.NEVER)<br>                        .withRenderNameCase(RenderNameCase.LOWER),<br>                ),<br>        )<br><br>    @Bean<br>    fun transactionalOperator(): TransactionalOperator =<br>        TransactionalOperator.create(R2dbcTransactionManager(cfi))<br>}</pre><p>DSLContext is initialized with the R2DBC ConnectionFactory — the same connection pool as before. jOOQ handles reactive execution through Reactor&#39;s Publisher API. The Settings configure lowercase, unquoted identifiers to match the PostgreSQL schema.</p><h3>Code generation from the schema</h3><p>jOOQ generates Kotlin classes directly from the Flyway migration SQL — the same SQL that was already in the project:</p><pre>jooq {<br>    configuration {<br>        generator {<br>            name = &quot;org.jooq.codegen.KotlinGenerator&quot;<br>            database {<br>                name = &quot;org.jooq.meta.extensions.ddl.DDLDatabase&quot;<br>                properties {<br>                    property {<br>                        key = &quot;scripts&quot;<br>                        value = &quot;src/main/resources/db/migration/*.sql&quot;<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>This generates GITHUB_REPO as a typed table reference and GithubRepoRecord as a typed row class. No new schema files. No separate ORM mapping configuration. The SQL migration is the single source of truth.</p><h3>Type-safe queries with the same Either wrapping</h3><p>The repository implementation looks different from before, but the interface it implements — GitHubRepoRepository — is identical:</p><pre>@Repository<br>class GitHubRepoRepositoryImpl(<br>    private val dsl: DSLContext,<br>) : GitHubRepoRepository {<br><br>    override suspend fun findById(id: GitHubRepoId): Either&lt;GitHubError, GitHubRepo&gt; =<br>        either {<br>            val record =<br>                Either<br>                    .catch {<br>                        Mono<br>                            .from(<br>                                dsl<br>                                    .selectFrom(GITHUB_REPO)<br>                                    .where(GITHUB_REPO.ID.eq(id.value)),<br>                            ).map { it.toDomain() }<br>                            .awaitSingleOrNull()<br>                    }.mapLeft { GitHubError.RepositoryError(&quot;Failed to find repo: ${it.message}&quot;, it) }<br>                    .bind()<br>            if (record == null) raise(GitHubError.NotFound(id))<br>            record<br>        }</pre><p>GITHUB_REPO.ID is a typed column reference generated from the schema. .eq(id.value) is type-checked — passing a String where a Long is expected won&#39;t compile.</p><p>The error wrapping pattern is the same as before: Either.catch { } captures any thrown exception, mapLeft converts it to a GitHubError.RepositoryError, and .bind() short-circuits the either { } block on failure.</p><h3>Upsert with jOOQ DSL</h3><p>The save operation benefits from jOOQ&#39;s expressive SQL DSL for the INSERT ... ON CONFLICT upsert:</p><pre>override suspend fun save(repo: GitHubRepo): Either&lt;GitHubError, GitHubRepo&gt; =<br>    Either<br>        .catch {<br>            Mono<br>                .from(<br>                    dsl<br>                        .insertInto(GITHUB_REPO)<br>                        .set(GITHUB_REPO.ID, repo.id.value)<br>                        .set(GITHUB_REPO.OWNER, repo.owner.value)<br>                        // ... remaining fields ...<br>                        .onConflict(GITHUB_REPO.ID)<br>                        .doUpdate()<br>                        .set(GITHUB_REPO.OWNER, excluded(GITHUB_REPO.OWNER))<br>                        // ... update fields ...<br>                        .returning(),<br>                ).awaitSingle()<br>                .toDomain()<br>        }.mapLeft { GitHubError.RepositoryError(&quot;Failed to save repo: ${it.message}&quot;, it) }</pre><p>.onConflict(GITHUB_REPO.ID).doUpdate() is standard SQL upsert semantics expressed as Kotlin. excluded(GITHUB_REPO.OWNER) references the value from the VALUES clause that was excluded by the conflict — the jOOQ equivalent of PostgreSQL&#39;s EXCLUDED.owner. The column references are compile-time constants. Mistype GITHUB_REPO.OWNR and the build fails.</p><p>The domain GitHubRepo entity is unchanged. The toDomain() mapping reads from GithubRepoRecord instead of the old Spring Data entity — but the output is the same domain object.</p><h3>Presentation: adding GraphQL with Netflix DGS</h3><h3>Schema-first with DGS</h3><p><a href="https://netflix.github.io/dgs/">Netflix DGS</a> (Domain Graph Service) takes a schema-first approach. The GraphQL schema lives in presentation/src/main/resources/schema/github.graphqls:</p><pre>scalar Long<br>scalar DateTime<br><br>type Query {<br>    githubRepo(id: Long!): GitHubRepo<br>    githubRepos(pageNumber: Int = 1, pageSize: Int = 20): GitHubRepoPage!<br>}<br><br>type Mutation {<br>    saveGitHubRepo(input: GitHubRepoInput!): GitHubRepo!<br>}<br><br>type GitHubRepo {<br>    id: Long!<br>    owner: String!<br>    name: String!<br>    fullName: String!<br>    description: String<br>    language: String<br>    stargazersCount: Int!<br>    forksCount: Int!<br>    isPrivate: Boolean!<br>    createdAt: DateTime!<br>    updatedAt: DateTime!<br>}<br><br>input GitHubRepoInput {<br>    id: Long!<br>    owner: String!<br>    # ...<br>}</pre><p>The ID type is replaced with Long — keeping it consistent with the domain&#39;s GitHubRepoId(Long). DateTime maps to OffsetDateTime in Kotlin. Both are custom scalars registered via graphql-java-extended-scalars:</p><pre>@DgsComponent<br>class ScalarConfig {<br>    @DgsRuntimeWiring<br>    fun addScalar(builder: RuntimeWiring.Builder): RuntimeWiring.Builder =<br>        builder<br>            .scalar(ExtendedScalars.GraphQLLong)<br>            .scalar(ExtendedScalars.DateTime)<br>}</pre><p>DGS codegen generates Kotlin data classes from this schema at build time — GitHubRepo, GitHubRepoPage, GitHubRepoInput — parallel to how jOOQ generates classes from the SQL schema. The schema is the source of truth; the generated types are implementation details.</p><h3>The DataFetcher: Either.fold as GraphQL adapter</h3><p>GitHubRepoDataFetcher is the GraphQL equivalent of the REST controller. It receives requests, calls use cases, and translates Either results to GraphQL responses:</p><pre>@DgsComponent<br>class GitHubRepoDataFetcher(<br>    private val gitHubRepoListUseCase: GitHubRepoListUseCase,<br>    private val gitHubRepoFindByIdUseCase: GitHubRepoFindByIdUseCase,<br>    private val gitHubRepoSaveUseCase: GitHubRepoSaveUseCase,<br>) {<br>    @DgsQuery(field = &quot;githubRepo&quot;)<br>    suspend fun githubRepo(<br>        @InputArgument id: Long,<br>    ): GitHubRepo? =<br>        gitHubRepoFindByIdUseCase<br>            .execute(id)<br>            .fold(<br>                ifLeft = { error -&gt;<br>                    when (error) {<br>                        is GitHubRepoFindByIdError.NotFound -&gt; null<br>                        is GitHubRepoFindByIdError.InvalidId,<br>                        is GitHubRepoFindByIdError.FetchFailed,<br>                        -&gt; throw GraphQLException(error.message)<br>                    }<br>                },<br>                ifRight = { repo -&gt; repo.toGraphQL() },<br>            )<br><br>    @DgsQuery(field = &quot;githubRepos&quot;)<br>    suspend fun githubRepos(<br>        @InputArgument pageNumber: Int = 1,<br>        @InputArgument pageSize: Int = 20,<br>    ): GitHubRepoPage =<br>        gitHubRepoListUseCase.execute(pageNumber, pageSize).fold(<br>            ifLeft = { error -&gt; throw GraphQLException(error.message) },<br>            ifRight = { page -&gt; page.toGraphQL() },<br>        )<br><br>    @DgsMutation(field = &quot;saveGitHubRepo&quot;)<br>    suspend fun saveGitHubRepo(<br>        @InputArgument input: GitHubRepoInput,<br>    ): GitHubRepo =<br>        gitHubRepoSaveUseCase.execute(input.toDto()).fold(<br>            ifLeft = { error -&gt; throw GraphQLException(error.message) },<br>            ifRight = { repo -&gt; repo.toGraphQL() },<br>        )<br>}</pre><p>The pattern is identical to the REST controller: call the use case, fold on the Either, map Right to the response type, handle Left based on the error type. The only difference is the output format — ResponseEntity becomes a GraphQL type or a GraphQLException.</p><p>Because the schema types id as Long!, DGS handles the coercion automatically. There&#39;s no need to manually parse or validate the ID in the DataFetcher — the type system does it.</p><p>Compare githubRepo with the REST findById:</p><ul><li>REST: NotFound → ResponseEntity.notFound().build()</li><li>GraphQL: NotFound → null (GraphQL convention for missing nullable fields)</li><li>REST: FetchFailed → ResponseEntity.badRequest()</li><li>GraphQL: FetchFailed → throw GraphQLException(error.message)</li></ul><p>Different protocols, different conventions — same use case, same error types, same business logic.</p><h3>The mapper: same pattern as REST DTOs</h3><p>Type conversion between domain objects and GraphQL types follows the same extension function pattern as the REST DTOs:</p><pre>fun DomainGitHubRepo.toGraphQL() =<br>    GitHubRepo(<br>        id = id.value,       // Long — matches scalar Long in schema<br>        owner = owner.value,<br>        name = name.value,<br>        fullName = fullName,<br>        // ...<br>    )<br><br>fun Page&lt;DomainGitHubRepo&gt;.toGraphQL() =<br>    GitHubRepoPage(<br>        items = items.map { it.toGraphQL() },<br>        totalCount = totalCount,<br>    )<br><br>fun GitHubRepoInput.toDto() =<br>    GitHubRepoDto(<br>        id = id,<br>        owner = owner,<br>        name = name,<br>        // ...<br>    )</pre><p>GitHubRepo here is the DGS-generated GraphQL type. DomainGitHubRepo is the domain entity — aliased to avoid the name collision. The mapper sits entirely within presentation, converting between what GraphQL needs and what the domain provides.</p><p>GitHubRepoInput.toDto() produces a GitHubRepoDto — a plain data class in the application layer. The DTO&#39;s toDomain() method then performs value-object construction with Arrow&#39;s either { } DSL, so validation errors propagate as Left through the use case rather than escaping as exceptions.</p><h3>What didn’t change: the proof</h3><p>Here’s the complete list of files modified across domain and application:</p><pre>(none)</pre><p>Every use case interface and implementation: unchanged. Every domain entity and value object: unchanged. Every error type: unchanged. Every application test from <a href="https://dev.to/wakita181009/your-tests-are-slow-because-your-architecture-has-no-seams-499o">Part 2</a>: still passing, without modification. Every domain test from Part 2: still passing, without modification.</p><p>The GitHubRepoListUseCase doesn&#39;t know whether its results go to a REST response or a GraphQL query. GitHubRepoFindByIdUseCaseImpl doesn&#39;t know whether the repository behind it uses Spring Data or jOOQ. PageSize.of(101) returns Left(PageSizeError.AboveMaximum(101)) regardless of what database is running.</p><p>This is what the dependency rule buys you. Infrastructure and presentation know about the domain. The domain knows about neither.</p><h3>The pattern that made this possible</h3><p>Three design choices made both changes straightforward:</p><p><strong>1. The repository interface is the only contract.</strong> Infrastructure implements GitHubRepoRepository. Whether the implementation uses jOOQ, Spring Data, or a flat file doesn&#39;t matter — as long as it returns the right Either&lt;GitHubError, T&gt;.</p><p><strong>2. Presentation layers are pure adapters.</strong> Both the REST controller and the GraphQL DataFetcher do exactly the same thing: receive a request, call a use case, translate the Either result to the protocol&#39;s response format. Adding a new protocol means adding a new adapter — not changing anything that exists.</p><p><strong>3. </strong><strong>Either.fold is protocol-neutral.</strong> The use case returns Either&lt;AppError, DomainResult&gt;. What you do with Left and Right is entirely up to the presentation layer. REST maps them to HTTP status codes. GraphQL maps them to nullable fields and exceptions. The use case doesn&#39;t need to know which.</p><p>The architecture didn’t just survive the change. It made the change straightforward.</p><p>The full source is on GitHub: <a href="https://github.com/wakita181009/clean-architecture-kotlin/tree/v2">https://github.com/wakita181009/clean-architecture-kotlin/tree/v2</a></p><ul><li><a href="https://medium.com/@wakita181009/clean-architecture-in-kotlin-no-exceptions-no-magic-no-compromise-d17310fb9cd0"><em>Part 1: Clean Architecture in Kotlin with Spring Boot: Gradle Modules + Arrow-kt in Practice→</em></a></li><li><a href="https://medium.com/@wakita181009/your-tests-are-slow-because-your-architecture-has-no-seams-5cd3bcaf738b"><em>Part 2: </em>Why Your Kotlin Tests Are Slow: How Clean Architecture Enables Sub-Second Unit Testing<em>→</em></a></li><li><a href="https://medium.com/@wakita181009/clean-architecture-in-kotlin-no-exceptions-no-magic-no-compromise-d17310fb9cd0"><em>Part 3: Clean Architecture in Practice: Swapping Database Clients and Adding GraphQL in Kotlin→</em></a></li><li><a href="https://medium.com/@wakita181009/cqrs-with-clean-architecture-in-kotlin-separating-read-and-write-paths-for-better-performance-cf8758cfad72"><em>Part 4: CQRS with Clean Architecture in Kotlin: Separating Read and Write Paths for Better Performance→</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a145b0f87934" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>