~/dev.log

cd ..

Airspace Boundaries: Structuring an Aviation Backend with Spring Modulith, Kotlin, and DuckDB

2026-11-26•#Spring Modulith#Spring Boot#Kotlin#DuckDB#Architecture#Spring AI

How strict two-level Spring Modulith sectors, embedded DuckDB with Parquet seeding, and automated ArchUnit guardrails keep an AI-ready Spring Boot 4 backend clean and fast.

Series Context: Part 02 of Spring Traffic Control
Audience: Spring / Kotlin Developers · Reading Track: Full-Stack & Spring Tracks
Previous: Part 01: Cleared for Takeoff · Next: Part 03: Live Radio Channel
Companion Reference Guide: Mise

In Part 01, I laid out the flight plan for Spring Traffic Control, a hands-on exploration playground designed to test AG-UI and A2UI across a real, data-rich application. Now let's step inside the Control Tower (the Spring Boot 4 / Kotlin backend).

Before we wire up a single LLM prompt or SSE stream, there is a foundational question every backend engineer hits when adding AI to an existing application: how do you stop coding agents get stuck in a chaotic holding pattern?


Why Controlled Airspace Matters for an AI Backend

In a typical demo, an AI @Tool method injects a repository directly, runs an ad-hoc SQL query, or calls a third-party REST API inline. That works for one tool, but it falls apart the moment your assistant needs to cross-reference airports, runways, radio frequencies, airline schedules, aircraft types, and live aircraft telemetry.

Strict module boundaries give you four immediate benefits:

  1. Vendor DTOs stay out of prompts and UI cards: Isolating third-party API payloads prevents a renamed JSON field from breaking your REST controllers, database mappers, and AI tools at the same time.
  2. Agent tools respect domain rules: Routing every tool through public services guarantees that normalisation, caching, and business filters (such as checking whether a runway can handle a wide-body aircraft) are never bypassed.
  3. Clean, acyclic dependencies: Keeping agents dependent on public APIs, and never the reverse, stops circular dependencies from creeping in and keeps each domain testable in isolation.
  4. Spring Security readiness out of the box: Even though this playground omits authentication, forcing both REST endpoints and AI @Tool calls through public service interfaces means method-level rules like @PreAuthorize or @PostFilter automatically enforce the exact same user permissions for LLM tool calls as for regular HTTP requests.

Real air-traffic control solves complexity by dividing the sky into airspace sectors with explicit handoff protocols. I apply the exact same principle to this Spring Boot 4 monolith using Spring Modulith.


Dividing the Sectors: A Strict Two-Level Modulith Layout

The backend is organised into six focused domain modules plus a completely isolated external API contract layer:

Spring Traffic Control Spring Modulith architecture diagram showing six application modules (agents, flightstate, stations, schedule, airlines, aircrafttypes) with public root APIs and internal packages connected via internal adapters to isolated OpenAIP, Schiphol, and OpenSky @HttpExchange vendor contracts

Six Spring Modulith airspace sectors: cross-module calls stay strictly on public root APIs, while internal adapters isolate all external @HttpExchange vendor DTOs.

What makes this structure hold up under pressure is a strict two-level package convention for every module:

  • Module root (<module>), Pure Public API: Contains only domain models and service interfaces. Zero Spring annotations, zero repository types, and zero vendor DTOs.
  • Internal package (<module>.internal), Restricted Airspace: Holds every implementation detail, including @RestController endpoints, @Service implementations, DuckDB @Repository classes, vendor mappers, and outbound sync adapters.
// Pure public API at the module root: zero Spring or vendor imports (simplified)
package app.stations

data class Station(
    val id: String,
    val name: String,
    val icao: String?,
    val iata: String?,
    val latitude: Double?,
    val longitude: Double?,
    val maxRunwayMeters: Int?,
    val emergencyMedicalCapable: Boolean,
)

interface StationDirectory {
    fun findByCode(code: String): Station?
    fun findAll(country: String? = null, query: String? = null): List<Station>
    fun findNearestCapable(
        lat: Double,
        lon: Double,
        requiredCategory: AircraftCategory,
        emergencyOnly: Boolean = false,
        limit: Int = 5,
    ): List<NearestStation>
}

Meanwhile, the @Service implementation, DuckDB repository, and sync wiring stay encapsulated inside internal/:

// Encapsulated implementation inside internal/ (simplified)
package app.stations.internal

@Service
internal class StationDirectoryImpl(
    private val repository: StationRepository,
    private val syncSource: AirportSyncSource,
) : StationDirectory {

    override fun findByCode(code: String): Station? = repository.findByCode(code)

    override fun findNearestCapable(
        lat: Double,
        lon: Double,
        requiredCategory: AircraftCategory,
        emergencyOnly: Boolean,
        limit: Int,
    ): List<NearestStation> = repository.findNearestCapable(lat, lon, requiredCategory, emergencyOnly, limit)
}

The payoff for Part 03 (Spring AI tools) is immediate: the agents module can only talk to stations, schedule, and flightstate through their public service interfaces. It can never touch a DuckDB repository, a Redis cache, or an upstream OpenSky client directly. Even REST controllers inside a module are forbidden from bypassing their own module's service boundary.


The Local Flight Log: Embedded DuckDB in Spring Boot

For an operations playground, and for many local-first analytical services, spinning up a heavyweight Postgres cluster with PostGIS just to query a few hundred airports and a few thousand scheduled flights adds friction without much benefit.

Embedded DuckDB fits this workload remarkably well:

  • Zero container overhead: The entire database lives in a single local file (spring-traffic-control.duckdb), loaded straight over standard JDBC with HikariCP.
  • Analytical SQL out of the box: Aggregations, array columns (VARCHAR[]), INSERT OR REPLACE upserts, and custom SQL macros run in milliseconds.
  • Fluent Spring JdbcClient: Instead of pulling in JPA/Hibernate or legacy JdbcTemplate, each repository uses Spring's modern JdbcClient with clean, readable SQL.

Zero-Extension Spatial Queries with a SQL Macro

One of the signature prompts in Spring Traffic Control is "find the 3 closest diversion airports to this flight". Rather than installing a full GIS extension, we can define a pure-SQL Haversine great-circle macro right in the schema file:

-- Pure DuckDB macro for great-circle distance in kilometres (simplified)
CREATE OR REPLACE MACRO haversine_km(lat1, lon1, lat2, lon2) AS (
    6371.0 * 2.0 * ASIN(SQRT(
        POWER(SIN(RADIANS(lat2 - lat1) / 2.0), 2) +
        COS(RADIANS(lat1)) * COS(RADIANS(lat2)) *
        POWER(SIN(RADIANS(lon2 - lon1) / 2.0), 2)
    ))
);

With that macro in place, finding the nearest landing-capable airports for an airborne aircraft becomes a single, readable query combining distance, runway category rank, and emergency medical capability, with no spatial plugin required:

-- Nearest diversion airports ranked by distance (simplified)
SELECT *, haversine_km(?, ?, latitude, longitude) AS distance_km
FROM stations
WHERE latitude IS NOT NULL
  AND longitude IS NOT NULL
  AND max_aircraft_category_rank >= ?
  AND (? = FALSE OR emergency_medical_capable = TRUE)
ORDER BY distance_km ASC
LIMIT ?;

Instant Offline Seeding from Parquet (DEMO_MODE)

A demo repository dies if a new contributor has to sign up for three aviation APIs before seeing a single airport on the map. Because DuckDB reads Parquet natively, the startup seeder checks whether each table is empty and loads compact ZSTD-compressed .parquet files directly in one SQL statement:

// Startup Parquet seeder for zero-key DEMO_MODE (simplified)
fun seedEmptyTables(seedDir: Path, jdbc: JdbcClient) {
    for (table in listOf("stations", "station_runways", "airlines", "aircraft_types", "scheduled_flights")) {
        val parquetFile = seedDir.resolve("$table.parquet")
        if (countRows(jdbc, table) == 0L && Files.isRegularFile(parquetFile)) {
            jdbc.sql("INSERT INTO $table SELECT * FROM read_parquet('$parquetFile')").update()
        }
    }

    // Keep demo flight schedules relevant on any day someone clones the repo
    jdbc.sql("UPDATE scheduled_flights SET schedule_date = ?")
        .param(LocalDate.now())
        .update()
}

That gives anyone who runs mise dev an immediately populated database (763 airports, 408 airlines, 239 aircraft types, and 4,671 scheduled flights) in under a second, with zero external credentials.


Filtering External Radar Feeds Without Leaking Vendor DTOs

Aviation data is notoriously inconsistent across providers:

  • OpenAIP returns paginated airport telemetry, runways, and radio frequencies.
  • Schiphol serves OAuth2-authenticated flight schedules, airlines, and aircraft types.
  • OpenSky streams live ADS-B aircraft state vectors and historical flight tracks, with strict rate limits.

To keep vendor quirks out of our core domain:

  1. Declarative @HttpExchange interfaces live in a separate support package: All vendor HTTP clients and wire DTOs are isolated outside the application modules and are forbidden from importing anything in the domain.
  2. Each module owns its own translation boundary: Inside <module>.internal, a dedicated *SyncSource fetches pages from the declarative client and a *Mapper translates vendor payloads into clean domain models before anything hits DuckDB or a service return value.
  3. Graceful caching & demo fallback for live radar: Live OpenSky calls pass through a caching layer that checks Redis first (when running), falls back to a local in-memory TTL cache (ConcurrentHashMap) if Redis is unavailable, and serves recorded snapshot JSON and 112 flight tracks automatically when DEMO_MODE is enabled without OpenSky credentials.
// Tiered read-through cache with demo fallback (simplified)
fun fetchLiveStates(bounds: GeoBounds?): List<StateVector> {
    val key = cacheKey("states", bounds)

    readFromRedis(key)?.let { return it }
    readFromLocalCache(key)?.let { return it }

    val states = if (!hasLiveCredentials() && demoModeEnabled) {
        loadRecordedDemoSnapshot(bounds)
    } else {
        openSkyApi.getAllStates(bounds).let(OpenSkyMapper::toDomain)
    }

    writeToRedis(key, states, ttl)
    writeToLocalCache(key, states, ttl)
    return states
}

The result is a backend that works equally well offline on a plane, locally with Docker Compose Redis, or connected to live upstream APIs.


Automated Airspace Checks: Spring Modulith + ArchUnit

Architecture diagrams rot the week after you draw them unless the build enforces them. In Spring Traffic Control, a single JUnit 5 test suite runs on every mise test to guard both module boundaries and Spring Boot 4 conventions:

// Automated Modulith + ArchUnit guardrails (simplified)
class ArchitectureTests {

    @Test
    fun `verifies spring modulith module boundaries`() {
        ApplicationModules.of(Application::class.java).verify()
    }

    @Test
    fun `keeps module root public APIs pure`() {
        noClasses()
            .that().resideInAPackage("app.*")
            .should().dependOnClassesThat().resideInAnyPackage(
                "app..internal..",
                "support..",
                "org.springframework..",
            )
            .check(productionClasses)
    }

    @Test
    fun `forbids legacy Spring and Jackson 2 APIs`() {
        noClasses()
            .that().resideInAPackage("app..")
            .should().dependOnClassesThat().resideInAnyPackage(
                "com.fasterxml.jackson.databind..",
                "javax.servlet..",
            )
            .check(productionClasses)
    }
}

Beyond ApplicationModules.verify(), the architecture suite catches a whole class of subtle regressions automatically:

  • Two-level package discipline: Every class lives in either the module root or internal/, with no @NamedInterface escape hatches.
  • Controller isolation: @RestController beans must call their module's public service interface, never repositories or sync sources directly.
  • Spring Boot 4 hygiene: Enforces Jackson 3 (tools.jackson.* only), Jakarta EE 11 (jakarta.*), fluent JdbcClient over JdbcTemplate, declarative @HttpExchange over RestTemplate, constructor injection over @Autowired fields, and immutable @ConfigurationProperties instead of @Value.

Guardrails for AI-Generated Code & Spring Security

Remember benefit #4 above? ArchUnit lets you turn that Spring Security convention into a hard CI rule, especially when coding agents or LLMs help generate controllers, tools, and services. Generated code often takes the shortest path by injecting a @Repository straight into a @Controller or adding a new service method without authorisation checks.

With ArchUnit running in CI, you can enforce two non-negotiable rules:

  1. Controllers (and @Tool adapters) can only talk to @Service boundaries, never directly to repositories or data sources.
  2. Every public @Service method must declare a Spring Security rule (such as @PreAuthorize or @Secured) so a newly generated endpoint or agent tool can never silently bypass authorisation:
// Enforcing Spring Security annotations on @Service methods in production (simplified)
@Test
fun `requires every public service method to declare security rules`() {
    methods()
        .that().areDeclaredInClassesThat().areAnnotatedWith(Service::class.java)
        .and().arePublic()
        .should().beAnnotatedWith(PreAuthorize::class.java)
        .orShould().beAnnotatedWith(Secured::class.java)
        .check(productionClasses)
}

Combining strict package boundaries with ArchUnit rules like this guarantees that neither human shortcuts nor AI-generated code can quietly punch a hole through your authorisation layer.

Gotchas & Trade-Offs: Java 25 Native Access, DuckDB Upserts & Jackson 3

DuckDB Native Access on Java 25

DuckDB's JDBC driver loads a native library via JNI. On Java 25, pass --enable-native-access=ALL-UNNAMED to both bootRun and test tasks in Gradle so the JVM stays quiet and future-proof.

Logical Foreign Keys for Clean Upserts

In DuckDB, strict foreign key constraints can complicate INSERT OR REPLACE batch upserts on parent rows (like updating an airport record that has child runway rows). Using logical station_id keys and managing child refreshes inside a @Transactional repository method keeps batch syncs fast and predictable.

Small Hikari Pool for Embedded DuckDB

Embedded DuckDB is designed for high-throughput analytical reads and serialised writes inside one process. Keeping hikari.maximum-pool-size small (for example, 5) prevents unnecessary contention while still serving concurrent HTTP and AI tool requests smoothly.

Spring Boot 4 + Jackson 3 Classpath Hygiene

One stray library pulling in Jackson 2 (com.fasterxml.jackson.databind.*) can silently introduce dual-mapper bugs, especially when serialising Kotlin data classes and java.time.* types. Adding an ArchUnit rule that forbids Jackson 2 imports catches accidental regressions the moment a dependency is added.


Clearing the Runway for Part 03

With six isolated Spring Modulith sectors, an instant Parquet-seeded DuckDB store, and automated architecture checks in place, our Control Tower is ready for the real fun.

Next up in Part 03: Live Radio Channel, we wire Spring AI 2 and com.ag-ui.community:java-core directly into Spring WebMVC's SseEmitter, preserve reasoning streams across local Gemma 4 and Google Gemini models, and turn these clean Modulith services into live, side-channel-emitting @Tool methods.