Skip to content

Kotlin/Native CIO server occasionally closes an accepted connection with zero response bytes under CPU load #5922

Closed

Description

Summary

On Kotlin/Native, embeddedServer(CIO) occasionally closes an accepted connection without sending any response bytes. It only happens when the machine is CPU-starved. I have not seen it on the JVM, with the server replaced by a plain POSIX one, or without load. A plain blocking POSIX client (no Ktor client code) sees it, so it originates on the server side.

I could not find an existing issue for this. I have not identified the exact line; there are two unconfirmed candidates at the end.

Environment

  • Ktor 3.6.0 (the same behaviour with 3.5.2, so not a 3.6.0 regression)
  • Kotlin 2.4.0, kotlinx-coroutines 1.11.0
  • macOS 26.6 arm64 (Apple M3 Pro, 12 cores), Kotlin/Native macosArm64. This is the same posixMain/nixMain source of ktor-network that iOS compiles.
  • JVM control: OpenJDK 21

We first noticed it as a roughly 1-in-60 intermittent failure of a test suite that runs a CIO server and a CIO client on the iOS simulator in CI (ClosedReadChannelException: Failed to parse HTTP response: the server prematurely closed the connection). I have only reproduced it on macOS native, not on an iOS simulator or device.

Reproduction

Gist with the whole project (Gradle build, Kotlin sources, load script): https://gist.github.com/bnvinay92/6b53b5a2e648b89917b1f9853badc414

The server:

val server = embeddedServer(CIO, port = port, host = "127.0.0.1") {
    routing {
        get("/ping") { call.respondText("""{"ok":true}""", ContentType.Application.Json) }
    }
}
server.start(wait = false)
// ... requests ... then:
server.stop(100, 500)

One run starts 200 servers one after another (fresh port each) in a single process, and makes 8 requests to each, each on a fresh connection, with a plain blocking POSIX client (socket/connect/send/recv). That is 1,600 requests. A failure is a connection that reaches end-of-file with zero response bytes. Load is 36 yes >/dev/null processes on the 12-core machine (hammer.sh <runs> <busy-processes> [cio|posix]).

./gradlew linkReleaseExecutableMacosArm64
./hammer.sh 100 36

Results

Each run is 1,600 requests.

Server Client Load Runs Runs with a failure
Ktor 3.6.0 CIO, native plain POSIX 36 busy processes 100 6 (6 failed requests of 160,000)
Ktor 3.6.0 CIO, native plain POSIX none 40 0
plain POSIX (blocking sockets), native plain POSIX 36 busy processes 100 0 (160,000 requests)
Ktor 3.6.0 CIO, JVM java.net.Socket 36 busy processes 99 counted 0

Notes on the table:

  • An earlier build of the same program (before I added the POSIX-server and JVM variants) failed in 9 of 60 loaded runs.
  • The JVM program runs its 100 batches in one JVM; the summary line of the first one was lost to a log line, so 99 are counted. No failure line was printed in any of the 100.
  • "None" means no extra busy processes. The machine was not idle: other unrelated builds were running, and the 1-minute load average was about 19 before the run.
  • The sleep of 3 s between runs in hammer.sh is needed: without it the client runs out of ephemeral ports (TIME_WAIT), and the client reports connect failures, which is unrelated.

An earlier, larger harness (Ktor CIO client and server in one native process, 8 requests per server including chunked responses written with respondBytesWriter, same 36 busy processes) gave:

  • Ktor 3.6.0, client and server: 5 failures in 184 runs (294,400 requests)
  • Ktor 3.5.2, same test: 5 failures in 150 runs
  • plain POSIX client, Ktor CIO server: 1 failure in 100 runs (EOF with zero response bytes after 0.5 ms)
  • Ktor CIO client, plain POSIX server: 0 failures in 100 runs (160,000 requests)
  • no load: 0 failures in about 30 runs (48,000 requests)
  • JVM, same test: 0 failures in 12 loaded runs (19,200 requests; too few to say much)

What the failure looks like

With the Ktor CIO client the failure is io.ktor.utils.io.ClosedReadChannelException: Failed to parse HTTP response: the server prematurely closed the connection, 1.5 to 8 ms after the request was sent (so not a timeout).

In the larger harness I tagged each request with a header and recorded in a server plugin whether the application saw it and whether the ResponseSent hook fired. Eight instrumented failures showed three shapes:

  1. The server never saw the request (the application got no call): 4 of 8.
  2. The server reported the response as sent (ResponseSent fired), and the client still got zero bytes: 3 of 8 (a POST, a 400 response and a chunked response).
  3. The handler was running when its write failed with ChannelWriteException: Cannot write to channel, so the server's socket output was already closed: 1 of 8.

One mechanism that fits all three is "the accepted socket is torn down from underneath a live request".

Candidate areas (not confirmed, not tested)

I read the 3.6.0 sources of ktor-network for native and found these. I did not rebuild ktor-network to test them.

  1. posixMain/.../CIOReader.kt (attachForReadingImpl): the catch (_: IOException) { break } around selector.select(selectable, SelectInterest.READ) is followed by channel.flushAndClose() in finally. Any IOException from the selector (Selector closed, Selectable closed, Bad descriptor N, Fail to select descriptor N, all raised in nixMain/.../SelectUtilsNix.kt) would therefore look like a clean end-of-file to the reader, which is what the peer sees.
  2. The same finally block calls ktor_shutdown(descriptor, ShutdownCommands.Receive), and CIOWriter.kt calls ktor_shutdown(descriptor, ShutdownCommands.Send) from invokeOnCompletion, both with the raw descriptor number. NativeSocketImpl.actualClose() hands the descriptor to the selector manager to close. If a pump finishes after the descriptor was closed and the number was reused by a newer connection, the shutdown would hit the new connection, which would give a zero-byte end-of-file on it. The repro opens and closes hundreds of sockets per second, so reuse is certain; whether the ordering race exists is not shown.

What is not identified

The exact line or sequence that closes the connection. I also do not know whether the iOS CI failures are this same mechanism (same symptom, same load dependence and a similar rate, but not shown to be the same).

Activity

  1. added 3 commits that reference this issue on Oct 26, 2026
    ba44b74
    8e2f5ac
    fa18e80
  2. added a commit that references this issue on Oct 28, 2026
    dbc9692
  3. ktor-service commented on Oct 28, 2026

    @ktor-service
    Contributor

    The YouTrack ticket KTOR-9969 was closed as Fixed.

  4. added a commit that references this issue on Nov 10, 2026
    e67a549
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions