0Pricing
Secure Coding & OWASP Top 10 for Backend · Урок

Ограничение и регулирование частоты запросов к API

Узнайте, как ограничение частоты запросов защищает API от злоупотреблений, перебора и отказа в обслуживании и как реализовать стратегии ведра токенов и скользящего окна.

«Ограничение и регулирование частоты запросов к API» — бесплатный урок Secure Coding & OWASP Top 10 for Backend на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Secure Coding & OWASP Top 10 for Backend, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Secure Coding & OWASP Top 10 for Backend содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why Rate Limiting?

Rate limiting caps how many requests a client can make in a time window. It protects APIs from brute-force attacks, scraping, accidental loops, and denial-of-service.

It is a key control listed under API security best practices.

Throttling vs Limiting

Rate limiting rejects requests over a hard cap; throttling slows them down (queuing or delaying) instead of rejecting outright. Both manage load and abuse, often used together.

What to Limit On

Choose a key to count requests against:

  • API key or user ID for authenticated traffic
  • IP address for anonymous traffic
  • Endpoint sensitivity (stricter limits on login)

Combining keys gives finer control and resists simple bypasses.

Fixed Window

The simplest approach counts requests in a fixed time window, resetting the counter each period. It is easy but allows bursts at window edges (twice the limit across a boundary).

import time

window = {}
LIMIT = 5
PERIOD = 60

def allow(key):
    now = int(time.time() // PERIOD)
    count = window.get((key, now), 0)
    if count >= LIMIT:
        return False
    window[(key, now)] = count + 1
    return True

Token Bucket

The token bucket refills tokens at a steady rate up to a capacity. Each request consumes a token; an empty bucket means the request is rejected. It allows controlled bursts while enforcing an average rate.

import time

class TokenBucket:
    def __init__(self, rate, capacity):
        self.rate = rate
        self.capacity = capacity
        self.tokens = capacity
        self.last = time.time()
    def allow(self):
        now = time.time()
        self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

Sliding Window

The sliding window tracks timestamps of recent requests and counts only those within the last N seconds. It avoids the burst problem of fixed windows at the cost of more bookkeeping.

Distributed Rate Limiting

With multiple servers, counters must be shared. A central store like Redis holds the counters so limits apply across the whole cluster, not per instance. Use atomic operations to avoid race conditions.

Communicating Limits

Tell clients about their limits with response headers so well-behaved clients can back off.

headers = {
    'X-RateLimit-Limit': '100',
    'X-RateLimit-Remaining': '42',
    'X-RateLimit-Reset': '1717000000',
    'Retry-After': '30',
}
for k, v in headers.items():
    print(k + ': ' + v)

Status Codes

Return 429 Too Many Requests when a client exceeds the limit, ideally with a Retry-After header. This is the standard signal clients and SDKs expect.

Protecting Sensitive Endpoints

Apply stricter limits to high-risk endpoints like login, password reset, and OTP verification. Tight limits here directly blunt brute-force and credential-stuffing attacks.

  • Login: a few attempts per minute
  • Password reset: a few per hour
  • General reads: generous limits

Avoiding Pitfalls

Watch for bypasses: rotating IPs, missing limits on some routes, and limits that reset on server restart. Place rate limiting at the gateway or middleware layer so every route is covered consistently.

Quick Check

Test your understanding of rate limiting.

Recap

You learned why APIs need rate limiting, how to choose a limiting key, and the trade-offs of fixed-window, token-bucket, and sliding-window strategies. You also saw distributed limiting with Redis, the 429 response, and stricter limits for sensitive endpoints.

Часто задаваемые вопросы

Урок «Ограничение и регулирование частоты запросов к API» бесплатный?

Да — полный текст урока «Ограничение и регулирование частоты запросов к API» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Secure Coding & OWASP Top 10 for Backend, подпишись на CoddyKit PRO. Курс Secure Coding & OWASP Top 10 for Backend содержит 4 уроков всего.

Чему я научусь в уроке «Ограничение и регулирование частоты запросов к API»?

Узнайте, как ограничение частоты запросов защищает API от злоупотреблений, перебора и отказа в обслуживании и как реализовать стратегии ведра токенов и скользящего окна. Ты практикуешь Secure Coding & OWASP Top 10 for Backend с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Secure Coding & OWASP Top 10 for Backend?

Предыдущий опыт не требуется. Secure Coding & OWASP Top 10 for Backend на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Ограничение и регулирование частоты запросов к API»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Secure Coding & OWASP Top 10 for Backend?

Да. Каждый урок Secure Coding & OWASP Top 10 for Backend включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Проектирование безопасных RESTful API
  2. Безопасность GraphQL API
  3. Предотвращение атак SSRF
  4. Ограничение и регулирование частоты запросов к API
← Назад к Secure Coding & OWASP Top 10 for Backend