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