Understanding Database Transactions, ACID, and Race Conditions
Imagine an application that transfers ₹500 from one bank account to another. It must subtract ₹500 from the sender and add ₹500 to the recipient. If the first operation succeeds but the second fails, the database could record an incomplete transfer. A similar problem occurs when two requests read the same account balance and overwrite each other's changes. Both operations may appear successful even though the final data is incorrect. A database transaction provides a way to group related operations into one logical unit of work. The application either commits the intended changes together or rolls them back when the transaction fails. Transaction guarantees become especially important when multiple users, API requests, background workers, or services access the same data concurrently.
// TABLE OF CONTENTS+
What Is a Database Transaction?
Imagine an application that transfers ₹500 from one bank account to another. It must subtract ₹500 from the sender and add ₹500 to the recipient. If the first operation succeeds but the second fails, the database could record an incomplete transfer. A similar problem occurs when two requests read the same account balance and overwrite each other's changes. Both operations may appear successful even though the final data is incorrect. A database transaction provides a way to group related operations into one logical unit of work. The application either commits the intended changes together or rolls them back when the transaction fails. Transaction guarantees become especially important when multiple users, API requests, background workers, or services access the same data concurrently.
A transaction is not simply a collection of SQL statements placed next to each other. It has a defined beginning, a set of operations, and a completion outcome. The database manages the transactional behavior, while the application defines which operations belong together and what business rules must hold. For example, an order might require creating an order record, reducing inventory, and recording a payment attempt. If these database changes must succeed together, they should be designed as one transaction. However, an external payment provider cannot automatically participate in a PostgreSQL transaction. That distinction matters when designing reliable applications that combine database writes with external services.
Understanding the Four ACID Properties
ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties describe four important aspects of reliable transaction processing. They address different failure modes, so understanding them separately is more useful than memorizing the acronym. Atomicity concerns whether a transaction's operations take effect together. Consistency concerns whether the transaction preserves the application's required data invariants. Isolation concerns how concurrent transactions interact. Durability concerns whether committed changes survive failures within the database's configured durability guarantees. ACID is not a promise that an application can never contain incorrect information. A transaction can atomically commit a logically incorrect operation if the application implements the wrong business rule. Correctness depends on database guarantees, constraints, and application logic working together.
Atomicity: All or Nothing
Atomicity means a transaction's database changes are treated as one logical unit: either the transaction commits, or its uncommitted changes are rolled back. This prevents an application from accidentally leaving only half of a multi-step database operation completed. Consider a transfer between two accounts. The sender's balance decreases by ₹500, and the recipient's balance increases by ₹500. Both updates belong in the same transaction. If the recipient update fails because the account does not exist or a constraint is violated, the sender's debit must not remain committed independently. Atomicity does not mean every individual SQL statement is indivisible at every internal execution stage. It describes the transaction's externally observable outcome and recovery behavior. The database uses mechanisms such as transaction logs, recovery procedures, and concurrency control to implement these guarantees.
BEGIN;
UPDATE accounts
SET balance = balance - 500
WHERE id = 1
AND balance >= 500;
-- The application must verify that exactly one
-- sender row was updated before proceeding.
UPDATE accounts
SET balance = balance + 500
WHERE id = 2;
-- The application must also verify that exactly
-- one recipient row was updated.
COMMIT;This example illustrates the transaction structure, not a complete production-ready transfer implementation. The application must check the affected-row count after each update and roll back if either account update does not affect exactly one row. It must also handle database errors and ensure that both operations use the same transaction and connection. For example, if the sender's update affects zero rows because the account is missing or the balance is insufficient, the application must not continue with the credit. If the recipient update affects zero rows, the application must roll back the debit. A production implementation must also consider duplicate requests, currency rules, authorization, transaction identifiers, and appropriate error handling.
Consistency: Preserve Valid Data
Consistency means a transaction should preserve the database's required invariants when it moves the database from one valid state to another. These invariants may include non-negative balances, unique email addresses, valid foreign-key references, and business rules governing inventory or orders. Database constraints are a critical part of this protection. A CHECK constraint can prevent negative account balances, a UNIQUE constraint can prevent duplicate identifiers, and a foreign key can prevent a record from referencing a nonexistent parent row. These rules are enforced by the database instead of relying exclusively on every application code path to remember them. However, consistency is broader than constraints. If a business requires a customer to receive a discount only once, the application may need an appropriate uniqueness rule or transactional workflow. ACID does not automatically know the business rules. Engineers must define those rules explicitly and enforce them at the correct layer.
CREATE TABLE accounts (
id BIGINT PRIMARY KEY,
balance NUMERIC(12, 2) NOT NULL
CHECK (balance >= 0)
);The constraint prevents a committed row from containing a negative balance through an ordinary insert or update that violates the rule. It provides an important last line of defense even if an application request contains a bug. It does not, by itself, solve every concurrency problem. A pair of operations might both pass an application-level check before attempting their writes. Nor does this constraint enforce more complicated rules involving multiple accounts or tables. Those rules may require conditional updates, suitable locks, transaction isolation, or additional database constraints.
Isolation: Control Interactions Between Concurrent Transactions
Isolation concerns what one transaction can observe about another transaction's work and how overlapping operations are coordinated. Without suitable concurrency control, two requests can make decisions from the same outdated information and overwrite one another's results. Suppose an account starts with ₹1,000. Two requests each want to withdraw ₹700. If both requests read the balance before either performs its update, both may conclude that the withdrawal is affordable. A safe implementation must ensure that the balance check and withdrawal are coordinated so that the account cannot be overdrawn. Isolation does not necessarily mean that every transaction executes entirely alone. Modern relational databases can allow substantial concurrency while using row locks, multiversion concurrency control, or validation mechanisms to maintain defined guarantees. The appropriate behavior depends on the isolation level and the statements used.
Durability: Committed Changes Persist
Durability means that once a transaction has been successfully committed, the database is responsible for preserving its committed result against the failures covered by its durability configuration. In PostgreSQL, write-ahead logging and recovery mechanisms help provide this guarantee. A successful COMMIT is therefore a meaningful boundary. The application can report success only after the database has confirmed that the transaction committed. If the connection drops around the time of the commit, however, the client may not know whether the commit succeeded. The database may have committed the transaction even though the application never received the acknowledgment. Durability also depends on configuration and the failure model. Local storage guarantees, synchronous replication settings, backup practices, and disaster recovery affect what can be recovered after different failures. A transaction's durability guarantee should not be confused with a guarantee that every machine, region, or external system can never lose data.
| Property | Main question | Example | Primary concern |
|---|---|---|---|
| Atomicity | Did all required database changes succeed together? | A failed transfer does not leave only the debit committed. | Partial operations. |
| Consistency | Does the transaction preserve required invariants? | An account balance cannot become negative under the defined rules. | Invalid data states. |
| Isolation | How do concurrent transactions interact? | Concurrent withdrawals cannot both spend the same available funds. | Conflicting operations. |
| Durability | Does a confirmed commit persist under the configured failure guarantees? | A committed order survives a supported database restart or recovery event. | Loss of committed changes. |
Race Conditions and the Lost-Update Problem
A race condition occurs when the correctness of a result depends on the timing or interleaving of concurrent operations. In database-backed applications, race conditions often appear when a request reads data, makes a decision, and later writes a result based on that earlier read. A particularly important example is the lost update. Two transactions read the same original value, calculate different new values, and then write their results. If the later write overwrites the earlier one instead of incorporating it, one update disappears from the final state. This problem is easy to miss during manual testing because requests are often executed sequentially. Under real traffic, multiple application workers may process requests simultaneously. The database must coordinate their operations, and application code must use the correct update pattern for the business rule.
Assume an account has a balance of ₹1,000. Request A deposits ₹200, while request B deposits ₹300. Both requests read ₹1,000 before either writes. Request A calculates ₹1,200 and request B calculates ₹1,300. If A writes first and B then overwrites the value, the final balance becomes ₹1,300. The correct result is ₹1,500. Both deposits should be reflected in the account. The problem is not that the arithmetic is wrong. The problem is that each request computed an absolute replacement value using a stale snapshot and did not preserve the other request's update. This is a lost update caused by an unsafe read-modify-write pattern. The same issue can affect counters, inventory quantities, likes, quotas, account balances, and any mutable value that multiple operations can change.
Reproducing the Unsafe Pattern
-- Illustrative pattern: the application reads the
-- current balance into a variable first.
SELECT balance
FROM accounts
WHERE id = 1;
-- The application calculates a replacement value
-- outside the database and later executes:
UPDATE accounts
SET balance = 1200
WHERE id = 1;The danger is the separation between reading the balance and writing a replacement value calculated from that read. The example assumes the application read ₹1,000 and calculated ₹1,200 for a deposit of ₹200. Another request can perform its own read and calculate a different replacement value during that gap. The SQL update does not communicate that the intended operation is “add ₹200 to the current balance.” It communicates “set the balance to ₹1,200.” Those instructions have different concurrency semantics. The former expresses a relative change; the latter may overwrite a more recent value. A transaction alone is not a universal fix. Under PostgreSQL's default READ COMMITTED isolation, putting the read and write inside a transaction does not automatically prevent every lost update caused by stale application-side calculations. The implementation must also choose an appropriate update strategy, lock, or concurrency-control mechanism.
Choosing the Right Transaction Isolation Level
A transaction's isolation level determines which concurrent execution anomalies the database prevents. Stronger isolation generally offers stronger guarantees, but some transactions may need to wait, abort, or retry when their operations conflict. PostgreSQL supports READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE as SQL isolation-level options. However, PostgreSQL implements READ UNCOMMITTED using the same behavior as READ COMMITTED. Its default isolation level is READ COMMITTED. PostgreSQL's transaction isolation documentation explains the differences in detail. PostgreSQL
| Isolation level | Read behavior | Concurrency implications | Typical use |
|---|---|---|---|
| Read Uncommitted | Behaves like Read Committed in PostgreSQL. | Does not provide a weaker dirty-read mode. | Applications selecting this standard SQL level for compatibility. |
| Read Committed | Each statement sees data committed before that statement begins, subject to PostgreSQL's concurrency rules. | Successive statements can observe different committed states. | Ordinary application queries and straightforward conditional updates. |
| Repeatable Read | Uses a stable transaction snapshot established by its first non-transaction-control statement. | Conflicting updates can cause a transaction to fail and require a retry. | Multi-step operations needing a stable view of existing data. |
| Serializable | Successful concurrent transactions must have an effect equivalent to some serial execution. | Serialization failures may require retrying the entire transaction. | Operations whose correctness depends on complex cross-row or cross-table invariants. |
Read Committed: The Default Is Not a Universal Safety Net
At READ COMMITTED, each ordinary SELECT sees a snapshot of the data committed before that statement began. Two separate queries in the same transaction can therefore return different results if another transaction commits between them. This behavior is useful for many applications because it provides a straightforward balance between consistency and concurrency. It also means developers must understand where their logic depends on multiple statements observing a consistent state. There is an important distinction between an unsafe application-side read-modify-write sequence and a direct SQL update. PostgreSQL coordinates concurrent updates to the same row. When one transaction updates a row first, a competing UPDATE may wait and then apply its operation to the newer row version if its condition still matches. Consequently, a statement such as SET balance = balance + 200 is fundamentally different from writing a hard-coded replacement balance calculated from an earlier query. PostgreSQL
Repeatable Read: A Stable Snapshot
REPEATABLE READ gives a transaction a stable view of data committed before its snapshot was established. Repeated reads do not simply pick up every concurrent commit made after that point. This is useful when multiple decisions need to be based on a consistent snapshot. However, a stable snapshot does not guarantee that every possible business invariant remains safe under concurrent execution. PostgreSQL's repeatable-read implementation can still permit serialization anomalies in certain multi-row workflows. Conflicting updates can also produce an error rather than silently proceeding. Applications using this level must be prepared to handle transaction failures and retry the complete transaction when appropriate. Retrying only the final SQL statement is not sufficient if earlier calculations depended on the transaction's old snapshot. PostgreSQL
Serializable: Results Equivalent to Running Transactions in Sequence
SERIALIZABLE provides PostgreSQL's strongest standard transaction isolation guarantee. The successful outcome of concurrent serializable transactions must be equivalent to an execution in which those transactions ran one after another in some order. This is useful when an operation depends on a broader condition rather than one isolated row. For example, an application might permit a booking only when fewer than a specified number of reservations exist. Two transactions could independently observe available capacity and attempt to reserve the last slot. A serializable transaction system can detect an unsafe concurrent execution and abort a transaction instead of allowing both incompatible decisions to commit. The cost is that an application must handle serialization failures. The database cannot guarantee that every attempted transaction will succeed on its first try. Correct implementations retry the entire transaction with bounded retries and suitable handling for repeated failures. Serializable isolation is a correctness tool, not a reason to ignore application-level error handling. PostgreSQL
Preventing Lost Updates in PostgreSQL
There is no single concurrency-control technique that is best for every database operation. The correct choice depends on whether an operation changes one known row, evaluates a condition across multiple records, or coordinates a sequence of dependent changes. Three practical approaches cover many common cases: perform arithmetic inside an UPDATE statement, lock rows that must be inspected before a decision, or use optimistic concurrency control to detect whether the data changed since it was read. These approaches can be combined with transactions and database constraints. The goal is not to eliminate concurrency; it is to ensure concurrent operations produce valid outcomes.
Approach 1: Use Atomic SQL Updates
When the intended operation is a simple increment or decrement, express the change directly in SQL instead of reading the value into application code and writing back a calculated replacement. For example, UPDATE accounts SET balance = balance + 200 WHERE id = 1 tells PostgreSQL to add ₹200 to the row's current balance. Concurrent updates to that row are coordinated by the database. This pattern avoids the particular stale absolute-value overwrite shown earlier, although it does not automatically enforce every business rule. For withdrawals, combine the balance condition with the update itself. Checking the affected-row count lets the application distinguish a successful withdrawal from one rejected because the account was missing or the balance was insufficient.
UPDATE accounts
SET balance = balance + 200
WHERE id = 1;UPDATE accounts
SET balance = balance - 700
WHERE id = 1
AND balance >= 700
RETURNING id, balance;If the withdrawal returns a row, the database updated the account. If it returns no rows, either the account does not exist or the condition was not satisfied. The application can handle these outcomes without relying on a separate balance check that might become stale before the write. The CHECK (balance >= 0) constraint remains valuable as a second layer of protection. If the update and constraint are correctly designed together, the application has a stronger defense against invalid balances. For a transfer that modifies two accounts, both account changes must still be enclosed in one transaction so that a failed second operation does not leave the first operation committed alone.
Approach 2: Lock Rows Before Reading and Deciding
Sometimes an application must inspect the current value before deciding what to do. In that case, PostgreSQL's SELECT ... FOR UPDATE can lock selected rows against conflicting updates until the transaction ends. For a withdrawal, the application can start a transaction, select the account row with FOR UPDATE, check the current balance, and then perform the debit. A competing transaction attempting to lock or modify that row must wait until the first transaction completes. This allows the second transaction to make its decision using the appropriate current row version under the transaction's isolation semantics. Row locking should be limited to the rows needed for the operation, and the transaction should finish promptly. A lock is held until the transaction commits or rolls back. Holding locks while waiting for user input, making a slow external request, or performing unrelated work can create unnecessary contention. PostgreSQL
BEGIN;
SELECT balance
FROM accounts
WHERE id = 1
FOR UPDATE;
-- Application checks the returned balance.
-- If sufficient, execute the debit.
-- Otherwise, roll back the transaction.
UPDATE accounts
SET balance = balance - 700
WHERE id = 1;
COMMIT;This is a transaction outline, not a complete application implementation. The application must check that the selected account exists and that its balance is sufficient before executing the debit. If either check fails, it should roll back and report the appropriate result. A conditional UPDATE is generally simpler for a single-row withdrawal. Explicit locking is more useful when several reads and decisions depend on the same protected row. The best design is the simplest one that reliably enforces the required invariant.
Approach 3: Optimistic Concurrency Control
Optimistic concurrency control assumes that conflicts can be detected when a write is attempted rather than preventing every competing operation from proceeding immediately. A common implementation adds a version column to a record. Each successful update increments the version, and a client must provide the version it originally read. Suppose an account record has version 4. Two requests both read version 4. Request A updates the balance and changes the version to 5. When request B attempts to update using version 4, its conditional update affects zero rows because the record no longer has that version. The second request can then reload the current record, reconsider its intended operation, and retry if appropriate. This is useful for profile editing, inventory administration, and other workflows where conflicts should be detected rather than silently overwritten. It is particularly valuable when a client may spend time editing data before submitting changes.
ALTER TABLE accounts
ADD COLUMN version BIGINT NOT NULL DEFAULT 0;
UPDATE accounts
SET balance = 1200,
version = version + 1
WHERE id = 1
AND version = 4
RETURNING balance, version;The application should interpret a returned row as a successful update and no returned row as a conflict or missing account. It must distinguish these cases if the user-facing behavior depends on them. The version check works only when every relevant writer follows the versioning protocol. A background worker that updates the balance without incrementing the version can undermine the protection. Version-based concurrency control also does not automatically protect business invariants involving multiple independent records. Those cases may need a transaction, locks, or serializable isolation.
| Strategy | Best suited for | Main advantage | Important limitation |
|---|---|---|---|
| Atomic UPDATE | Simple increments, decrements, and conditional changes to known rows. | Compact SQL; the database applies the operation to the row under its concurrency rules. | Does not automatically enforce complex multi-row business rules. |
| SELECT FOR UPDATE | A decision that requires inspecting one or more rows before writing. | Protects selected rows from conflicting updates while the transaction is active. | Can cause waiting and deadlocks; requires short, carefully structured transactions. |
| Version column | User edits or application workflows that should detect stale writes. | Explicitly identifies whether a record changed since it was read. | All relevant writers must follow the versioning protocol. |
| Serializable isolation | Complex operations that depend on cross-row or cross-table consistency. | Prevents successful executions that cannot be explained by a serial ordering. | Serialization failures require retrying the complete transaction. |
Transaction Boundaries and Rollback
A transaction boundary defines which database operations must succeed or fail together. Poorly chosen boundaries can undermine an otherwise correct database design. Consider an order-creation workflow that inserts an order, inserts its line items, and reduces inventory. If these operations belong to one logical database change, a failure after the first insert should not leave a partially created order. The application should execute the related operations within one transaction and commit only after all required steps succeed. In PostgreSQL, BEGIN starts an explicit transaction block, COMMIT completes it, and ROLLBACK cancels its uncommitted changes. When explicit transaction control is not used, PostgreSQL normally operates in autocommit mode, where each successful statement is committed as its own transaction. PostgreSQL
BEGIN;
INSERT INTO orders (id, customer_id, status)
VALUES (1001, 42, 'pending');
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (1001, 7, 2);
UPDATE inventory
SET quantity = quantity - 2
WHERE product_id = 7
AND quantity >= 2;
-- The application must verify that exactly one
-- inventory row was updated. If not, roll back.
COMMIT;This example demonstrates the boundary rather than a complete order-processing implementation. The application must check the affected-row count for the inventory update and roll back the transaction if insufficient inventory is available. It should also validate the requested quantity and ensure that the product and order identifiers satisfy the relevant constraints. An application must not commit merely because every SQL statement was syntactically valid. The transaction should commit only after the required business conditions have been verified. A successful INSERT does not prove that the entire order is valid.
Why External Side Effects Need Separate Planning
A PostgreSQL transaction cannot automatically roll back an email already sent, a message already published to an external service, or a payment already processed by another provider. Those operations occur outside the database transaction. For example, an application might insert an order, call a payment provider, and then discover that the database transaction failed. The database can undo its own changes, but it cannot erase the provider's already-completed operation merely because a SQL rollback occurred. A common design is the transactional outbox pattern. The application stores the order and an event record in the same database transaction. A separate worker publishes the event after the transaction commits. The worker and consumers must handle duplicate delivery safely, because message delivery and retries can occur more than once. For payment workflows, idempotency keys, explicit payment states, and reconciliation procedures can help manage uncertain outcomes. The central principle is to keep database atomicity within the database boundary and design explicit recovery behavior for operations outside it.
Deadlocks, Retries, and Failure Handling
Concurrency control introduces failure modes that applications must handle deliberately. A deadlock occurs when two or more transactions hold locks that each needs the other transaction to release. Neither can continue, so PostgreSQL detects the cycle and aborts one transaction to allow progress. For example, transaction A locks account 1 and then requests account 2. Transaction B locks account 2 and then requests account 1. Each waits for the other. If both transactions need those locks to finish, the wait forms a deadlock. One practical defense is to acquire locks in a consistent order. If every transfer locks the lower account identifier first and then the higher one, two transfers involving the same accounts are less likely to form this particular cycle. Consistent ordering does not eliminate every possible deadlock, so applications must still handle deadlock errors. PostgreSQL
- Keep transactions short and avoid waiting for user input while holding locks.
- Acquire multiple rows in a consistent order wherever practical.
- Handle deadlocks and serialization failures as transaction failures.
- Retry the entire transaction when the database requires it, not merely the final statement.
- Use a bounded retry policy with a delay strategy to avoid repeated synchronized retries.
- Log failures with enough context to diagnose recurring conflicts without exposing sensitive data.
- Make external side effects idempotent or coordinate them through a durable workflow.
Retrying Without Creating Duplicate Operations
Retries must be designed around the transaction's complete logical operation. If a serializable transaction fails after performing several reads and calculations, the application should begin a new transaction and repeat the relevant reads, decisions, and writes against the new transaction state. A bounded retry loop can be appropriate for transient serialization failures and deadlocks. However, the application should not blindly retry every database error. A unique-constraint violation caused by an invalid request, for example, usually requires a different response from a transient concurrency conflict. There is another important distinction between a transaction that definitely failed and a transaction whose outcome is unknown to the client. If the network connection drops around a commit, the application may not know whether the database committed the transaction. Repeating the operation without a deduplication strategy can apply the same business action twice. For operations such as creating an order or recording a deposit, use an appropriate request identifier and a database uniqueness constraint where suitable. The application can then determine whether the logical operation has already been recorded instead of assuming that every missing acknowledgment means failure.
Testing Transaction Correctness Under Concurrency
A concurrency strategy should be tested with independent database connections, not only with sequential unit tests. Sequential tests can verify arithmetic and ordinary validation, but they cannot reliably reproduce the interleavings that cause lost updates or deadlocks. Start by creating a known initial balance. Then execute two concurrent deposits from separate connections and verify that the final balance includes both deposits. Repeat the test for withdrawals, insufficient funds, and a transaction that fails between related writes. The expected result should be defined before the test runs. For stronger tests, synchronize the requests so that they attempt the critical operation at approximately the same time. Use barriers or test coordination rather than arbitrary delays alone. Timing-based tests that rely only on sleeping can pass accidentally because the problematic interleaving never occurs.
- Create an account with a known starting balance.
- Open two independent database connections.
- Execute concurrent updates that both target the same account.
- Wait for both operations to finish and inspect their outcomes.
- Verify the final balance against the expected result.
- Check that failed transactions leave no partial database changes.
- Repeat the test under the isolation level and concurrency strategy used by the application.
- Test retry behavior, duplicate requests, and transactions that encounter insufficient funds.
SELECT id, balance, version
FROM accounts
WHERE id = 1;For two successful deposits of ₹200 and ₹300 into an account starting at ₹1,000, the expected final balance is ₹1,500. If the final balance is ₹1,200 or ₹1,300, the test has exposed a problem in the operation or test assumptions. Do not rely solely on the final value. Check the individual operation outcomes as well. A test that produces the expected balance while one request incorrectly reports success or failure can still reveal a correctness problem. For transfers, verify both account balances and the corresponding transaction records. Also test rollback explicitly. Force a failure after one of the transaction's writes, then confirm that none of the transaction's intended changes remain committed. Use isolated test data and reset the database state between test cases so that one test cannot conceal another test's failure.
Common Transaction Design Mistakes
- Assuming that BEGIN alone prevents every race condition.
- Reading a value into application memory and later writing an absolute replacement value.
- Checking inventory or balance in one transaction and performing the write in an unrelated transaction.
- Forgetting to roll back when a business condition fails.
- Ignoring the number of rows affected by a conditional update.
- Using serializable isolation without implementing serialization-failure handling.
- Retrying only the final SQL statement when earlier decisions relied on stale data.
- Holding locks during slow external calls or user interactions.
- Assuming a database rollback reverses a payment, email, or published message.
- Treating a lost commit acknowledgment as proof that the transaction failed.
- Assuming that a single-row constraint automatically enforces every cross-row business invariant.
A Practical Checklist for Safe Backend Transactions
Before shipping a database-backed operation that changes important data, review the transaction from the perspective of failure and concurrency rather than only the happy path. Identify which writes must succeed together, what business invariants must remain true, and how concurrent requests interact. Choose the simplest concurrency-control technique that correctly protects those invariants. For a basic counter, a direct atomic update may be sufficient. For a decision involving locked rows, explicit locking can be appropriate. For complex multi-row rules, consider serializable isolation and implement retries. For client edits, version-based optimistic concurrency can detect stale submissions. The implementation should also be observable. Record relevant transaction failures, constraint violations, deadlocks, and retry counts. These signals help identify contention and recurring application bugs. Do not log passwords, payment credentials, or unnecessary personal data. Performance tuning should follow measurement: stronger isolation, additional locks, and retries have costs that should be understood under realistic workloads.
Conclusion
Database transactions are a fundamental tool for building reliable backend systems, but they are not a substitute for careful application design. ACID explains the guarantees that matter: atomicity prevents partial transactional outcomes, consistency preserves required invariants, isolation governs concurrent interactions, and durability protects committed changes within the database's configured failure guarantees. Race conditions become easier to reason about when engineers distinguish a transaction boundary from a concurrency-control strategy. A multi-statement transaction groups related changes, but safe concurrent updates may also require conditional SQL, row locks, version checks, stronger isolation, or a combination of these mechanisms. The most useful starting point is to express simple changes directly in SQL and let the database coordinate writes to the relevant rows. When business decisions depend on multiple reads or records, choose a stronger strategy deliberately and test it with genuinely concurrent operations. Finally, design retries and external side effects as part of the workflow rather than treating them as afterthoughts. Reliable backend engineering is not about assuming that requests will arrive one at a time. It is about making the system correct when they do not.
OPEN
Thoughts on the article.