0

Is there a way to exempt certain domains from rate limiting using the slowapi extension for Python FastAPI? I want the frontend (my_domain.com) to be exempt from rate-limiting, but any other requests should be rate limited. For example, I am looking for something like this:

def my_key_func(request):
    """Set up a key function that exempts my_domain.com"""
    if "my_domain.com" in request.client.host:
        # Exempt from limiting
    else:
        # Do limiting

limiter = Limiter(key_func=my_key_func)
app = FastAPI(lifespan=lifespan)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.get("/limited-route")
@limiter.limit("10/minute")
async def function():
    return {"success": 200}

Any ideas? Thanks

gbiz123
  • 11
  • 6
  • How would you know that the request _actually_ came from your frontend, and not from some other API-client sending the same "Origin" (or different) header? Generally you can't know that unless you employ some other method like request signing, so you can send any magic header that you want to verify against (`client.host` would refer to the host of _the client_, and not the site the client is making the request on behalf of). – MatsLindh Jun 01 '23 at 07:54
  • @MatsLindh Could this be accomplished using a secret key on the frontend? If so how would you implement it? – gbiz123 Jun 02 '23 at 02:33
  • That wouldn't really solve anything other than giving your users a magical key that is exempt from rate limiting, so you'd end up in the same case - anything known by the client isn't really secret, if you're trying to protect yourself against _the client itself_. Generally you solve the issue by rate limiting based on user (which would be this secret key), but you'd not exempt anyone from rate limiting - allow a higher rate for authenticated users for example. – MatsLindh Jun 02 '23 at 07:49

0 Answers0