fix(core): bind the DB proxies and EC2 port forwards with a 4096 backlog (#6744)

This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-29 00:20:54 -04:00
1 parent de2e5192b2
commit 1356cbbc84
12 files changed
+183 -22

No files matched your search

@@ -0,0 +1,50 @@
package io.github.hectorvent.floci.core.common;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
/**
* The accept backlog Floci's data-plane TCP listeners bind with.
*
* <p>A plain {@code ServerSocket} listens with a backlog of 50, socat with 5. A burst of
* connections (a pool refilling, a service fanning out) overflows an accept queue that
* small before the listener can drain it, and the kernel then silently drops the
* handshake's final ACK: the client believes it is connected, sends its first message and
* waits on retransmits, about a second for one drop, tens of seconds when the drops repeat,
* and a reset or a hang for a connection dropped half-open.
*
* <p>The kernel caps the backlog at {@code net.core.somaxconn}, so a value beyond what the
* host allows clamps the queue rather than failing the bind. The RDS, Redshift, ElastiCache
* (with MemoryDB) and Neptune auth proxies pass this to their {@code ServerSocket} bind, and
* the EC2 port-forward socat to its {@code backlog=} option.
*/
public final class ListenBacklog {
/** The accept backlog of the database auth proxies and the EC2 port-forward socat. */
public static final int ACCEPT = 4096;
/**
* Binds the accept socket for one of Floci's data-plane listeners: reuse-address on, a
* bind at the given port with the given backlog, and the socket closed when the bind
* fails so a caller's retry cannot leak one socket per attempt.
*/
public static ServerSocket acceptSocket(int port, int backlog) throws IOException {
ServerSocket socket = new ServerSocket();
try {
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(port), backlog);
return socket;
} catch (IOException e) {
try {
socket.close();
} catch (IOException ignored) {
// the socket was never bound, so nothing could have been listening on it
}
throw e;
}
}
private ListenBacklog() {
}
}
@@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.ContainerNetwork;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ListenBacklog;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
@@ -41,6 +42,10 @@ import java.util.function.Consumer;
* with delayed ACK stretches that to roughly 40 ms on the Docker network, so a request the
* client sends as two writes pays a visible stall on every round trip.
*
* <p>The listen address also sets {@code backlog} to {@link ListenBacklog#ACCEPT}, since
* socat's default accept queue of 5 silently drops the final ACK of a burst's overflow
* connections, which the client then pays for in retransmit stalls or a reset.
*
* <p>Because each forward is a fresh container, ports opened <em>after</em> launch via
* {@code authorize-security-group-ingress} are handled the same way as ports present at
* launch. The instance container itself is never modified.
@@ -211,7 +216,7 @@ public class Ec2PortForwardManager {
.withName(name)
.withEntrypoint(List.of("socat"))
.withCmd(List.of(
"TCP-LISTEN:" + appPort + ",fork,reuseaddr,nodelay",
"TCP-LISTEN:" + appPort + ",fork,reuseaddr,nodelay,backlog=" + ListenBacklog.ACCEPT,
"TCP:" + target.ip() + ":" + appPort + ",nodelay"))
.withPortBinding(appPort, hostPort)
.withLogRotation();
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.core.common.ListenBacklog;
import org.jboss.logging.Logger;
import java.io.IOException;
@@ -118,13 +119,21 @@ public abstract class AbstractRedisAuthProxy {
}
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket(proxyPort);
serverSocket = listenSocket(proxyPort, ListenBacklog.ACCEPT);
running = true;
Thread.ofVirtual().name(threadPrefix + "-proxy-accept-" + resourceId).start(this::acceptLoop);
log.infov("{0} proxy started for {1} on port {2} → {3}:{4}",
serviceName, resourceId, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
}
/**
* Opens the listening socket. A seam so a test can pin the accept backlog: a bound
* {@code ServerSocket} does not report the backlog it was created with.
*/
ServerSocket listenSocket(int proxyPort, int backlog) throws IOException {
return new ServerSocket(proxyPort, backlog);
}
int localPort() {
return serverSocket.getLocalPort();
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.neptune.proxy;
import io.github.hectorvent.floci.core.common.ListenBacklog;
import org.jboss.logging.Logger;
import java.io.IOException;
@@ -37,13 +38,21 @@ public class NeptuneGremlinProxy {
}
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket(proxyPort);
serverSocket = listenSocket(proxyPort, ListenBacklog.ACCEPT);
running = true;
Thread.ofVirtual().name("neptune-proxy-accept-" + clusterId).start(this::acceptLoop);
LOG.infov("Neptune Gremlin proxy started for cluster {0} on port {1} → {2}:{3}",
clusterId, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
}
/**
* Opens the listening socket. A seam so a test can pin the accept backlog: a bound
* {@code ServerSocket} does not report the backlog it was created with.
*/
ServerSocket listenSocket(int proxyPort, int backlog) throws IOException {
return new ServerSocket(proxyPort, backlog);
}
public void stop() {
running = false;
try {
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.rds.proxy;
import io.github.hectorvent.floci.core.common.ListenBacklog;
import io.github.hectorvent.floci.services.rds.container.RdsBackendGate;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import org.jboss.logging.Logger;
@@ -148,9 +149,7 @@ public class RdsAuthProxy {
}
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(proxyPort));
serverSocket = listenSocket(proxyPort, ListenBacklog.ACCEPT);
running = true;
acceptThread = Thread.ofVirtual().name("rds-proxy-accept-" + instanceId).unstarted(this::acceptLoop);
acceptThread.start();
@@ -158,6 +157,14 @@ public class RdsAuthProxy {
instanceId, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
}
/**
* Binds the listening socket. A seam so a test can pin the accept backlog: a bound
* {@code ServerSocket} does not report the backlog it was created with.
*/
ServerSocket listenSocket(int proxyPort, int backlog) throws IOException {
return ListenBacklog.acceptSocket(proxyPort, backlog);
}
/** Swap the master-password snapshot after a rotation; new connections authenticate against it. */
public void updateMasterPassword(String newPassword) {
this.masterPassword = newPassword;
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.ListenBacklog;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.PostgresProtocolHandler;
@@ -154,17 +155,10 @@ public class RedshiftAuthProxy {
private ServerSocket bindListener(int proxyPort) throws IOException {
BindException lastFailure = null;
for (int attempt = 0; attempt < 40; attempt++) {
ServerSocket socket = new ServerSocket();
try {
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(proxyPort));
return socket;
return listenSocket(proxyPort, ListenBacklog.ACCEPT);
} catch (BindException e) {
closeQuietly(socket);
lastFailure = e;
} catch (IOException e) {
closeQuietly(socket);
throw e;
}
try {
Thread.sleep(25);
@@ -176,6 +170,14 @@ public class RedshiftAuthProxy {
throw lastFailure;
}
/**
* Binds one listener attempt. A seam so a test can pin the accept backlog: a bound
* {@code ServerSocket} does not report the backlog it was created with.
*/
ServerSocket listenSocket(int proxyPort, int backlog) throws IOException {
return ListenBacklog.acceptSocket(proxyPort, backlog);
}
private static void closeQuietly(ServerSocket s) {
try {
s.close();
@@ -242,7 +242,7 @@ class Ec2PortForwardManagerTest {
}
@Test
void publishedForwardDisablesNagleOnBothSocatSockets() {
void publishedForwardDisablesNagleAndBindsABurstTolerantAcceptBacklog() {
DockerClient dockerClient = mock(DockerClient.class);
when(dockerClient.inspectContainerCmd(anyString())).thenThrow(new RuntimeException("docker down"));
PortAllocator portAllocator = mock(PortAllocator.class);
@@ -274,8 +274,8 @@ class Ec2PortForwardManagerTest {
verify(lifecycleManager).create(spec.capture());
assertEquals("alpine/socat", spec.getValue().image());
assertEquals(List.of("socat"), spec.getValue().entrypoint());
assertEquals(List.of("TCP-LISTEN:80,fork,reuseaddr,nodelay", "TCP:172.17.0.3:80,nodelay"),
spec.getValue().cmd());
assertEquals(List.of("TCP-LISTEN:80,fork,reuseaddr,nodelay,backlog=4096",
"TCP:172.17.0.3:80,nodelay"), spec.getValue().cmd());
assertEquals(Map.of(80, 30000), spec.getValue().portBindings());
}
@@ -7,6 +7,7 @@ import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -125,7 +126,26 @@ class AbstractRedisAuthProxyRelayTest {
}
}
private static final class TestProxy extends AbstractRedisAuthProxy {
@Test
void bindsWithABurstTolerantAcceptBacklog() throws Exception {
AtomicInteger acceptBacklog = new AtomicInteger();
TestProxy proxy = new TestProxy("127.0.0.1", 1) {
@Override
ServerSocket listenSocket(int proxyPort, int backlog) throws IOException {
acceptBacklog.set(backlog);
return super.listenSocket(proxyPort, backlog);
}
};
proxy.start(0);
try {
assertEquals(4096, acceptBacklog.get(),
"a connection burst must not overflow the proxy's accept queue");
} finally {
proxy.stop();
}
}
private static class TestProxy extends AbstractRedisAuthProxy {
private TestProxy(String backendHost, int backendPort) {
super(org.jboss.logging.Logger.getLogger(TestProxy.class), "test", "test", "relay",
backendHost, backendPort);
@@ -2,9 +2,11 @@ package io.github.hectorvent.floci.services.neptune.proxy;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -126,4 +128,23 @@ class NeptuneGremlinProxyRelayTest {
}
}
}
@Test
void bindsWithABurstTolerantAcceptBacklog() throws Exception {
AtomicInteger acceptBacklog = new AtomicInteger();
NeptuneGremlinProxy proxy = new NeptuneGremlinProxy("cluster", "127.0.0.1", 1) {
@Override
ServerSocket listenSocket(int proxyPort, int backlog) throws IOException {
acceptBacklog.set(backlog);
return super.listenSocket(proxyPort, backlog);
}
};
proxy.start(0);
try {
assertEquals(4096, acceptBacklog.get(),
"a connection burst must not overflow the proxy's accept queue");
} finally {
proxy.stop();
}
}
}
@@ -18,6 +18,7 @@ import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -26,9 +27,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
* Covers the connection bounds (handshake timeout, backend-connect deferral, permit pool) added
* to {@link RdsAuthProxy} for the POSTGRES engine, mirroring the equivalent coverage in
* {@code RedshiftAuthProxyTest}.
* Covers the connection bounds (handshake timeout, backend-connect deferral, permit pool,
* accept backlog) added to {@link RdsAuthProxy} for the POSTGRES engine, mirroring the
* equivalent coverage in {@code RedshiftAuthProxyTest}.
*/
class RdsAuthProxyBoundsTest {
@@ -146,6 +147,24 @@ class RdsAuthProxyBoundsTest {
assertTrue(released.await(5, TimeUnit.SECONDS), "the lease is released when the connection ends");
}
@Test
void bindsWithABurstTolerantAcceptBacklog() throws Exception {
AtomicInteger acceptBacklog = new AtomicInteger();
proxy = new RdsAuthProxy("db-1", "localhost", 1, "runtime:db-1",
DatabaseEngine.POSTGRES, false, "admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
5000, 5000, 100) {
@Override
ServerSocket listenSocket(int proxyPort, int backlog) throws IOException {
acceptBacklog.set(backlog);
return super.listenSocket(proxyPort, backlog);
}
};
proxy.start(0);
assertEquals(4096, acceptBacklog.get(),
"a connection burst must not overflow the proxy's accept queue");
}
private RdsAuthProxy newProxy(int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections) {
return newProxy("runtime:db-1", handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections);
@@ -29,6 +29,7 @@ import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -306,6 +307,24 @@ class RedshiftAuthProxyTest {
assertEquals("rotated", f.get(proxy));
}
@Test
void bindsWithABurstTolerantAcceptBacklog() throws Exception {
AtomicInteger acceptBacklog = new AtomicInteger();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", 1,
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.REJECT,
mock(S3Service.class), mock(IamService.class), 5000, 5000, 100) {
@Override
ServerSocket listenSocket(int proxyPort, int backlog) throws IOException {
acceptBacklog.set(backlog);
return super.listenSocket(proxyPort, backlog);
}
};
proxy.start(0);
assertEquals(4096, acceptBacklog.get(),
"a connection burst must not overflow the proxy's accept queue");
}
private RdsProxyTlsCertificates realTls() {
return new RdsProxyTlsCertificates(FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")),
new CertificateGenerator());