1

I have created a flask app that I would limit to add a Flask-Limiter too. It intends to let the user use the route once per minute. If the user tries again it redirects to a custom 429 page. On localhost it works absolutely perfectly, however on committing it to my Heroku app the limiter does not prevent the use from using the route multiple times. It also doesn't redirect to the 429 page.

app = Flask(__name__)
limiter = Limiter(
    app,
    key_func=get_remote_address,
    default_limits=["200 per day", "50 per hour"]
)

@main_bp.route('/main', methods=['POST'])
@limiter.limit("1/minute")
def text_sum():
   the code blah blah blah

@main_bp.errorhandler(429)
def ratelimit_handler(e):
    return render_template('main429.html', result = "Please try again in 1 minute")
  • 1
    This could be due to [heroku defaulting to 2 gunicorn workers](https://stackoverflow.com/a/62330039/2052575). Incoming requests hit a random worker which each have their own memory. Quick workaround would be to specify 1 worker (as in the answer I linked). If you need to scale to several workers, then use a storage backend for Flask-Limiter such as Redis [as documented](https://limits.readthedocs.io/en/latest/storage.html#storage-scheme). On Heroku you'd need a [redis add-on](https://elements.heroku.com/addons/heroku-redis) which *may* push you into the paid teir. – v25 Aug 06 '20 at 18:43

1 Answers1

2

As v25 stated - I simply changed the procfile to this:

web: gunicorn --workers 1 wsgi:app
  • 1
    Just keep an eye on performance under load with this. Should be fine for a small amount of traffic, particularly if you don't have functions that 'block'. To be sure you could test with a loadtesting tool like [hey](https://github.com/rakyll/hey). For handling larger ammounts of traffic you may wish to look at Redis as a backend for Limiter, allowing you to start with several sync workers, or move to async workers like gevent or eventlet. You can read more about concurency in threads [like this one](https://github.com/benoitc/gunicorn/issues/1488). – v25 Aug 08 '20 at 22:20