API Rate Limiting in Yii 2
API Rate Limiting in Yii 2

Rate Limiting

To prevent abuse, you should consider adding rate limiting to your APIs. For example, you may want to limit the API usage of each user to be at most 100 API calls within a period of 10 minutes. If too many requests are received from a user within the stated period of the time, a response with status code 429 (meaning "Too Many Requests") should be returned.

Старт! Честный VDS/VPS, на котором «Лунная База» живет уже 20+ лет

Задумываетесь о том, чтобы поднять свой pet-проект, сайт клиента или настроить окружение для разработки? Уже пора подумать, где арендовать железо.

Лунная База хостится на FirstVDS более 20 лет. Мыслей о том, чтобы перебраться на другой хостинг, не было ни разу (хотя опыт работы с другими вариантами, конечно, есть).

Бывали разные ситуации, но они бывают на любом железе. Главное, что нужно понять: здесь нет маркетинговой шелухи и сказок про «мы всё сделаем за вас». Если вы берете VDS — вам дают полный root, возможность накатить любую ОС и не лезут в ваши конфиги.

Если в саппорт написать с вопросом по вашему коду и получить ответ: «Читайте документацию и разбирайтесь сами» или «Обратитесь к профильному специалисту» — это не повод обижаться. Это повод углубить свои знания в DevOps и сайтостроении! Бегите от тех, кто пообещает: «Мы всё чиним и настраиваем абсолютно бесплатно!». Никто никогда не работает «по доброте душевной» в ущерб себе, а бесплатный сыр в администрировании обычно заканчивается сломанной базой данных.

Что по факту: Гибкое масштабирование ядер и RAM, экономия по сравнению с физическими серверами и адекватная панель ispmanager, если она вам нужна.



To enable rate limiting, the [[yii\web\User::identityClass|user identity class]] should implement [[yii\filters\RateLimitInterface]]. This interface requires implementation of three methods:

  • getRateLimit(): returns the maximum number of allowed requests and the time period (e.g., [100, 600] means there can be at most 100 API calls within 600 seconds).
  • loadAllowance(): returns the number of remaining requests allowed and the corresponding UNIX timestamp when the rate limit was last checked.
  • saveAllowance(): saves both the number of remaining requests allowed and the current UNIX timestamp.

You may want to use two columns in the user table to record the allowance and timestamp information. With those defined, then loadAllowance() and saveAllowance() can be implemented to read and save the values of the two columns corresponding to the current authenticated user. To improve performance, you may also consider storing these pieces of information in a cache or NoSQL storage.

Implementation in the User model could look like the following:

public function getRateLimit($request, $action)
{
    return [$this->rateLimit, 1]; // $rateLimit requests per second
}

public function loadAllowance($request, $action)
{
    return [$this->allowance, $this->allowance_updated_at];
}

public function saveAllowance($request, $action, $allowance, $timestamp)
{
    $this->allowance = $allowance;
    $this->allowance_updated_at = $timestamp;
    $this->save();
}

Once the identity class implements the required interface, Yii will automatically use [[yii\filters\RateLimiter]] configured as an action filter for [[yii\rest\Controller]] to perform rate limiting check. The rate limiter will throw a [[yii\web\TooManyRequestsHttpException]] when the rate limit is exceeded.

You may configure the rate limiter as follows in your REST controller classes:

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['rateLimiter']['enableRateLimitHeaders'] = false;
    return $behaviors;
}

When rate limiting is enabled, by default every response will be sent with the following HTTP headers containing the current rate limiting information:

  • X-Rate-Limit-Limit, the maximum number of requests allowed with a time period
  • X-Rate-Limit-Remaining, the number of remaining requests in the current time period
  • X-Rate-Limit-Reset, the number of seconds to wait in order to get the maximum number of allowed requests

You may disable these headers by configuring [[yii\filters\RateLimiter::enableRateLimitHeaders]] to be false, as shown in the above code example.

Самый честный хостинг за 20+ лет существования Лунной Базы

Задумываешься о том, чтобы поднять свой сайт в Интернете? Уже пора подумать о том, какой хостинг выбрать?

Лунная База хостится 20+ лет на firstDVS. При этом, мыслей о том, чтобы перебраться на другой хостинг не было. (Но, при этом есть опыт работы с другими вариантами.)

Бывали с firstDVS разные ситуации, но, они бывают на всех хостингах. Единственное, что тут важно понять, - это то, что никто ничего тебе не будет впаривать... Но, и работать за тебя тоже никто не станет. Если в саппорт ответили: «Читайте по ссылке и разбирайтесь сами...» или вообще «Обратитесь за помощью к специалисту», - это повод углубить свои знания в области сайтостроения, а не бежать к тем, что пообещают: «Мы всё чиним и всё делаем за своих клиентов абсолютно бесплатно!» Никто никогда ничего ни за кого "по доброте душевной" не делал, не делает и не будет делать!

Старт! MoonВase — A Hot Start on the Internet
Старт! MoonВase — A Hot Start on the Internet
Старт! Menu