2

我正在寻找实现Web应用程序移动时间窗口速率限制算法的有效方法。由此我正在寻找一种可扩展的算法。为App Engine中的Web请求实现速率限制或限制算法的有效方法?

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

这里的算法伪语言:

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的上下文中的其他问题。

+0

如果关注的是简单地用侮辱性的主机/网处理,想指出的DOS保护功能:https://developers.google.com/appengine/docs/python/config/dos – shollyman

+0

我会尝试在第3项中使用memcache(便宜!)而不是ndb(昂贵!),因此不必在第6项中将计数器(昂贵!)碎片化。呃,问题是什么?目前的答案是肯定的;-) –

+0

看看我写回来的这个python包,它在redis之上建立了一个非常好的速率限制算法。 https://github.com/HeyImAlex/rratelimit –

回答

3

你可以做这样的事情完全在内存缓存,虽然这将无法生存的随机密钥驱逐或潮红:

# 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 
+0

您将如何过期通过的限制? – softwarevamp