kotlinnetwork-programmingktor

Rate limiter for specific client IP?


The Rate limiter plugin in KTor does not distinguish between client IPs i.e. all clients use the same token bucket.

  1. Is there a way to have a unique bucket for each client IP address?
  2. The rate limiter only seems to work if the client is accessing a valid page, but does not count any tokens if client is accessing a page that does not exist. I have applied a global rate limiter and not a route specific one so I would expect it should work (I want this so that someone cannot bring down my server with brute force attack of million requests per minute)

Solution

    1. You can use the requestKey configuration method to have independent rate limits based on the client's IP address:
    install(RateLimit) {
        global {
            requestKey {
                call -> call.request.origin.remoteAddress
            }
        }
    }
    
    1. By default, the global rate limiter considers non-existent routes.