r/javascript • • 23h ago

AskJS [AskJS] I tested concurrent download limits in PostgreSQL. Here's what happened.

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?

0 Upvotes

8 comments sorted by

•

u/RaspberryWestern6600 23h ago

`SELECT FOR UPDATE` would work but it's gonna queue everyone up, which you probably don't want if you're sensitive to latency. The atomic UPDATE is nice because it's a single trip and fails fast.

If you're doing this across multiple services though, a single UPDATE inside Postgres isn't enough. That's where Redis locks or Lua scripts start to make sense.

•

u/jorgeurios 23h ago

Good point about SELECT FOR UPDATE. Both approaches can create contention when multiple requests target the same row.

The difference, as I understand it, is the lock duration. With a conditional UPDATE, the check and increment happen in a single database statement. With SELECT FOR UPDATE, you typically hold the lock while the application reads, makes a decision and performs the update.

One thing I'm curious about: if multiple services are all hitting the same PostgreSQL database and updating the same row, wouldn't the atomic UPDATE still guarantee the limit across services?

I agree Redis or Lua scripts become interesting when coordination spans multiple systems, or when the shared state no longer lives in that PostgreSQL row.

What specific scenario would make you move away from the single UPDATE approach?

•

u/Discordbothost 23h ago

I'd keep the UPDATE and commit before streaming. For flaky connections, store a unique attempt key in the same transaction as the increment. Let the same downloader resume that attempt for a short window without burning another slot.

•

u/jorgeurios 22h ago

That's a really good point. The flaky connection case is easy to overlook when focusing only on concurrent requests.

I like the idea of storing a unique attempt key in the same transaction as the counter increment. That way, a retry from the same downloader can reuse the original attempt instead of consuming another slot.

One question: how would you scope that attempt key so only the original authorized downloader can reuse it? Would you bind it to an authenticated user/session, or use a signed, unguessable token?

Would you also give the attempt key an expiration window, so retries are idempotent only for a limited period?

And do you distinguish between a download attempt being accepted and the file being successfully delivered? Committing before streaming makes sense for concurrency, but it raises an interesting question about what exactly counts as a download.

•

u/OkCardiologist8006 11h ago

for mongo it's the same trick, findOneAndUpdate with the limit in the filter ($expr: { $lt: ["$downloadCount", "$maxDownloads"] } plus the revoked/expiry checks) and $inc in the update. single-document writes are atomic so you get the same exactly-N result without needing a transaction

•

u/jorgeurios 11h ago

Nice! That's exactly the kind of equivalent I was curious about.

I like that MongoDB can enforce the limit with a single-document atomic operation, without needing a separate transaction.

One edge case worth considering: how would you handle links with no download limit? If maxDownloads is null or the field is missing, the $lt comparison would fail, potentially denying downloads that should be unlimited.

Would you handle that with an additional $or condition in the filter?

Curious if you've run into this in production.

•

u/acefolio_dev 2h ago

Yes, the single UPDATE holds across services as long as they all hit the same Postgres row. Under READ COMMITTED, a second UPDATE on that row waits for the first to commit, then re-checks the WHERE clause against the new row version, so download_count < max_downloads is evaluated against the fresh value. You only need Redis if the counter lives outside that row. For retries on failed downloads, I'd decrement in a compensating UPDATE or use the attempt key idea above.