Skip to content

Commit e1e4929

Browse files
authored
Report waiting time only for currently waiting clients (#678)
The pool maxwait metric currently operates differently from Pgbouncer. The way it operates today is that we keep track of max_wait on each connected client, when SHOW POOLS query is made, we go over the connected clients and we get the max of max_wait times among clients. This means the pool maxwait will never reset, it will always be monotonically increasing until the client with the highest maxwait disconnects. This PR changes this behavior, by keeping track of the wait_start time on each client, when a client goes into WAITING state, we record the time offset from connect_time. When we either successfully or unsuccessfully checkout a connection from the pool, we reset the wait_start time. When SHOW POOLS query is made, we go over all connected clients and we only consider clients whose wait_start is non-zero, for clients that have non-zero wait times, we compare them and report the maximum waiting time as maxwait for the pool.
1 parent dc4d6ed commit e1e4929

File tree

4 files changed

+55
-23
lines changed

4 files changed

+55
-23
lines changed

src/pool.rs

+4-8
Original file line numberDiff line numberDiff line change
@@ -769,7 +769,6 @@ impl ConnectionPool {
769769
);
770770
self.ban(address, BanReason::FailedCheckout, Some(client_stats));
771771
address.stats.error();
772-
client_stats.idle();
773772
client_stats.checkout_error();
774773
continue;
775774
}
@@ -788,7 +787,7 @@ impl ConnectionPool {
788787
// Health checks are pretty expensive.
789788
if !require_healthcheck {
790789
let checkout_time = now.elapsed().as_micros() as u64;
791-
client_stats.checkout_time(checkout_time);
790+
client_stats.checkout_success();
792791
server
793792
.stats()
794793
.checkout_time(checkout_time, client_stats.application_name());
@@ -802,7 +801,7 @@ impl ConnectionPool {
802801
.await
803802
{
804803
let checkout_time = now.elapsed().as_micros() as u64;
805-
client_stats.checkout_time(checkout_time);
804+
client_stats.checkout_success();
806805
server
807806
.stats()
808807
.checkout_time(checkout_time, client_stats.application_name());
@@ -814,10 +813,7 @@ impl ConnectionPool {
814813
}
815814
}
816815

817-
client_stats.idle();
818-
819-
let checkout_time = now.elapsed().as_micros() as u64;
820-
client_stats.checkout_time(checkout_time);
816+
client_stats.checkout_success();
821817

822818
Err(Error::AllServersDown)
823819
}
@@ -843,7 +839,7 @@ impl ConnectionPool {
843839
Ok(res) => match res {
844840
Ok(_) => {
845841
let checkout_time: u64 = start.elapsed().as_micros() as u64;
846-
client_info.checkout_time(checkout_time);
842+
client_info.checkout_success();
847843
server
848844
.stats()
849845
.checkout_time(checkout_time, client_info.application_name());

src/stats/client.rs

+34-4
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ pub struct ClientStats {
4141
/// Maximum time spent waiting for a connection from pool, measures in microseconds
4242
pub max_wait_time: Arc<AtomicU64>,
4343

44+
// Time when the client started waiting for a connection from pool, measures in microseconds
45+
// We use connect_time as the reference point for this value
46+
// U64 can represent ~5850 centuries in microseconds, so we should be fine
47+
pub wait_start_us: Arc<AtomicU64>,
48+
4449
/// Current state of the client
4550
pub state: Arc<AtomicClientState>,
4651

@@ -64,6 +69,7 @@ impl Default for ClientStats {
6469
pool_name: String::new(),
6570
total_wait_time: Arc::new(AtomicU64::new(0)),
6671
max_wait_time: Arc::new(AtomicU64::new(0)),
72+
wait_start_us: Arc::new(AtomicU64::new(0)),
6773
state: Arc::new(AtomicClientState::new(ClientState::Idle)),
6874
transaction_count: Arc::new(AtomicU64::new(0)),
6975
query_count: Arc::new(AtomicU64::new(0)),
@@ -111,6 +117,9 @@ impl ClientStats {
111117

112118
/// Reports a client is waiting for a connection
113119
pub fn waiting(&self) {
120+
let wait_start = self.connect_time.elapsed().as_micros() as u64;
121+
122+
self.wait_start_us.store(wait_start, Ordering::Relaxed);
114123
self.state.store(ClientState::Waiting, Ordering::Relaxed);
115124
}
116125

@@ -122,6 +131,13 @@ impl ClientStats {
122131
/// Reports a client has failed to obtain a connection from a connection pool
123132
pub fn checkout_error(&self) {
124133
self.state.store(ClientState::Idle, Ordering::Relaxed);
134+
self.update_wait_times();
135+
}
136+
137+
/// Reports a client has succeeded in obtaining a connection from a connection pool
138+
pub fn checkout_success(&self) {
139+
self.state.store(ClientState::Active, Ordering::Relaxed);
140+
self.update_wait_times();
125141
}
126142

127143
/// Reports a client has had the server assigned to it be banned
@@ -130,12 +146,26 @@ impl ClientStats {
130146
self.error_count.fetch_add(1, Ordering::Relaxed);
131147
}
132148

133-
/// Reporters the time spent by a client waiting to get a healthy connection from the pool
134-
pub fn checkout_time(&self, microseconds: u64) {
149+
fn update_wait_times(&self) {
150+
if self.wait_start_us.load(Ordering::Relaxed) == 0 {
151+
return;
152+
}
153+
154+
let wait_time_us = self.get_current_wait_time_us();
135155
self.total_wait_time
136-
.fetch_add(microseconds, Ordering::Relaxed);
156+
.fetch_add(wait_time_us, Ordering::Relaxed);
137157
self.max_wait_time
138-
.fetch_max(microseconds, Ordering::Relaxed);
158+
.fetch_max(wait_time_us, Ordering::Relaxed);
159+
self.wait_start_us.store(0, Ordering::Relaxed);
160+
}
161+
162+
pub fn get_current_wait_time_us(&self) -> u64 {
163+
let wait_start_us = self.wait_start_us.load(Ordering::Relaxed);
164+
let microseconds_since_connection_epoch = self.connect_time.elapsed().as_micros() as u64;
165+
if wait_start_us == 0 || microseconds_since_connection_epoch < wait_start_us {
166+
return 0;
167+
}
168+
microseconds_since_connection_epoch - wait_start_us
139169
}
140170

141171
/// Report a query executed by a client against a server

src/stats/pool.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,11 @@ impl PoolStats {
6464
ClientState::Idle => pool_stats.cl_idle += 1,
6565
ClientState::Waiting => pool_stats.cl_waiting += 1,
6666
}
67-
let max_wait = client.max_wait_time.load(Ordering::Relaxed);
68-
pool_stats.maxwait = std::cmp::max(pool_stats.maxwait, max_wait);
67+
let wait_start_us = client.wait_start_us.load(Ordering::Relaxed);
68+
if wait_start_us > 0 {
69+
let wait_time_us = client.get_current_wait_time_us();
70+
pool_stats.maxwait = std::cmp::max(pool_stats.maxwait, wait_time_us);
71+
}
6972
}
7073
None => debug!("Client from an obselete pool"),
7174
}

tests/ruby/stats_spec.rb

+12-9
Original file line numberDiff line numberDiff line change
@@ -233,17 +233,19 @@
233233
sleep(1.1) # Allow time for stats to update
234234
admin_conn = PG::connect(processes.pgcat.admin_connection_string)
235235
results = admin_conn.async_exec("SHOW POOLS")[0]
236-
%w[cl_idle cl_cancel_req sv_idle sv_used sv_tested sv_login maxwait].each do |s|
236+
237+
%w[cl_idle cl_cancel_req sv_idle sv_used sv_tested sv_login].each do |s|
237238
raise StandardError, "Field #{s} was expected to be 0 but found to be #{results[s]}" if results[s] != "0"
238239
end
239240

241+
expect(results["maxwait"]).to eq("1")
240242
expect(results["cl_waiting"]).to eq("2")
241243
expect(results["cl_active"]).to eq("2")
242244
expect(results["sv_active"]).to eq("2")
243245

244246
sleep(2.5) # Allow time for stats to update
245247
results = admin_conn.async_exec("SHOW POOLS")[0]
246-
%w[cl_active cl_waiting cl_cancel_req sv_active sv_used sv_tested sv_login].each do |s|
248+
%w[cl_active cl_waiting cl_cancel_req sv_active sv_used sv_tested sv_login maxwait].each do |s|
247249
raise StandardError, "Field #{s} was expected to be 0 but found to be #{results[s]}" if results[s] != "0"
248250
end
249251
expect(results["cl_idle"]).to eq("4")
@@ -255,22 +257,23 @@
255257

256258
it "show correct max_wait" do
257259
threads = []
260+
admin_conn = PG::connect(processes.pgcat.admin_connection_string)
258261
connections = Array.new(4) { PG::connect("#{pgcat_conn_str}?application_name=one_query") }
259262
connections.each do |c|
260263
threads << Thread.new { c.async_exec("SELECT pg_sleep(1.5)") rescue nil }
261264
end
262-
263-
sleep(2.5) # Allow time for stats to update
264-
admin_conn = PG::connect(processes.pgcat.admin_connection_string)
265+
sleep(1.1)
265266
results = admin_conn.async_exec("SHOW POOLS")[0]
266-
267+
# Value is only reported when there are clients waiting
267268
expect(results["maxwait"]).to eq("1")
268-
expect(results["maxwait_us"].to_i).to be_within(200_000).of(500_000)
269-
connections.map(&:close)
269+
expect(results["maxwait_us"].to_i).to be_within(20_000).of(100_000)
270270

271-
sleep(4.5) # Allow time for stats to update
271+
sleep(2.5) # Allow time for stats to update
272272
results = admin_conn.async_exec("SHOW POOLS")[0]
273+
# no clients are waiting so value is 0
273274
expect(results["maxwait"]).to eq("0")
275+
expect(results["maxwait_us"]).to eq("0")
276+
connections.map(&:close)
274277

275278
threads.map(&:join)
276279
end

0 commit comments

Comments
 (0)