I have an API that is somewhat popular (10,000+ requests/day). After 10 requests per day from an IP address I return a message telling the user they need to cough of some cash if they want to use the service more.
This morning, I found that my web service was running terribly slow. I checked out the DB and I was getting absolutely spammed with requests from IP addresses originating in China. They would use an IP address 10 times and then increment the last octet. Sad times.
I'd like to limit or completely cut off requests from China, for the sake of keeping the system alive. What's the best way to do this? Geolookup each request and ban by country code in PHP? This seems like an inefficient way. There's nothing I can do at the htaccess level, is there?
Just block the entire china IP range: in .htaccess
They might be using Chinese IP addresses now, but ban one country and eventually another country will be the problem. Mostly because country has nothing to do with it; the user is the problem. Instead of banning IP ranges, you should detect IP addresses that are increasing by one octet each time they outlive a free trial.
I use the MaxMind GeoIP web service: http://www.maxmind.com/en/web_services#country
You get 2,000,000 lookups for $200. Works great, low latency, and you don't have to maintain a local database.
Block the entire subnet of the abuser to solve the problem temporarily. These types of users will appear from other countries as well so your best bet may be to require a registration and an API key to use the API.
If you still want to block based on IP rather than API key, check how large the abusing subnet is using whois (or BGP) and block the entire IP range.