perf(rds): run proxy relays on platform threads and buffer the IAM relay input (#7401)

Every request and every response wakes a relay thread blocked on a socket
read. On a virtual thread that wakeup goes through the JDK poller and a
carrier handoff, which made the relay itself cost about 0.13 ms per
roundtrip in one Docker network (0.063 ms direct, 0.198 ms through the
proxy). The relay loops of the PostgreSQL, MySQL and opaque TCP bridges now
run on daemon platform threads; the accept loop and the handshake stay
virtual.

The IAM session guard read each backend message's type, length and payload
straight from the socket, plus an available() call per message. Its input
is now buffered, and the flush-on-pause check asks the socket only once the
buffer is drained.

A MySQL or MariaDB client that disconnects without COM_QUIT ended the
client-to-backend relay but left the backend-to-client relay blocked on a
backend that never speaks, and bridge() waited for both before closing
either socket. Close both sockets as soon as either relay ends, as the
PostgreSQL bridge already does, so a dropped client no longer holds a relay
thread and a backend connection open.
This commit is contained in:
PiotrDuz authored and GitHub committed 2026-11-04 14:15:20 -04:00
1 parent 31451dfff3
commit 57a961fdb8
9 files changed
+311 -13

No files matched your search

@@ -12,6 +12,7 @@ import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -879,10 +880,29 @@ public class MySqlProtocolHandler {
return;
}
Thread t1 = Thread.ofVirtual().name("rds-mysql-c2b")
.start(() -> relayClientCommands(clientIn, backendOut));
Thread t2 = Thread.ofVirtual().name("rds-mysql-b2c")
.start(() -> relay(backendIn, clientOut));
// Either side going away ends the session: a client that drops without COM_QUIT would
// otherwise leave the backend-to-client relay blocked on a backend that never speaks.
AtomicBoolean closed = new AtomicBoolean();
Runnable closeBoth = () -> {
if (closed.compareAndSet(false, true)) {
closeQuietly(client);
closeQuietly(backend);
}
};
Thread t1 = RelayThreads.start("rds-mysql-c2b", () -> {
try {
relayClientCommands(clientIn, backendOut);
} finally {
closeBoth.run();
}
});
Thread t2 = RelayThreads.start("rds-mysql-b2c", () -> {
try {
relay(backendIn, clientOut);
} finally {
closeBoth.run();
}
});
try {
t1.join();
t2.join();
@@ -1562,10 +1562,9 @@ public class PostgresProtocolHandler {
closeQuietly(backend);
}
};
Thread t1 = Thread.ofVirtual().name("rds-pg-c2b")
.start(() -> relay(clientIn, backendOut, closeBoth));
Thread t2 = Thread.ofVirtual().name("rds-pg-b2c")
.start(() -> relayToClient(backendIn, clientOut, session.iamRole(), closeBoth));
Thread t1 = RelayThreads.start("rds-pg-c2b", () -> relay(clientIn, backendOut, closeBoth));
Thread t2 = RelayThreads.start("rds-pg-b2c",
() -> relayToClient(backendIn, clientOut, session.iamRole(), closeBoth));
try {
t1.join();
t2.join();
@@ -1585,7 +1584,7 @@ public class PostgresProtocolHandler {
}
BufferedOutputStream buffered = new BufferedOutputStream(to, 8192);
try {
relayGuardingSessionRole(from, buffered, iamRole);
relayGuardingSessionRole(new RelayInputStream(from), buffered, iamRole);
} catch (IOException e) {
// Either side closing mid-relay is the normal way a session ends, so this stays at
// debug: it is one line per connection teardown, not per message.
@@ -1605,7 +1604,7 @@ public class PostgresProtocolHandler {
* Copies framed backend messages, stopping the session if PostgreSQL ever reports a
* {@code session_authorization} other than {@code iamRole}.
*/
private static void relayGuardingSessionRole(InputStream from, OutputStream to, String iamRole)
private static void relayGuardingSessionRole(RelayInputStream from, OutputStream to, String iamRole)
throws IOException {
byte[] buf = new byte[8192];
while (true) {
@@ -1652,7 +1651,7 @@ public class PostgresProtocolHandler {
}
// Batch while the backend keeps talking, flush as soon as it pauses.
if (from.available() == 0) {
if (from.isDrained()) {
to.flush();
}
}
@@ -0,0 +1,26 @@
package io.github.hectorvent.floci.services.rds.proxy;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Buffers a relay's socket input, so a relay that reads message by message (type byte, length,
* payload) costs one socket read per segment rather than three or more per message.
*/
final class RelayInputStream extends BufferedInputStream {
private static final int BUFFER_SIZE = 64 * 1024;
RelayInputStream(InputStream socketInput) {
super(socketInput, BUFFER_SIZE);
}
/**
* Whether the peer has paused: nothing buffered and nothing readable on the socket. Asks the
* socket only once the buffer is drained, i.e. once per segment, not once per message.
*/
boolean isDrained() throws IOException {
return pos >= count && in.available() == 0;
}
}
@@ -0,0 +1,23 @@
package io.github.hectorvent.floci.services.rds.proxy;
/**
* Starts the threads that copy a database session's bytes between client and backend.
*
* <p>They are platform threads on purpose. A relay thread blocks on a socket read between every
* request and every response, so the latency of waking it up is paid twice per round trip. A
* virtual thread parked on a socket is woken by the poller and then has to be scheduled on a
* carrier thread; a platform thread is woken by the kernel directly. Measured with an otherwise
* identical 8 KiB copy loop between pgbench and PostgreSQL in one Docker network: 0.198 ms per
* {@code SELECT 1} on virtual threads, 0.113 ms on platform threads, 0.063 ms without a relay.
* The accept loop and the per-connection handshake stay on virtual threads: they run once per
* connection, not once per message.
*/
final class RelayThreads {
private RelayThreads() {
}
static Thread start(String name, Runnable relay) {
return Thread.ofPlatform().daemon().name(name).start(relay);
}
}
@@ -18,8 +18,8 @@ final class TcpStreamBridge {
static void relay(Socket client, Socket backend) {
CountDownLatch directions = new CountDownLatch(2);
Thread.ofVirtual().start(() -> copy(client, backend, directions));
Thread.ofVirtual().start(() -> copy(backend, client, directions));
RelayThreads.start("rds-tcp-c2b", () -> copy(client, backend, directions));
RelayThreads.start("rds-tcp-b2c", () -> copy(backend, client, directions));
try {
directions.await();
} catch (InterruptedException e) {
@@ -130,6 +130,66 @@ class MySqlProtocolHandlerTest {
assertEquals("admin", extractUsername(backendResponsePayload.get()));
}
@Test
void closesTheBackendWhenTheClientDropsWithoutQuitting() throws Exception {
byte[] nonce = fixedNonce();
AtomicReference<Integer> backendReadAfterDrop = new AtomicReference<>();
try (ServerSocket backendServer = new ServerSocket(0);
ServerSocket clientServer = new ServerSocket(0)) {
Thread backendThread = Thread.ofVirtual().start(() -> {
try (Socket socket = backendServer.accept()) {
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
out.write(buildHandshakeV10(nonce));
out.flush();
readMysqlPacketRaw(in);
writeMysqlPacket(out, 2, OK_PAYLOAD);
out.flush();
// Stays connected and silent, as an idle MySQL server does.
socket.setSoTimeout(5_000);
backendReadAfterDrop.set(in.read());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
Socket proxyClient;
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
proxyClient = clientServer.accept();
Socket backend = new Socket("localhost", backendServer.getLocalPort());
Thread authThread = Thread.ofVirtual().start(() -> {
try {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, NO_RECONNECT, "admin", "secret",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000,
username -> true, testBinding());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
InputStream clientIn = ourClient.getInputStream();
OutputStream clientOut = ourClient.getOutputStream();
assertNotNull(readMysqlPacketRaw(clientIn));
clientOut.write(buildHandshakeResponse41("admin", scrambleNativePassword("secret", nonce), (byte) 1));
clientOut.flush();
assertNotNull(readMysqlPacketRaw(clientIn));
// No COM_QUIT: the client just goes away.
ourClient.close();
joinAll(backendThread, authThread);
}
assertTrue(proxyClient.isClosed(), "the proxy must close its side of the dropped client");
}
assertEquals(-1, backendReadAfterDrop.get(), "the proxy must close the backend once the client drops");
}
@Test
void validatesCachingSha2MasterScrambleAndForwardsResponse() throws Exception {
byte[] nonce = fixedNonce();
@@ -1455,6 +1455,81 @@ class PostgresProtocolHandlerTest {
}
}
@Test
void iamSessionIsTerminatedWhenAnotherSessionRoleFollowsABurstOfRows() throws Exception {
int rows = 2_000;
try (ServerSocket backendServer = new ServerSocket(0);
ServerSocket clientServer = new ServerSocket(0)) {
int backendPort = backendServer.getLocalPort();
Thread backendThread = Thread.ofVirtual().start(() -> {
try {
mockBackendRoleSwitch(backendServer, new AtomicReference<>(),
new AtomicReference<>(), "approle", true, (in, out) -> {
answerRoleAdmission(in, out, "approle", true, true);
readSimpleQuery(in);
// One write, so the rows and the role switch reach the relay
// together and are parsed out of its buffer, not off the socket.
ByteArrayOutputStream burst = new ByteArrayOutputStream();
DataOutputStream burstOut = new DataOutputStream(burst);
for (int i = 0; i < rows; i++) {
writeDataRow(burstOut, Integer.toString(i));
}
writeCommandComplete(burstOut, "SELECT " + rows);
writeParameterStatus(burstOut, "session_authorization", "masteruser");
writeParameterStatus(burstOut, "is_superuser", "on");
writeCommandComplete(burstOut, "RESET");
writeReadyForQuery(burstOut);
burst.writeTo(out);
out.flush();
});
} catch (IOException e) {
throw new RuntimeException(e);
}
});
Socket proxyClient;
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
ourClient.setSoTimeout(5_000);
proxyClient = clientServer.accept();
Socket backend = new Socket("localhost", backendPort);
Thread authThread = startIamAuth(proxyClient, backend);
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
writeStartup(clientOut, "approle", "postgres");
readCleartextPasswordChallenge(clientIn);
writePassword(clientOut, rdsToken("approle"));
readAuthenticationOk(clientIn);
readParametersUntilReadyForQuery(clientIn);
writeSimpleQuery(clientOut, "SELECT g FROM generate_series(0, 1999) g; RESET SESSION AUTHORIZATION");
for (int i = 0; i < rows; i++) {
assertEquals('D', clientIn.readByte(), "row " + i + " must arrive whole and in order");
byte[] row = clientIn.readNBytes(clientIn.readInt() - 4);
String value = Integer.toString(i);
assertEquals(value, new String(row, row.length - value.length(), value.length(),
StandardCharsets.UTF_8));
}
assertEquals('C', clientIn.readByte());
clientIn.readNBytes(clientIn.readInt() - 4);
Map<Character, String> error = readErrorResponse(clientIn);
assertEquals("FATAL", error.get('S'));
assertEquals("42501", error.get('C'));
assertEquals("permission denied to set session authorization", error.get('M'));
assertEquals(-1, clientIn.read(), "session must be closed, not handed back as master");
authThread.join(5_000);
backendThread.join(5_000);
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
}
}
}
@Test
void nonIamSessionRelaysSessionAuthorizationChanges() throws Exception {
try (ServerSocket backendServer = new ServerSocket(0);
@@ -0,0 +1,70 @@
package io.github.hectorvent.floci.services.rds.proxy;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RelayInputStreamTest {
@Test
void isNotDrainedWhileBytesRemainInTheBuffer() throws IOException {
SegmentedInput socket = new SegmentedInput(new byte[] {1, 2, 3}, Integer.MAX_VALUE);
RelayInputStream relay = new RelayInputStream(socket);
assertEquals(1, relay.read());
socket.availableCalls.set(0);
assertFalse(relay.isDrained());
assertEquals(0, socket.availableCalls.get(), "a non-empty buffer must not ask the socket");
}
@Test
void isDrainedOnceTheBufferIsEmptyAndTheSocketHasNothingReadable() throws IOException {
RelayInputStream relay = new RelayInputStream(new SegmentedInput(new byte[] {1, 2, 3}, Integer.MAX_VALUE));
assertArrayEquals(new byte[] {1, 2, 3}, relay.readNBytes(3));
assertTrue(relay.isDrained());
}
@Test
void isNotDrainedWhenTheSocketHasMoreToRead() throws IOException {
SegmentedInput socket = new SegmentedInput(new byte[] {1, 2, 3}, 1);
RelayInputStream relay = new RelayInputStream(socket);
assertEquals(1, relay.read());
assertFalse(relay.isDrained());
assertEquals(1, socket.availableCalls.get());
}
/** Hands out at most {@code segment} bytes per read, as a socket hands out one segment. */
private static final class SegmentedInput extends ByteArrayInputStream {
private final int segment;
final AtomicInteger availableCalls = new AtomicInteger();
SegmentedInput(byte[] bytes, int segment) {
super(bytes);
this.segment = segment;
}
@Override
public synchronized int read(byte[] b, int off, int len) {
return super.read(b, off, Math.min(len, segment));
}
@Override
public synchronized int available() {
availableCalls.incrementAndGet();
return super.available();
}
}
}
@@ -0,0 +1,25 @@
package io.github.hectorvent.floci.services.rds.proxy;
import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RelayThreadsTest {
@Test
void relaysRunOnNamedDaemonPlatformThreads() throws InterruptedException {
AtomicReference<Thread> ran = new AtomicReference<>();
Thread relay = RelayThreads.start("rds-test-relay", () -> ran.set(Thread.currentThread()));
relay.join(5_000);
assertEquals(relay, ran.get());
assertFalse(relay.isVirtual(), "a relay woken per message must not pay the virtual-thread wakeup");
assertTrue(relay.isDaemon(), "a relay must not keep the JVM alive");
assertEquals("rds-test-relay", relay.getName());
}
}