The count-then-insert race
The first version counted tasks created in the last minute, compared the count to the limit, and then inserted the task. Sequential requests behaved perfectly. Thirty parallel requests with a 20-per-minute limit created 24 tasks.
The requests all read the same count before any of them inserted. The check and the insert were separate statements, so the limit was advisory under concurrency.
select count(*) from tasks
where api_key_id = $1
and created_at >= now() - interval '1 minute';
-- insert happens later, outside this snapshot
insert into tasks (...) values (...);A single atomic upsert
The fix is a counter row keyed by API key and minute window. The insert increments the counter in one statement and returns the new value. Postgres serializes conflicting upserts, so concurrent requests see a single ordered count.
If the returned count is above the limit, the request is rejected before a task is created. Rejected attempts still count; that is intentional, because retry storms should not be free.
insert into rate_limit_counters (api_key_id, window_start, count)
values ($1, date_trunc('minute', now()), 1)
on conflict (api_key_id, window_start)
do update set count = rate_limit_counters.count + 1
returning count;The stress test that proves it
Thirty parallel creations with a 20-per-minute key returned exactly 20 successes and 10 rate-limit responses. No request returned a 5xx. The 429 responses carried Retry-After and X-RateLimit-Limit headers, and the database contained exactly 20 tasks.
The counter recorded 30 attempts. Old windows are deleted by maintenance after an hour, so the table stays small.
Tasks created at 20/min
- Before
- 24
- After
- 20
Rate-limit rejections
- Before
- not captured
- After
- 10
5xx responses
- Before
- 0
- After
- 0
Where the counter does not help
A rate counter is not a concurrency limiter. Concurrency is about tasks currently in flight, not tasks created per minute. Keep the two checks separate, and be explicit about which one a 429 refers to.
The counter also assumes one database. If you shard across databases, you need a shared counter or a per-shard budget.
- Rate limit: attempts per key per minute.
- Concurrency limit: active tasks per organization.
- Both should return a stable error code and Retry-After.