Sobes.tech
Junior — Middle

What approaches and methods will you use to eliminate competition when two users access the database simultaneously?

sobes.tech AI

Answer from AI

The following approaches are used to eliminate competition when two users access the database simultaneously:

  1. Transactions and locks — using transactions with an appropriate isolation level (e.g., Serializable, Repeatable Read). This helps avoid conflicts during data read and write.

  2. Optimistic locking — when updating data, it checks whether the data has changed since the last read (e.g., via a version field). If it has changed, the operation is rolled back or retried.

  3. Pessimistic locking — explicitly locking rows or tables during an operation so that other users cannot modify the data.

  4. Using atomic operations — for example, some DBMSs support commands that guarantee atomicity of updates.

  5. Queues and request serialization — if operations are critical, a queue for data modification requests can be organized.

Example using transactions in Python with the psycopg2 library for PostgreSQL:

import psycopg2

conn = psycopg2.connect(...)
try:
    with conn:
        with conn.cursor() as cur:
            cur.execute("BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;")
            cur.execute("SELECT balance FROM accounts WHERE id = %s FOR UPDATE;", (account_id,))
            balance = cur.fetchone()[0]
            new_balance = balance - amount
            cur.execute("UPDATE accounts SET balance = %s WHERE id = %s;", (new_balance, account_id))
    # the transaction is automatically committed
except Exception as e:
    conn.rollback()
    print("Error updating balance:", e)