Sobes.tech
Junior

If two services want to write the same record to the database simultaneously, what will happen?

sobes.tech AI

Answer from AI

When two services attempt to write the same record to a database simultaneously, the behavior depends on the locking mechanisms and transaction isolation levels in the DBMS.

In most cases:

  • One of the services will acquire a lock for writing (e.g., at the row or table level).
  • The second service will wait for the lock to be released or will receive an error (e.g., conflict or deadlock).

If a transaction with an isolation level such as "Read Committed" or "Serializable" is used, the database guarantees data consistency.

Example:

  • Service A starts a transaction and updates a record.
  • Service B attempts to update the same record and waits until Service A completes the transaction.
  • After the transaction completes, Service B either applies its changes or receives an error if the data has changed.

To avoid issues, the following are often used:

  • Optimistic locking mechanisms (version check of the record).
  • Explicit locks (SELECT ... FOR UPDATE).
  • Queues or other synchronization tools between services.

Thus, concurrent writing requires proper management of concurrent data access.