การจำกัดอัตราและการควบคุมความถี่
นำการจำกัดอัตราและการควบคุมความถี่มาใช้ เพื่อปกป้อง API จากการใช้งานในทางที่ผิดและรับรองการใช้งานอย่างเป็นธรรมระหว่างไคลเอ็นต์
การจำกัดอัตราและการควบคุมความถี่ เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is Rate Limiting?
Imagine a popular API. Without limits, a single user or malicious bot could flood it with requests, slowing it down for everyone or even crashing it.
Rate limiting is a technique to control the number of requests a client can make to a server within a specific time window. It's like a bouncer at a club, ensuring fair entry for all.
Protecting Your API
Rate limiting is vital for several reasons:
- Prevent Abuse: Stops bots and malicious users from overwhelming your API.
- Ensure Fair Usage: Guarantees that all users get a reasonable share of API resources.
- DDoS Protection: A basic layer of defense against distributed denial-of-service attacks.
- Cost Management: For cloud-based services, too many requests can lead to higher bills.
Rate Limiting in Action
Let's see a simple example of how a rate limiter might work behind the scenes. This script tracks requests from different "IP addresses" and allows only a certain number within a time window.
const requestCounts = new Map<string, { count: number; resetTime: number }>();
const LIMIT = 3; // Max 3 requests
const WINDOW_MS = 5000; // per 5 seconds
function checkRateLimit(ip: string): boolean {
const now = Date.now();
let entry = requestCounts.get(ip);
if (!entry || now > entry.resetTime) {
entry = { count: 1, resetTime: now + WINDOW_MS };
requestCounts.set(ip, entry);
return true; // Request allowed
}
if (entry.count < LIMIT) {
entry.count++;
requestCounts.set(ip, entry);
return true; // Request allowed
}
return false; // Request denied
}
// Simulate requests for IP "192.168.1.1"
console.log("Req 1 (IP A):", checkRateLimit("192.168.1.1"));
console.log("Req 2 (IP A):", checkRateLimit("192.168.1.1"));
console.log("Req 3 (IP A):", checkRateLimit("192.168.1.1"));
console.log("Req 4 (IP A):", checkRateLimit("192.168.1.1")); // Denied
console.log("Req 1 (IP B):", checkRateLimit("192.168.1.2"));What is Throttling?
While often used interchangeably, throttling has a subtle difference. Rate limiting is a hard cap: once you hit the limit, you're blocked.
Throttling, however, aims to smooth out the request rate, often by delaying requests or allowing a slower, sustained rate rather than blocking entirely. It's more about resource management and preventing a system from becoming overloaded.
Introducing NestJS Throttler
NestJS provides a robust solution for both rate limiting and throttling through the @nestjs/throttler package. It's built on top of the express-rate-limit or fastify-rate-limit packages, offering a declarative way to protect your endpoints.
The module uses a guard to intercept requests and apply rules before they reach your controller logic.
Global Throttling Configuration
First, install the package. Then, integrate ThrottlerModule into your root module (AppModule) and apply the ThrottlerGuard globally.
// 1. Install package
// npm install @nestjs/throttler
// 2. src/app.module.ts
import { Module } from '@nestjs/common';
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
import { APP_GUARD } from '@nestjs/core'; // For global guard
@Module({
imports: [
ThrottlerModule.forRoot([{
ttl: 60000, // Time to live (1 minute)
limit: 10 // Max 10 requests
}]),
],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule {}Overriding Limits per Route
Sometimes, you need different limits for specific endpoints. For example, a login route might have a stricter limit than a public data endpoint. You can override the global settings using the @Throttle() decorator.
// src/app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
@Controller('posts')
export class PostsController {
@Get()
findAll(): string {
return 'This is a public list of posts.';
}
@Throttle({ default: { limit: 3, ttl: 60000 } }) // 3 req/min
@Get('protected')
findProtected(): string {
return 'This is a protected list of posts.';
}
@Throttle({ default: { limit: 1, ttl: 5000 } }) // 1 req/5s
@Get('critical')
findCritical(): string {
return 'Accessing critical data.';
}
}Skipping Throttling
There might be routes you want to completely exempt from any throttling rules, such as health check endpoints or webhook receivers that expect high traffic. Use the @SkipThrottle() decorator for this.
// src/status.controller.ts
import { Controller, Get } from '@nestjs/common';
import { SkipThrottle } from '@nestjs/throttler';
@Controller('status')
export class StatusController {
@SkipThrottle() // This route will ignore all throttling
@Get('health')
getHealth(): string {
return 'API is healthy!';
}
@Get('metrics')
getMetrics(): string {
return 'Application metrics data.'; // This route is throttled
}
}Beyond IP Address
By default, the NestJS Throttler module identifies clients by their IP address. However, for authenticated users, you might want to apply limits based on their user ID, rather than their IP.
This requires extending the ThrottlerGuard and overriding the getRequestResponse method to extract a different key (e.g., from a JWT token). This ensures that a single user cannot bypass limits by changing IPs.
Understanding Throttling
You've learned about rate limiting and throttling. Let's test your understanding!
Summary of Protection
Great job! In this lesson, you learned about the importance of rate limiting and throttling to protect your NestJS APIs. You explored how to set up the @nestjs/throttler module, configure global limits, apply route-specific rules, and even skip throttling for certain endpoints.
Implementing these techniques is a crucial step in building robust and secure backend services. Keep exploring how to fine-tune these limits and integrate them with other security measures!
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 20
- บทเรียน
- 76
คำถามที่พบบ่อย
บทเรียน “การจำกัดอัตราและการควบคุมความถี่” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การจำกัดอัตราและการควบคุมความถี่” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การจำกัดอัตราและการควบคุมความถี่”
นำการจำกัดอัตราและการควบคุมความถี่มาใช้ เพื่อปกป้อง API จากการใช้งานในทางที่ผิดและรับรองการใช้งานอย่างเป็นธรรมระหว่างไคลเอ็นต์ คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน
บทเรียน “การจำกัดอัตราและการควบคุมความถี่” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม
ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การจำกัดอัตราและการควบคุมความถี่
- การบันทึกข้อมูลการทำงานด้วย Winston/Pino
- การตรวจสอบด้วย Prometheus