Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions google/cloud/storage/google_cloud_cpp_storage.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ google_cloud_cpp_storage_hdrs = [
"internal/hash_validator.h",
"internal/hash_validator_impl.h",
"internal/hash_values.h",
"internal/hedge_limiter.h",
"internal/hedged_object_read_source.h",
"internal/hedged_read_metrics.h",
"internal/hedging_thread_pool.h",
Expand Down
2 changes: 2 additions & 0 deletions google/cloud/storage/google_cloud_cpp_storage.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ add_library(
internal/hash_validator_impl.h
internal/hash_values.cc
internal/hash_values.h
internal/hedge_limiter.h
internal/hedged_object_read_source.cc
internal/hedged_object_read_source.h
internal/hedged_read_metrics.cc
Expand Down Expand Up @@ -462,6 +463,7 @@ if (BUILD_TESTING)
internal/hash_function_impl_test.cc
internal/hash_validator_test.cc
internal/hash_values_test.cc
internal/hedge_limiter_test.cc
internal/hedged_object_read_source_test.cc
internal/hedged_read_metrics_test.cc
internal/hedging_thread_pool_test.cc
Expand Down
174 changes: 174 additions & 0 deletions google/cloud/storage/internal/hedge_limiter.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H

#include "google/cloud/storage/version.h"
#include "google/cloud/internal/clock.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <memory>
#include <mutex>
#include <utility>

namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {

/**
* Enforces connection-wide rate, concurrency, and lifetime limits on
* speculative hedged requests.
*
* Values `<= 0` disable the corresponding limit; `capacity` is clamped to at
* least `1.0` so fractional rate limits (`0.0 < rate_limit < 1.0`) can still
* issue hedges once refilled.
*/
class HedgeLimiter {
public:
using Clock = google::cloud::internal::SteadyClock;

HedgeLimiter(double rate_limit, double capacity, std::int64_t max_concurrent,
std::int64_t max_total)
: HedgeLimiter(rate_limit, capacity, max_concurrent, max_total,
std::make_shared<Clock>()) {}

/// @p clock must not be null. Tests inject `testing_util::FakeSteadyClock`.
HedgeLimiter(double rate_limit, double capacity, std::int64_t max_concurrent,
std::int64_t max_total, std::shared_ptr<Clock const> clock)
: clock_(std::move(clock)),
rate_limit_(rate_limit),
tokens_capacity_((std::max)(1.0, capacity)),
tokens_((std::max)(1.0, capacity)),
last_refill_(clock_->Now()),
max_concurrent_hedges_(max_concurrent),
max_total_hedges_(max_total) {}
Comment thread
ajayky-os marked this conversation as resolved.
Resolved

~HedgeLimiter() = default;

HedgeLimiter(HedgeLimiter const&) = delete;
HedgeLimiter& operator=(HedgeLimiter const&) = delete;
HedgeLimiter(HedgeLimiter&&) = delete;
HedgeLimiter& operator=(HedgeLimiter&&) = delete;

/**
* Reserves capacity for one hedged request.
*
* On success the caller *must* eventually call `ReleaseHedgeSlot()`.
*/
bool TryAcquireHedgeToken() {
// Once the lifetime budget is spent, deny with a single atomic load.
if (IsTotalBudgetSpent()) return false;

// Gate 1: the ceiling on concurrently active hedges. When
// max_concurrent_hedges_ <= 0, concurrency limiting is disabled.
if (max_concurrent_hedges_ > 0) {
std::int64_t current =
active_concurrent_hedges_.load(std::memory_order_relaxed);
do {
if (current >= max_concurrent_hedges_) return false;
} while (!active_concurrent_hedges_.compare_exchange_weak(
current, current + 1, std::memory_order_relaxed));
}

// Gate 2: the rate limit on new hedges (token bucket). When
// rate_limit_ <= 0.0, rate limiting is disabled.
if (rate_limit_ > 0.0) {
std::lock_guard<std::mutex> lock(limiter_mutex_);
Refill();
if (tokens_ < 1.0) {
ReleaseHedgeSlot();
return false;
}
tokens_ -= 1.0;
}

// Gate 3: the lifetime budget. Checked last so the counter only moves for
// a hedge that is granted, which keeps `IsTotalBudgetSpent()` exact. If
// another thread took the last unit since the check above, return what the
// earlier gates reserved. When max_total_hedges_ <= 0, the lifetime limit
// is disabled.
if (max_total_hedges_ > 0) {
std::int64_t granted =
total_hedges_granted_.load(std::memory_order_relaxed);
do {
if (granted >= max_total_hedges_) {
ReleaseHedgeSlot();
ReturnRateToken();
return false;
}
} while (!total_hedges_granted_.compare_exchange_weak(
granted, granted + 1, std::memory_order_relaxed));
}

return true;
}

/// Releases the concurrency slot. The lifetime budget is never returned.
void ReleaseHedgeSlot() {
if (max_concurrent_hedges_ > 0) {
active_concurrent_hedges_.fetch_sub(1, std::memory_order_relaxed);
}
}

/// Returns true once the lifetime budget is spent. No hedge is granted after
/// that, so callers can skip racing altogether.
bool IsTotalBudgetSpent() const {
return max_total_hedges_ > 0 &&
total_hedges_granted_.load(std::memory_order_relaxed) >=
max_total_hedges_;
}

private:
void ReturnRateToken() {
if (rate_limit_ <= 0.0) return;
std::lock_guard<std::mutex> lock(limiter_mutex_);
tokens_ = (std::min)(tokens_capacity_, tokens_ + 1.0);
}

void Refill() {
Clock::time_point const now = clock_->Now();
double const elapsed =
std::chrono::duration_cast<std::chrono::duration<double>>(now -
last_refill_)
.count();
last_refill_ = now;
tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_);
}
Comment thread
ajayky-os marked this conversation as resolved.
Resolved

std::shared_ptr<Clock const> const clock_;
double const rate_limit_;
double const tokens_capacity_;
double tokens_;
Clock::time_point last_refill_;
std::mutex limiter_mutex_;

std::int64_t const max_concurrent_hedges_;
std::atomic<std::int64_t> active_concurrent_hedges_{0};

std::int64_t const max_total_hedges_;
std::atomic<std::int64_t> total_hedges_granted_{0};
};

} // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage
} // namespace cloud
} // namespace google

#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H
180 changes: 180 additions & 0 deletions google/cloud/storage/internal/hedge_limiter_test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "google/cloud/storage/internal/hedge_limiter.h"
#include "google/cloud/testing_util/fake_clock.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <memory>
#include <thread>
#include <vector>

namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {

using ::google::cloud::testing_util::FakeSteadyClock;
using ::testing::Eq;

TEST(HedgeLimiterTest, MaxConcurrentHedgesLimit) {
HedgeLimiter limiter(0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/0);

EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());

limiter.ReleaseHedgeSlot();

EXPECT_TRUE(limiter.TryAcquireHedgeToken());
}

TEST(HedgeLimiterTest, RateLimiter) {
// 5 tokens/second (one token per 200ms), burst capacity of 2 tokens.
auto clock = std::make_shared<FakeSteadyClock>();
HedgeLimiter limiter(5.0, 2.0, 0, 0, clock);

EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());

// Half-token step margins avoid IEEE-754 boundary rounding sensitivity.
clock->AdvanceTime(std::chrono::milliseconds(100)); // +0.5 token
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
clock->AdvanceTime(std::chrono::milliseconds(200)); // +1.0 token => 1.5
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());

// Refill is clamped at burst capacity (2 tokens).
clock->AdvanceTime(std::chrono::seconds(10));
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
}

TEST(HedgeLimiterTest, FractionalRateLimiter) {
// 0.5 tokens/second (one token per 2s); capacity 0.5 clamps to floor 1.0.
auto clock = std::make_shared<FakeSteadyClock>();
HedgeLimiter limiter(0.5, 0.5, 0, 0, clock);

EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());

clock->AdvanceTime(std::chrono::seconds(1)); // +0.5 token
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
clock->AdvanceTime(std::chrono::seconds(2)); // +1.0 token => clamped to 1.0
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
}

TEST(HedgeLimiterTest, ZeroRateLimitDisablesRateLimiting) {
HedgeLimiter limiter(0.0, 0.0, 0, 0);

for (int i = 0; i < 100; ++i) {
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
}
}

TEST(HedgeLimiterTest, MaxTotalHedgesLimit) {
HedgeLimiter limiter(0.0, 0.0, 0, /*max_total=*/3);

EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.IsTotalBudgetSpent());
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_TRUE(limiter.IsTotalBudgetSpent());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());

// Releasing a hedge frees its concurrency slot, never its lifetime budget.
limiter.ReleaseHedgeSlot();
limiter.ReleaseHedgeSlot();
limiter.ReleaseHedgeSlot();
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
}

TEST(HedgeLimiterTest, ConcurrencyDenialDoesNotSpendTotalBudget) {
HedgeLimiter limiter(0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/2);

EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.IsTotalBudgetSpent());
limiter.ReleaseHedgeSlot();

EXPECT_TRUE(limiter.TryAcquireHedgeToken());
limiter.ReleaseHedgeSlot();
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
}

TEST(HedgeLimiterTest, RateLimitDenialDoesNotSpendTotalBudget) {
auto clock = std::make_shared<FakeSteadyClock>();
HedgeLimiter limiter(0.001, 1.0, 0, /*max_total=*/2, clock);

EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
EXPECT_FALSE(limiter.IsTotalBudgetSpent());

clock->AdvanceTime(std::chrono::seconds(1500));
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
EXPECT_TRUE(limiter.IsTotalBudgetSpent());
}

TEST(HedgeLimiterTest, ZeroMaxTotalDisablesLifetimeLimit) {
HedgeLimiter limiter(0.0, 0.0, 0, /*max_total=*/0);

for (int i = 0; i < 100; ++i) {
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
}
EXPECT_FALSE(limiter.IsTotalBudgetSpent());
}

TEST(HedgeLimiterTest, MaxTotalHedgesUnderContention) {
std::int64_t const max_total = 100;
// A rate limit that never runs out, so threads racing for the last unit of
// budget also exercise returning the rate token.
HedgeLimiter limiter(1e9, 1e9, /*max_concurrent=*/4, max_total);

std::atomic<std::int64_t> granted{0};
std::vector<std::thread> threads;
threads.reserve(8);
for (int t = 0; t != 8; ++t) {
threads.emplace_back([&limiter, &granted] {
for (int i = 0; i != 1000; ++i) {
if (!limiter.TryAcquireHedgeToken()) continue;
++granted;
limiter.ReleaseHedgeSlot();
}
});
}
for (std::thread& t : threads) t.join();

while (limiter.TryAcquireHedgeToken()) {
++granted;
limiter.ReleaseHedgeSlot();
}
EXPECT_THAT(granted.load(), Eq(max_total));
EXPECT_TRUE(limiter.IsTotalBudgetSpent());
}

} // namespace
} // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage
} // namespace cloud
} // namespace google
Loading
Loading