寻找一种更好的方法来计算 API 的 5 分钟请求率

问题描述

我正在尝试使用 AWS CloudWatch Logs Insights 来计算 API 5 分钟内来自每个 IP 地址的请求数。

这是我想要获取的数据示例。

时间范围:01:05 - 01:10

请求来源 请求数量
53.240.51.81 314
36.241.227.134 237
201.72.45.51 201

时间范围:01:10 - 01:15

请求来源 请求数量
43.142.151.81 334
36.131.237.174 230
161.72.15.52 198

时间范围:01:15 - 01:20

请求来源 请求数量
31.132.141.91 334
39.138.217.174 230
191.76.15.42 198

...

这是我的查询

fields @timestamp,@message 
| filter (@message like "/my_api") 
| parse @message '* - * [*] * * * "*" * * * "*" "*" "*"' as remote_addr,remote_user,time_local,http_method,path,http_version,header,status_code,request_length,body_bytes_sent,http_referer,http_user_agent,http_x_forwarded_for
| stats count() as requestCount by http_x_forwarded_for 
| sort requestCount desc

上面查询的问题是只统计了我指定的时间范围内的请求数。

因此,如果我想获取过去 24 小时内的数据,则必须将 Logs Insights 的时间范围指定为 24 * 60 / 5 = 288 次。并运行查询 288 次。

执行我上面描述的步骤会非常耗时。

我想获取数据的原因是我想使用 AWS WAF 对我的 API 设置速率限制。

在应用速率限制之前,我需要知道我的 API 在正常情况下的请求速率。

解决方法

针对我的 CloudTrail 事件日志尝试了类似的查询,而 bin() 正是您想要的:

fields @timestamp,@message
| stats count(*) by eventName,bin(5m)
| sort desc
| limit 20