0
# Gateway Flow Rules
1
2
The Gateway Flow Rules system provides comprehensive flow control capabilities for API gateways, supporting QPS/thread-based limiting, burst control, and parameter-based flow control. Rules are automatically converted to Sentinel's core flow control rules for seamless integration.
3
4
## Capabilities
5
6
### GatewayFlowRule
7
8
Core configuration class for gateway flow control rules with support for various control behaviors and parameter-based limiting.
9
10
```java { .api }
11
/**
12
* Configuration for gateway flow control rules
13
*/
14
class GatewayFlowRule {
15
/** Default constructor */
16
GatewayFlowRule();
17
18
/** Constructor with resource name */
19
GatewayFlowRule(String resource);
20
21
/** Get the resource name (route ID or API name) */
22
String getResource();
23
24
/** Set the resource name (fluent interface) */
25
GatewayFlowRule setResource(String resource);
26
27
/** Get the resource mode (route ID or custom API name) */
28
int getResourceMode();
29
30
/** Set the resource mode (fluent interface) */
31
GatewayFlowRule setResourceMode(int resourceMode);
32
33
/** Get the flow control grade (QPS or thread count) */
34
int getGrade();
35
36
/** Set the flow control grade (fluent interface) */
37
GatewayFlowRule setGrade(int grade);
38
39
/** Get the threshold count for flow control */
40
double getCount();
41
42
/** Set the threshold count (fluent interface) */
43
GatewayFlowRule setCount(double count);
44
45
/** Get the time interval in seconds for counting */
46
long getIntervalSec();
47
48
/** Set the time interval in seconds (fluent interface) */
49
GatewayFlowRule setIntervalSec(long intervalSec);
50
51
/** Get the control behavior when threshold is exceeded */
52
int getControlBehavior();
53
54
/** Set the control behavior (fluent interface) */
55
GatewayFlowRule setControlBehavior(int controlBehavior);
56
57
/** Get the burst size for traffic bursts */
58
int getBurst();
59
60
/** Set the burst size (fluent interface) */
61
GatewayFlowRule setBurst(int burst);
62
63
/** Get the maximum queuing timeout in milliseconds */
64
int getMaxQueueingTimeoutMs();
65
66
/** Set the maximum queuing timeout (fluent interface) */
67
GatewayFlowRule setMaxQueueingTimeoutMs(int maxQueueingTimeoutMs);
68
69
/** Get the parameter flow item for parameter-based control */
70
GatewayParamFlowItem getParamItem();
71
72
/** Set the parameter flow item (fluent interface) */
73
GatewayFlowRule setParamItem(GatewayParamFlowItem paramItem);
74
}
75
```
76
77
**Usage Examples:**
78
79
```java
80
// Basic QPS limiting
81
GatewayFlowRule qpsRule = new GatewayFlowRule("user-api")
82
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
83
.setGrade(RuleConstant.FLOW_GRADE_QPS)
84
.setCount(100) // 100 QPS limit
85
.setIntervalSec(1);
86
87
// Thread-based limiting with burst support
88
GatewayFlowRule threadRule = new GatewayFlowRule("order-processing")
89
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID)
90
.setGrade(RuleConstant.FLOW_GRADE_THREAD)
91
.setCount(10) // 10 concurrent threads
92
.setBurst(5); // Allow up to 5 additional threads during bursts
93
94
// Rate limiting with queueing
95
GatewayFlowRule rateLimitRule = new GatewayFlowRule("payment-api")
96
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
97
.setGrade(RuleConstant.FLOW_GRADE_QPS)
98
.setCount(50)
99
.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
100
.setMaxQueueingTimeoutMs(2000); // Queue for up to 2 seconds
101
```
102
103
### GatewayParamFlowItem
104
105
Configuration for parameter-based flow control, enabling fine-grained control based on request parameters.
106
107
```java { .api }
108
/**
109
* Configuration for parameter-based flow control
110
*/
111
class GatewayParamFlowItem {
112
/** Get the parameter parsing strategy */
113
int getParseStrategy();
114
115
/** Set the parameter parsing strategy (fluent interface) */
116
GatewayParamFlowItem setParseStrategy(int parseStrategy);
117
118
/** Get the field name for header/URL param/cookie extraction */
119
String getFieldName();
120
121
/** Set the field name (fluent interface) */
122
GatewayParamFlowItem setFieldName(String fieldName);
123
124
/** Get the matching pattern for parameter values */
125
String getPattern();
126
127
/** Set the matching pattern (fluent interface) */
128
GatewayParamFlowItem setPattern(String pattern);
129
130
/** Get the matching strategy for parameter values */
131
int getMatchStrategy();
132
133
/** Set the matching strategy (fluent interface) */
134
GatewayParamFlowItem setMatchStrategy(int matchStrategy);
135
}
136
```
137
138
**Usage Examples:**
139
140
```java
141
// Client IP-based flow control
142
GatewayParamFlowItem ipParam = new GatewayParamFlowItem()
143
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP);
144
145
GatewayFlowRule ipBasedRule = new GatewayFlowRule("api-gateway")
146
.setGrade(RuleConstant.FLOW_GRADE_QPS)
147
.setCount(10) // 10 QPS per IP
148
.setParamItem(ipParam);
149
150
// Header-based flow control
151
GatewayParamFlowItem userIdParam = new GatewayParamFlowItem()
152
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
153
.setFieldName("X-User-ID");
154
155
GatewayFlowRule userBasedRule = new GatewayFlowRule("user-api")
156
.setGrade(RuleConstant.FLOW_GRADE_QPS)
157
.setCount(50) // 50 QPS per user
158
.setParamItem(userIdParam);
159
160
// URL parameter with pattern matching
161
GatewayParamFlowItem apiKeyParam = new GatewayParamFlowItem()
162
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
163
.setFieldName("api_key")
164
.setPattern("premium_.*") // Only apply to premium API keys
165
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX);
166
167
GatewayFlowRule premiumRule = new GatewayFlowRule("premium-api")
168
.setGrade(RuleConstant.FLOW_GRADE_QPS)
169
.setCount(1000) // Higher limits for premium users
170
.setParamItem(apiKeyParam);
171
```
172
173
### GatewayRuleManager
174
175
Manager class for loading, validating, and managing gateway flow rules with automatic conversion to Sentinel parameter rules.
176
177
```java { .api }
178
/**
179
* Manager for gateway flow rules with validation and conversion
180
*/
181
final class GatewayRuleManager {
182
/** Register a property for rule updates */
183
static void register2Property(SentinelProperty<Set<GatewayFlowRule>> property);
184
185
/** Load gateway rules, replacing existing ones */
186
static boolean loadRules(Set<GatewayFlowRule> rules);
187
188
/** Get all currently loaded gateway rules */
189
static Set<GatewayFlowRule> getRules();
190
191
/** Get rules for a specific resource */
192
static Set<GatewayFlowRule> getRulesForResource(String resourceName);
193
194
/** Get converted parameter rules for internal use */
195
static List<ParamFlowRule> getConvertedParamRules(String resourceName);
196
197
/** Validate if a gateway rule is properly configured */
198
static boolean isValidRule(GatewayFlowRule rule);
199
}
200
```
201
202
**Usage Examples:**
203
204
```java
205
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.*;
206
import java.util.Set;
207
208
// Create multiple gateway rules
209
Set<GatewayFlowRule> rules = Set.of(
210
// API-level QPS limiting
211
new GatewayFlowRule("user-api")
212
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
213
.setGrade(RuleConstant.FLOW_GRADE_QPS)
214
.setCount(200),
215
216
// Route-level with parameter control
217
new GatewayFlowRule("payment-route")
218
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID)
219
.setGrade(RuleConstant.FLOW_GRADE_QPS)
220
.setCount(50)
221
.setParamItem(new GatewayParamFlowItem()
222
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)),
223
224
// Thread-based limiting
225
new GatewayFlowRule("processing-api")
226
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
227
.setGrade(RuleConstant.FLOW_GRADE_THREAD)
228
.setCount(20)
229
.setBurst(10)
230
);
231
232
// Load rules
233
boolean loaded = GatewayRuleManager.loadRules(rules);
234
235
// Retrieve rules for specific resources
236
Set<GatewayFlowRule> userApiRules = GatewayRuleManager.getRulesForResource("user-api");
237
238
// Get all rules
239
Set<GatewayFlowRule> allRules = GatewayRuleManager.getRules();
240
241
// Validate individual rule
242
GatewayFlowRule testRule = new GatewayFlowRule("test")
243
.setGrade(RuleConstant.FLOW_GRADE_QPS)
244
.setCount(100);
245
boolean isValid = GatewayRuleManager.isValidRule(testRule);
246
```
247
248
## Control Behaviors
249
250
Gateway flow rules support different control behaviors from Sentinel's `RuleConstant`:
251
252
- **CONTROL_BEHAVIOR_DEFAULT (0)**: Direct rejection when threshold exceeded
253
- **CONTROL_BEHAVIOR_WARM_UP (1)**: Gradual warm-up period for traffic ramp-up
254
- **CONTROL_BEHAVIOR_RATE_LIMITER (2)**: Rate limiting with request queueing
255
- **CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER (3)**: Combination of warm-up and rate limiting
256
257
## Resource Modes
258
259
Gateway rules can target different types of resources:
260
261
- **RESOURCE_MODE_ROUTE_ID (0)**: Target specific gateway routes
262
- **RESOURCE_MODE_CUSTOM_API_NAME (1)**: Target API groups defined by `ApiDefinition`
263
264
## Parameter Parse Strategies
265
266
Parameter-based flow control supports multiple extraction strategies:
267
268
- **CLIENT_IP (0)**: Extract client IP address
269
- **HOST (1)**: Extract host header
270
- **HEADER (2)**: Extract arbitrary request header (requires `fieldName`)
271
- **URL_PARAM (3)**: Extract URL query parameter (requires `fieldName`)
272
- **COOKIE (4)**: Extract cookie value (requires `fieldName`)
273
274
## Parameter Matching Strategies
275
276
When using patterns with parameter flow items:
277
278
- **EXACT (0)**: Exact string match
279
- **PREFIX (1)**: Prefix-based matching
280
- **REGEX (2)**: Regular expression matching
281
- **CONTAINS (3)**: Substring matching
282
283
## Rule Validation
284
285
Rules are automatically validated when loaded. A rule is considered invalid if:
286
287
- Resource name is null or empty
288
- Resource mode is negative
289
- Grade is negative
290
- Count is negative
291
- Burst is negative
292
- Control behavior is negative
293
- Interval is zero or negative
294
- Rate limiter control behavior with negative queuing timeout
295
- Parameter item with invalid parse strategy or missing required field name
296
297
## Best Practices
298
299
1. **Start with simple QPS rules** before adding parameter-based controls
300
2. **Use appropriate resource modes** - API names for grouped endpoints, route IDs for specific routes
301
3. **Configure burst sizes** for handling traffic spikes gracefully
302
4. **Use rate limiting with queueing** for APIs that can tolerate slight delays
303
5. **Monitor parameter rule performance** as they have higher overhead than simple rules
304
6. **Validate rules** using `isValidRule()` before loading in production
305
7. **Use regex patterns sparingly** in parameter matching for performance reasons