MySql concurrency with COUNT
Just as SELECT ... FOR UPDATE is sometimes needed, I think you must implement your action in a transaction:

BEGIN;
SELECT COUNT(*) FROM the_table WHERE user_id = 40987 FOR UPDATE;
if the count &gt;= 5, ROLLBACK and exit.
INSERT INTO the_table (product_id, user_id) VALUES (121, 40987);
COMMIT;


Or...

BEGIN;
INSERT INTO the_table (product_id, user_id) VALUES (121, 40987);
SELECT COUNT(*) FROM the_table WHERE user_id = 40987;
if the count &gt; 5, ROLLBACK and exit.
COMMIT;


(Three diffs:  order of statements; FOR UPDATE; &gt;= vs &gt;.)

In your original code, see if you can add FOR UPDATE to the subquery in the WHERE clause.