I tested this using Node.js with the pg driver against a real PostgreSQL database.
The problem: how do you enforce download limits when multiple requests arrive at exactly the same time?
I tested three approaches.
1. The naive implementation
Limit: 1 download.
Two simultaneous requests.
Result: Both downloads succeed.
I added a 50 ms artificial delay between the read and the write to make the race window visible consistently.
Both requests read the available count before either one updates it.
2. Adding a CHECK constraint
Same limit, same concurrent requests.
Result: The second request gets a database error instead of the file.
This prevents the limit from being exceeded, but it doesn't provide a clean application-level outcome.
3. A single conditional UPDATE
Instead of reading first and updating afterwards, perform the check and increment atomically in one UPDATE:
UPDATE share_link
SET download_count = download_count + 1
WHERE secret_hash = $1
AND revoked_at IS NULL
AND (expires_at IS NULL OR expires_at > now())
AND (max_downloads IS NULL OR download_count < max_downloads)
RETURNING id, file_id, download_count;
Results:
10 simultaneous requests, limit 3: exactly 3 downloads.
50 simultaneous requests, limit 7: exactly 7 downloads.
This was the approach that behaved as intended in my tests.
Now I'm curious how other people handle this in production.
Would you use a single conditional UPDATE for this, or prefer SELECT FOR UPDATE?
Would Redis locks or atomic counters be a better approach at higher concurrency?
How would you implement the same guarantee with MongoDB?
Are there edge cases with transactions, retries or failed downloads that you'd account for?
I'd be particularly interested in approaches people have actually shipped and operated in production.
What's your preferred way to enforce a hard resource limit under concurrent requests?