Skip to content

Commit 70e2483

Browse files
committed
refactor(storage): extract HedgeLimiter from HedgingThreadPool
Extract the connection-wide rate, concurrency, and lifetime hedge limiter out of HedgingThreadPool into internal/hedge_limiter.h so AsyncConnectionImpl can share the same rate/concurrency/total limiter state machine without instantiating a thread pool.
1 parent 92e3ffe commit 70e2483

4 files changed

Lines changed: 156 additions & 103 deletions

File tree

‎google/cloud/storage/google_cloud_cpp_storage.bzl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ google_cloud_cpp_storage_hdrs = [
7474
"internal/hash_validator.h",
7575
"internal/hash_validator_impl.h",
7676
"internal/hash_values.h",
77+
"internal/hedge_limiter.h",
7778
"internal/hedged_object_read_source.h",
7879
"internal/hedged_read_metrics.h",
7980
"internal/hedging_thread_pool.h",

‎google/cloud/storage/google_cloud_cpp_storage.cmake‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ add_library(
117117
internal/hash_validator_impl.h
118118
internal/hash_values.cc
119119
internal/hash_values.h
120+
internal/hedge_limiter.h
120121
internal/hedged_object_read_source.cc
121122
internal/hedged_object_read_source.h
122123
internal/hedged_read_metrics.cc
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
// Copyright 2026 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H
16+
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H
17+
18+
#include "google/cloud/storage/version.h"
19+
#include <algorithm>
20+
#include <atomic>
21+
#include <chrono>
22+
#include <cstdint>
23+
#include <mutex>
24+
25+
namespace google {
26+
namespace cloud {
27+
namespace storage {
28+
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
29+
namespace internal {
30+
31+
/**
32+
* Enforces connection-wide rate, concurrency, and lifetime limits on
33+
* speculative hedged requests. Values `<= 0` disable the corresponding limit;
34+
* `capacity` is clamped to at least `1.0`.
35+
*/
36+
class HedgeLimiter {
37+
public:
38+
HedgeLimiter(double rate_limit, double capacity, std::int64_t max_concurrent,
39+
std::int64_t max_total)
40+
: rate_limit_(rate_limit),
41+
tokens_capacity_((std::max)(1.0, capacity)),
42+
tokens_((std::max)(1.0, capacity)),
43+
last_refill_(std::chrono::steady_clock::now()),
44+
max_concurrent_hedges_(max_concurrent),
45+
max_total_hedges_(max_total) {}
46+
47+
~HedgeLimiter() = default;
48+
49+
HedgeLimiter(HedgeLimiter const&) = delete;
50+
HedgeLimiter& operator=(HedgeLimiter const&) = delete;
51+
HedgeLimiter(HedgeLimiter&&) = delete;
52+
HedgeLimiter& operator=(HedgeLimiter&&) = delete;
53+
54+
/// Reserves capacity for one hedge; callers *must* call `ReleaseHedgeSlot()`.
55+
bool TryAcquireHedgeToken() {
56+
if (IsTotalBudgetSpent()) return false;
57+
58+
if (max_concurrent_hedges_ > 0) {
59+
std::int64_t current =
60+
active_concurrent_hedges_.load(std::memory_order_relaxed);
61+
do {
62+
if (current >= max_concurrent_hedges_) return false;
63+
} while (!active_concurrent_hedges_.compare_exchange_weak(
64+
current, current + 1, std::memory_order_relaxed));
65+
}
66+
67+
if (rate_limit_ > 0.0) {
68+
std::lock_guard<std::mutex> lock(limiter_mutex_);
69+
Refill();
70+
if (tokens_ < 1.0) {
71+
ReleaseHedgeSlot();
72+
return false;
73+
}
74+
tokens_ -= 1.0;
75+
}
76+
77+
// Checked last so `total_hedges_granted_` moves only for granted hedges.
78+
if (max_total_hedges_ > 0) {
79+
std::int64_t granted =
80+
total_hedges_granted_.load(std::memory_order_relaxed);
81+
do {
82+
if (granted >= max_total_hedges_) {
83+
ReleaseHedgeSlot();
84+
ReturnRateToken();
85+
return false;
86+
}
87+
} while (!total_hedges_granted_.compare_exchange_weak(
88+
granted, granted + 1, std::memory_order_relaxed));
89+
}
90+
91+
return true;
92+
}
93+
94+
/// Releases the concurrency slot. The lifetime budget is never returned.
95+
void ReleaseHedgeSlot() {
96+
if (max_concurrent_hedges_ > 0) {
97+
active_concurrent_hedges_.fetch_sub(1, std::memory_order_relaxed);
98+
}
99+
}
100+
101+
/// Returns true once the lifetime budget is permanently exhausted.
102+
bool IsTotalBudgetSpent() const {
103+
return max_total_hedges_ > 0 &&
104+
total_hedges_granted_.load(std::memory_order_relaxed) >=
105+
max_total_hedges_;
106+
}
107+
108+
private:
109+
void ReturnRateToken() {
110+
if (rate_limit_ <= 0.0) return;
111+
std::lock_guard<std::mutex> lock(limiter_mutex_);
112+
tokens_ = (std::min)(tokens_capacity_, tokens_ + 1.0);
113+
}
114+
115+
void Refill() {
116+
auto const now = std::chrono::steady_clock::now();
117+
double const elapsed =
118+
std::chrono::duration_cast<std::chrono::duration<double>>(now -
119+
last_refill_)
120+
.count();
121+
last_refill_ = now;
122+
tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_);
123+
}
124+
125+
double rate_limit_;
126+
double tokens_capacity_;
127+
double tokens_;
128+
std::chrono::steady_clock::time_point last_refill_;
129+
std::mutex limiter_mutex_;
130+
131+
std::int64_t const max_concurrent_hedges_;
132+
std::atomic<std::int64_t> active_concurrent_hedges_{0};
133+
134+
std::int64_t const max_total_hedges_;
135+
std::atomic<std::int64_t> total_hedges_granted_{0};
136+
};
137+
138+
} // namespace internal
139+
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
140+
} // namespace storage
141+
} // namespace cloud
142+
} // namespace google
143+
144+
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H

‎google/cloud/storage/internal/hedging_thread_pool.h‎

Lines changed: 10 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@
1515
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGING_THREAD_POOL_H
1616
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGING_THREAD_POOL_H
1717

18+
#include "google/cloud/storage/internal/hedge_limiter.h"
1819
#include "google/cloud/storage/version.h"
1920
#include <algorithm>
20-
#include <atomic>
21-
#include <chrono>
2221
#include <condition_variable>
22+
#include <cstddef>
2323
#include <cstdint>
2424
#include <functional>
2525
#include <memory>
@@ -137,13 +137,9 @@ class ThreadPool {
137137
/**
138138
* Coordinates and bounds speculative hedged requests across a storage client.
139139
*
140-
* Hedged requests are gated by `TryAcquireHedgeToken()`, which enforces three
141-
* limits: a maximum number of hedges over the life of the pool (when
142-
* `max_total > 0`), a maximum number of concurrently active hedges (when
143-
* `max_concurrent > 0`), and a maximum rate of new hedges per second via a
144-
* token bucket (when `rate_limit > 0.0`). Setting `rate_limit <= 0.0` disables
145-
* rate limiting (unlimited hedges per second). Task execution is dispatched
146-
* onto a dedicated internal `ThreadPool`.
140+
* Hedged requests are gated by `TryAcquireHedgeToken()` (delegated to
141+
* `HedgeLimiter`), and task execution is dispatched onto a dedicated internal
142+
* `ThreadPool`.
147143
*/
148144
class HedgingThreadPool {
149145
public:
@@ -162,12 +158,7 @@ class HedgingThreadPool {
162158
*/
163159
HedgingThreadPool(std::size_t max_threads, double rate_limit, double capacity,
164160
std::int64_t max_concurrent, std::int64_t max_total)
165-
: rate_limit_(rate_limit),
166-
tokens_capacity_((std::max)(1.0, capacity)),
167-
tokens_((std::max)(1.0, capacity)),
168-
last_refill_(std::chrono::steady_clock::now()),
169-
max_concurrent_hedges_(max_concurrent),
170-
max_total_hedges_(max_total),
161+
: limiter_(rate_limit, capacity, max_concurrent, max_total),
171162
pool_(max_threads) {}
172163

173164
~HedgingThreadPool() = default;
@@ -191,103 +182,19 @@ class HedgingThreadPool {
191182
*
192183
* On success the caller *must* eventually call `ReleaseHedgeSlot()`.
193184
*/
194-
bool TryAcquireHedgeToken() {
195-
// Once the lifetime budget is spent, deny with a single atomic load.
196-
if (IsTotalBudgetSpent()) return false;
197-
198-
// Gate 1: the ceiling on concurrently active hedges. When
199-
// max_concurrent_hedges_ <= 0, concurrency limiting is disabled.
200-
if (max_concurrent_hedges_ > 0) {
201-
std::int64_t current =
202-
active_concurrent_hedges_.load(std::memory_order_relaxed);
203-
do {
204-
if (current >= max_concurrent_hedges_) return false;
205-
} while (!active_concurrent_hedges_.compare_exchange_weak(
206-
current, current + 1, std::memory_order_relaxed));
207-
}
208-
209-
// Gate 2: the rate limit on new hedges (token bucket). When
210-
// rate_limit_ <= 0.0, rate limiting is disabled.
211-
if (rate_limit_ > 0.0) {
212-
std::lock_guard<std::mutex> lock(limiter_mutex_);
213-
Refill();
214-
if (tokens_ < 1.0) {
215-
ReleaseHedgeSlot();
216-
return false;
217-
}
218-
tokens_ -= 1.0;
219-
}
220-
221-
// Gate 3: the lifetime budget. Checked last so the counter only moves for
222-
// a hedge that is granted, which keeps `IsTotalBudgetSpent()` exact. If
223-
// another thread took the last unit since the check above, return what
224-
// the earlier gates reserved. When max_total_hedges_ <= 0, the lifetime
225-
// limit is disabled.
226-
if (max_total_hedges_ > 0) {
227-
std::int64_t granted =
228-
total_hedges_granted_.load(std::memory_order_relaxed);
229-
do {
230-
if (granted >= max_total_hedges_) {
231-
ReleaseHedgeSlot();
232-
ReturnRateToken();
233-
return false;
234-
}
235-
} while (!total_hedges_granted_.compare_exchange_weak(
236-
granted, granted + 1, std::memory_order_relaxed));
237-
}
238-
239-
return true;
240-
}
185+
bool TryAcquireHedgeToken() { return limiter_.TryAcquireHedgeToken(); }
241186

242187
/// Releases the concurrency slot. The lifetime budget is never returned.
243-
void ReleaseHedgeSlot() {
244-
if (max_concurrent_hedges_ > 0) {
245-
active_concurrent_hedges_.fetch_sub(1, std::memory_order_relaxed);
246-
}
247-
}
188+
void ReleaseHedgeSlot() { limiter_.ReleaseHedgeSlot(); }
248189

249190
/// Returns true once the lifetime budget is spent. No hedge is granted after
250191
/// that, so callers can skip racing altogether.
251-
bool IsTotalBudgetSpent() const {
252-
return max_total_hedges_ > 0 &&
253-
total_hedges_granted_.load(std::memory_order_relaxed) >=
254-
max_total_hedges_;
255-
}
192+
bool IsTotalBudgetSpent() const { return limiter_.IsTotalBudgetSpent(); }
256193

257194
std::size_t max_threads() const { return pool_.max_threads(); }
258195

259196
private:
260-
void ReturnRateToken() {
261-
if (rate_limit_ <= 0.0) return;
262-
std::lock_guard<std::mutex> lock(limiter_mutex_);
263-
tokens_ = (std::min)(tokens_capacity_, tokens_ + 1.0);
264-
}
265-
266-
void Refill() {
267-
std::chrono::steady_clock::time_point const now =
268-
std::chrono::steady_clock::now();
269-
double const elapsed =
270-
std::chrono::duration_cast<std::chrono::duration<double>>(now -
271-
last_refill_)
272-
.count();
273-
last_refill_ = now;
274-
tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_);
275-
}
276-
277-
// Token bucket rate limiter. A rate_limit_ <= 0.0 disables rate limiting.
278-
double rate_limit_;
279-
double tokens_capacity_;
280-
double tokens_;
281-
std::chrono::steady_clock::time_point last_refill_;
282-
std::mutex limiter_mutex_;
283-
284-
// Concurrency limiter. A max_concurrent_hedges_ <= 0 disables limit.
285-
std::int64_t const max_concurrent_hedges_;
286-
std::atomic<std::int64_t> active_concurrent_hedges_{0};
287-
288-
// Lifetime limiter. A max_total_hedges_ <= 0 disables limit.
289-
std::int64_t const max_total_hedges_;
290-
std::atomic<std::int64_t> total_hedges_granted_{0};
197+
HedgeLimiter limiter_;
291198

292199
// Declared last so the pool (and its worker threads) is destroyed and joined
293200
// first, before any other member variables are torn down.

0 commit comments

Comments
 (0)