Senior
What happens if two reservation requests arrive simultaneously? How to ensure consistency?
sobes.tech AI
Answer from AI
If two reservation requests arrive simultaneously, a race condition may occur without proper synchronization, and both requests could successfully reserve the same resource, violating data consistency.
To prevent this, several approaches can be used:
- Database-level locking transactions — for example, using
SELECT ... FOR UPDATEto lock the record until the operation completes. - Optimistic locking — storing a record version and checking that the version has not changed since reading during an update.
- Queue mechanisms and request serialization — processing reservation requests sequentially.
- Using atomic operations — for example, in Redis, commands like
SETNXcan be used to set a value only if the key does not exist.
An example with a transaction in Python using SQLAlchemy:
from sqlalchemy import select, update
from sqlalchemy.orm import Session
with Session(engine) as session:
with session.begin():
reservation = session.execute(
select(Reservation).where(Reservation.id == resource_id).with_for_update()
).scalar_one()
if reservation.is_available:
reservation.is_available = False
session.commit()
else:
raise Exception("Resource already reserved")
This approach guarantees that two requests cannot reserve the same resource simultaneously.