Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Redis

Serverless Rate Limiting: ปกป้องและเพิ่มประสิทธิภาพทรัพยากรในสภาพแวดล้อม Stateless

การรักษาความพร้อมใช้งานของระบบเป็นหนึ่งในภารกิจสำคัญที่สุดสำหรับผลิตภัณฑ์ใดๆ น่าเสียดายที่ผู้คนอาจใช้ประโยชน์โดยท่วมท้นทรัพยากร หรือคุณต้องการจำกัดการใช้งานและเรียกเก็บค่าบริการ Rate Limiting เป็นโซลูชันมาตรฐานสำหรับปัญหาเหล่านี้และควรทำงานได้ทันที ไร้การสร้างระบบ Rate Limiting ที่ทำงานดีในสภาพแวดล้อม Stateless เช่น Serverless Functions

ประกาศ @upstash/ratelimit

พร้อมใช้งานบน GitHub, npm หรือ Deno

วันนี้เราเผยแพร่ @upstash/ratelimit โซลูชัน Rate Limiting สำหรับสภาพแวดล้อม Serverless เช่น Vercel, Cloudflare, Deno, Fastly และ Netlify สร้างบน Upstash Serverless Redis และให้โซลูชัน Rate Limiting ใช้ Database หนึ่งหรือหลายตัว เพื่อประสบการณ์ Low Latency สำหรับผู้ใช้ทั่วโลก!

เริ่มต้นใช้งาน

@upstash/ratelimit นำอัลกอริทึมมาตรฐาน 3 แบบมา Implement อ่านรายละเอียดใน README ของโปรเจกต์

เราจัดเตรียม 2 Methods:

  • limit(identifier: string): Promise<RatelimitResponse>

limit จะคืนค่า true หรือ false พร้อม Metadata เกี่ยวกับ Requests ที่เหลือ ใช้ได้หากต้องการปฏิเสธ Requests ที่เกิน Limit ที่ตั้งไว้

  • blockUntilReady(identifier: string, timeout: number): Promise<RatelimitResponse>

กรณีที่ไม่ต้องการปฏิเสธ Request ทันที แต่ต้องการรอจนกว่าจะประมวลผลได้ โปรดทราบว่าแพลตฟอร์มบางแห่งคิดค่าใช้จ่ายจาก Execution Time ของ Function

Single Regional Database

Rate Limiting ด้วย Database เดียวตรงไปตรงมา สร้าง Database บน Upstash และเริ่มใช้งาน:

import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

// สร้าง Rate Limiter ใหม่ อนุญาต 10 Requests ต่อ 10 วินาที
const ratelimit = new Ratelimit({
    redis: Redis.fromEnv(),
    limiter: Ratelimit.slidingWindow(10, "10 s"),
});

// ใช้ String คงที่เพื่อจำกัดทุก Requests ด้วย Rate Limit เดียว
// หรือใช้ UserID, API Key หรือ IP Address สำหรับ Limit แบบรายบุคคล
const identifier = "api";
const { success } = await ratelimit.limit(identifier);

if (!success) {
    return "Unable to process at this time";
}
doExpensiveCalculation();
return "Here you go!";

Global Replicated Rate Limiting

สมมติคุณมีลูกค้าใน US และ Europe ในกรณีนี้ สร้าง Regional Redis Databases 2 ตัวบน Upstash และผู้ใช้จะได้ Latency ของ DB ที่ใกล้ที่สุด

import { GlobalRatelimit } from "@upstash/ratelimit";
// for deno: see above
import { Redis } from "@upstash/redis";

// สร้าง Rate Limiter ใหม่ อนุญาต 10 Requests ต่อ 10 วินาที
const ratelimit = new GlobalRatelimit({
    redis: [
        new Redis({ /* europe */ }),
        new Redis({ /* north america */ }),
    ],
    limiter: Ratelimit.slidingWindow(10, "10 s"),
});

ข้อสรุป

หากมีคำถาม กรุณาติดต่อเราที่ GitHub หรือช่องทางด้านล่าง

ติดตามเราที่ Discord และ Twitter