Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

virus379's avatar

How to prevent race condition in this case laravel 11

I have a table named gym_sessions it has user_id | status columns. status column can contains: 1 ==> active; 2 ==> completed; 3 ==> declined;

Conditions:

  • User must have sufficient balance to start new session.
  • User can't have two active sessions at the same time.
  • User can have many sessions of status: 2 | 3;

This is my method for creating new session for a user:

Attack Scenario:(Race Condition) If the user sent multiple requests in parallel, the system will create many sessions with status 1.

I want to know how to prevent this problem on application level (using Laravel methods) not on database level?

Env
Laravel 11
MySql
php 8.2.8

0 likes
6 replies
jaseofspades88's avatar

You are already validating against active sessions. I recommend you create a form request class to abstract the validation and subsequent checks you're performing (balance and active status). You have access to the currently authenticated user in a form request class, so you could promote your balance check to authorisation level or stick with custom validation rules.

virus379's avatar

@jaseofspades88 But the problem arises when the same user perform race condition attack (send multiple requests in parallel).

Prokosa's avatar

You need to combine the session check and the creation of a new session into one transaction.

JussiMannisto's avatar

@virus379 First things first: Are you familiar with the concept of database transactions? If not, Wikipedia has a short article on the topic. After that, you can read about how to use them in Laravel.

Transactions are a crucial feature of relational databases. Once you know how to use them, preventing race conditions like these is very straightforward and you can write the code yourself.

Please or to participate in this conversation.