CodeJournal Blog Header

How to Prevent Race Conditions When Multiple Users Update the Same Database Record

How to Prevent Race Conditions When Multiple Users Update the Same Database Record

Table of Contents

Imagine two employees opening the same customer record in a web application. One changes the phone number, while the other updates the customer’s address. Both submit their changes within seconds, but the final database record unexpectedly loses one of the updates. In another scenario, two customers attempt to purchase the last item in stock, and both requests succeed because each request checks the inventory before either one completes the purchase.

These are examples of database concurrency problems. They occur when multiple requests read or modify shared data in overlapping operations without adequate coordination.

To prevent race conditions when multiple users update the same database record, use a concurrency-control strategy that matches the operation: optimistic locking for detecting conflicting changes, database transactions for maintaining consistency, and row-level locks when an operation must safely read and modify shared data. Atomic SQL updates and database constraints can also prevent specific classes of race conditions.

The important point is that making an API endpoint work correctly for one user does not guarantee it will remain correct when requests execute concurrently. The database must enforce the rules even when requests arrive from different application servers.

NOT SURE WHAT TO DO NEXT?

Let’s Figure It Out.

Tell us what you’re working on and we’ll help you identify the right next step.

Talk to an Expert

What Is a Database Race Condition?

A race condition occurs when the outcome of an operation depends on the timing or ordering of concurrent actions.

A common example is the lost update problem. Two requests read the same value, independently calculate a replacement, and then overwrite each other’s results.

Suppose a product has five units in stock. Two customers attempt to purchase one unit each.

  1. Request A reads stock as 5.
  2. Request B also reads stock as 5.
  3. Request A calculates 4 and saves it.
  4. Request B calculates 4 and saves it.

The final stock is 4 instead of 3, even though two purchases occurred.

The issue is not necessarily that either request failed. Both may return success while the stored value becomes incorrect.

Concurrency bugs can also affect bank balances, booking availability, order status, user permissions, inventory, and counters. Microsoft’s documentation on handling concurrency conflicts explains how concurrent modifications can cause inconsistent data and how applications can detect those conflicts.

Why Concurrent Database Updates Cause Data Loss

The Application Reads Before It Writes

A typical backend performs three separate actions: read the current record, calculate a change, and write the new value. If another request changes the record between the read and the write, the first request may save a value based on outdated data.

This is especially common when business logic runs in application code instead of a single database statement.

The Database Does Not Know Your Business Rule

A database can execute valid SQL statements while the application still violates a business rule. For example, two requests may each check that an appointment slot is available before attempting to book it.

The database needs an appropriate constraint, transaction, or locking strategy to ensure that the availability check and booking operation cannot produce an invalid result.

Multiple Backend Instances Share the Same Data

A process-level JavaScript mutex or an in-memory lock only coordinates code within the scope in which that lock operates. It does not automatically coordinate requests handled by other processes, containers, or servers.

When several application instances share one database, use database-enforced concurrency controls or a correctly designed distributed coordination mechanism. Database constraints and transactions are often the most direct way to protect data integrity.

Use Optimistic Locking to Detect Conflicting Updates

Optimistic concurrency control is useful when conflicts are possible but relatively infrequent. Instead of locking a record while a user edits it, the application records the version it originally read and checks that version when saving.

How version-based concurrency works

Add a version number to the record:

CREATE TABLE products (

    id BIGINT PRIMARY KEY,

    name VARCHAR(200) NOT NULL,

    stock INTEGER NOT NULL,

    version INTEGER NOT NULL DEFAULT 1

);

When the application reads a product, it also retrieves its version. Suppose the version is 7. The update must succeed only if the database still contains version 7.

UPDATE products

SET name = ‘Updated Product’,

    version = version + 1

WHERE id = 42

  AND version = 7;

After executing the query, check the number of affected rows.

  • If one row was updated, the expected version matched and the operation succeeded.
  • If zero rows were updated, the record may have been modified or deleted since it was read. The application should treat this as a concurrency conflict rather than silently overwriting newer data.

The example assumes the version is incremented on every relevant update and that the application checks the affected-row count. Other database-generated version mechanisms are also possible.

Why this works: The database performs the version check and update as one atomic statement. Two requests using the same original version cannot both successfully update the row under this condition.

How should the application handle a conflict?

Do not automatically overwrite the latest record with stale data. Depending on the operation, the backend can:

  • Return HTTP 409 Conflict and ask the user to reload the latest version.
  • Compare the submitted changes with the latest record and merge non-conflicting fields.
  • Re-read the data and retry a safe operation using the current version.

The correct response depends on the business rules. A user editing a profile may be able to merge changes, while a purchase request should recheck stock and price before retrying.

Microsoft’s concurrency documentation explains how concurrency tokens detect stale updates and how applications can resolve conflicts.

Use Database Transactions and Row-Level Locks

Optimistic locking detects conflicts, but some operations need to read current data and make a decision before updating it. Inventory reservations, account transfers, and limited booking slots are examples.

In these situations, a transaction combined with an appropriate row-level lock can prevent another transaction from changing the relevant record until the first operation finishes.

For PostgreSQL and MySQL’s InnoDB engine, SELECT … FOR UPDATE is a common locking read. It locks the selected rows for conflicting updates until the transaction ends. The exact behavior depends on the database engine and transaction isolation level. See the PostgreSQL explicit locking guide and MySQL locking reads documentation.

For example, in PostgreSQL:

BEGIN;

SELECT stock

FROM products

WHERE id = 42

FOR UPDATE;

— Check the current stock in application logic.

UPDATE products

SET stock = stock – 1

WHERE id = 42

  AND stock > 0;

COMMIT;

The application must check whether the update affected a row. If the stock is unavailable, it should not report a successful purchase. It should also roll back the transaction if the operation cannot complete.

This pattern is useful when the application must inspect the current value before deciding what to do. Keep the transaction short: do not hold database locks while waiting for user input or calling external services.

For simple inventory deductions, a conditional atomic update can be even simpler.

UPDATE products

SET stock = stock – 1

WHERE id = 42

  AND stock > 0;

Check the affected-row count. One affected row means stock was available and deducted; zero means the condition was not satisfied or the product was not found. If the application needs to distinguish those cases, perform an appropriate follow-up check.

This single-statement approach avoids the separate read-then-write race for the stock deduction.

Use Database Constraints for Rules That Must Never Be Violated

Application checks are not enough when multiple requests can pass the same validation simultaneously. Database constraints provide a final enforcement layer.

For example, if each appointment slot can be booked only once, enforce that rule with a unique constraint on the slot identifier:

ALTER TABLE bookings

ADD CONSTRAINT unique_booking_slot

UNIQUE (slot_id);

This example assumes each slot can have only one booking across the entire table. If slots are specific to a provider, date, or resource, the constraint should include the appropriate combination of columns instead.

When two transactions attempt to insert a conflicting booking, the database permits only one to satisfy the uniqueness rule. Your backend must handle the resulting constraint violation and return a useful response, such as a conflict message asking the customer to choose another slot.

Other useful constraints include:

  • CHECK constraints for valid numeric ranges, such as nonnegative inventory where appropriate.
  • Foreign keys to prevent references to nonexistent records.
  • Unique constraints to prevent duplicate business identifiers.
  • NOT NULL constraints for required values.

Constraints do not replace transactions or concurrency control in every situation, but they protect important invariants even when requests originate from different services or application instances.

Prevent Deadlocks and Handle Retries Safely

Locks solve some race conditions, but they can introduce deadlocks. A deadlock occurs when transactions wait on one another in a cycle, preventing all of them from proceeding.

For example, transaction A locks product 1 and then requests product 2, while transaction B locks product 2 and then requests product 1. Neither can continue until the other releases its lock.

Reduce this risk by acquiring locks in a consistent order, keeping transactions short, and locking only the rows required. PostgreSQL documents these techniques in its deadlock guidance.

Some databases detect deadlocks and abort one transaction. The application should recognize retryable errors and retry the entire transaction when appropriate, rather than blindly repeating only the last statement.

Retries also require care outside the database. If a transaction sends a payment request or triggers an external action before failing, repeating the operation could cause duplicate effects. Use idempotency keys or other safeguards for operations that must not happen twice.

How to Test for Database Race Conditions

A concurrency fix should be tested with overlapping operations, not only sequential requests.

  1. Create a test record with a known starting value.
  2. Send multiple requests that attempt to update the same record at nearly the same time.
  3. Verify that the final value matches the expected result.
  4. Confirm that version conflicts, uniqueness violations, and insufficient-stock cases produce the correct responses.
  5. Repeat the test with multiple backend instances if your production deployment uses them.

For an inventory test, if ten successful requests each purchase one unit from an initial stock of ten, the final stock should be zero. Additional purchase attempts must not reduce it below zero or succeed without a corresponding stock deduction.

Monitor transaction duration, lock waits, deadlocks, and retry counts under load. If the application also experiences database connection exhaustion, investigate whether long transactions are holding connections for too long; connection-pool problems can amplify the impact of concurrency bottlenecks.

Conclusion

Race conditions happen when concurrent requests act on shared data without adequately protecting the business rules involved. The best prevention strategy depends on the operation: optimistic locking detects stale edits, row-level locks coordinate critical read-modify-write sequences, atomic SQL statements protect simple numeric changes, and database constraints enforce rules such as unique bookings.

Keep transactions short, handle conflicts explicitly, and retry only operations that are safe to repeat. Most importantly, test with concurrent requests and verify the final database state—not merely whether the API returned a successful response.

Frequently Asked Questions (FAQs)

What is the best way to prevent race conditions in a database?

The best approach depends on the operation. Use optimistic concurrency with a version column when users edit records that may have changed since they were loaded. Use transactions and row-level locks when a workflow must read and modify shared data safely. For simple operations, an atomic SQL update or a database constraint may provide a simpler solution.

How do I prevent two users from overwriting each other’s database updates?

Add a version column or another concurrency token and include its original value in the update condition. If another request has already changed the record, the update affects zero rows and the application can report a conflict. This prevents silent overwrites, provided every relevant update follows the concurrency-checking strategy.

Is SELECT FOR UPDATE enough to prevent database race conditions?

Not by itself. Use SELECT FOR UPDATE inside an appropriate transaction, perform the required checks and updates while the lock is held, and commit or roll back correctly. The lock protects the selected rows from conflicting operations, but it does not automatically protect unrelated rows or enforce every business rule. Database constraints may still be necessary.

What is the difference between optimistic locking and pessimistic locking?

Optimistic locking allows concurrent work to proceed and detects a conflict when an update is attempted using stale data. Pessimistic locking acquires a lock before proceeding with a critical operation, making conflicting transactions wait or fail according to the database behavior. Optimistic locking is often suitable for occasional conflicts, while pessimistic locking can suit operations that must coordinate access to shared records.

Can database transactions alone prevent race conditions?

Not necessarily. Transactions group operations into a unit of work, but their protection depends on the isolation level, the statements used, and the database engine. A transaction that reads a value and later writes a calculated replacement can still lose an update under some conditions. Use atomic statements, concurrency tokens, appropriate locks, or constraints to enforce the required rule.

How can I test whether my API has a database race condition?

Send concurrent requests against the same test record and verify the final database state. For inventory, confirm that successful purchases never reduce stock below zero. For editable records, verify that stale updates generate conflicts instead of silently overwriting newer data. Repeat tests across multiple backend instances and inspect transaction errors, deadlocks, and retry behavior.

NEED HELP WITH THIS?

Let’s Talk About Your Business

Not sure which approach is right for your business? Get a free consultation with our team.

Get Free Consultation

Leave a Reply

Your email address will not be published. Required fields are marked *

NOT SURE WHAT TO DO NEXT?

Let's Figure It Out.

Tell us what you’re working on and we’ll help you identify the right next step.

NEED HELP WITH THIS?

Let's Talk About Your Business

Not sure which approach is right for your business? Get a free consultation with our team.