pythonbottle

Throttling restful actions on a per user basis


What is the best approach to throttling the number of actions a user can do to one per minute?

@route('/do_something/<cmd>',method=['GET','POST'])
def my_command(cmd):
    # Only allow this to be executed once every 60s per user/ip.

I am looking for a server side solution, as I want to enforce this based on the users IP-address.


Solution

  • There may be already existing throttling solutions in python and more specifically bottle framework. You may roll out your own using a storage, and some minor scripting. Since,your throttling period is pretty small i.e. 1 minute, memcache would be a good candidate to store the values.

    1. Generate a hash based on conditions required to throttle. eg hash(user+ip) etc.
    2. When you receive new request, check memcache for values existing with hash as key.

    3 (a). Value does not exist : - Store current timestamp integer in memcache with this hash as key, TTL 1 minute.

    (b) Value exists : - Discard the request.

    Here is a very good decorator written for redis ( for flask framework, but will work anywhere else too ) :

    http://flask.pocoo.org/snippets/70/