Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Rate Limiting cho Serverless Apps: Bảo vệ Resources & Kiểm soát Chi phí

Điều tuyệt vời nhất serverless là khả năng scale ngay cả khi traffic spike lớn. Nhưng scale không miễn phí cả về tài chính lẫn kỹ thuật. Developer cần kiểm soát scalability ứng dụng. Lý do chính cần rate limiting trong serverless app:

1- Bảo vệ resources: Nếu cung cấp public API, traffic spikes degrade service quality, có thể dẫn đến service outage cho tất cả users. Cần bảo vệ hệ thống khỏi cascading failures và self-inflicted DDoS. Bug trong app có thể trigger vấn đề này. Internal process retry endpoint indefinitely khi failure dễ exhaust resources.

2- Quản lý user quotas: Muốn define quotas cho users để fair use services. Cần quotas nếu cung cấp services ở different pricing tiers.

3- Kiểm soát chi phí: Nhiều ví dụ thực tế uncontrolled system gây large bills. Rủi ro lớn cho serverless nhờ highly scalable nature. Rate limiting giúp kiểm soát costs.

Các giải pháp

Nhiều alternative rate limiting solutions ở các layer khác nhau. Liệt kê 3 chính với pros/cons:

1- Concurrency Level của Function:

Cloud providers tạo multiple containers scale function executions. Set limit max concurrent containers/instances. Giúp limit concurrency nhưng không control số lần function called per second.

Cách limit concurrency cho AWS Lambda và Google Cloud Functions.

  • Pros: No overhead, Easy to configure
  • Cons: Không complete solution. Chỉ control concurrency. Executions per second không limited.

2- Rate limiting trên API Gateway

Nếu access functions qua API Gateway, apply rate limiting policy lên API Gateway. Cả AWS và GCP có guides cấu hình.

  • Pros: No overhead, Easy to configure
  • Cons: Chỉ áp dụng nếu dùng API Gateway. Không support sophisticated cases như quotas per user hoặc per IP.

3- Rate limiting với Redis

Giải pháp complete và powerful nhất. Nhiều Redis-based rate limiting libraries. Trong blog post của Jeremy Daly, ông từ chối Elasticache, nói rằng this adds a "non-serverless" component and another thing to manage. Upstash trở thành alternative tốt với serverless model và per-request-pricing.

  • Pros: Powerful, implement customized logic fit user model. Scalable (xem GitHub dùng Redis rate limiting). Rich ecosystem: redis_rate, redis-cell, node-ratelimiter
  • Cons: Overhead dùng Redis.

Code: Rate Limiting với Redis

Nhờ rate limiting libraries, dễ apply rate limiting vào app code. Ví dụ limit execution AWS Lambda function per IP per second:

const RateLimiter = require("async-ratelimiter");
const Redis = require("ioredis");
const { getClientIp } = require("request-ip");
const rateLimiter = new RateLimiter({
  db: new Redis("YOUR_REDIS_URL"),
  max: 1,
  duration: 5_000,
});
module.exports.hello = async (event) => {
  const clientIp = getClientIp(event) || "NA";
  const limit = await rateLimiter.get({ id: clientIp });
  if (!limit.remaining) {
    return {
      statusCode: 429,
      body: JSON.stringify({ message: "Sorry, you are rate limited. Wait for 5 seconds" }),
    };
  }
  return {
    statusCode: 200,
    body: JSON.stringify({ message: "hello!" }),
  };
};

Xem tutorial đầy đủ.

Reading List