Support the ongoing development of Laravel.io →
Database Queues

Hi guys,

I've tried to get some insight at #laravel but it doesnt help.

So I have this project with a concurrency issue.

  • Lets say we have an app with five users, and each user has an amount of "points".
  • Each user can giveaway one "point".
  • Daily, each user can receive two "points".
  • When a user giveaway one "point", it runs a command queue that random pick a user from the database and give him that "point".

Question? How to prevent a user from receive more than two "points" daily at the random pick? Cause if the five users giveaway one "point" at the same time, the random can pick the same user twice or more, right?

Any thoughts on this will be very appreciated.

Thanks in advance.

Last updated 3 years ago.
0
  1. You could design this process to run as one loop that gives away all of the "free" points that users have donated. Remove any user that has received > 1 point until all points are assigned. One advantage of this approach is that you could do it all in a single database transaction.

  2. Keep track of the points donated per day some other way, say in Redis or in a database table. Set your worker queue so that there is no concurrency, i.e., number_of_workers=1. On each worker run, give away a point, and note who received it. If number_received(today) > 1 then find someone else.

Anywhere you can avoid concurrency problems, you should.

0

Also, quick note on #2 and concurrency in general: this is what database transactions are for. Database transactions make sure your rules are consistently enforced, even if the point giveaway happens in real time. Something like:

BEGIN TRANSACTION; SELECT * FROM points_to_assign LIMIT 1 FOR UPDATE; SELECT * FROM assigned_points WHERE day = today() FOR UPDATE; -- grab random user for update, locking that record -- perform update -- make sure that assigned_points for that user is < 2 or ROLLBACK COMMIT;

This is a good candidate for a database stored procedure.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.