userver: userver/utils/aimd_limiter.hpp Source File
Loading...
Searching...
No Matches
aimd_limiter.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/aimd_limiter.hpp
4/// @brief @copybrief utils::AimdLimiter
5
6#include <atomic>
7#include <cstddef>
8
9#include <userver/yaml_config/fwd.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace utils {
14
15/// @ingroup userver_universal userver_concurrency
16///
17/// @brief Thread safe AIMD (Additive Increase Multiplicative Decrease) limiter
18///
19/// Keeps an adaptive limit within `[min_limit, max_limit]`:
20///
21/// * on success the limit is additively increased:
22/// `limit = min(max_limit, limit + alpha / limit)`;
23/// * on failure the limit is multiplicatively decreased:
24/// `limit = max(min_limit, limit * beta)`.
25///
26/// If `max_limit` is set below `Policy::min_limit`, `max_limit` wins and
27/// GetCurrentLimit() returns `max_limit`.
28class AimdLimiter final {
29public:
30 /// AIMD limit update policy
31 struct Policy {
32 /// Lower bound for the limit, must be positive
33 std::size_t min_limit{2};
34 /// Additive increase coefficient, must be positive and finite
35 double alpha{1.0};
36 /// Multiplicative decrease coefficient, must be in range (0, 1)
37 double beta{0.5};
38 };
39
40 /// Create a limiter with the current limit set to `max_limit`
41 /// @throws std::runtime_error if the policy is invalid
42 AimdLimiter(std::size_t max_limit, Policy policy);
43
44 AimdLimiter(const AimdLimiter&) = delete;
45 AimdLimiter(AimdLimiter&&) = delete;
46 AimdLimiter& operator=(const AimdLimiter&) = delete;
47 AimdLimiter& operator=(AimdLimiter&&) = delete;
48
49 /// Set the upper bound for the limit, clamping down the current limit if needed
50 void SetMaxLimit(std::size_t max_limit) noexcept;
51
52 /// Set limit update policy
53 /// @throws std::runtime_error if the policy is invalid
54 void SetPolicy(Policy policy);
55
56 /// Get the upper bound for the limit (might be inaccurate as the result is stale)
57 std::size_t GetMaxLimit() const noexcept;
58
59 /// Get current limit (might be inaccurate as the result is stale)
60 std::size_t GetCurrentLimit() const noexcept;
61
62 /// Additively increase the limit up to the max limit
63 void OnSuccess() noexcept;
64
65 /// Multiplicatively decrease the limit down to the min limit
66 void OnFailure() noexcept;
67
68private:
69 std::atomic<std::size_t> max_limit_;
70 std::atomic<std::size_t> min_limit_;
71 std::atomic<double> alpha_;
72 std::atomic<double> beta_;
73 std::atomic<double> current_limit_;
74};
75
76/// @brief Parse the required `min-limit`, `alpha` and `beta` YAML fields.
77/// Numeric policy constraints are checked by @ref utils::AimdLimiter.
78AimdLimiter::Policy Parse(const yaml_config::YamlConfig& config, formats::parse::To<AimdLimiter::Policy>);
79
80} // namespace utils
81
82USERVER_NAMESPACE_END