全局限流与按服务限流
了解边缘位置应用的全局限流与针对单个微服务的具体限制之间的差异及相互作用。
全局限流与按服务限流 是 CoddyKit 上的免费 API Rate Limiting & Scalability Patterns 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 API Rate Limiting & Scalability Patterns 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 API Rate Limiting & Scalability Patterns 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Global vs. Per-Service Limits
APIs often handle diverse traffic, from general users to specific internal systems. To manage this, we need different rate limiting strategies.
Today, we'll explore two key approaches: global rate limiting and per-service rate limiting. Understanding their differences helps build robust and fair APIs.
Guarding the Gates Globally
Global rate limiting is applied at the very edge of your system, before requests even reach individual services. Think of it as a bouncer at the club entrance.
- It protects your entire infrastructure.
- Often implemented in API Gateways, load balancers, or edge proxies.
- Focuses on overall request volume to prevent system overload or DDoS attacks.
Global Limit Configuration
Here's a simplified example of how a global rate limit might be configured in an API Gateway like Nginx. It limits requests across all endpoints.
http {
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
server {
location / {
limit_req zone=mylimit burst=20 nodelay;
proxy_pass http://backend_services;
}
}
}Why Global Limits Matter
Implementing global rate limits offers several advantages:
- DDoS Protection: Blocks malicious traffic before it impacts your services.
- Overall Stability: Ensures your entire system isn't overwhelmed by sudden traffic spikes.
- Centralized Control: Easy to manage and modify limits for the whole API landscape.
- Resource Efficiency: Less work for individual services to do for basic filtering.
Fine-Grained Service Control
Per-service rate limiting happens inside a specific microservice. It's like individual rules for different rooms within the club.
- It applies to particular endpoints or operations within that service.
- Implemented directly in the service's code or via a sidecar proxy.
- Focuses on protecting specific service resources and enforcing business logic.
Per-Service Limit Code
Here's a tiny Java example illustrating a basic per-service rate limit for a specific endpoint. This uses a simple in-memory counter for demonstration.
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.time.Instant;
public class Main {
private static final int MAX_REQUESTS_PER_MINUTE = 3;
private static final long WINDOW_MILLIS = 60 * 1000; // 1 minute
private static ConcurrentHashMap<String, Long> lastResetTime =
new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, AtomicInteger> requestCounts =
new ConcurrentHashMap<>();
public static boolean allowRequest(String userId) {
long currentTime = Instant.now().toEpochMilli();
lastResetTime.computeIfAbsent(userId, k -> currentTime);
requestCounts.computeIfAbsent(userId, k -> new AtomicInteger(0));
// Reset if window passed
if (currentTime - lastResetTime.get(userId) > WINDOW_MILLIS) {
lastResetTime.put(userId, currentTime);
requestCounts.get(userId).set(0);
}
if (requestCounts.get(userId).get() < MAX_REQUESTS_PER_MINUTE) {
requestCounts.get(userId).incrementAndGet();
return true;
}
return false;
}
public static void main(String[] args) {
String userA = "user123";
System.out.println("User A requests:");
for (int i = 0; i < 5; i++) {
System.out.println("Request " + (i + 1) + ": " +
(allowRequest(userA) ? "Allowed" : "Denied"));
}
System.out.println("\nUser B requests:");
String userB = "user456";
for (int i = 0; i < 2; i++) {
System.out.println("Request " + (i + 1) + ": " +
(allowRequest(userB) ? "Allowed" : "Denied"));
}
}
}Why Per-Service Limits are Key
Per-service rate limits provide more granular control:
- Resource Protection: Prevents one endpoint from exhausting a service's specific resources (e.g., database connections).
- Business Logic: Enforces limits based on specific user tiers or API functionality (e.g., "premium users get 1000 calls/min to this endpoint").
- Isolation: A limit breach in one service doesn't necessarily bring down others.
Working Together: Layered Defense
The most robust systems use both global and per-service rate limits. They act as a layered defense:
- Global limits: Act as a first line of defense, filtering out bulk traffic and protecting the entire system's entry point.
- Per-service limits: Provide fine-tuned control within individual services, protecting specific resources and enforcing business rules.
Think of it as multiple checkpoints, each with a different purpose.
When to Use Which?
When designing your rate limiting strategy, consider:
- Global: Best for broad protection, anonymous traffic, and preventing DDoS. Easy to implement at the infrastructure level.
- Per-service: Ideal for protecting specific backend resources, enforcing user-specific quotas, or handling authenticated traffic with distinct access levels. Requires more application-level logic.
Often, a combination is the best approach.
Test Your Knowledge
Consider an API with a global rate limit of 1000 requests/second and a specific microservice endpoint that has a per-user limit of 10 requests/minute. A user makes 50 requests in 30 seconds to this specific endpoint.
Global vs. Per-Service Recap
We've explored the critical differences and synergy between global and per-service rate limiting:
- Global limits: Act at the system's edge, protecting overall infrastructure from high-volume attacks.
- Per-service limits: Provide fine-grained control within microservices, protecting specific resources and enforcing business rules.
Combining both strategies creates a robust, multi-layered defense for your APIs. Next, we'll dive into handling rate limit exceedance gracefully.
常见问题解答
「全局限流与按服务限流」课时是免费的吗?
是的 — 「全局限流与按服务限流」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 API Rate Limiting & Scalability Patterns 课程的其余内容,请升级到 CoddyKit PRO。 API Rate Limiting & Scalability Patterns 课程共包含 4 节课。
「全局限流与按服务限流」这节课中我会学到什么?
了解边缘位置应用的全局限流与针对单个微服务的具体限制之间的差异及相互作用。 你通过在浏览器中直接运行的动手代码来练习 API Rate Limiting & Scalability Patterns,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 API Rate Limiting & Scalability Patterns 需要有经验吗?
无需任何先前经验。CoddyKit 上的 API Rate Limiting & Scalability Patterns 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「全局限流与按服务限流」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 API Rate Limiting & Scalability Patterns 课中编写并运行代码吗?
能。每节 API Rate Limiting & Scalability Patterns 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- API 网关集成模式
- 全局限流与按服务限流
- 动态限流配置
- 使用 Redis 实现分布式限流