Race conditions happen when the outcome is dependent on the sequence or timing of other uncontrollable events, like loading data from a table or saving a record to the database. If two users read a value from a record and then update it simultaneously, one of the values has to “win”. Without locking, the outcome can be different every time.
There are two ways of locking data in a database: Pessimistic locking locks a record immediately when the lock is requested, while in an optimistic lock the record is only locked when the changes made to that record are updated. This article describes how to do this with ActiveRecord and Postgres (works in the same way with MySQL though).