I have to rate limit PHP REST API endpoint. Each request is already made with unique client/customer id. I have to be able to add following rules:
- rate limit per 5min (last 5 min at any time)
- rate limit per hour (last 60 min at any time)
- rate limit per week (starting to count at 1st day of week)
- rate limit per month (starting to count at 1st day of each month)
Also I have to log each request type and some meta-data. Of course it should work as fast as possible to minimize extra overhead on API endpoint.
In Postgres it would look like this:
INSERT INTO requests (created_at, client_id)
SELECT now(), client_id
FROM clients c
WHERE
c.id = 123 -- client id is passed inside request
AND (
SELECT COUNT(*)
FROM requests r
WHERE r.client_id = c.id
AND r.created_at > now() - '5 minutes'::interval
) > c.limit_per_5min
AND (
SELECT COUNT(*)
FROM requests r
WHERE r.client_id = c.id
AND r.created_at > now() - '1 hour'::interval
) > c.limit_per_1hour
-- and other limits...
But I am not sure if it's a good idea to use Postgres here. I thought also about MongoDB or Redis but I am also not sure if they can handle so many rules (and how?).
Please advice what technology should I use here?
Also I will have to query for example how many requests of some type, were served to customer with id xxx.