Knowledgebase

Handling Concurrency and Race Conditions Print

  • phplaravel, database, guide, howto, solution, zillionkinghost, hosting, support
  • 0

Simultaneous requests.

WHAT A RACE CONDITION IS

Two requests doing something at the same time, producing a result neither intended.

WHERE THEY OCCUR

Stock levels Account balances Sequential reference numbers Booking limited availability Anything read, modified and written back

WHY THEY ARE MISSED

They do not occur in development, where requests arrive one at a time.

WHAT PREVENTS THEM

Database-level locking during the operation Atomic operations, where the database performs the change Unique constraints, which reject a duplicate outright

WHAT TO USE FOR COUNTERS

An atomic increment, rather than reading and writing back.

WHAT TO USE FOR STOCK AND BALANCES

A transaction with a lock on the affected row.

WHAT TO USE FOR REFERENCES

A database sequence or a unique constraint with retry.

WHAT ELSE TO CONSIDER

Duplicate submissions, from double clicks or retries.

WHAT PREVENTS THOSE

An idempotency key, recorded and checked.

WHAT TO TEST

Two simultaneous attempts at the same operation.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot