Skip to content

feat: add jitter to max lifetime in connection pool #1496

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,21 @@
import io.vertx.tests.sqlclient.ProxyServer;
import org.junit.Rule;
import org.junit.Test;
import org.testcontainers.shaded.com.trilead.ssh2.ConnectionInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collector;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
Expand Down Expand Up @@ -619,4 +623,63 @@ public void testConnectionClosedInHook(TestContext ctx) {
}));
}));
}

@Test
@Repeat(2)
public void testConnectionJitter(TestContext ctx) {
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(1)
.setMaxLifetime(3000)
.setMaxLifetimeUnit(TimeUnit.MILLISECONDS)
.setJitter(1)
.setJitterUnit(TimeUnit.SECONDS)
.setPoolCleanerPeriod(50);

Pool pool = createPool(options, poolOptions);
Async latch = ctx.async();

List<Integer> pids = Collections.synchronizedList(new ArrayList<>());
List<Long> times = Collections.synchronizedList(new ArrayList<>());
AtomicInteger lastPid = new AtomicInteger(-1);
AtomicLong timerId = new AtomicLong();

Consumer<TestContext> checkPid = testCtx -> {
pool.query("SELECT pg_backend_pid() as pid")
.execute()
.onComplete(testCtx.asyncAssertSuccess(rs -> {
int currentPid = rs.iterator().next().getInteger("pid");
if (lastPid.get() != currentPid) {
pids.add(currentPid);
times.add(System.currentTimeMillis());
lastPid.set(currentPid);

if (pids.size() == 3) {
vertx.cancelTimer(timerId.get());
long diff1to2 = times.get(1) - times.get(0);
long diff2to3 = times.get(2) - times.get(1);

// Verify time ranges
int maxLifetime = 3000;
int jitter = 1000;
int buffer = 100;
int lowerBound = maxLifetime - jitter + buffer;
int upperBound = maxLifetime + jitter + buffer;

ctx.assertTrue(diff1to2 >= lowerBound && diff1to2 <= upperBound,
String.format("Time between PIDs %d->%d (%dms) should be between %dms and %dms",
pids.get(0), pids.get(1), diff1to2, lowerBound, upperBound));

ctx.assertTrue(diff2to3 >= lowerBound && diff2to3 <= upperBound,
String.format("Time between PIDs %d->%d (%dms) should be between %dms and %dms",
pids.get(1), pids.get(2), diff2to3, lowerBound, upperBound));

pool.close().onComplete(ctx.asyncAssertSuccess(v -> latch.complete()));
}
}
}));
};

timerId.set(vertx.setPeriodic(30, id -> checkPid.accept(ctx)));
latch.awaitSuccess(20000);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@ static void fromJson(Iterable<java.util.Map.Entry<String, Object>> json, PoolOpt
obj.setMaxLifetime(((Number)member.getValue()).intValue());
}
break;
case "jitter":
if (member.getValue() instanceof Number) {
obj.setJitter(((Number)member.getValue()).intValue());
}
break;
case "jitterUnit":
if (member.getValue() instanceof String) {
obj.setJitterUnit(java.util.concurrent.TimeUnit.valueOf((String)member.getValue()));
}
break;
case "poolCleanerPeriod":
if (member.getValue() instanceof Number) {
obj.setPoolCleanerPeriod(((Number)member.getValue()).intValue());
Expand Down Expand Up @@ -93,6 +103,10 @@ static void toJson(PoolOptions obj, java.util.Map<String, Object> json) {
json.put("maxLifetimeUnit", obj.getMaxLifetimeUnit().name());
}
json.put("maxLifetime", obj.getMaxLifetime());
json.put("jitter", obj.getJitter());
if (obj.getJitterUnit() != null) {
json.put("jitterUnit", obj.getJitterUnit().name());
}
json.put("poolCleanerPeriod", obj.getPoolCleanerPeriod());
if (obj.getConnectionTimeoutUnit() != null) {
json.put("connectionTimeoutUnit", obj.getConnectionTimeoutUnit().name());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ public class PoolOptions {
*/
public static final int DEFAULT_EVENT_LOOP_SIZE = 0;

/**
* Default jitter value = 0
*/
public static final int DEFAULT_JITTER = 0;

/**
* Default jitter unit = milliseconds
*/
public static final TimeUnit DEFAULT_JITTER_UNIT = TimeUnit.SECONDS;

private int maxSize = DEFAULT_MAX_SIZE;
private int maxWaitQueueSize = DEFAULT_MAX_WAIT_QUEUE_SIZE;
private int idleTimeout = DEFAULT_IDLE_TIMEOUT;
Expand All @@ -105,7 +115,9 @@ public class PoolOptions {
private boolean shared = DEFAULT_SHARED_POOL;
private String name = DEFAULT_NAME;
private int eventLoopSize = DEFAULT_EVENT_LOOP_SIZE;

private int jitter = DEFAULT_JITTER;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we also need a jitterTimeUnit property which should be by default Willis

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added

private TimeUnit jitterUnit = DEFAULT_JITTER_UNIT;

public PoolOptions() {
}

Expand Down Expand Up @@ -241,6 +253,49 @@ public PoolOptions setMaxLifetime(int maxLifetime) {
return this;
}

/**
* Get the jitter value that will be applied to maxLifetime.
*
* @return the jitter value in milliseconds
*/
public int getJitter() {
return this.jitter;
}

/**
* Set the jitter value, to be applied to maxLifetime.
*
* @param jitter the jitter value
* @return a reference to this, so the API can be used fluently
*/
public PoolOptions setJitter(int jitter) {
if (jitter < 0) {
throw new IllegalArgumentException("jitter must be >= 0");
}
this.jitter = jitter;
return this;
}

/**
* Get the time unit for the jitter value.
*
* @return the jitter time unit
*/
public TimeUnit getJitterUnit() {
return this.jitterUnit;
}

/**
* Set the time unit for the jitter value.
*
* @param jitterUnit the jitter time unit
* @return a reference to this, so the API can be used fluently
*/
public PoolOptions setJitterUnit(TimeUnit jitterUnit) {
this.jitterUnit = jitterUnit;
return this;
}

/**
* @return the connection pool cleaner period in ms.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import io.vertx.sqlclient.spi.DatabaseMetadata;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.stream.Collectors;

Expand All @@ -56,6 +57,7 @@ public class SqlConnectionPool {
private final boolean pipelined;
private final long idleTimeout;
private final long maxLifetime;
private final long jitter;
private final int maxSize;

public SqlConnectionPool(Function<Context, Future<SqlConnection>> connectionProvider,
Expand All @@ -66,6 +68,7 @@ public SqlConnectionPool(Function<Context, Future<SqlConnection>> connectionProv
VertxInternal vertx,
long idleTimeout,
long maxLifetime,
long jitter,
int maxSize,
boolean pipelined,
int maxWaitQueueSize,
Expand All @@ -82,6 +85,7 @@ public SqlConnectionPool(Function<Context, Future<SqlConnection>> connectionProv
this.pipelined = pipelined;
this.idleTimeout = idleTimeout;
this.maxLifetime = maxLifetime;
this.jitter = jitter;
this.maxSize = maxSize;
this.hook = hook;
this.connectionProvider = connectionProvider;
Expand Down Expand Up @@ -309,7 +313,8 @@ public class PooledConnection implements Connection, Connection.Holder {
this.factory = factory;
this.conn = conn;
this.listener = listener;
this.lifetimeEvictionTimestamp = maxLifetime > 0 ? System.currentTimeMillis() + maxLifetime : Long.MAX_VALUE;
long randomizedJitter = (maxLifetime > 0 && jitter > 0 && maxLifetime > jitter) ? ThreadLocalRandom.current().nextLong(-jitter, jitter + 1) : 0;
this.lifetimeEvictionTimestamp = maxLifetime > 0 ? System.currentTimeMillis() + maxLifetime + randomizedJitter : Long.MAX_VALUE;
Copy link

@chirag-manwani chirag-manwani Mar 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
long randomizedJitter = (maxLifetime > 0 && jitter > 0 && maxLifetime > jitter) ? ThreadLocalRandom.current().nextLong(-jitter, jitter + 1) : 0;
this.lifetimeEvictionTimestamp = maxLifetime > 0 ? System.currentTimeMillis() + maxLifetime + randomizedJitter : Long.MAX_VALUE;
this.lifetimeEvictionTimestamp = maxLifetime > 0 ? System.currentTimeMillis() + maxLifetime + Math.max(0, ThreadLocalRandom.current().nextLong(0, jitter)) : Long.MAX_VALUE;

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added this with nextLong(0, jitter+1)

refresh();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public class PoolImpl extends SqlClientBase implements Pool, Closeable {
private final long idleTimeout;
private final long connectionTimeout;
private final long maxLifetime;
private final long jitter;
private final long cleanerPeriod;
private final boolean pipelined;
private final Handler<SqlConnection> connectionInitializer;
Expand Down Expand Up @@ -80,11 +81,12 @@ public PoolImpl(VertxInternal vertx,
this.idleTimeout = MILLISECONDS.convert(poolOptions.getIdleTimeout(), poolOptions.getIdleTimeoutUnit());
this.connectionTimeout = MILLISECONDS.convert(poolOptions.getConnectionTimeout(), poolOptions.getConnectionTimeoutUnit());
this.maxLifetime = MILLISECONDS.convert(poolOptions.getMaxLifetime(), poolOptions.getMaxLifetimeUnit());
this.jitter = MILLISECONDS.convert(poolOptions.getJitter(), poolOptions.getJitterUnit());
this.cleanerPeriod = poolOptions.getPoolCleanerPeriod();
this.timerID = -1L;
this.pipelined = pipelined;
this.vertx = vertx;
this.pool = new SqlConnectionPool(connectionProvider, poolMetrics, hook, afterAcquire, beforeRecycle, vertx, idleTimeout, maxLifetime, poolOptions.getMaxSize(), pipelined, poolOptions.getMaxWaitQueueSize(), poolOptions.getEventLoopSize());
this.pool = new SqlConnectionPool(connectionProvider, poolMetrics, hook, afterAcquire, beforeRecycle, vertx, idleTimeout, maxLifetime, jitter, poolOptions.getMaxSize(), pipelined, poolOptions.getMaxWaitQueueSize(), poolOptions.getEventLoopSize());
this.closeFuture = closeFuture;
this.connectionInitializer = connectionInitializer;
}
Expand Down