Skip to content

Commit 2e0f0b0

Browse files
authored
feat(backup_request): add rate-limited backup request policy (apache#3228) (apache#3229)
* feat(backup_request): add rate-limited backup request policy (apache#3228) * docs(backup_request): restructure rate-limiting section, add lifecycle guidance - Promote built-in factory function to its own subsection (before custom interface) - Add unique_ptr usage example for policy lifetime management - Add RateLimitedBackupPolicyOptions parameter table with defaults/constraints - Document NULL return on invalid params - Keep cn/en docs in sync * fix(backup_request): address review issues — sentinel fallback, comments, tests - controller.cpp: When policy returns -1 (inherit sentinel), fall back to _backup_request_ms set from ChannelOptions, so backup timer is actually armed when using a policy with backup_request_ms=-1. - backup_request_policy.cpp: Clarify OnRPCEnd comment to say 'RPC legs' (both original and backup completions counted as denominator). - backup_request_policy.cpp: Warn when update_interval_seconds exceeds window_size_seconds (window would rarely refresh within its period). - backup_request_policy.h: Fix comment typo ('Called when an RPC ends'). - brpc_channel_unittest.cpp: Replace nullptr with NULL to match codebase convention; use ASSERT_TRUE(p != NULL) for unique_ptr null checks. - brpc_channel_unittest.cpp: Add ValidMaxRatioAtBoundary behavioral assert and AfterColdStartBackupSuppressedUntilRpcCompletes test. * fix(backup_request): correct docs table defaults and add suppression test - docs: fix backup_request_ms default (0→-1) and constraint (>=0→>=-1); add note that -1 inherit only works via ChannelOptions injection path, not Controller::set_backup_request_policy(). - test: replace no-op AfterColdStart test with a real behavioral assertion: after cold-start backup fires, wait 1.2s for ratio refresh, verify DoBackup() returns false (conservative ratio=1.0 path triggers). * fix(backup_request): clarify comments — negative defer semantics and burst caveat * fix(backup_request): address Copilot review — sentinel contract, OnRPCEnd comment, re-allow test, docs - controller.cpp: treat -1 specifically (not all negatives) as the inherit sentinel; other negatives still disable backup, preserving old behavior for custom policies that return negative values to disable backup - backup_request_policy.h: document the -1 sentinel contract on GetBackupRequestMs() so custom implementors know the new interface - backup_request_policy.cpp: fix OnRPCEnd comment — called once per user-level RPC, not once per leg (total_count tracks user RPCs) - test: add OnRPCEndDrivesRatioDownAndReAllows — fires 20 backups to suppress, then completes 50 RPCs via OnRPCEnd, verifies DoBackup re-allows once ratio refreshes below max_backup_ratio - docs (EN+CN): rephrase backup_request_ms=-1 note to clarify the channel-level fallback only applies when set via ChannelOptions * fix(backup_request): explain why std::nothrow is intentionally omitted Plain new follows brpc's project-wide OOM convention (abort rather than return NULL). The factory's NULL return already exclusively signals invalid parameters, not allocation failure — adding std::nothrow would conflate the two. Comment added to suppress future linter/AI suggestions. * docs(backup_request): clarify policy lifetime — channel must be destroyed before policy The unique_ptr comment was ambiguous: 'released when goes out of scope, as long as it outlives the channel' can be read as contradictory. Reword to make the ordering explicit: destroy channel first, then policy. * test(backup_request): fix inaccurate cold-start comment in ValidMaxRatioAtBoundary ratio=1.0 conservative path only applies when backup>0 && total==0. True cold start (both zero) sets ratio=0.0 and allows freely.
1 parent c32ddee commit 2e0f0b0

8 files changed

Lines changed: 515 additions & 6 deletions

File tree

docs/cn/backup_request.md

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ Channel开启backup request。这个Channel会先向其中一个server发送请
66

77
示例代码见[example/backup_request_c++](https://github.com/apache/brpc/blob/master/example/backup_request_c++)。这个例子中,client设定了在2ms后发送backup request,server在碰到偶数位的请求后会故意睡眠20ms以触发backup request。
88

9-
运行后,client端和server端的日志分别如下,index是请求的编号。可以看到server端在收到第一个请求后会故意sleep 20ms,client端之后发送另一个同样index的请求,最终的延时并没有受到故意sleep的影响。
9+
运行后,client端和server端的日志分别如下,"index"是请求的编号。可以看到server端在收到第一个请求后会故意sleep 20ms,client端之后发送另一个同样index的请求,最终的延时并没有受到故意sleep的影响。
1010

1111
![img](../images/backup_request_1.png)
1212

@@ -39,6 +39,80 @@ my_func_latency << tm.u_elapsed(); // u代表微秒,还有s_elapsed(), m_elap
3939
// 好了,在/vars中会显示my_func_qps, my_func_latency, my_func_latency_cdf等很多计数器。
4040
```
4141
42+
## Backup Request 限流
43+
44+
如需限制 backup request 的发送比例,可使用内置工厂函数创建限流策略,也可自行实现 `BackupRequestPolicy` 接口。
45+
46+
优先级顺序:`backup_request_policy` > `backup_request_ms`。
47+
48+
### 使用内置限流策略
49+
50+
调用 `CreateRateLimitedBackupPolicy` 创建限流策略,并将其设置到 `ChannelOptions.backup_request_policy`:
51+
52+
```c++
53+
#include "brpc/backup_request_policy.h"
54+
#include <memory>
55+
56+
brpc::RateLimitedBackupPolicyOptions opts;
57+
opts.backup_request_ms = 10; // 超过10ms未返回时发送backup请求
58+
opts.max_backup_ratio = 0.3; // backup请求比例上限30%
59+
opts.window_size_seconds = 10; // 滑动窗口宽度(秒)
60+
opts.update_interval_seconds = 5; // 缓存比例的刷新间隔(秒)
61+
62+
// CreateRateLimitedBackupPolicy返回的指针由调用方负责释放。
63+
// policy的生命周期必须长于channel——先销毁channel,再销毁policy。
64+
std::unique_ptr<brpc::BackupRequestPolicy> policy(
65+
brpc::CreateRateLimitedBackupPolicy(opts));
66+
67+
brpc::ChannelOptions options;
68+
options.backup_request_policy = policy.get(); // Channel不拥有该对象
69+
channel.Init(..., &options);
70+
// channel必须在policy析构之前销毁。
71+
```
72+
73+
参数说明(`RateLimitedBackupPolicyOptions`):
74+
75+
| 字段 | 默认值 | 说明 |
76+
|------|--------|------|
77+
| `backup_request_ms` | -1 | 超时阈值(毫秒)。-1 表示继承 `ChannelOptions.backup_request_ms`(仅在通过 `ChannelOptions.backup_request_policy` 设置策略时有效;通过 Controller 注入时没有 channel 级的回退值,应显式指定 >= 0 的值)。必须 >= -1。 |
78+
| `max_backup_ratio` | 0.1 | backup比例上限,取值范围 (0, 1] |
79+
| `window_size_seconds` | 10 | 滑动窗口宽度(秒),取值范围 [1, 3600] |
80+
| `update_interval_seconds` | 5 | 缓存刷新间隔(秒),必须 >= 1 |
81+
82+
参数不合法时 `CreateRateLimitedBackupPolicy` 返回 `NULL`
83+
84+
### 使用自定义 BackupRequestPolicy
85+
86+
如需完全控制,可实现 `BackupRequestPolicy` 接口并设置到 `ChannelOptions.backup_request_policy`
87+
88+
```c++
89+
#include "brpc/backup_request_policy.h"
90+
91+
class MyBackupPolicy : public brpc::BackupRequestPolicy {
92+
public:
93+
int32_t GetBackupRequestMs(const brpc::Controller*) const override {
94+
return 10; // 10ms后发送backup
95+
}
96+
bool DoBackup(const brpc::Controller*) const override {
97+
return should_allow_backup(); // 自定义逻辑
98+
}
99+
void OnRPCEnd(const brpc::Controller*) override {
100+
// 每次RPC结束时调用,可在此更新统计
101+
}
102+
};
103+
104+
MyBackupPolicy my_policy;
105+
brpc::ChannelOptions options;
106+
options.backup_request_policy = &my_policy; // Channel不拥有该对象,需保证其生命周期长于Channel
107+
channel.Init(..., &options);
108+
```
109+
110+
### 实现说明
111+
112+
- 比例通过bvar计数器在滑动时间窗口内统计。缓存值通过无锁CAS选举最多每 `update_interval_seconds` 刷新一次,因此每次RPC的开销极低(公共路径仅有两次原子读)。
113+
- Backup决策在做出时立即计数(RPC完成前),以便在延迟抖动期间更快地反馈。总RPC数在完成时统计。这意味着比例在抖动期间可能短暂滞后,这是设计有意为之——限流器的目标是近似的尽力而为的节流,而非精确执行。
114+
- 每个使用限流的Channel会维护两个 `bvar::Window` 采样任务,在Channel数量极多的部署中请留意此开销。
115+
42116
# 当后端server不能挂在一个命名服务内时
43117
44118
【推荐】建立一个开启backup request的SelectiveChannel,其中包含两个sub channel。访问这个SelectiveChannel和上面的情况类似,会先访问一个sub channel,如果在ChannelOptions.backup_request_ms后没返回,再访问另一个sub channel。如果一个sub channel对应一个集群,这个方法就是在两个集群间做互备。SelectiveChannel的例子见[example/selective_echo_c++](https://github.com/apache/brpc/tree/master/example/selective_echo_c++),具体做法请参考上面的过程。

docs/en/backup_request.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,80 @@ my_func_latency << tm.u_elapsed(); // u represents for microsecond, and s_elaps
3939
// All work is done here. My_func_qps, my_func_latency, my_func_latency_cdf and many other counters would be shown in /vars.
4040
```
4141
42+
## Rate-limited backup requests
43+
44+
To limit the ratio of backup requests sent, use the built-in factory function or implement the `BackupRequestPolicy` interface yourself.
45+
46+
Priority order: `backup_request_policy` > `backup_request_ms`.
47+
48+
### Using the built-in rate-limiting policy
49+
50+
Call `CreateRateLimitedBackupPolicy` and set the result on `ChannelOptions.backup_request_policy`:
51+
52+
```c++
53+
#include "brpc/backup_request_policy.h"
54+
#include <memory>
55+
56+
brpc::RateLimitedBackupPolicyOptions opts;
57+
opts.backup_request_ms = 10; // send backup if RPC does not complete within 10ms
58+
opts.max_backup_ratio = 0.3; // cap backup requests at 30% of total
59+
opts.window_size_seconds = 10; // sliding window width in seconds
60+
opts.update_interval_seconds = 5; // how often the cached ratio is refreshed
61+
62+
// The caller owns the returned pointer.
63+
// The policy must outlive the channel — destroy the channel before the policy.
64+
std::unique_ptr<brpc::BackupRequestPolicy> policy(
65+
brpc::CreateRateLimitedBackupPolicy(opts));
66+
67+
brpc::ChannelOptions options;
68+
options.backup_request_policy = policy.get(); // NOT owned by channel
69+
channel.Init(..., &options);
70+
// channel must be destroyed before policy goes out of scope.
71+
```
72+
73+
`RateLimitedBackupPolicyOptions` fields:
74+
75+
| Field | Default | Description |
76+
|-------|---------|-------------|
77+
| `backup_request_ms` | -1 | Timeout threshold in ms. -1 means inherit from `ChannelOptions.backup_request_ms` (only works when the policy is set via `ChannelOptions.backup_request_policy`; at controller level there is no channel-level fallback, so set an explicit >= 0 value instead). Must be >= -1. |
78+
| `max_backup_ratio` | 0.1 | Max backup ratio; range (0, 1] |
79+
| `window_size_seconds` | 10 | Sliding window width in seconds; range [1, 3600] |
80+
| `update_interval_seconds` | 5 | Cached-ratio refresh interval in seconds; must be >= 1 |
81+
82+
`CreateRateLimitedBackupPolicy` returns `NULL` if any parameter is invalid.
83+
84+
### Using a custom BackupRequestPolicy
85+
86+
For full control, implement the `BackupRequestPolicy` interface and set it on `ChannelOptions.backup_request_policy`:
87+
88+
```c++
89+
#include "brpc/backup_request_policy.h"
90+
91+
class MyBackupPolicy : public brpc::BackupRequestPolicy {
92+
public:
93+
int32_t GetBackupRequestMs(const brpc::Controller*) const override {
94+
return 10; // send backup after 10ms
95+
}
96+
bool DoBackup(const brpc::Controller*) const override {
97+
return should_allow_backup(); // your logic here
98+
}
99+
void OnRPCEnd(const brpc::Controller*) override {
100+
// called on every RPC completion; update stats if needed
101+
}
102+
};
103+
104+
MyBackupPolicy my_policy;
105+
brpc::ChannelOptions options;
106+
options.backup_request_policy = &my_policy; // NOT owned by channel; must outlive channel
107+
channel.Init(..., &options);
108+
```
109+
110+
### Implementation notes
111+
112+
- The ratio is computed over a sliding time window using bvar counters. The cached value is refreshed at most once per `update_interval_seconds` using a lock-free CAS election, so the overhead per RPC is very low (two atomic loads in the common path).
113+
- Backup decisions are counted immediately at decision time (before the RPC completes) to provide faster feedback during latency spikes. Total RPCs are counted on completion. This means the ratio may transiently lag during a spike, but this is intentional — the limiter is designed for approximate, best-effort throttling, not exact enforcement.
114+
- Each channel using rate limiting maintains two `bvar::Window` sampler tasks. Keep this in mind in deployments with a very large number of channels.
115+
42116
# When backend servers cannot be hung in a naming service
43117
44118
[Recommended] Define a SelectiveChannel that sets backup request, in which contains two sub channel. The visiting process of this SelectiveChannel is similar to the above situation. It will visit one sub channel first. If the response is not returned after channelOptions.backup_request_ms ms, then another sub channel is visited. If a sub channel corresponds to a cluster, this method does backups between two clusters. An example of SelectiveChannel can be found in [example/selective_echo_c++](https://github.com/apache/brpc/tree/master/example/selective_echo_c++). More details please refer to the above program.

src/brpc/backup_request_policy.cpp

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
#include "brpc/backup_request_policy.h"
19+
20+
#include "butil/logging.h"
21+
#include "bvar/reducer.h"
22+
#include "bvar/window.h"
23+
#include "butil/atomicops.h"
24+
#include "butil/time.h"
25+
26+
namespace brpc {
27+
28+
// Standalone statistics module for tracking backup/total request ratio
29+
// within a sliding time window. Each instance schedules two bvar::Window
30+
// sampler tasks; keep this in mind for high channel-count deployments.
31+
class BackupRateLimiter {
32+
public:
33+
BackupRateLimiter(double max_backup_ratio,
34+
int window_size_seconds,
35+
int update_interval_seconds)
36+
: _max_backup_ratio(max_backup_ratio)
37+
, _update_interval_us(update_interval_seconds * 1000000LL)
38+
, _total_count()
39+
, _backup_count()
40+
, _total_window(&_total_count, window_size_seconds)
41+
, _backup_window(&_backup_count, window_size_seconds)
42+
, _cached_ratio(0.0)
43+
, _last_update_us(0) {
44+
}
45+
46+
// All atomic operations use relaxed ordering intentionally.
47+
// This is best-effort rate limiting: a slightly stale ratio is
48+
// acceptable for approximate throttling. Within a single update interval,
49+
// the cached ratio is not updated, so bursts up to update_interval_seconds
50+
// in duration can exceed the configured max_backup_ratio transiently.
51+
bool ShouldAllow() const {
52+
const int64_t now_us = butil::cpuwide_time_us();
53+
int64_t last_us = _last_update_us.load(butil::memory_order_relaxed);
54+
double ratio = _cached_ratio.load(butil::memory_order_relaxed);
55+
56+
if (now_us - last_us >= _update_interval_us) {
57+
if (_last_update_us.compare_exchange_strong(
58+
last_us, now_us, butil::memory_order_relaxed)) {
59+
int64_t total = _total_window.get_value();
60+
int64_t backup = _backup_window.get_value();
61+
// Fall back to cumulative counts when the window has no
62+
// sampled data yet (cold-start within the first few seconds).
63+
if (total <= 0) {
64+
total = _total_count.get_value();
65+
backup = _backup_count.get_value();
66+
}
67+
if (total > 0) {
68+
ratio = static_cast<double>(backup) / total;
69+
} else if (backup > 0) {
70+
// Backups issued but no completions in window yet (latency spike).
71+
// Be conservative to prevent backup storms.
72+
ratio = 1.0;
73+
} else {
74+
// True cold-start: no traffic yet. Allow freely.
75+
ratio = 0.0;
76+
}
77+
_cached_ratio.store(ratio, butil::memory_order_relaxed);
78+
}
79+
}
80+
81+
bool allow = ratio < _max_backup_ratio;
82+
if (allow) {
83+
// Count backup decisions immediately for faster feedback
84+
// during latency spikes (before RPCs complete).
85+
_backup_count << 1;
86+
}
87+
return allow;
88+
}
89+
90+
void OnRPCEnd(const Controller* /*controller*/) {
91+
// Count each completed user-level RPC (called once per RPC, not per leg).
92+
// Backup decisions are counted in ShouldAllow() at decision time for
93+
// faster feedback. As a result, the effective suppression threshold is
94+
// (backup_count / total_count), where total_count is the number of
95+
// user RPCs that have completed.
96+
_total_count << 1;
97+
}
98+
99+
private:
100+
double _max_backup_ratio;
101+
int64_t _update_interval_us;
102+
103+
bvar::Adder<int64_t> _total_count;
104+
mutable bvar::Adder<int64_t> _backup_count;
105+
bvar::Window<bvar::Adder<int64_t>> _total_window;
106+
bvar::Window<bvar::Adder<int64_t>> _backup_window;
107+
108+
mutable butil::atomic<double> _cached_ratio;
109+
mutable butil::atomic<int64_t> _last_update_us;
110+
};
111+
112+
// Internal BackupRequestPolicy that composes a BackupRateLimiter
113+
// for ratio-based suppression.
114+
class RateLimitedBackupPolicy : public BackupRequestPolicy {
115+
public:
116+
RateLimitedBackupPolicy(int32_t backup_request_ms,
117+
double max_backup_ratio,
118+
int window_size_seconds,
119+
int update_interval_seconds)
120+
: _backup_request_ms(backup_request_ms)
121+
, _rate_limiter(max_backup_ratio, window_size_seconds,
122+
update_interval_seconds) {
123+
}
124+
125+
int32_t GetBackupRequestMs(const Controller* /*controller*/) const override {
126+
return _backup_request_ms;
127+
}
128+
129+
bool DoBackup(const Controller* /*controller*/) const override {
130+
return _rate_limiter.ShouldAllow();
131+
}
132+
133+
void OnRPCEnd(const Controller* controller) override {
134+
_rate_limiter.OnRPCEnd(controller);
135+
}
136+
137+
private:
138+
int32_t _backup_request_ms;
139+
BackupRateLimiter _rate_limiter;
140+
};
141+
142+
BackupRequestPolicy* CreateRateLimitedBackupPolicy(
143+
const RateLimitedBackupPolicyOptions& options) {
144+
if (options.backup_request_ms < -1) {
145+
LOG(ERROR) << "Invalid backup_request_ms=" << options.backup_request_ms
146+
<< ", must be >= -1 (-1 means inherit from ChannelOptions)";
147+
return NULL;
148+
}
149+
if (options.max_backup_ratio <= 0 || options.max_backup_ratio > 1.0) {
150+
LOG(ERROR) << "Invalid max_backup_ratio=" << options.max_backup_ratio
151+
<< ", must be in (0, 1]";
152+
return NULL;
153+
}
154+
if (options.window_size_seconds < 1 || options.window_size_seconds > 3600) {
155+
LOG(ERROR) << "Invalid window_size_seconds=" << options.window_size_seconds
156+
<< ", must be in [1, 3600]";
157+
return NULL;
158+
}
159+
if (options.update_interval_seconds < 1) {
160+
LOG(ERROR) << "Invalid update_interval_seconds="
161+
<< options.update_interval_seconds << ", must be >= 1";
162+
return NULL;
163+
}
164+
if (options.update_interval_seconds > options.window_size_seconds) {
165+
LOG(WARNING) << "update_interval_seconds=" << options.update_interval_seconds
166+
<< " exceeds window_size_seconds=" << options.window_size_seconds
167+
<< "; the ratio window will rarely refresh within its own period";
168+
}
169+
// Plain new (without std::nothrow): brpc follows the project-wide convention
170+
// of letting OOM throw/abort rather than returning NULL. NULL return from
171+
// this factory already signals invalid parameters, not allocation failure.
172+
return new RateLimitedBackupPolicy(
173+
options.backup_request_ms, options.max_backup_ratio,
174+
options.window_size_seconds, options.update_interval_seconds);
175+
}
176+
177+
} // namespace brpc

0 commit comments

Comments
 (0)