如何对 API 进行速率限制 [英] How To Rate-Limit An API

查看:51
本文介绍了如何对 API 进行速率限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限制 API 请求的最佳方法是什么?基本上,我们希望将用户限制为每小时 360 个 API 请求(每 10 秒一个请求).我想到的是跟踪每个 API 请求并进行存储:

What is the best way to limit requests for an API? Basically, we want to limit users to 360 API requests an hour (a request every 10 seconds). What comes to mind is tracking every API request and storing:

  ip-address          hourly-requests
  1.2.3.4             77
  2.3.4.5             34
  3.4.5.6             124

如果 ip-address 请求大于 360,只需返回一个头部:

If the ip-address requests is greater than 360, simply return a header with:

  429 - Too Many Requests

然后每小时回滚计数器hourly-requests.这似乎是一种非常低效的方法,因为我们必须对每个 API 请求进行 MySQL 查询以增加计数器.此外,我们需要一个 cron 任务来每小时重置所有计数器.

Then rollback the counter hourly-requests every hour. This seems like an very inefficient method, since we have to make a MySQL query on every API request to increment the counter. Also, we would need a cron task to reset all counters every hour.

有更优雅/更高效的解决方案吗?

Is there a more elegant/efficient solution?

推荐答案

可以尝试使用Redis,有几个限速模式

You can try to use Redis, there are few pattern for rate limiting

这篇关于如何对 API 进行速率限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆