Repository navigation
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 sameposixMain/nixMainsource ofktor-networkthat 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.shis 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 bytesafter 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:
- The server never saw the request (the application got no call): 4 of 8.
- The server reported the response as sent (
ResponseSentfired), and the client still got zero bytes: 3 of 8 (aPOST, a 400 response and a chunked response). - 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.
posixMain/.../CIOReader.kt(attachForReadingImpl): thecatch (_: IOException) { break }aroundselector.select(selectable, SelectInterest.READ)is followed bychannel.flushAndClose()infinally. AnyIOExceptionfrom the selector (Selector closed,Selectable closed,Bad descriptor N,Fail to select descriptor N, all raised innixMain/.../SelectUtilsNix.kt) would therefore look like a clean end-of-file to the reader, which is what the peer sees.- The same
finallyblock callsktor_shutdown(descriptor, ShutdownCommands.Receive), andCIOWriter.ktcallsktor_shutdown(descriptor, ShutdownCommands.Send)frominvokeOnCompletion, 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
KTOR-9969 Shut down native socket output inside the writer coroutine
KTOR-9969 Shut down native socket output inside the writer coroutine
KTOR-9969 Shut down native socket output inside the writer coroutine
KTOR-9969 Shut down native socket output inside the writer coroutine
ktor-service commentedon Oct 28, 2026
The YouTrack ticket KTOR-9969 was closed as Fixed.
chore: Merge release to main (#5992)