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 2 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,17 @@
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.*;

Choose a reason for hiding this comment

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

remove star import

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 All @@ -59,6 +59,17 @@ public class PgPoolTest extends PgPoolTestBase {

private Set<Pool> pools = new HashSet<>();

// Static inner class to store connection info with timestamp
private static class ConnectionRecord {
final int pid;
final long timestamp;

ConnectionRecord(int pid, long timestamp) {
this.pid = pid;
this.timestamp = timestamp;
}
}

@Override
public void tearDown(TestContext ctx) {
int size = pools.size();
Expand Down Expand Up @@ -619,4 +630,61 @@ public void testConnectionClosedInHook(TestContext ctx) {
}));
}));
}

@Test
@Repeat(2)
public void testConnectionJitter(TestContext ctx) {
poolOptions
.setMaxSize(1)
.setMaxLifetime(2000)
.setMaxLifetimeUnit(TimeUnit.MILLISECONDS)
.setJitter(400)
.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 = 2000;
int jitter = 400;
int lowerBound = maxLifetime - jitter;
int upperBound = maxLifetime + jitter;

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,11 @@ 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 "poolCleanerPeriod":
if (member.getValue() instanceof Number) {
obj.setPoolCleanerPeriod(((Number)member.getValue()).intValue());
Expand Down Expand Up @@ -93,6 +98,7 @@ 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());
json.put("poolCleanerPeriod", obj.getPoolCleanerPeriod());
if (obj.getConnectionTimeoutUnit() != null) {
json.put("connectionTimeoutUnit", obj.getConnectionTimeoutUnit().name());
Expand Down
29 changes: 29 additions & 0 deletions vertx-sql-client/src/main/java/io/vertx/sqlclient/PoolOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ public class PoolOptions {
*/
public static final int DEFAULT_EVENT_LOOP_SIZE = 0;

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

private int maxSize = DEFAULT_MAX_SIZE;
private int maxWaitQueueSize = DEFAULT_MAX_WAIT_QUEUE_SIZE;
private int idleTimeout = DEFAULT_IDLE_TIMEOUT;
Expand All @@ -105,6 +110,7 @@ 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


public PoolOptions() {
}
Expand Down Expand Up @@ -241,6 +247,29 @@ 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;
}

/**
* @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 = jitter > 0 ? ThreadLocalRandom.current().nextLong(-jitter, jitter + 1) : 0;
this.lifetimeEvictionTimestamp = maxLifetime > 0 ? System.currentTimeMillis() + maxLifetime + randomizedJitter : Long.MAX_VALUE;
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.getMaxLifetimeUnit());
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