【问题标题】:Efficient way to implement a rate-limiting or throttling algorithm for web requests in App Engine?在 App Engine 中为 Web 请求实施速率限制或节流算法的有效方法?
【发布时间】:2014-04-17 01:32:22
【问题描述】:

我正在寻找一种有效的方法来为 Web 应用程序实现移动时间窗口速率限制算法。我正在寻找一种可扩展的算法。

到目前为止,我正在考虑使用分片计数器和内存缓存。

这里是伪语言的算法:

For each request:
1: get the number of requests in the last N minutes from memcache
2: if nothing found in the memcache (memcache flushed or first call?)
3:   get the number of requests in the last N minutes from ndb (expensive!)
4: if the number is to high
5:   block the request
6: increment the sharding counter
7: increment the memcache value (failsafe, if an error occurs here ignore it)
8: process the request

到目前为止我发现的其他问题不适用于 App Engine 的上下文。

【问题讨论】:

  • 如果关心的只是处理滥用主机/网络,想指出dos保护功能:developers.google.com/appengine/docs/python/config/dos
  • 我会尝试在第 3 项中使用 memcache(更便宜!)而不是 ndb(昂贵!),因此不必在第 6 项中对计数器进行分片(昂贵!)。呃,什么是问题?目前答案是肯定的;-)
  • 看看我不久前写的这个python包,它有一个非常好的基于redis的速率限制算法。 github.com/HeyImAlex/rratelimit
  • 我更喜欢使用 App Engine Memcache 的解决方案,因为它是免费的

标签: python algorithm google-app-engine throttling rate-limiting


【解决方案1】:

您可以完全在 memcache 中执行类似的操作,尽管它无法在随机键逐出或刷新中存活:

# Create a key based on time truncated to the minute.
key = 'X' + str(datetime.datetime.utcnow().replace(second=0, microsecond=0))
# Initialize the key and have it expire after a while.
if not memcache.add(key, 1, time=90):
    # If the key already exists, increment the value and save the result.
    count = memcache.incr(key)
    # Do something if it's greater than your per minute rate limit.
    if count > MAX_X_PER_MINUTE:
        raise Error

【讨论】:

  • 您将如何过期已通过的限制?
猜你喜欢
  • 2010-11-29
  • 2011-01-20
  • 2013-02-08
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
相关资源
最近更新 更多