<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Henry Brown's Notes on the JVM]]></title><description><![CDATA[Practical notes on software development for the JVM, from Cape Town. Mostly Kotlin and Spring Boot: coroutines and structured concurrency, virtual threads, reac]]></description><link>https://blog.hbrown.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6a6df6b110d8ecdf29cfd44b/8e730ee0-3168-45a3-a296-1b304136504a.png</url><title>Henry Brown&apos;s Notes on the JVM</title><link>https://blog.hbrown.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 09 Nov 2026 04:56:47 GMT</lastBuildDate><atom:link href="https://blog.hbrown.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Make Invalid Domain States Hard to Represent with Kotlin and Arrow]]></title><description><![CDATA[A practical Kotlin example showing how value classes, context parameters and Arrow can make domain invariants explicit and validation composable.]]></description><link>https://blog.hbrown.dev/make-invalid-domain-states-hard-to-represent-with-kotlin-and-arrow</link><guid isPermaLink="true">https://blog.hbrown.dev/make-invalid-domain-states-hard-to-represent-with-kotlin-and-arrow</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[arrow]]></category><category><![CDATA[Validation]]></category><category><![CDATA[DDD]]></category><dc:creator><![CDATA[Henry Brown]]></dc:creator><pubDate>Mon, 24 Aug 2026 14:49:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a6df6b110d8ecdf29cfd44b/55bba153-4396-40b2-95bc-c0e5c578f5aa.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Domain-Driven Design gives us a useful question to ask when modelling a domain:</p>
<blockquote>
<p>What does it mean for this object to be valid?</p>
</blockquote>
<p>It is tempting to answer that question with nullable properties and a validation method somewhere in the service layer. The problem is that every caller then has to remember to call that method. Between construction and validation, the object can represent something the domain does not allow.</p>
<p>In this example, we use a blog post as a domain to model. A blog post consists of an ID, title, content, and author. The model is deliberately small, but it demonstrates a pattern that scales well: make domain concepts explicit, keep construction behind a validation boundary, and represent failure in the type returned by the operation.</p>
<p>The result is a domain model that can be used without Spring, a database, or a framework-managed lifecycle. It is just Kotlin code with business rules that are visible at the boundary.</p>
<h2>Start with domain concepts, not primitives</h2>
<p>The first step is to stop treating every string as the same thing. A <code>Title</code> and a <code>BlogPostId</code> may all be represented by strings at runtime, but they are different concepts in the domain.</p>
<p>Kotlin value classes let us express that distinction without introducing the allocation and ceremony of a traditional wrapper class:</p>
<pre><code class="language-kotlin">@JvmInline
value class BlogPostId(val value: String) {
    override fun toString(): String = value
}

@JvmInline
value class Title(val value: String) {
    override fun toString(): String = value
}
</code></pre>
<p>This gives the compiler useful information. A function accepting a <code>BlogPostId</code> cannot be passed an arbitrary <code>String</code> without an explicit conversion. It also communicates intent: this is an identifier, and this is a title.</p>
<p>There is an important nuance here. A value class by itself does not validate its contents, so <code>Title("")</code> is still possible in this example. The aggregate factory below is the current invariant boundary. If a title has rules that must hold everywhere, the same pattern can be applied to <code>Title</code> itself by hiding its constructor and exposing a validated factory.</p>
<p>Value objects can also represent several related values. For example, a publication window could own the rule that its end date cannot precede its start date:</p>
<pre><code class="language-kotlin">@ConsistentCopyVisibility
data class PublicationPeriod private constructor(
    val from: LocalDate,
    val to: LocalDate
) {
    operator fun contains(date: LocalDate): Boolean =
        !date.isBefore(from) &amp;&amp; !date.isAfter(to)

    companion object {
        fun validateThenCreate(
            from: LocalDate,
            to: LocalDate
        ): Either&lt;NonEmptyList&lt;DomainError&gt;, PublicationPeriod&gt; = either {
            zipOrAccumulate(
                { ensure(!to.isBefore(from)) {
                    DomainError("'to' date must not be before 'from' date")
                } }
            ) {
                PublicationPeriod(from, to)
            }
        }
    }
}
</code></pre>
<p>The value object does more than hold data. It owns behaviour related to that data, such as answering whether a date falls within the publication period.</p>
<h2>Put construction behind a domain boundary</h2>
<p><code>BlogPost</code> is a data class because value-based equality and a useful <code>toString()</code> are convenient. Its primary constructor is private, however. Callers must go through <code>validateThenCreate</code>:</p>
<pre><code class="language-kotlin">@ConsistentCopyVisibility
data class BlogPost private constructor(
    val id: BlogPostId,
    val title: Title,
    val content: Content,
    val authorId: AuthorId
) {
    companion object {
        fun validateThenCreate(
            id: BlogPostId?,
            title: Title?,
            content: Content?,
            authorId: AuthorId?
        ): Either&lt;NonEmptyList&lt;DomainError&gt;, BlogPost&gt; = either {
            zipOrAccumulate(
                { ensureNotNull(id) {
                    DomainError("Blog Post ID must not be null")
                } },
                { validateTitle(title) },
                { validateContent(content) },
                { ensureNotNull(authorId) {
                    DomainError("Author ID must not be null")
                } }
            ) { validId, validTitle, validContent, validAuthorId -&gt;
                BlogPost(validId, validTitle, validContent, validAuthorId)
            }
        }
    }
}
</code></pre>
<p>The nullable inputs are intentional. They model data arriving from an untrusted boundary: an HTTP request, message, persistence layer, or user interface. Once the factory succeeds, the resulting <code>BlogPost</code> has non-null fields and has passed its rules.</p>
<p>This is a useful DDD boundary. The outside world may contain incomplete or invalid data; the inside of the domain should contain objects that satisfy the domain's invariants.</p>
<h2>Context parameters keep validation focused</h2>
<p>The validation helpers need a way to report a domain error. Arrow's <code>Raise&lt;DomainError&gt;</code> provides that capability. Rather than passing it explicitly through every function, the model uses a Kotlin context parameter:</p>
<pre><code class="language-kotlin">context(raise: Raise&lt;DomainError&gt;)
private fun validateTitle(title: Title?): Title {
    raise.ensureNotNull(title) { DomainError("Title must not be blank") }
    raise.ensure(title.value.isNotBlank()) {
        DomainError("Title must not be blank")
    }
    return title
}
</code></pre>
<p>The function reads naturally: given a <code>Raise&lt;DomainError&gt;</code> context, validate this title and return it. The error channel is available to the function, but it does not become part of the ordinary argument list.</p>
<p><code>ensure</code> and <code>ensureNotNull</code> short-circuit a single validation branch. At the aggregate level, <code>zipOrAccumulate</code> combines those branches so a caller receives all independent problems at once instead of fixing them one at a time.</p>
<p>That difference matters at an input boundary. Given four missing fields, the result is a <code>Left</code> containing four <code>DomainError</code> values. Given valid input, it is a <code>Right&lt;BlogPost&gt;</code>:</p>
<pre><code class="language-kotlin">when (val result = BlogPost.validateThenCreate(id, title, content, authorId)) {
    is Either.Left -&gt; result.value.all.forEach(::println)
    is Either.Right -&gt; publish(result.value)
}
</code></pre>
<p>There is no exception to catch for an expected business validation failure, and the return type makes it difficult for a caller to ignore the possibility of failure accidentally.</p>
<h2>Why <code>@ConsistentCopyVisibility</code> matters</h2>
<p>There is a subtle escape hatch when a validated type is a data class. Kotlin generates <code>copy()</code> for data classes. Historically, that generated method could remain public even when the primary constructor was private. A caller could then copy a valid post while replacing one property with an invalid value, bypassing the factory:</p>
<pre><code class="language-kotlin">val invalid = validPost.copy(title = Title(""))
</code></pre>
<p><code>@ConsistentCopyVisibility</code> opts this class into the newer behaviour: the generated <code>copy()</code> has the same visibility as the private constructor. Callers cannot use either the constructor or <code>copy()</code> as a back door around validation.</p>
<p>The trade-off is deliberate. To change a validated aggregate, expose a domain operation or construct a new instance through the validation boundary. Re-running the rules is more important than retaining a convenient unrestricted <code>copy()</code>.</p>
<p>Value classes also have practical boundaries: they can be boxed in some generic contexts and their JVM signatures are subject to name mangling, which can make Java interoperability less pleasant. That is usually a reasonable trade-off for a pure Kotlin domain module, but it is worth considering before exposing these types across a Java-facing API.</p>
<h2>Testing the domain model</h2>
<p>Because the rules live in ordinary Kotlin classes, the tests are small and fast. There is no application context to start and no database to configure. The test suite checks the successful path, accumulation of missing-field errors, whitespace-only values, and the visibility of generated construction methods.</p>
<p>This style of testing is valuable beyond speed. The tests describe the model's language directly:</p>
<pre><code class="language-kotlin">val result = BlogPost.validateThenCreate(
    id = BlogPostId("post-1"),
    title = Title("A useful post"),
    content = Content("Some content"),
    authorId = AuthorId("author-1")
)

val post = assertIs&lt;Either.Right&lt;BlogPost&gt;&gt;(result).value
</code></pre>
<p>The application layer can decide how to translate <code>DomainError</code> into an HTTP response, message rejection, or user-facing form error. The domain does not need to know which transport is involved.</p>
<h2>A small pattern with useful consequences</h2>
<p>The sample is intentionally modest, but the design has a clear shape:</p>
<ol>
<li>Use value classes and value objects to give domain concepts names and types.</li>
<li>Keep construction private when an object has invariants.</li>
<li>Validate untrusted input at the boundary.</li>
<li>Use <code>Either</code> to make expected failure explicit.</li>
<li>Accumulate independent validation errors for better feedback.</li>
<li>Keep domain rules framework-free and easy to test.</li>
</ol>
<p>This is not about using functional programming vocabulary for its own sake. It is about making invalid states harder to represent, making failure visible, and giving each rule a natural home. Kotlin supplies the language features; Arrow supplies a concise error-handling model; DDD supplies the discipline for deciding what the rules mean.</p>
<hr />
<p>As usual, full source code is available on GitHub: <a href="https://github.com/hgbrown/demo-arrow-validation">demo-arrow-validation</a></p>
]]></content:encoded></item><item><title><![CDATA[Stop External Services from Breaking Your Build with JUnit Tags]]></title><description><![CDATA[Use JUnit 5 tags and Gradle to separate live external-service tests from your regular Kotlin build, keeping everyday tests fast, deterministic, and…]]></description><link>https://blog.hbrown.dev/keep-external-services-out-of-your-regular-build-with-junit-tags</link><guid isPermaLink="true">https://blog.hbrown.dev/keep-external-services-out-of-your-regular-build-with-junit-tags</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Testing]]></category><category><![CDATA[junit]]></category><dc:creator><![CDATA[Henry Brown]]></dc:creator><pubDate>Thu, 20 Aug 2026 18:57:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a6df6b110d8ecdf29cfd44b/3a9e68b5-e424-43bc-a2c8-8bb38f88eed9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Fast, dependable tests get run.</p>
<p>Slow or fragile tests gradually teach a team to avoid the test suite. A developer makes a small change, remembers that the build sometimes waits for an external API, and decides not to run it. 
A red build is retried because “that service is probably down again”. Eventually a genuine regression is dismissed as another unreliable test.</p>
<p>The problem is not that integration tests are bad. A test that proves your application can talk to a real service can reveal DNS, TLS, authentication, request-format and response-format problems that a unit test cannot.</p>
<p>The problem is allowing a resource outside your control to decide whether every local build succeeds.</p>
<p>JUnit 5 tags provide a small and useful boundary. We can mark tests that contact an external system, exclude them from Gradle's normal <code>test</code> task, and give them a separate task that must be selected deliberately.</p>
<p>In this post we will build a small Kotlin application that sends a JSON request to <a href="https://httpbingo.org/">httpbingo</a>, an HTTP request-and-response service compatible with the familiar httpbin endpoints. The application will have:</p>
<ol>
<li>A fast test backed by Ktor's in-memory <code>MockEngine</code>.</li>
<li>A live integration test tagged with <code>@Tag("integration")</code>.</li>
<li>A normal Gradle build that never needs the network.</li>
<li>A separate Gradle task for running the live test.</li>
</ol>
<p>The complete example uses the standard Gradle source layout and can be copied into an empty directory.</p>
<h2>What should run in the regular build?</h2>
<p>The regular test suite should be deterministic. Given the same source and the same inputs, it should produce the same result.</p>
<p>A test that calls a public HTTP service also depends on conditions that are not part of the source tree:</p>
<ul>
<li>The machine must have a working network connection.</li>
<li>DNS and TLS negotiation must succeed.</li>
<li>The remote service must be available and behave as expected.</li>
<li>A proxy, firewall or rate limit must not block the request.</li>
<li>If the API is authenticated, its credentials and test data must still be valid.</li>
</ul>
<p>None of those conditions tells us whether a local calculation, validation rule or request mapper is correct.</p>
<p>When an ordinary build fails because a third-party service is unavailable, the failure is noisy but not useful. Worse, repeated false alarms make real failures easier to ignore. Keeping the regular suite fast and trustworthy makes
developers more likely to run it and more likely to investigate a failure immediately.</p>
<p>This does not mean hiding the integration tests or ignoring their results. It means running them at the right time: explicitly during development, in a suitable scheduled environment, or in a dedicated CI job with controlled credentials and
network access.</p>
<h2>The example project</h2>
<p>Create the following directory structure:</p>
<pre><code class="language-text">tagged-http-example/
├── build.gradle.kts
├── settings.gradle.kts
├── gradle/
│   └── libs.versions.toml
└── src/
    ├── main/
    │   └── kotlin/
    │       └── dev/hbrown/tags/
    │           ├── HttpEchoClient.kt
    │           └── Main.kt
    └── test/
        └── kotlin/
            └── dev/hbrown/tags/
                ├── HttpEchoClientTest.kt
                └── HttpEchoIntegrationTest.kt
</code></pre>
<p>The live test stays under <code>src/test/kotlin</code> with the other tests. A tag describes how it should be selected; we do not need a custom source tree or a second copy of the test dependencies.</p>
<h2>Step 1: Configure the Gradle project</h2>
<p>Start with <code>settings.gradle.kts</code>:</p>
<pre><code class="language-kotlin">rootProject.name = "tagged-http-example"
</code></pre>
<p>The project uses a Gradle version catalog. Add the following to <code>gradle/libs.versions.toml</code>:</p>
<pre><code class="language-toml">[versions]
kotlin = "2.4.10"
ktor = "3.5.2"
coroutines = "1.11.0"
jackson = "2.15.4"
junit = "5.10.1"
junit-platform = "1.10.1"

[libraries]
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }

ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "ktor" }
ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-serialization-jackson = { module = "io.ktor:ktor-serialization-jackson", version.ref = "ktor" }
ktor-client-mock = { module = "io.ktor:ktor-client-mock", version.ref = "ktor" }

jackson-module-kotlin = { module = "com.fasterxml.jackson.module:jackson-module-kotlin", version.ref = "jackson" }

junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" }
junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher", version.ref = "junit-platform" }

[bundles]
ktor-client = [
    "ktor-client-core",
    "ktor-client-cio",
    "ktor-client-content-negotiation",
    "ktor-serialization-jackson",
]

[plugins]
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
</code></pre>
<p>There are two Ktor engines in the catalog for different reasons.</p>
<p>The CIO engine makes a real HTTP call when the application or integration test runs. The mock engine executes a Ktor request entirely in memory, allowing the fast test to verify the method, URL, headers, JSON body and response mapping
without opening a socket.</p>
<p>Now add <code>build.gradle.kts</code>:</p>
<pre><code class="language-kotlin">import org.jetbrains.kotlin.gradle.dsl.JvmTarget

plugins {
    alias(libs.plugins.kotlin.jvm)
    application
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(libs.kotlinx.coroutines.core)
    implementation(libs.bundles.ktor.client)
    implementation(libs.jackson.module.kotlin)

    testImplementation(libs.junit.jupiter)
    testImplementation(libs.ktor.client.mock)
    testRuntimeOnly(libs.junit.platform.launcher)
}

kotlin {
    jvmToolchain(21)
    compilerOptions {
        jvmTarget.set(JvmTarget.JVM_21)
    }
}

application {
    mainClass.set("dev.hbrown.tags.MainKt")
}

val integrationTestTag = "integration"

tasks.test {
    useJUnitPlatform {
        excludeTags(integrationTestTag)
    }
}

tasks.register&lt;Test&gt;("integrationTest") {
    group = "verification"
    description = "Runs tests that communicate with external services"

    testClassesDirs = sourceSets["test"].output.classesDirs
    classpath = sourceSets["test"].runtimeClasspath

    useJUnitPlatform {
        includeTags(integrationTestTag)
    }

    shouldRunAfter(tasks.test)
}
</code></pre>
<p>The last two task configurations are the important part.</p>
<p>The standard <code>test</code> task uses the JUnit Platform but excludes every test carrying the <code>integration</code> tag. Gradle's <code>build</code> and <code>check</code> lifecycle tasks depend on <code>test</code>, so the live HTTP call is also kept out of the regular build.</p>
<p>The new <code>integrationTest</code> task uses the same compiled test classes and runtime classpath. Its JUnit Platform configuration does the opposite: it includes only tests carrying the tag.</p>
<p>Notice that <code>integrationTest</code> is not added as a dependency of <code>check</code> or <code>build</code>. That omission is deliberate. If it were attached to the normal lifecycle, an <code>httpbingo</code> outage could break the build again and the separation would provide
little value.</p>
<h2>Step 2: Write the HTTP adapter</h2>
<p>The HTTP code follows a useful boundary pattern: application-owned request and response models are exposed by a small client, while the Ktor details remain inside the adapter.</p>
<p>Create <code>src/main/kotlin/dev/hbrown/tags/HttpEchoClient.kt</code>:</p>
<pre><code class="language-kotlin">package dev.hbrown.tags

import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.call.body
import io.ktor.client.request.accept
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.serialization.jackson.jackson

data class EchoRequest(
    val message: String,
    val source: String,
)

data class EchoResponse(
    val json: EchoRequest,
    val url: String,
)

class HttpEchoClient(
    private val httpClient: HttpClient,
    private val baseUrl: String = "https://httpbingo.org",
) {
    suspend fun echo(request: EchoRequest): EchoResponse {
        val response = httpClient.post("$baseUrl/anything/junit-tags") {
            accept(ContentType.Application.Json)
            contentType(ContentType.Application.Json)
            setBody(request)
        }

        check(response.status.value in 200..299) {
            "HTTP echo request failed, status=[${response.status.value}]"
        }

        return response.body()
    }
}

fun createHttpClient(
    engine: HttpClientEngine = CIO.create(),
): HttpClient = HttpClient(engine) {
    install(ContentNegotiation) {
        jackson {
            registerKotlinModule()
            disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
        }
    }
}
</code></pre>
<p>The adapter sends a <code>POST</code> request to httpbingo's <code>anything</code> endpoint. The service returns details of the request it received, including the JSON body and URL, which makes it convenient for a small integration example.</p>
<p>The <code>HttpClientEngine</code> is injected into the factory. Production code gets CIO by default, while a test can supply <code>MockEngine</code>. This is the same seam we would use around a paid messaging API, payment provider or another remote boundary.</p>
<h2>Step 3: Make the application runnable</h2>
<p>Create <code>src/main/kotlin/dev/hbrown/tags/Main.kt</code>:</p>
<pre><code class="language-kotlin">package dev.hbrown.tags

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    createHttpClient().use { httpClient -&gt;
        val response = HttpEchoClient(httpClient).echo(
            EchoRequest(
                message = "Hello from Kotlin",
                source = "tagged-http-example",
            ),
        )

        println("HTTP service echoed: ${response.json.message}")
        println("request URL: ${response.url}")
    }
}
</code></pre>
<p>Run it with:</p>
<pre><code class="language-shell">./gradlew run
</code></pre>
<p>This command deliberately uses the real network because that is the application's job. The distinction we are making concerns what must happen during every test and build.</p>
<h2>Step 4: Test the HTTP behaviour without the network</h2>
<p>Create <code>src/test/kotlin/dev/hbrown/tags/HttpEchoClientTest.kt</code>:</p>
<pre><code class="language-kotlin">package dev.hbrown.tags

import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.engine.mock.toByteArray
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test

class HttpEchoClientTest {
    @Test
    fun `echo sends the expected request and maps the response`() = runBlocking {
        val expectedRequest = EchoRequest(
            message = "Hello from a fast test",
            source = "mock-engine",
        )

        val engine = MockEngine { request -&gt;
            assertEquals(HttpMethod.Post, request.method)
            assertEquals("/anything/junit-tags", request.url.encodedPath)
            assertEquals(ContentType.Application.Json, request.body.contentType)

            val requestBody = request.body.toByteArray().decodeToString()
            assertTrue(requestBody.contains("Hello from a fast test"))
            assertTrue(requestBody.contains("mock-engine"))

            respond(
                content = """
                    {
                      "json": {
                        "message": "Hello from a fast test",
                        "source": "mock-engine"
                      },
                      "url": "https://httpbingo.org/anything/junit-tags"
                    }
                """.trimIndent(),
                status = HttpStatusCode.OK,
                headers = headersOf(
                    HttpHeaders.ContentType,
                    ContentType.Application.Json.toString(),
                ),
            )
        }

        createHttpClient(engine).use { httpClient -&gt;
            val response = HttpEchoClient(httpClient).echo(expectedRequest)

            assertEquals(expectedRequest, response.json)
            assertEquals(
                "https://httpbingo.org/anything/junit-tags",
                response.url,
            )
        }
    }
}
</code></pre>
<p>This is not a pretend test of the business logic. It exercises Ktor's request pipeline, JSON serialization, response deserialization and the adapter's mapping. The only substituted component is the network engine.</p>
<p>Because the test has no tag, it is included in the normal <code>test</code> task. It is fast, does not need credentials, and cannot fail because httpbingo is unavailable.</p>
<h2>Step 5: Tag the live integration test</h2>
<p>Create <code>src/test/kotlin/dev/hbrown/tags/HttpEchoIntegrationTest.kt</code>:</p>
<pre><code class="language-kotlin">package dev.hbrown.tags

import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test

@Tag("integration")
class HttpEchoIntegrationTest {
    @Test
    fun `httpbingo accepts and echoes a real JSON request`() = runBlocking {
        val request = EchoRequest(
            message = "Hello from a live integration test",
            source = "junit-tag",
        )

        createHttpClient().use { httpClient -&gt;
            val response = HttpEchoClient(httpClient).echo(request)

            assertEquals(request, response.json)
            assertTrue(response.url.endsWith("/anything/junit-tags"))
        }
    }
}
</code></pre>
<p><code>@Tag</code> comes from JUnit Jupiter. Placing it on the class applies the tag to every test in that class. If a class contains a mixture of test types, the annotation can instead be placed on individual test methods.</p>
<p>A class-level tag is usually clearer for live integration tests. It is difficult to add a new test method and accidentally forget that the whole class crosses an external boundary.</p>
<p>The tag name is a label, not a Gradle task name. Gradle connects the two when <code>includeTags("integration")</code> and <code>excludeTags("integration")</code> are passed to the JUnit Platform.</p>
<h2>Step 6: Run the two suites</h2>
<p>Run the fast, deterministic tests with:</p>
<pre><code class="language-shell">./gradlew test
</code></pre>
<p>Run the regular build with:</p>
<pre><code class="language-shell">./gradlew build
</code></pre>
<p>Neither command executes <code>HttpEchoIntegrationTest</code>. They will still succeed if the network is disconnected or httpbingo is unavailable.</p>
<p>Run the live test explicitly with:</p>
<pre><code class="language-shell">./gradlew integrationTest
</code></pre>
<p>Run both suites, while keeping their results and responsibilities separate, with:</p>
<pre><code class="language-shell">./gradlew test integrationTest
</code></pre>
<p>If the project does not yet have a Gradle wrapper, generate one once with an installed Gradle distribution:</p>
<pre><code class="language-shell">gradle wrapper
</code></pre>
<p>After that, commit the generated wrapper files and use <code>./gradlew</code> so developers and CI run the same Gradle version.</p>
<h2>What a failure now means</h2>
<p>This configuration gives the two tasks different contracts.</p>
<p>When <code>test</code> fails, the cause should be in the source, test data or local test environment. That is a high-signal failure and should be investigated immediately.</p>
<p>When <code>integrationTest</code> fails, the application may have broken its external contract, but the first investigation should also consider availability, authentication, rate limits, test-account state and network policy. The failure still
matters; it simply belongs to a different diagnostic context.</p>
<p>This distinction also leads to a better CI design. A pull-request job can run the fast suite on every change. A separate integration job can run in an environment that owns the necessary secrets and network access. Depending on the
importance and stability of the external service, that job may run on demand, after deployment, or on a schedule.</p>
<p>Do not “solve” fragility by catching exceptions and allowing a live test to pass when the service is unreachable. A test that silently ignores the condition it exists to verify is worse than no test because it creates false confidence.
Separation lets the live test remain strict without making every build dependent on it.</p>
<h2>More than one kind of integration test</h2>
<p>JUnit tags can describe several categories, and Gradle can select more than one tag. For example, a larger project might distinguish database, messaging and end-to-end tests:</p>
<pre><code class="language-kotlin">useJUnitPlatform {
    includeTags("database", "messaging")
}
</code></pre>
<p>It can also combine tag expressions:</p>
<pre><code class="language-kotlin">useJUnitPlatform {
    includeTags("integration &amp; !expensive")
}
</code></pre>
<p>Start with the smallest taxonomy that solves the problem. One <code>integration</code> tag and one explicit task are often enough. A complicated collection of tags can become another system that developers need to remember and maintain.</p>
<h2>Conclusion</h2>
<p>Integration tests are valuable because they cross a boundary that unit tests deliberately avoid. That same boundary makes them slower and more vulnerable to conditions outside the build.</p>
<p>JUnit's <code>@Tag</code> annotation lets us preserve both kinds of feedback:</p>
<ul>
<li>Fast, deterministic tests run whenever we test or build the project.</li>
<li>Strict live tests remain available through an explicit Gradle task.</li>
<li>A remote outage does not train the team to accept a red regular build.</li>
<li>A real regular-test failure keeps its urgency because the suite is trusted.</li>
</ul>
<p>The implementation is small: annotate the external test, exclude its tag from <code>test</code>, and include it in a dedicated <code>Test</code> task. The more important result is behavioural. When the reliable path is also the quick path, people run it more
often—and they pay attention when it fails.</p>
<hr />
<p>The full source code for this example is available on Github: <a href="https://github.com/hgbrown/tagged-http-example">tagged-http-example</a>.</p>
]]></content:encoded></item><item><title><![CDATA[PgBouncer with Spring Boot 4: Setup, Gotchas, and the Proof]]></title><description><![CDATA[Configure PgBouncer transaction pooling for Spring Boot 4 and PostgreSQL, avoid common JDBC pitfalls, and benchmark direct versus pooled connections.]]></description><link>https://blog.hbrown.dev/pgbouncer-spring-boot-4-setup-benchmark</link><guid isPermaLink="true">https://blog.hbrown.dev/pgbouncer-spring-boot-4-setup-benchmark</guid><category><![CDATA[PgBouncer]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Henry Brown]]></dc:creator><pubDate>Mon, 17 Aug 2026 14:20:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a6df6b110d8ecdf29cfd44b/77a6f195-fd69-411b-a00e-81ba9ad55d74.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every Postgres connection is a process on the server. That's a deliberate design choice — it makes Postgres simple and robust — but it also means connections are expensive to open and there's a hard ceiling on how many can exist at once (<code>max_connections</code>, 100 by default). An application that opens-and-closes connections per request, or that just runs a lot of instances, each with their own pool, can hit that ceiling long before the database itself is under any real load.</p>
<p>PgBouncer sits between your application and Postgres and pools connections <em>at the proxy</em>: your app can open as many client connections to PgBouncer as it wants, and PgBouncer multiplexes them onto a much smaller number of real Postgres connections. This post walks through adding it to a Spring Boot 4 / Kotlin app, step by step, using the <a href="https://github.com/hgbrown/spring-demo-pgbouncer"><code>spring-demo-pgbouncer</code></a> project as the running example.</p>
<h2>1. Add PgBouncer to <code>compose.yml</code></h2>
<p>Postgres and PgBouncer as two services, PgBouncer pointed at Postgres by its Compose service name:</p>
<pre><code class="language-yaml">services:
  postgres:
    image: postgres:17-alpine
    environment:
      POSTGRES_DB: demo
      POSTGRES_USER: demo
      POSTGRES_PASSWORD: demo
    ports:
      - "5432:5432"
    healthcheck:
      test: [ "CMD-SHELL", "pg_isready -U demo -d demo" ]
      interval: 5s
      timeout: 5s
      retries: 10

  pgbouncer:
    image: edoburu/pgbouncer:latest
    environment:
      DATABASE_URL: postgres://demo:demo@postgres:5432/demo
      POOL_MODE: transaction
      MAX_CLIENT_CONN: "1000"
      DEFAULT_POOL_SIZE: "20"
      AUTH_TYPE: scram-sha-256
    ports:
      - "6432:6432"
    depends_on:
      postgres:
        condition: service_healthy
</code></pre>
<p>A couple of details are worth noting:</p>
<ul>
<li><p><code>edoburu/pgbouncer</code> <strong>listens on port 5432 inside the container by default</strong> — it's built to be a drop-in replacement that your app talks to as if it <em>were</em> Postgres. If you want it on the conventional PgBouncer port (6432, so it's obvious at a glance which one you're hitting), you need to set <code>LISTEN_PORT: "6432"</code> explicitly. Skip this, and the container starts, prints its config, and then just sits there listening on the wrong port while your <code>ports:</code> mapping (or a Testcontainers wait strategy) times out waiting for 6432 to open.</p>
</li>
<li><p><code>AUTH_TYPE: scram-sha-256</code> matches modern Postgres's default auth method. The image parses <code>DATABASE_URL</code>, writes the credentials into <code>/etc/pgbouncer/userlist.txt</code> on startup, and generates <code>pgbouncer.ini</code> from the environment variables — you don't hand-write either file for a setup this simple.</p>
</li>
</ul>
<h2>2. Pick a pool mode</h2>
<p><code>POOL_MODE: transaction</code> is the one that actually delivers the connection-multiplexing benefit. PgBouncer supports three:</p>
<ul>
<li><p><strong>session</strong> — a client connection gets a server connection for its entire session. Safest (works with everything Postgres supports, including session-level <code>SET</code>/prepared statements), but doesn't help with connection ceilings — it's a 1:1 mapping, just proxied.</p>
</li>
<li><p><strong>transaction</strong> — a server connection is only checked out for the duration of a transaction, then returned to the pool the instant it commits/rolls back. This is the mode that lets <code>MAX_CLIENT_CONN=1000</code> sit on top of <code>DEFAULT_POOL_SIZE=20</code> real Postgres connections.</p>
</li>
<li><p><strong>statement</strong> — checked out per statement, even more aggressive, but breaks multi-statement transactions. Rarely what you want for an application backend.</p>
</li>
</ul>
<p>Transaction pooling has one consequence worth knowing before you flip it on: because a given client connection might get a <em>different</em> backend server connection for its next transaction, session-level state doesn't survive — including the JDBC driver's server-side prepared statement cache. The fix on the Spring/Hikari side is one property:</p>
<pre><code class="language-properties"># application-pgbouncer.properties
spring.datasource.url=jdbc:postgresql://localhost:6432/demo
spring.datasource.username=demo
spring.datasource.password=demo
spring.datasource.hikari.data-source-properties.prepareThreshold=0
</code></pre>
<p><code>prepareThreshold=0</code> tells the PostgreSQL JDBC driver never to switch to server-side prepared statements, which avoids <code>ERROR: prepared statement "..." already exists</code> / "does not exist" errors that show up under transaction pooling once the driver starts trying to reuse a statement name against a connection that PgBouncer has quietly swapped out from under it.</p>
<h2>3. Point the application at PgBouncer instead of Postgres</h2>
<p>The demo app keeps this as a separate Spring profile rather than baking it into the default config, specifically so you can flip between the two for comparison:</p>
<pre><code class="language-properties"># application.properties (default — direct to Postgres)
spring.datasource.url=jdbc:postgresql://localhost:5432/demo
</code></pre>
<pre><code class="language-properties"># application-pgbouncer.properties (routed through PgBouncer)
spring.datasource.url=jdbc:postgresql://localhost:6432/demo
</code></pre>
<pre><code class="language-bash">./gradlew bootRun --args='--spring.profiles.active=pgbouncer'
</code></pre>
<p>Everything else about the application — the entities, the repositories, Hikari itself — is unchanged. That's the point of PgBouncer being a proxy: it speaks the Postgres wire protocol, so from the JDBC driver's point of view it <em>is</em> Postgres.</p>
<h2>4. Benchmark it</h2>
<p>The proof, as they say, is in the pudding. The demo project's <code>PgBouncerConcurrencyBenchmarkTest</code> starts a real Postgres and a real PgBouncer in Testcontainers (on a shared Docker network, PgBouncer addressing Postgres by its network alias), opens a Hikari pool against each, and runs the same concurrent workload — 80 workers × 25 short <code>SELECT</code> queries each — against both:</p>
<pre><code class="language-kotlin">private fun runLoad(dataSource: HikariDataSource): LoadStats = runBlocking(Dispatchers.IO) {
    val totalNanos = measureNanoTime {
        val perWorkerLatencies = (1..CONCURRENCY).map {
            async {
                (1..QUERIES_PER_WORKER).map {
                    measureNanoTime {
                        dataSource.connection.use { connection -&gt;
                            connection.createStatement().use { statement -&gt;
                                statement.executeQuery("SELECT id FROM benchmark_probe WHERE id = 1").use { it.next() }
                            }
                        }
                    }
                }
            }
        }
        // ...collect percentiles from perWorkerLatencies
    }
}
</code></pre>
<p>A captured run, logged by the test itself:</p>
<pre><code class="language-plaintext">PgBouncer concurrency benchmark completed, concurrency=[80] queriesPerWorker=[25]
directTotalMs=[127] directP50Ms=[0] directP95Ms=[2] directMaxMs=[114]
pgbouncerTotalMs=[110] pgbouncerP50Ms=[0] pgbouncerP95Ms=[3] pgbouncerMaxMs=[103]
</code></pre>
<p><strong>At 80 concurrent clients, they're a wash</strong> — both comfortably under Postgres's default <code>max_connections=100</code>, so direct connections never queue and PgBouncer's extra network hop costs essentially nothing (a millisecond or two at p95). That's actually the right takeaway for <em>this</em> concurrency level: PgBouncer isn't a magic performance multiplier, it's insurance.</p>
<p>An insurance that pays off at the point where direct connections start queuing or getting rejected. Push the same benchmark's <code>CONCURRENCY</code> past Postgres's <code>max_connections</code> (100 by default, minus a handful reserved for superusers) and the direct-to-Postgres run starts throwing <code>FATAL: sorry, too many clients already</code> while PgBouncer — sitting on its fixed pool of 20 real backend connections — just queues the excess client connections for a few milliseconds and keeps going. That's the actual value proposition: PgBouncer doesn't make each query faster, it lets your application scale its <em>client-side</em> concurrency (more app instances, more threads, bursty traffic) far past what the database's connection limit would otherwise allow, without you having to provision Postgres for a peak <code>max_connections</code> it only needs for a few seconds a day.</p>
<h2>Summary</h2>
<ul>
<li><p>Transaction-mode PgBouncer sits between your app and Postgres, pooling a small number of real backend connections behind a much larger number of client connections.</p>
</li>
<li><p>It costs a small, consistent per-query latency overhead (low single-digit milliseconds at p95 in this benchmark) — not free, but cheap.</p>
</li>
<li><p>Its actual job is absorbing client-side concurrency that would otherwise hit Postgres's <code>max_connections</code> ceiling directly — the benefit doesn't show up at moderate concurrency, it shows up when you'd otherwise be paged.</p>
</li>
<li><p>Watch for prepared-statement caching under transaction pooling (<code>prepareThreshold=0</code>on the JDBC datasource) and the <code>edoburu/pgbouncer</code> image's default listen port (<code>LISTEN_PORT</code>) — both are easy to trip over on a first setup.</p>
</li>
</ul>
<p>See the full project at <a href="https://github.com/hgbrown/spring-demo-pgbouncer">spring-demo-pgbouncer</a> for the complete Spring Boot 4 application, this benchmark runs inside, including the<code>PgBouncerConcurrencyBenchmarkTest</code> source in full.</p>
]]></content:encoded></item><item><title><![CDATA[I Built a Spring Boot 4 App to Put PgBouncer to the Test]]></title><description><![CDATA[Build a hexagonal Spring Boot 4 and Kotlin application for benchmarking PgBouncer against direct PostgreSQL connections under concurrent load.]]></description><link>https://blog.hbrown.dev/spring-boot-4-kotlin-pgbouncer-benchmark-app</link><guid isPermaLink="true">https://blog.hbrown.dev/spring-boot-4-kotlin-pgbouncer-benchmark-app</guid><category><![CDATA[PgBouncer]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[performance]]></category><category><![CDATA[architecture]]></category><dc:creator><![CDATA[Henry Brown]]></dc:creator><pubDate>Mon, 17 Aug 2026 14:16:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a6df6b110d8ecdf29cfd44b/397d9682-23d0-4840-8f16-049a3ba1a33c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This post describes a small books-and-authors catalogue, but its real job is to be a testbed: it demonstrates what PgBouncer, a lightweight connection pool manager, actually buys you in front of PostgreSQL, and it does so with a Spring Boot 4 / Kotlin codebase built the way I'd build a production service — hexagonal architecture, modular starters, structured logging, and a full test pyramid including a concurrency benchmark.</p>
<p>This post walks through the project step by step: the domain, the architecture, the database, the PgBouncer setup, and finally the benchmark numbers. If you only care about PgBouncer itself, the companion post: <a href="https://blog.hbrown.dev/pgbouncer-spring-boot-4-setup-benchmark">PgBouncer with Spring Boot 4: Setup, Gotchas, and the Proof</a> is a narrower, standalone walkthrough of just that piece.</p>
<h2>The domain</h2>
<p>Books, authors, and tags, with the usual relationships:</p>
<ul>
<li><p>A <strong>Book</strong> has a title, ISBN, and subject, belongs to exactly one <strong>Author</strong>, and can carry any number of <strong>Tags</strong>.</p>
</li>
<li><p>An <strong>Author</strong> has a name and can write many books.</p>
</li>
<li><p>A <strong>Tag</strong> has a value and can be attached to many books.</p>
</li>
<li><p>A single search endpoint looks across all three: title for books, name for authors, value for tags — case-insensitive, partial match.</p>
</li>
</ul>
<h2>Architecture: hexagonal, feature-packaged</h2>
<p>The core rule this codebase follows: <strong>the domain and business logic never import Spring, JPA, or Jakarta Validation.</strong> Everything framework-specific lives behind a port interface, implemented by an adapter. Packages are named by feature (<code>book</code>, <code>author</code>,<code>tag</code>, <code>search</code>), not by technical layer — there's no <code>controllers</code> or <code>services</code> package sitting at the top level.</p>
<p>Each feature module looks like this (using <code>book</code> as the example):</p>
<pre><code class="language-plaintext">book/
├── domain/Book.kt                          # plain Kotlin data class, no annotations
├── port/
│   ├── input/BookUseCase.kt                # what the outside world can ask the core to do
│   └── output/BookRepository.kt            # what the core needs from persistence
├── service/BookService.kt                  # implements BookUseCase, depends on BookRepository
└── adapter/
    ├── web/                                # RestController + request/response DTOs + Jakarta Validation
    └── persistence/                        # JPA entity + Spring Data repository + mapper
</code></pre>
<p><code>port/input</code> and <code>port/output</code> rather than the more common <code>port/in</code>/<code>port/out</code> — <code>in</code> is a Kotlin keyword, and backtick-escaping a package name everywhere it's used isn't worth the readability cost.</p>
<p>The domain model itself is unapologetically plain:</p>
<pre><code class="language-kotlin">// book/domain/Book.kt
data class Book(
    val id: Long? = null,
    val title: String,
    val isbn: String,
    val subject: String,
    val author: Author,
    val tags: Set&lt;Tag&gt; = emptySet(),
)
</code></pre>
<p>And the input port is just an interface — the service class is the only thing that knows it's backed by Spring:</p>
<pre><code class="language-kotlin">// book/port/input/BookUseCase.kt
interface BookUseCase {
    fun createBook(title: String, isbn: String, subject: String, authorId: Long, tagIds: Set&lt;Long&gt;): Book
    fun getBook(id: Long): Book
    fun getAllBooks(): List&lt;Book&gt;
    fun updateBook(id: Long, title: String, isbn: String, subject: String, authorId: Long, tagIds: Set&lt;Long&gt;): Book
    fun deleteBook(id: Long)
    fun searchBooks(query: String): List&lt;Book&gt;
}
</code></pre>
<p><strong>Where does validation live?</strong> Jakarta Validation (<code>@NotBlank</code>, <code>@NotNull</code>) is a framework dependency, so it never touches the <code>domain</code>/<code>port</code>/<code>service</code> packages. It's applied to the web adapter's request DTOs instead:</p>
<pre><code class="language-kotlin">// book/adapter/web/BookRequest.kt
data class BookRequest(
    @field:NotBlank val title: String,
    @field:NotBlank val isbn: String,
    @field:NotBlank val subject: String,
    @field:NotNull val authorId: Long?,
    val tagIds: Set&lt;Long&gt; = emptySet(),
)
</code></pre>
<p><code>@Valid @RequestBody</code> on the controller method triggers validation before the request ever reaches <code>BookUseCase</code>. A <code>GlobalExceptionHandler</code> (<code>@RestControllerAdvice</code>) turns <code>MethodArgumentNotValidException</code> into a 400 with the field errors, and a small <code>EntityNotFoundException</code> in <code>common/exception</code> becomes a 404 the same way.</p>
<h3>Entity graphs for the Book ↔ Author/Tag relationships</h3>
<p><code>Book</code> has a lazy <code>@ManyToOne</code> to <code>Author</code> and a lazy <code>@ManyToMany</code> to <code>Tag</code> (through a <code>book_tags</code> join table). Lazy is the right default, but list/detail endpoints need both loaded in one query — that's what <code>@NamedEntityGraph</code> is for:</p>
<pre><code class="language-kotlin">// book/adapter/persistence/BookEntity.kt
@Entity
@Table(name = "books")
@NamedEntityGraph(
    name = "Book.withAuthorAndTags",
    attributeNodes = [NamedAttributeNode("author"), NamedAttributeNode("tags")],
)
class BookEntity(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null,
    var title: String = "",
    var isbn: String = "",
    var subject: String = "",
    @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "author_id", nullable = false) var author: AuthorEntity? = null,
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "book_tags", joinColumns = [JoinColumn(name = "book_id")], inverseJoinColumns = [JoinColumn(name = "tag_id")])
    var tags: MutableSet&lt;TagEntity&gt; = mutableSetOf(),
)
</code></pre>
<p>The Spring Data repository references the graph by name on the finder methods that need it, so a <code>findAll()</code>-style call doesn't pay for eager loading it doesn't need:</p>
<pre><code class="language-kotlin">// book/adapter/persistence/SpringDataBookRepository.kt
interface SpringDataBookRepository : JpaRepository&lt;BookEntity, Long&gt; {
    @EntityGraph(value = "Book.withAuthorAndTags")
    @Query("select b from BookEntity b where b.id = :id")
    fun findWithAuthorAndTagsById(id: Long): BookEntity?

    @EntityGraph(value = "Book.withAuthorAndTags")
    @Query("select b from BookEntity b")
    fun findAllWithAuthorAndTags(): List&lt;BookEntity&gt;

    @EntityGraph(value = "Book.withAuthorAndTags")
    fun findByTitleContainingIgnoreCase(query: String): List&lt;BookEntity&gt;
}
</code></pre>
<p>With <code>spring.jpa.open-in-view=false</code> (Open Session In View is a footgun, not a convenience), every query that gets mapped back to a domain <code>Book</code> has to fetch what it needs up front — the entity graph is what makes that possible without N+1 queries.</p>
<h3>Cross-aggregate search</h3>
<p>The search feature doesn't belong to <code>book</code>, <code>author</code>, or <code>tag</code> — it reads from all three. It gets its own module that depends on the other three modules' <em>output ports</em> (not their internals):</p>
<pre><code class="language-kotlin">// search/service/SearchService.kt
@Service
class SearchService(
    private val bookRepository: BookRepository,
    private val authorRepository: AuthorRepository,
    private val tagRepository: TagRepository,
) : SearchUseCase {
    override fun search(query: String): List&lt;SearchResult&gt; {
        val books = bookRepository.searchByTitleContainingIgnoreCase(query)
            .map { SearchResult.BookResult(requireNotNull(it.id), it.title) }
        val authors = authorRepository.searchByNameContainingIgnoreCase(query)
            .map { SearchResult.AuthorResult(requireNotNull(it.id), it.name) }
        val tags = tagRepository.searchByValueContainingIgnoreCase(query)
            .map { SearchResult.TagResult(requireNotNull(it.id), it.value) }
        return books + authors + tags
    }
}
</code></pre>
<p><code>GET /api/search?query=dune</code> returns the matches grouped by type:</p>
<pre><code class="language-json">{
  "books": [
    {
      "id": 1,
      "title": "Dune"
    },
    {
      "id": 2,
      "title": "Children of Dune"
    }
  ],
  "authors": [],
  "tags": []
}
</code></pre>
<h2>Logging</h2>
<p>Every request/response boundary crossing logs at INFO, in a fixed <code>static text, var1=[value1] var2=[value2]</code> format so log lines stay greppable:</p>
<pre><code class="language-plaintext">HTTP request received to create book, title=[Dune] authorId=[1]
HTTP response sent for create book, bookId=[1]
</code></pre>
<p>Errors are written twice, once to the class logger (no exception, safe to alert on) and once to a dedicated <code>error.logger</code> (with the exception, for full stack traces):</p>
<pre><code class="language-kotlin">// common/adapter/web/GlobalExceptionHandler.kt
@ExceptionHandler(Exception::class)
fun handleUnexpected(ex: Exception): ResponseEntity&lt;ErrorResponse&gt; {
    val message = "Unexpected error handling request, exceptionType=[${ex.javaClass.simpleName}]"
    log.error(message)
    errorLog.error(message, ex)
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResponse(message = "Internal server error"))
}
</code></pre>
<p><code>common/logging/Logging.kt</code> provides the small helpers every class uses: <code>logger()</code> for a class-scoped <code>Logger</code> via <code>companion object { val log = logger() }</code>, and inline <code>debug { "expensive to build" }</code> / <code>info { }</code> extensions so the message lambda only runs when the level is actually enabled.</p>
<h2>Tech stack</h2>
<ul>
<li><p><strong>Spring Boot 4.1.0</strong> on <strong>Kotlin 2.4.10</strong> / <strong>Java 21</strong>, built with the Gradle Kotlin DSL and a <code>gradle/libs.versions.toml</code> version catalog.</p>
</li>
<li><p><strong>Modular starters</strong> throughout — <code>spring-boot-starter-webmvc</code> (not the deprecated <code>spring-boot-starter-web</code>), <code>spring-boot-starter-data-jpa</code>, <code>spring-boot-starter-validation</code>, <code>spring-boot-starter-actuator</code>, <code>spring-boot-starter-opentelemetry</code>, each paired with its own <code>-test</code> starter (<code>spring-boot-starter-webmvc-test</code>, etc.) rather than one do-everything test starter.</p>
</li>
<li><p><strong>Testcontainers</strong> for persistence tests (real Postgres, not H2), <strong>spring-boot-docker-compose</strong> for local dev so <code>docker compose up</code> isn't something you have to remember to run separately.</p>
</li>
<li><p><strong>Actuator</strong> (<code>/actuator/health</code>, <code>/actuator/info</code>, <code>/actuator/metrics</code>) and <strong>OpenTelemetry</strong> (<code>spring-boot-starter-opentelemetry</code>) for traces and metrics.</p>
</li>
</ul>
<h2>Database</h2>
<p><code>schema.sql</code> is the single source of truth for the schema — it drops and recreates <code>authors</code>, <code>tags</code>, <code>books</code>, and the <code>book_tags</code> join table on every startup (<code>spring.sql.init.mode=always</code>), and Hibernate is set to <code>ddl-auto=validate</code> rather than letting it generate DDL. <code>data.sql</code> seeds five authors, six tags, and eight books so there's something to query immediately.</p>
<pre><code class="language-sql">CREATE TABLE books
(
    id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title     VARCHAR(255) NOT NULL,
    isbn      VARCHAR(32)  NOT NULL,
    subject   VARCHAR(255) NOT NULL,
    author_id BIGINT       NOT NULL REFERENCES authors (id)
);
</code></pre>
<h2>Running it</h2>
<pre><code class="language-bash">docker compose up -d
./gradlew bootRun
</code></pre>
<p>Spring Boot's Docker Compose support will also start <code>compose.yml</code> automatically if you skip the first step and just run <code>./gradlew bootRun</code> — it detects the running services either way.</p>
<pre><code class="language-bash">curl localhost:8080/api/authors
curl localhost:8080/api/books
curl "localhost:8080/api/search?query=dune"
curl -X POST localhost:8080/api/authors -H "Content-Type: application/json" -d '{"name":"Liu Cixin"}'
</code></pre>
<p>To run against PgBouncer instead of Postgres directly, activate the <code>pgbouncer</code> profile, which points the datasource at port <code>6432</code> instead of <code>5432</code>:</p>
<pre><code class="language-bash">./gradlew bootRun --args='--spring.profiles.active=pgbouncer'
</code></pre>
<h2>Testing</h2>
<p>Every layer has its own kind of test:</p>
<ul>
<li><p><strong>Service tests</strong> use handwritten fake ports (no mocking framework needed — the ports are small interfaces) to test business logic in isolation.</p>
</li>
<li><p><strong>Persistence tests</strong> (<code>@DataJpaTest</code> + <code>@AutoConfigureTestDatabase(replace = NONE)</code>) run against a real Postgres via Testcontainers, imported through a shared <code>TestContainersConfiguration</code>.</p>
</li>
<li><p><strong>Web slice tests</strong> (<code>@WebMvcTest</code>) mock the use case port and assert on HTTP status, validation errors, and JSON shape.</p>
</li>
<li><p><strong>A concurrency benchmark</strong> (below) spins up Postgres <em>and</em> PgBouncer in Testcontainers and fires the same load at both.</p>
</li>
</ul>
<pre><code class="language-bash">./gradlew test
</code></pre>
<h2>The PgBouncer benchmark</h2>
<p><code>PgBouncerConcurrencyBenchmarkTest</code> starts a Postgres container and a PgBouncer container (in transaction pooling mode) on a shared Testcontainers network, opens a Hikari pool against each, and fires 80 concurrent workers × 25 queries at both — then logs total time and p50/p95/max latency for each:</p>
<pre><code class="language-plaintext">PgBouncer concurrency benchmark completed, concurrency=[80] queriesPerWorker=[25]
directTotalMs=[127] directP50Ms=[0] directP95Ms=[2] directMaxMs=[114]
pgbouncerTotalMs=[110] pgbouncerP50Ms=[0] pgbouncerP95Ms=[3] pgbouncerMaxMs=[103]
</code></pre>
<p>At this concurrency (80 clients, comfortably under Postgres's default <code>max_connections=100</code>), the two are neck-and-neck — PgBouncer adds a fraction of a millisecond of hop overhead per query, which is exactly what you'd hope for: it isn't free, but it's close enough to free not to matter. That's not the interesting part of the story, though — see <a href="https://blog.hbrown.dev/pgbouncer-spring-boot-4-setup-benchmark">PgBouncer with Spring Boot 4: Setup, Gotchas, and the Proof</a> for why PgBouncer earns its keep at higher concurrency, where direct connections start hitting Postgres's connection ceiling and PgBouncer just keeps going.</p>
<hr />
<p>Source code for this application is available in my Github repo: <a href="https://github.com/hgbrown/spring-demo-pgbouncer">spring-demo-pgbouncer</a></p>
]]></content:encoded></item><item><title><![CDATA[Guardrails for AI-Generated Kotlin with detekt and ktlint]]></title><description><![CDATA[Add detekt and ktlint to a Spring Boot 4 Kotlin project to give AI coding agents enforceable quality and formatting guardrails.]]></description><link>https://blog.hbrown.dev/providing-your-agent-with-guardrails-with-detekt-and-ktlint</link><guid isPermaLink="true">https://blog.hbrown.dev/providing-your-agent-with-guardrails-with-detekt-and-ktlint</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[detekt]]></category><category><![CDATA[KtLint]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[gradle]]></category><dc:creator><![CDATA[Henry Brown]]></dc:creator><pubDate>Mon, 10 Aug 2026 16:02:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a6df6b110d8ecdf29cfd44b/fe1265d4-7104-4c92-8b2e-27fbaf24406e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When we adopt agentic coding workflows, our job starts to shift from typing every line of code to defining the conditions that generated code must satisfy.</p>
<p>An AI coding agent can produce a working implementation very quickly.
That does not mean the implementation follows the conventions of the project, avoids known code smells, or uses Kotlin in the way the team has agreed.
A prompt such as “follow our coding standards” helps, but it is still only an instruction expressed in natural language.
The agent may interpret it differently from one task to the next.</p>
<p>The stronger approach is to make those standards executable.
In this post I will add two guardrails to a Spring Boot 4 project written in Kotlin:</p>
<ol>
<li><a href="https://detekt.dev/">detekt</a> for static analysis and code-smell detection.</li>
<li><a href="https://ktlint.github.io/ktlint/">ktlint</a> for consistent Kotlin formatting and style.</li>
</ol>
<p>These tools do not make generated code correct, secure, or well designed on their own.
Tests, code review, architecture and human judgement still matter.
What they do is turn a useful subset of the team's expectations into fast, repeatable checks that can run after every change.</p>
<p>The complete example is available in the <a href="https://github.com/hgbrown/springboot4-detekt-demo">springboot4-detekt-demo repository</a>.</p>
<h2>Why the existing codebase matters</h2>
<p>An agent does not work from the task description alone.
It also reads nearby classes, tests, build files and configuration to infer how the project is organised.
The existing codebase therefore becomes part of the prompt, whether we intend it to or not.</p>
<p>If the repository contains several ways to name the same concept, inconsistent formatting and multiple patterns for solving the same problem, the agent has weak examples to follow.
It may reproduce any of them or introduce yet another variation.
If the repository is consistent, the agent has a much clearer signal.</p>
<p>This is similar to the broken windows theory: visible disorder can suggest that further disorder will be tolerated.
In a codebase, one ignored warning or one “temporary” exception is not likely to cause a disaster.
The problem is accumulation.
Once inconsistent code becomes normal, both people and agents use it as precedent for the next change.</p>
<p>There are therefore two complementary ways to guide an agent:</p>
<ol>
<li>Give it good examples in the existing code.</li>
<li>Give it automated checks that reject code which falls outside the agreed boundaries.</li>
</ol>
<p>The first shapes what the agent is likely to generate.
The second verifies what it actually generated.
That feedback loop is the guardrail: generate a change, run the checks, inspect the failures, correct the change and repeat until the build is clean.</p>
<h2>What detekt and ktlint each contribute</h2>
<p>There is some overlap between the tools, but they solve different problems.</p>
<p>ktlint is primarily concerned with the shape of Kotlin code.
It enforces matters such as indentation, whitespace, wrapping and imports, and it can automatically fix many violations.
This removes formatting debates from prompts and code reviews because the project carries its style in configuration rather than in personal IDE settings.</p>
<p>detekt performs static analysis.
Its rule sets can identify complexity, naming problems, risky exception handling, potential bugs and Kotlin-specific code smells.
It is also configurable, so the rules can express decisions that matter in a particular project—for example, prohibiting <code>GlobalScope</code> or preferring <code>delay</code> over <code>Thread.sleep</code> in coroutine code.</p>
<p>Together they provide a useful division of responsibility:</p>
<ul>
<li>ktlint answers, “Is this code formatted according to the project style?”</li>
<li>detekt answers, “Does this code contain patterns that the project has decided to reject?”</li>
</ul>
<p>Both tools are deterministic.
The same source and configuration produce the same findings regardless of whether the code was written by a person or generated by an agent.</p>
<h2>Step 1: Add the plugin versions</h2>
<p>The example project uses a Gradle version catalog.
Add the detekt and ktlint Gradle plugin versions to the <code>[versions]</code> section of <code>gradle/libs.versions.toml</code>:</p>
<pre><code class="language-yaml">detekt = "2.0.0-alpha.6"
ktlint-gradle = "14.2.0"
</code></pre>
<p>The demo uses detekt 2.0 because Spring Boot 4 and recent Kotlin versions require a compatible analysis toolchain.
At the time of writing, detekt 2.0 is still an alpha release, so check the <a href="https://detekt.dev/docs/introduction/compatibility/">detekt compatibility table</a> and <a href="https://detekt.dev/changelog-2.0.0/">release notes</a> before choosing a version for your own project.</p>
<p>The second version is for the <a href="https://github.com/JLLeitschuh/ktlint-gradle">ktlint Gradle plugin</a>, which wraps ktlint and creates convenient Gradle check and format tasks.</p>
<p>The version catalog also needs plugin aliases that map these versions to the <code>dev.detekt</code> and <code>org.jlleitschuh.gradle.ktlint</code> plugin ids.
Those mappings are present in the complete demo repository.</p>
<h2>Step 2: Apply the plugins</h2>
<p>Apply both aliases in <code>build.gradle.kts</code>:</p>
<pre><code class="language-kotlin">plugins {
    // ...
    alias(libs.plugins.detekt)
    alias(libs.plugins.ktlint)
}
</code></pre>
<p>Once applied, the plugins add their tasks to the Gradle build.
The important tasks for this article are <code>detekt</code>, <code>ktlintCheck</code> and <code>ktlintFormat</code>.</p>
<h2>Step 3: Configure the guardrails</h2>
<p>Next, configure both plugins in <code>build.gradle.kts</code>:</p>
<pre><code class="language-kotlin">detekt {
    buildUponDefaultConfig = true
    allRules = false
    parallel = true
    ignoreFailures = false
    autoCorrect = false
}

ktlint {
    verbose.set(true)
    outputToConsole.set(true)
    ignoreFailures.set(false)
    enableExperimentalRules.set(false)
    coloredOutput.set(true)

    additionalEditorconfig.set(
        mapOf(
            "ktlint_code_style" to "intellij_idea",
            "max_line_length" to "120",
        ),
    )

    reporters {
        reporter(ReporterType.PLAIN)
        reporter(ReporterType.CHECKSTYLE)
    }

    filter {
        exclude("**/generated/**")
        exclude("**/build/**")
        include("**/kotlin/**")
        include("*.gradle.kts")
    }
}
</code></pre>
<p>There are a few deliberate decisions in this configuration.</p>
<p>For detekt, <code>buildUponDefaultConfig = true</code> starts with detekt's defaults and lets the project override only the rules it cares about.
<code>allRules = false</code> avoids enabling every optional rule simply because it exists.
That is important: a guardrail should reflect an intentional team decision, not create a wall of findings that everybody learns to ignore.</p>
<p><code>ignoreFailures = false</code> is what makes a finding enforceable.
The Gradle task fails instead of printing a warning and allowing the build to continue.
<code>autoCorrect = false</code> also keeps static-analysis changes explicit.
Unlike formatting, many detekt findings require a design decision and should not be rewritten blindly.</p>
<p>The ktlint configuration follows the same fail-the-build approach.
It prints detailed findings to the console and produces plain and Checkstyle reports.
The filter excludes generated output and includes Kotlin source and Gradle Kotlin scripts, so the tool checks code that the team owns rather than generated code that will be overwritten.</p>
<p>The style values are supplied here as additional EditorConfig properties.
Later we will put the same project-wide decisions in <code>.editorconfig</code>, where IDEs and other compatible tools can also discover them.</p>
<h2>Step 4: Make the checks part of the normal build</h2>
<p>A quality task that nobody remembers to run is documentation, not a guardrail.
Connect both checks to Gradle's standard <code>check</code> lifecycle and add a memorable formatting alias:</p>
<pre><code class="language-kotlin">tasks.named("check") {
    dependsOn("detekt", "ktlintCheck")
}

tasks.register("format") {
    group = "formatting"
    description = "Formats Kotlin source and Gradle Kotlin scripts."
    dependsOn("ktlintFormat")
}
</code></pre>
<p>Now the same command used for tests also evaluates the static-analysis and formatting rules.
The <code>format</code> task gives developers and agents a simple way to apply ktlint's safe formatting corrections before checking again.</p>
<p>With the configuration in place, the normal workflow is:</p>
<ul>
<li>Run everything with <code>./gradlew check</code>.</li>
<li>Run static analysis only with <code>./gradlew detekt</code>.</li>
<li>Check formatting only with <code>./gradlew ktlintCheck</code>.</li>
<li>Apply ktlint's automatic formatting with <code>./gradlew format</code> or <code>./gradlew ktlintFormat</code>.</li>
</ul>
<p>I would instruct an AI agent to run <code>./gradlew format</code> after editing Kotlin, followed by <code>./gradlew check</code> before it considers the task complete.
The first command handles mechanical formatting.
The second provides the actual acceptance gate, including tests and findings that need judgement.</p>
<p>Run the same <code>./gradlew check</code> command in continuous integration.
That prevents a local tool configuration, an IDE setting or an agent that skipped validation from becoming a way around the rules.</p>
<h2>Step 5: Add project-specific detekt rules</h2>
<p>The default rules are a good start, but the most valuable guardrails describe decisions that are specific to the project.
detekt supports a YAML configuration file for enabling rules and changing their options.
You can generate a starting file with <code>./gradlew detektGenerateConfig</code>, then keep it under version control.
The <a href="https://detekt.dev/docs/introduction/configurations/">detekt configuration guide</a> describes the file structure, validation and ways to maintain a smaller override file on top of the defaults.</p>
<p>For example, a Spring Boot application that uses coroutines can enable the following rules:</p>
<pre><code class="language-yaml">coroutines:
  active: true

  GlobalCoroutineUsage:
    active: true

  InjectDispatcher:
    active: true
    dispatcherNames:
      - IO
      - Default
      - Unconfined

  RedundantSuspendModifier:
    active: true

  SleepInsteadOfDelay:
    active: true

  SuspendFunSwallowedCancellation:
    active: true

  SuspendFunWithCoroutineScopeReceiver:
    active: true
</code></pre>
<p>These rules make several coroutine expectations executable.
They can catch global coroutine usage, hard-coded dispatchers, blocking sleeps in coroutine code, swallowed cancellation and unnecessary or misleading suspend APIs.
The result is more useful than telling an agent to “use coroutines correctly”, because a violation produces a concrete rule id and source location that it can act on.</p>
<p>Save the configuration as <code>config/detekt/detekt.yml</code> and point the detekt Gradle extension at it with <code>config.setFrom(files("$rootDir/config/detekt/detekt.yml"))</code>.
In the linked demo repository that line is present but commented out; uncomment it when you want these project-specific rules to take effect.
Without that reference, detekt continues to use its default configuration.</p>
<p>The demo's full configuration also covers complexity, exception handling, naming, potential bugs and style.
Treat it as a starting point rather than a universal standard.
Enable rules deliberately, agree on legitimate exceptions and tune thresholds to the codebase.
A small set of trusted checks is more effective than a large set that developers routinely suppress.</p>
<p>For an existing project, consider introducing strict rules gradually.
detekt supports <a href="https://detekt.dev/docs/introduction/baseline/">baselines</a>, which record existing findings so the build can reject new violations without requiring a large clean-up before the first adoption.
The baseline should be a migration tool, not a permanent hiding place: review it and reduce it as the code improves.</p>
<h2>Step 6: Put the formatting contract in <code>.editorconfig</code></h2>
<p>An <code>.editorconfig</code> file is a plain-text project configuration file for formatting conventions.
Editors and IDEs that support EditorConfig discover it automatically, which allows team members to use different tools while sharing the same basic rules.</p>
<p>Place the file near the repository root and commit it to version control:</p>
<pre><code class="language-yaml">root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.{kt,kts}]
indent_style = space
indent_size = 4
continuation_indent_size = 4
max_line_length = 120
ktlint_code_style = intellij_idea

[*.yml]
indent_style = space
indent_size = 2
</code></pre>
<p>The general section standardises encoding, line endings, final newlines and trailing whitespace.
The Kotlin section selects four-space indentation, a 120-character line length and ktlint's IntelliJ IDEA code style.
The YAML section uses two-space indentation.</p>
<p>ktlint reads its rule properties from EditorConfig, so the file is more than an IDE preference.
It is a versioned formatting contract that the Gradle task can enforce.
The <a href="https://ktlint.github.io/ktlint/latest/rules/standard/">ktlint rule documentation</a> lists the standard rules and their EditorConfig properties, while the <a href="https://github.com/JLLeitschuh/ktlint-gradle">ktlint Gradle plugin documentation</a> explains task configuration, filtering, reporters and baselines.</p>
<p>Keeping the formatting rules with the source prevents unnecessary formatting-only changes and makes reviews easier to read.
It also means an agent can format its own changes with the same rules used by every developer and by CI.</p>
<h2>The feedback loop for an AI coding agent</h2>
<p>After this setup, the build becomes part of the agent's working instructions.
A useful task-level instruction can be as simple as:</p>
<blockquote>
<p>After changing Kotlin code, run <code>./gradlew format</code> and then <code>./gradlew check</code>. Fix any detekt, ktlint or test failures before finishing. Do not suppress a rule unless the reason is explained.</p>
</blockquote>
<p>This works because the instruction points to project-owned tools instead of trying to repeat every coding rule in the prompt.
When the standards change, update the repository configuration once.
Developers, CI and AI agents all receive the same new contract.</p>
<p>The order matters as well.
Formatting first removes mechanical noise, then <code>check</code> evaluates the formatted result.
If detekt reports a design smell, the agent should fix the underlying code and run the checks again.
A suppression should be a conscious exception reviewed in the same way as any other design decision, not the quickest route to a green build.</p>
<h2>Conclusion</h2>
<p>The quality of AI-generated code is influenced by the environment in which the agent works.
A clean and consistent repository gives it better examples, while executable quality checks give it clear boundaries.
You need both.</p>
<p>In this Spring Boot 4 project, ktlint makes formatting predictable and automatically corrects many style issues.
detekt catches code smells and lets the project encode more specific Kotlin and coroutine decisions.
Connecting both to <code>./gradlew check</code> turns them from optional tools into an acceptance gate that applies equally to human-written and generated code.</p>
<p>Guardrails do not replace review, testing or engineering judgement.
They make that judgement reusable.
Instead of explaining the same expectation in every prompt and every pull request, you record it in the project and let fast, deterministic tooling provide feedback whenever the code starts to drift.</p>
<p>The full source code is available at <a href="https://github.com/hgbrown/springboot4-detekt-demo">github.com/hgbrown/springboot4-detekt-demo</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Fan-in with Kotlin Coroutines and Flow]]></title><description><![CDATA[Learn the fan-in pattern in Kotlin using channelFlow and Flow. Understand structured concurrency, cancellation, and backpressure with practical examples]]></description><link>https://blog.hbrown.dev/fan-in-with-kotlin-coroutines-and-flow</link><guid isPermaLink="true">https://blog.hbrown.dev/fan-in-with-kotlin-coroutines-and-flow</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[coroutines]]></category><category><![CDATA[flow]]></category><category><![CDATA[structured concurrency]]></category><category><![CDATA[channel]]></category><dc:creator><![CDATA[Henry Brown]]></dc:creator><pubDate>Wed, 22 Jul 2026 08:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a6df6b110d8ecdf29cfd44b/8052358a-d6f9-4d50-9d29-9d83dcfedce0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sometimes you need to start several pieces of work at the same time and handle each result as soon as it is available.
The fan-in pattern is a good fit for this: many concurrent producers send their results into one stream, and one consumer collects that stream.</p>
<p>Consider comparison shopping for a pair of headphones.
If you want prices from four stores, you would not ask the first store, wait for its response, and only then ask the second store.
You would send all four requests and process the quotes in the order they arrive.</p>
<p>In Kotlin, <code>channelFlow</code> gives us a convenient way to express that pattern while keeping the result as an ordinary <code>Flow</code>.</p>
<p>The example uses the <code>kotlinx-coroutines-core</code> dependency:</p>
<pre><code class="language-kotlin">implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
</code></pre>
<p>Here is the complete example:</p>
<pre><code class="language-kotlin">import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.Locale
import kotlin.random.Random

data class PriceQuote(val store: String, val price: Double)

// Simulates a store API with its own latency
fun fetchPrice(store: String, product: String): Flow&lt;PriceQuote&gt; = flow {
    println("Requesting $product price from $store")
    delay(Random.nextLong(300, 2_000))
    emit(PriceQuote(store, Random.nextDouble(80.0, 120.0)))
}

fun comparePrices(product: String): Flow&lt;PriceQuote&gt; = channelFlow {
    val stores = listOf("Amazon", "Takealot", "eBay", "AliExpress")

    for (store in stores) {
        launch {
            fetchPrice(store, product).collect { quote -&gt;
                send(quote)
            }
        }
    }
}

fun main() = runBlocking {
    comparePrices("headphones").collect { quote -&gt;
        println("${quote.store}: \$${"%.2f".format(Locale.US, quote.price)}")
    }

    println("All stores answered.")
}
</code></pre>
<p>One run may produce the following output:</p>
<pre><code class="language-text">Requesting headphones price from Amazon
Requesting headphones price from Takealot
Requesting headphones price from eBay
Requesting headphones price from AliExpress
eBay: $94.13
Amazon: $101.87
AliExpress: $83.42
Takealot: $109.55
All stores answered.
</code></pre>
<p>The request is logged before each coroutine reaches <code>delay</code>, so those messages appear before their corresponding quotes.
Neither the request messages nor the quotes have a guaranteed order, although the requests will normally start in store-list order in this small example.</p>
<h2>Why use <code>channelFlow</code> instead of <code>flow</code>?</h2>
<p>A normal <code>flow { }</code> is designed for sequential emission from its own coroutine.
It preserves the coroutine context in which it is collected, so starting child coroutines inside it and calling <code>emit</code> from those children violates the flow invariant.</p>
<p><code>channelFlow</code> is designed for the case where several coroutines need to produce values for the same flow.
Its block provides a <code>ProducerScope</code>, and each child coroutine can safely call <code>send</code> on that scope.
The channel merges those values into a single flow for the collector.</p>
<p>The resulting flow is still cold.
Nothing happens when <code>comparePrices("headphones")</code> is called; the store requests start when the flow is collected.
Collecting it a second time starts four new requests and produces a new set of quotes.</p>
<h2>Why launch inside the loop?</h2>
<p>Without <code>launch</code>, the collections would run one after another:</p>
<pre><code class="language-kotlin">for (store in stores) {
    fetchPrice(store, product).collect { quote -&gt;
        send(quote)
    }
}
</code></pre>
<p><code>collect</code> is a suspending call and does not return until that store's flow completes.
Amazon would therefore finish before Takealot starts, followed by eBay and AliExpress.
The total waiting time would be close to the sum of all four delays.</p>
<p>With <code>launch</code>, each store flow is collected by a child coroutine.
All four delays can overlap, so the total waiting time is close to the slowest request rather than the sum of every request.
This is concurrency; it does not require four dedicated threads.
While one coroutine is suspended in <code>delay</code> or waiting for non-blocking I/O, another coroutine can make progress.</p>
<h2>Why does the flow wait for every store?</h2>
<p>The child coroutines launched inside <code>channelFlow</code> belong to its scope.
Because this follows structured concurrency, the flow does not complete until the builder block and all of its children have completed.</p>
<p>The loop itself finishes quickly, but its children are still fetching and sending quotes.
Only after the last child finishes does collection complete and <code>All stores answered.</code> print.
There is no need to maintain a counter, close a channel manually, or call <code>joinAll</code>.</p>
<p>Structured concurrency also defines the failure behaviour.
If one store flow throws an exception, its failure cancels the <code>channelFlow</code> and the other child coroutines, and the exception reaches the collector.
If a failed store should not stop the comparison, handle that failure inside the individual store flow and decide what result to send instead.</p>
<h2>Why use <code>send</code> instead of <code>emit</code>?</h2>
<p><code>send</code> is the channel operation provided by the <code>ProducerScope</code> inside <code>channelFlow</code>.
Each store coroutine sends its quote into the same channel, and the downstream collector receives quotes as they become available.
That interleaving of several producers into one consumer is the fan-in.</p>
<p>From <code>main</code>'s point of view, <code>comparePrices</code> is simply a <code>Flow&lt;PriceQuote&gt;</code>.
The concurrency is kept inside the producer, so callers can use normal flow operators and terminal operations without knowing how the values were produced.</p>
<h2>Cancellation and backpressure</h2>
<p>Cancellation follows the same parent-child relationship.
If the collector is cancelled or stops early, the work inside <code>channelFlow</code> and its child coroutines is cancelled as well.
For example, <code>comparePrices("headphones").first()</code> returns the first quote to arrive and cancels the remaining requests.
It finds the fastest response, not necessarily the cheapest price.</p>
<p><code>channelFlow</code> uses a buffered channel by default.
Producers can get ahead of a slow collector until that buffer is full; after that, <code>send</code> suspends until capacity becomes available.
That gives the flow backpressure without allowing producers to grow an unbounded queue.
If every send must wait for the collector, apply <code>buffer(0)</code> to the returned flow to use rendezvous behaviour.</p>
<h2>The shorter version with <code>merge</code></h2>
<p>For this example, the <code>merge</code> flow operator is the idiomatic shortcut:</p>
<pre><code class="language-kotlin">import kotlinx.coroutines.flow.merge

fun comparePrices(product: String): Flow&lt;PriceQuote&gt; {
    val stores = listOf("Amazon", "Takealot", "eBay", "AliExpress")

    return stores
        .map { store -&gt; fetchPrice(store, product) }
        .merge()
}
</code></pre>
<p><code>merge</code> collects all of the flows concurrently and emits their values without preserving the order of the source flows.
For a straightforward fan-in, I would normally use <code>merge</code>.
When the producer needs more control over how child coroutines send values, handle callbacks, or combine different kinds of concurrent work, <code>channelFlow</code> makes the underlying pattern explicit.</p>
<p>The useful part of fan-in is that the consumer does not have to coordinate the producers.</p>
<p>Each producer works at its own pace, while the collector sees one flow of results and retains the normal completion, failure, cancellation, and backpressure behaviour of Kotlin coroutines.</p>
]]></content:encoded></item><item><title><![CDATA[Accessing Apple's on-device AI from Kotlin using apfel]]></title><description><![CDATA[Learn how to use the Apfel Kotlin library to integrate with the OpenAI API, send prompts, and build AI-powered applications with clean code.]]></description><link>https://blog.hbrown.dev/accessing-apple-s-on-device-ai-from-kotlin-using-apfel</link><guid isPermaLink="true">https://blog.hbrown.dev/accessing-apple-s-on-device-ai-from-kotlin-using-apfel</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[apfel]]></category><category><![CDATA[openai]]></category><category><![CDATA[Apple Intelligence]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Henry Brown]]></dc:creator><pubDate>Thu, 09 Jul 2026 08:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a6df6b110d8ecdf29cfd44b/fc8f4f41-bd63-46d4-9914-f68171aeafe4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you own a modern Mac with an Apple Silicon chip and Apple Intelligence enabled, then you already have access to a local foundation model.
There is no separate model to download, no API key to create, and no token bill to worry about.</p>
<p>macOS Tahoe ships with Apple's on-device foundation model, roughly a 3B parameter LLM, and <a href="https://apfel.franzai.com/">apfel</a> gives it a very convenient front door.
It wraps Apple's <code>FoundationModels</code> framework and exposes the model in three ways:</p>
<ol>
<li>A UNIX-style command-line tool.</li>
<li>An OpenAI-compatible HTTP server.</li>
<li>An interactive chat mode.</li>
</ol>
<p>In this post I will show how to use apfel from the command line, then call the same local model from a Kotlin script using the OpenAI-compatible API.</p>
<h2>Installing apfel</h2>
<p>The installation is a single Homebrew command:</p>
<pre><code class="language-shell">brew install apfel
</code></pre>
<p>apfel requires Apple Silicon, macOS Tahoe, and Apple Intelligence to be enabled.
Once those pieces are in place, there is no extra configuration needed.</p>
<p>The important part is that the model runs on your Mac.
For short prompts, small text transformations, command explanations, shell one-liners, translations, and local scripting tasks, that is very appealing.
You get a useful local assistant without sending the prompt to a cloud model.</p>
<h2>Prompting from the terminal</h2>
<p>After installing apfel, you can prompt the model directly:</p>
<pre><code class="language-shell">apfel --stream "Can you write some Kotlin code to print Hello World to the screen?"
</code></pre>
<p>You can also use it in the normal UNIX way by redirecting output:</p>
<pre><code class="language-shell">apfel "Write a Kotlin script to print Hello World to the console without any explanation or anything else besides the script." &gt; hello.kts
</code></pre>
<p>The model is still a small local model, so you should inspect what it writes, but the output is easier to pipe into a file.</p>
<h2>Starting the OpenAI-compatible server</h2>
<p>The most interesting part for Kotlin is the server mode.
apfel can expose the local model as an OpenAI-compatible API:</p>
<pre><code class="language-shell">apfel --serve
</code></pre>
<p>By default, this starts a server on:</p>
<pre><code class="language-text">http://127.0.0.1:11434
</code></pre>
<p>If that port is already busy, or you just prefer a different port, you can specify one:</p>
<pre><code class="language-shell">apfel --serve --port 11435
</code></pre>
<p>The server exposes the familiar chat completions endpoint:</p>
<pre><code class="language-text">POST /v1/chat/completions
</code></pre>
<p>It also supports useful OpenAI-style features such as streaming, <code>GET /v1/models</code>, tool calling, <code>response_format: json_object</code>, <code>temperature</code>, <code>max_tokens</code>, <code>seed</code>, and CORS for browser clients.</p>
<p>For this post, we only need the basic chat completions endpoint.</p>
<h2>Calling apfel from Kotlin</h2>
<p>Because the server speaks the OpenAI API shape, calling it from Kotlin is straightforward.
The model name is <code>apple-foundationmodel</code>, and the API key can be any placeholder value because the local server does not require authentication by default.</p>
<p>Here is a complete Kotlin script:</p>
<pre><code class="language-kotlin">@file:DependsOn("tools.jackson.core:jackson-databind:3.0.3")

import tools.jackson.databind.json.JsonMapper
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse

val baseUrl = "http://localhost:11434/v1"
val apiKey = "unused"

val body = """
    {
      "model": "apple-foundationmodel",
      "messages": [
        {
          "role": "user",
          "content": "Translate to Korean: Thank you"
        }
      ],
      "temperature": 0.2,
      "max_tokens": 100
    }
""".trimIndent()

val request = HttpRequest.newBuilder(URI.create("$baseUrl/chat/completions"))
    .header("Content-Type", "application/json")
    .header("Authorization", "Bearer $apiKey")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build()

runCatching {
    val response = HttpClient.newHttpClient()
        .send(request, HttpResponse.BodyHandlers.ofString())

    check(response.statusCode() in 200..299) {
        "HTTP ${response.statusCode()}: ${response.body()}"
    }

    val root = JsonMapper.shared().readTree(response.body())
    val content = root.path("choices").get(0)
        ?.path("message")?.path("content")?.asString()
        ?: error("Unexpected response shape: ${response.body()}")

    println(content)
}.onFailure { System.err.println("Error: ${it.message}") }
</code></pre>
<p>Save this as <code>apfel.main.kts</code>.
With Kotlin on your path, you can run it directly:</p>
<pre><code class="language-shell">kotlin apfel.main.kts
</code></pre>
<p>Here is the output I get:</p>
<pre><code class="language-text">감사합니다.
</code></pre>
<p>If you started apfel on the alternate port shown earlier, change the script to:</p>
<pre><code class="language-kotlin">val baseUrl = "http://localhost:11435/v1"
</code></pre>
<p>That is the main benefit of the OpenAI-compatible API.
The code is ordinary HTTP client code.
If you already have a client abstraction that talks to OpenAI, you can often point it at <code>http://localhost:11434/v1</code>, use the <code>apple-foundationmodel</code> model name, and keep most of the rest of the code the same.</p>
<h2>Checking the available model</h2>
<p>The server also exposes a models endpoint, which is useful when you want to verify that the server is running:</p>
<pre><code class="language-shell">curl http://localhost:11434/v1/models
</code></pre>
<p>For apfel, the important model id is:</p>
<pre><code class="language-text">apple-foundationmodel
</code></pre>
<p>There is no model picker here in the same sense as a cloud API or a local model manager such as Ollama.
apfel is intentionally wrapping the Apple model that is already available through macOS.</p>
<h2>What this is good for</h2>
<p>The local model is not meant to replace larger cloud-based models.
It has a smaller context window, around 4,096 tokens for input and output combined, and it is not the tool I would choose for long documents, complex code generation, or tasks that need strong factual recall.</p>
<p>Where it becomes interesting is in small, local, everyday tasks:</p>
<ol>
<li>Explaining a shell command.</li>
<li>Generating a small regex.</li>
<li>Rephrasing a short paragraph.</li>
<li>Translating a phrase.</li>
<li>Summarising a short file.</li>
<li>Turning command output into something easier to read.</li>
<li>Building a small local Kotlin utility that needs just enough language understanding.</li>
</ol>
<p>The local context is the part I like most.
Cloud models cannot see the output of <code>df -h</code>, <code>lsof</code>, <code>git log</code>, or <code>ls</code> unless you explicitly send that data to them.
With apfel, you can pipe local command output into a local model and keep the whole loop on your machine.</p>
<p>For example:</p>
<pre><code class="language-shell">df -h | apfel "Which volume is closest to full? Reply in one sentence."
</code></pre>
<p>or:</p>
<pre><code class="language-shell">git log --oneline -10 | apfel "Summarise these commits in three bullets."
</code></pre>
<p>That makes apfel feel less like a replacement for a big hosted model and more like a small language-aware UNIX tool.</p>
<h2>Final thoughts</h2>
<p>For me, the nice thing about apfel is not only that it provides CLI access to Apple's on-device model.
It is that it exposes the model through interfaces developers already know: standard input and output for shell scripts, and an OpenAI-compatible API for application code.</p>
<p>That makes it easy to experiment from Kotlin.
Start <code>apfel --serve</code>, point a small Kotlin script at <code>http://localhost:11434/v1</code>, send a normal chat completions request, and you have a private local model call running on your Mac.</p>
<p>It will not replace cloud models for every use case, and it should not be treated as if it has the same capabilities as a larger hosted model.
But for quick local automation, small text transforms, and developer workflows where privacy and zero setup matter, it is a very useful tool to have installed.</p>
]]></content:encoded></item><item><title><![CDATA[How many threads can you create with Spring Boot and Java virtual threads?]]></title><description><![CDATA[Learn the differences between Java platform and virtual threads, including scalability, performance, and real-world use cases.]]></description><link>https://blog.hbrown.dev/how-many-threads-can-you-create-with-spring-boot-and-java-virtual-threads</link><guid isPermaLink="true">https://blog.hbrown.dev/how-many-threads-can-you-create-with-spring-boot-and-java-virtual-threads</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[virtualthreads]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Henry Brown]]></dc:creator><pubDate>Fri, 22 May 2026 08:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a6df6b110d8ecdf29cfd44b/e64eae15-d244-495a-8bd6-459fb4b36a5c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In looking at enabling virtual threads for a Spring Boot application, I began to wonder how many virtual threads I could spawn compared to platform threads.
I knew the answer would be "many more", but I wanted to see the difference on my own machine rather than just repeat the theory.</p>
<p>So I wrote a deliberately simple experiment.
It does not simulate a full production workload.
It does not call a database, marshal JSON, apply business rules, or exercise a web server.
It simply asks one question:</p>
<blockquote>
<p>How many parked threads can this JVM create before something gives way?</p>
</blockquote>
<p>That is still a useful question, because it shows the most important difference between platform threads and virtual threads.
Platform threads are expensive because they are backed by operating system threads.
Virtual threads are cheap because they are managed by the JVM and only use a platform thread while they are actually running.</p>
<h2>Spawning platform threads</h2>
<p>The first test creates platform threads using the normal <code>Thread</code> constructor.
Each thread immediately parks itself so that it stays alive without doing any useful work.</p>
<pre><code class="language-kotlin">import org.junit.jupiter.api.Test
import java.util.concurrent.locks.LockSupport

class PlatformThreadLimitTest {
    @Test
    fun `how many platform threads can be created`() {
        var threadCount = 0
        try {
            while (true) {
                Thread {
                    while (true) LockSupport.park()
                }.start()
                threadCount++
            }
        } catch (_: OutOfMemoryError) {
            System.err.println("Platform thread limit reached: $threadCount")
        }
    }
}

</code></pre>
<p>This is not a test I would leave in a normal build.
It is intentionally trying to exhaust a resource, and the exact failure point depends on the machine, operating system limits, JVM settings, and other processes running at the same time.</p>
<p>The important point is that every platform thread needs an operating system thread underneath it.
That means the limit is not only about Java heap.
Native memory, per-thread stack size, process limits, and the operating system scheduler all matter.</p>
<h2>Spawning virtual threads</h2>
<p>The second test creates one million virtual threads.
Again, each thread parks itself immediately.</p>
<pre><code class="language-kotlin">import org.junit.jupiter.api.Test
import java.util.concurrent.locks.LockSupport

class VirtualThreadLimitTest {
    @Test
    fun `how many virtual threads can be created`() {
        val n = 1_000_000
        repeat(n) {
            Thread.startVirtualThread {
                while (true) LockSupport.park()
            }
        }
        val rt = Runtime.getRuntime()
        val usedMb = (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024)
        println("Mounted $n virtual threads, heap used: ${usedMb}MB")
    }
}
</code></pre>
<p>This is where virtual threads feel quite different.
There is no attempt here to create a million operating system threads.
Instead, the JVM creates a million lightweight <code>Thread</code> instances whose continuations can be mounted on a much smaller number of carrier platform threads when they need to run.</p>
<p>Because the threads are parked, most of them are not mounted on carrier threads most of the time.
That is exactly the kind of situation virtual threads are designed for: lots of concurrent tasks, many of which spend most of their lives waiting.</p>
<h2>Results</h2>
<p>On my MacBook Pro M4 with 48 GB RAM, I got the following results.</p>
<h3>Platform threads</h3>
<pre><code class="language-text">Platform thread limit reached: 12253
</code></pre>
<h3>Virtual threads</h3>
<pre><code class="language-text">Mounted 1000000 virtual threads, heap used: 581MB
</code></pre>
<h2>Result analysis</h2>
<p>The platform-thread test dies in the low thousands, around 12k on my machine.
The virtual-thread test manages to create one million parked virtual threads on a normal heap size.</p>
<p>That is a remarkable difference, but it is worth being precise about what this proves.
It proves that virtual threads have a much lower per-thread footprint when they are parked or blocked in a way the JVM can unmount.
It does not prove that a Spring Boot application can handle one million useful concurrent requests.</p>
<p>Real applications have other bottlenecks:</p>
<ol>
<li>Database connection pools.</li>
<li>HTTP client connection pools.</li>
<li>Downstream service limits.</li>
<li>CPU-bound work.</li>
<li>Memory used by request objects, responses, buffers, caches, and application state.</li>
<li>Rate limits, queues, and back-pressure policies.</li>
</ol>
<p>Virtual threads remove one very old bottleneck: the need to keep a large pool of expensive platform threads around just because requests might block.
They do not remove the need to size and protect the rest of the system.</p>
<p>The number of virtual threads you can create is mainly a memory question rather than an operating-system-thread question.
If you increase the heap with <code>-Xmx</code>, you can usually create more parked virtual threads.
If each virtual thread has a deeper stack or holds more request state, you will create fewer.</p>
<h2>Why this matters for Spring MVC</h2>
<p>Spring MVC traditionally uses a request-per-thread model.
That model is wonderfully simple: a request comes in, a thread handles it, and the code can be written in a direct blocking style.</p>
<p>The downside has always been scalability.
If a request spends time waiting for a database, a REST call, a message broker, or a filesystem operation, the platform thread is still occupied while it waits.
That is one of the reasons reactive programming with Spring WebFlux became attractive for high-concurrency I/O-heavy applications.</p>
<p>Virtual threads change that trade-off.
For many I/O-bound workloads, you can keep the straightforward blocking style of Spring MVC while allowing the JVM to park blocked work cheaply.
That does not make WebFlux obsolete.
Reactive programming is still a very good fit for streaming, back-pressure, and end-to-end reactive systems.
But virtual threads make the simple blocking model scale much further than it used to.</p>
<h2>Enabling virtual threads in Spring Boot</h2>
<p>Enabling virtual threads in Spring Boot is as simple as setting a property in your <code>application.properties</code> or <code>application.yaml</code> file:</p>
<pre><code class="language-properties">spring.threads.virtual.enabled=true
</code></pre>
<p>At least Java 21 is required for this to work.
Spring Boot's reference documentation also notes that the feature affects auto-configured task execution and scheduling.
When virtual threads are enabled, Boot uses virtual-thread-friendly executor and scheduler choices in places where its auto-configuration is responsible for creating them.</p>
<p>That means this property is not only about embedded Tomcat handling requests.
It can also affect pieces such as <code>@Async</code>, Spring MVC asynchronous request handling, blocking execution support in WebFlux, and scheduled task infrastructure depending on how the application is configured.</p>
<p>There is one small Spring Boot detail that is easy to miss.
Virtual threads are daemon threads.
If your application relies on scheduled work or other virtual-thread-based infrastructure to keep the JVM alive, you may need:</p>
<pre><code class="language-properties">spring.main.keep-alive=true
</code></pre>
<p>This is called out in the Spring Boot reference documentation and is worth knowing before enabling virtual threads in a service that mostly does background or scheduled work.</p>
<h2>Things to watch out for</h2>
<p>Virtual threads are very useful, but they are not magic performance dust.
I would pay attention to at least the following when enabling them in a Spring Boot application.</p>
<h3>Pinning</h3>
<p>A virtual thread can usually unmount from its carrier thread when it blocks.
There are cases where it cannot, which is known as pinning.
Historically, blocking while inside a <code>synchronized</code> block or native method could pin the virtual thread to its carrier.
If enough virtual threads are pinned for long periods, throughput can suffer because the carrier threads are no longer free to run other virtual threads.</p>
<p>The JDK has been improving this area, but it is still worth testing your own application.
The official Java documentation and Spring Boot reference both point to tools such as JDK Flight Recorder and <code>jcmd</code> for detecting pinned virtual threads.
Spring Boot's current reference documentation also strongly recommends Java 24 or later for the best virtual-thread experience, even though Java 21 is the minimum version required.</p>
<h3>Pool sizing still matters</h3>
<p>With platform threads, the web server thread pool often acted as an accidental concurrency limit.
Turning on virtual threads can remove or greatly raise that limit.
That is usually what you want, but it means other limits become more visible.</p>
<p>If your database pool has 20 connections, then allowing 20,000 requests to reach code that all needs a database connection will not make the database faster.
It may just move the waiting from the servlet thread pool to the connection pool.</p>
<p>For that reason, virtual threads often pair well with explicit bulkheads, timeouts, rate limits, and connection-pool sizing.</p>
<h3>CPU-bound work does not become cheaper</h3>
<p>Virtual threads are excellent when work blocks or waits.
They do not give the CPU more cores.
If the workload is mostly CPU-bound, creating more virtual threads can increase scheduling overhead without improving throughput.</p>
<p>For CPU-heavy work, the usual rules still apply: measure, use bounded parallelism, and size around the available processors.</p>
<h3>Be careful with ThreadLocal usage</h3>
<p>Virtual threads are still instances of <code>java.lang.Thread</code>, and they support <code>ThreadLocal</code>.
That is useful for compatibility with existing libraries.
However, virtual threads are intended to be numerous and short-lived, so using <code>ThreadLocal</code> as a cache for expensive resources is a bad fit.</p>
<p>Use normal Spring-managed beans, connection pools, and scoped context mechanisms where appropriate.
Do not treat a virtual thread as a long-lived worker thread with reusable state attached to it.</p>
<h2>Useful references</h2>
<p>These are the pages I would keep close by when experimenting with this in a Spring Boot application:</p>
<ol>
<li><a href="https://docs.spring.io/spring-boot/reference/features/spring-application.html#features.spring-application.virtual-threads">Spring Boot reference documentation: Virtual threads</a></li>
<li><a href="https://docs.spring.io/spring-boot/reference/features/task-execution-and-scheduling.html">Spring Boot reference documentation: Task execution and scheduling</a></li>
<li><a href="https://spring.io/guides/gs/rest-service/">Spring Guide: Building a RESTful Web Service</a></li>
<li><a href="https://spring.io/guides/gs/reactive-rest-service/">Spring Guide: Building a Reactive RESTful Web Service</a></li>
<li><a href="https://spring.io/blog/2022/10/11/embracing-virtual-threads">Spring blog: Embracing Virtual Threads</a></li>
<li><a href="https://openjdk.org/jeps/444">OpenJDK JEP 444: Virtual Threads</a></li>
<li><a href="https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html">Oracle Java documentation: Virtual Threads</a></li>
</ol>
<h2>Final thoughts</h2>
<p>For me, the experiment makes the appeal of virtual threads very concrete.
With platform threads, the JVM runs into a practical wall after a few thousand parked threads.
With virtual threads, a million parked tasks is not especially dramatic.</p>
<p>That difference matters for Spring Boot applications because so many business systems are mostly waiting: waiting for databases, waiting for downstream APIs, waiting for queues, waiting for storage.</p>
<p>Virtual threads let you keep the readable request-per-thread programming model while dramatically reducing the cost of waiting.
They are not a replacement for good system design, sensible limits, or performance testing.
But for many Spring MVC applications running on Java 21 or later, <code>spring.threads.virtual.enabled=true</code> is now one of the most interesting properties worth testing.</p>
]]></content:encoded></item><item><title><![CDATA[Configure a background coroutine for your Spring Boot application]]></title><description><![CDATA[Learn how to configure background coroutines in Kotlin using structured concurrency, dispatchers, and best practices for production apps.]]></description><link>https://blog.hbrown.dev/configure-a-background-coroutine-for-your-spring-boot-application</link><guid isPermaLink="true">https://blog.hbrown.dev/configure-a-background-coroutine-for-your-spring-boot-application</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[coroutines]]></category><category><![CDATA[Springboot]]></category><dc:creator><![CDATA[Henry Brown]]></dc:creator><pubDate>Fri, 01 May 2026 07:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a6df6b110d8ecdf29cfd44b/f1ea3aba-2206-4dcd-95ca-c8147d3c2b6b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sometimes you need to run work in the background of a Spring Boot application. This may be work that should not block the HTTP request that triggered it, or work that is started by a scheduled process, event listener, message consumer, or application service.</p>
<p>In Kotlin, coroutines make it straightforward to start asynchronous work. However, I prefer not to scatter calls to <code>CoroutineScope(...)</code> or <code>Dispatchers.IO</code>, (and definitely <em>NOT</em> <code>GlobalScope</code>) throughout an application. Instead, I like to define an explicit background coroutine configuration and inject it where it is needed.</p>
<p>This gives the application a named place for background execution, error handling, and shutdown behaviour.</p>
<pre><code class="language-kotlin">@Configuration
@OptIn(ExperimentalCoroutinesApi::class)
class CoroutineConfig : DisposableBean {

    private val backgroundExecutor: ExecutorService = Executors.newVirtualThreadPerTaskExecutor()
    private val backgroundDispatcher = backgroundExecutor.asCoroutineDispatcher()

    private val handler = CoroutineExceptionHandler { ctx, e -&gt;
        val correlationId = ctx[CorrelationIdContextElement]?.correlationId ?: NO_CORRELATION_ID
        log.error("&gt;&gt;&gt; Unhandled background coroutine error, correlationId=[$correlationId]", ctx, e)
    }

    @Bean
    @Qualifier(BACKGROUND_DISPATCHER_NAME)
    fun backgroundDispatcher(): CoroutineDispatcher = backgroundDispatcher

    @Bean
    @Qualifier(BACKGROUND_SCOPE_NAME)
    fun backgroundScope(): CoroutineScope {
        return CoroutineScope(SupervisorJob() + handler + backgroundDispatcher + CoroutineName(BACKGROUND_SCOPE_NAME))
    }

    override fun destroy() {
        backgroundDispatcher.close()
        backgroundExecutor.shutdown()
    }

    companion object {
        private val log = CoroutineLogger(LoggerFactory.getLogger(CoroutineConfig::class.java))
    }
}

const val BACKGROUND_DISPATCHER_NAME = "backgroundDispatcher"
const val BACKGROUND_SCOPE_NAME = "backgroundScope"
private const val NO_CORRELATION_ID = "&lt;no correlation id&gt;"
</code></pre>
<h2>Why define a background coroutine configuration?</h2>
<p>The main reason is ownership.</p>
<p>When a coroutine is launched, something should own its lifecycle. In a web application, the request normally owns request-scoped work. If the request is cancelled, times out, or completes, that work should usually stop with it.</p>
<p>Background work is different. It often needs to continue independently of the request that caused it. For example, an endpoint may accept a command, persist the initial state, and then trigger some follow-up processing in the background. That follow-up processing should not be tied to the HTTP connection staying open.</p>
<p>By exposing a dedicated <code>CoroutineScope</code> as a Spring bean, you make that decision explicit:</p>
<pre><code class="language-kotlin">@Bean
@Qualifier(BACKGROUND_SCOPE_NAME)
fun backgroundScope(): CoroutineScope {
    return CoroutineScope(SupervisorJob() + handler + backgroundDispatcher + CoroutineName(BACKGROUND_SCOPE_NAME))
}
</code></pre>
<p>Any class that needs to launch background work can inject this scope using the qualifier. That keeps the application honest about which work is request-bound and which work is intentionally detached.</p>
<h2>Why use a dedicated dispatcher?</h2>
<p>The configuration creates an <code>ExecutorService</code> and adapts it into a coroutine dispatcher:</p>
<pre><code class="language-kotlin">private val backgroundExecutor: ExecutorService = Executors.newVirtualThreadPerTaskExecutor()
private val backgroundDispatcher = backgroundExecutor.asCoroutineDispatcher()
</code></pre>
<p>In this case, the executor uses Java virtual threads. That makes the dispatcher a good fit for many typical application-level background jobs. Especially where the job may spend time waiting on blocking I/O such as database calls, HTTP calls, file operations, or SDK clients that are not coroutine-native.</p>
<p>The important point is not only that this uses virtual threads. The important point is that background work is not silently being pushed onto an unrelated dispatcher. It has a specific execution policy that can be named, tested, monitored, and changed later without hunting through the codebase.</p>
<p>For example, if you later decide that a particular application needs a bounded thread pool, a different executor, or more detailed instrumentation, the change can happen in this configuration class rather than at every call site.</p>
<h2>Why use a SupervisorJob?</h2>
<p>The scope uses a <code>SupervisorJob</code>:</p>
<pre><code class="language-kotlin">CoroutineScope(SupervisorJob() + handler + backgroundDispatcher + CoroutineName(BACKGROUND_SCOPE_NAME))
</code></pre>
<p>This is useful for background processing because one failing child coroutine should not necessarily cancel every other background task running in the same scope.</p>
<p>For example, if three independent notification jobs are launched and one fails because a downstream provider is unavailable, the other two should usually be allowed to continue. <code>SupervisorJob</code> gives you that isolation.</p>
<p>This does not mean failures are ignored. It means failures are contained. The exception handler is still important.</p>
<h2>Centralised exception handling</h2>
<p>Background work can fail after the original caller has already received a response. That means you cannot rely on normal request handling to surface errors.</p>
<p>This configuration adds a <code>CoroutineExceptionHandler</code>:</p>
<pre><code class="language-kotlin">private val handler = CoroutineExceptionHandler { ctx, e -&gt;
    val correlationId = ctx[CorrelationIdContextElement]?.correlationId ?: NO_CORRELATION_ID
    log.error("&gt;&gt;&gt; Unhandled background coroutine error, correlationId=[$correlationId]", ctx, e)
}
</code></pre>
<p>The useful part here is that the error handling is not an afterthought at each launch site. Unhandled background coroutine failures are logged in one place, and the log entry attempts to include a correlation id from the coroutine context.</p>
<p>That is especially valuable when the background job was triggered by a request, message, or scheduled process, and you want to connect the failure back to the original flow.</p>
<h2>Clean shutdown</h2>
<p>The configuration implements <code>DisposableBean</code>:</p>
<pre><code class="language-kotlin">override fun destroy() {
    backgroundDispatcher.close()
    backgroundExecutor.shutdown()
}
</code></pre>
<p>The dispatcher is backed by an executor, and the executor should be shut down when the Spring application context is closed. Without this, you risk leaving executor resources alive longer than intended during shutdown, tests, redeployments, or local development restarts.</p>
<h2>Typical use cases</h2>
<p>I would typically use a background dispatcher like this for work that is application-owned, asynchronous, and not part of the direct response path.</p>
<p>Some examples are:</p>
<ol>
<li><p>Sending email, SMS, push notifications, or webhooks after a command has been accepted.</p>
</li>
<li><p>Calling third-party APIs where the user does not need to wait for the result immediately.</p>
</li>
<li><p>Post-processing uploaded files, generated reports, images, or exported data.</p>
</li>
<li><p>Updating derived state, caches, search indexes, or read models after a write.</p>
</li>
<li><p>Running fan-out tasks where one action needs to trigger several independent downstream operations.</p>
</li>
<li><p>Starting work from a Spring event listener or scheduled job while keeping the coroutine execution policy consistent.</p>
</li>
<li><p>Running blocking I/O integrations from coroutine-based services without mixing that concern into every service method.</p>
</li>
</ol>
<p>The common theme is that the work should be visible as background work in the code. Injecting a specifically named scope or dispatcher makes that intent clear.</p>
<h2>How it might be used</h2>
<p>A service can inject the scope and launch work on it:</p>
<pre><code class="language-kotlin">@Service
class NotificationService(
    @Qualifier(BACKGROUND_SCOPE_NAME)
    private val backgroundScope: CoroutineScope,
) {

    fun sendWelcomeNotification(command: WelcomeNotificationCommand) {
        backgroundScope.launch {
            sendEmail(command)
            sendSms(command)
        }
    }
}
</code></pre>
<p>If the launched coroutine fails unexpectedly, the exception handler configured on the scope will log the failure. If multiple jobs are running in the same background scope, <code>SupervisorJob</code> prevents one failing job from cancelling the entire scope.</p>
<h2>When not to use it</h2>
<p>This configuration is not a replacement for every asynchronous processing pattern.</p>
<p>If the work must be durable, retryable, or guaranteed to run after the application restarts, then a queue, database-backed job table, workflow engine, or message broker is usually a better fit. A coroutine launched in memory is still in-memory work. If the process dies, that work is gone.</p>
<p>I would also avoid using this for request-bound concurrency. If the work is part of producing the HTTP response, prefer structured concurrency inside the suspend function handling the request. That way cancellation and error propagation remain tied to the request lifecycle.</p>
<p>For me, this configuration is the middle ground: useful for application-owned background work that should be explicit, observable, and cleaned up correctly, but does not need the durability guarantees of a full job processing system.</p>
]]></content:encoded></item></channel></rss>