What Are ACID Transactions - and When You Don't Need Them Across Services

What are ACID transactions? They are a database's promise that a group of reads and writes behaves like one indivisible operation: it either happens completely or not at all, and while it is in flight other work cannot see it half-done.

The acronym covers four guarantees - atomicity, consistency, isolation, durability. In practice you only care about them when something goes wrong: a process dies between two writes, two requests touch the same row at the same moment, or the machine loses power one millisecond after you returned 200 OK.

Without transactions you get to handle all of that yourself, in application code, correctly, under concurrency. That is the problem ACID exists to remove. The interesting question is not whether the guarantees are useful - they are - but how far across your architecture you can realistically stretch them. Two steel security vault doors attached to a vintage brick wall, showcasing industrial strength.

ConceptACID transactions (Atomicity, Consistency, Isolation, Durability)
Where it sitsData layer - inside a single database engine, between your application and the storage it writes to
In one sentenceA set of guarantees that lets a group of database operations succeed or fail as one unit, even under concurrency and crashes.

The 60-Second Answer

What it does: lets you group several reads and writes into a unit that either commits entirely or leaves no trace, with defined behaviour when other transactions run concurrently.

The problem it solves: partial writes. No state where money left one account and never arrived at the other, and no need to write compensating cleanup logic for every failure point.

The cost it adds: coordination. Commits must reach durable storage before they are acknowledged, concurrent transactions must be ordered or versioned, and both show up as latency and contention on hot rows.

Default answer in a design review: if it is one database, use transactions - they are already there and already cheap. If it spans two services or two databases, you do not have ACID and should design for that instead of pretending otherwise.

How It Actually Works

1. A transaction is an explicit boundary you open, not a property of a statement

Begin, work, commit or roll back

You tell the database where the unit starts and ends. Everything between is one transaction with its own identity inside the engine, and nothing you wrote becomes visible to anyone else until you commit.

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

If you never open a boundary, most engines put each statement in its own implicit transaction. That is why a single UPDATE touching a thousand rows is still all-or-nothing, while two separate statements are not.

⚠️ In production — Autocommit is the quiet default. A lot of production bugs are two statements that the author assumed were atomic because they were adjacent in the same function. Adjacency in your code is not a transaction boundary; BEGIN is. Check what your ORM or connection pool does on your behalf, because it decides where your boundaries actually are.


2. Atomicity comes from writing the intent to a log before touching the data

Write-ahead logging makes rollback possible

Before a change lands on the real data pages, the engine appends a record describing it to an append-only write-ahead log. Appending sequentially is cheap and, crucially, it is recoverable: the log is the authoritative statement of what was supposed to happen.

That ordering is what makes all-or-nothing achievable. Because the engine has a durable record of every change belonging to your transaction, it can undo them if you roll back and redo them if it crashes before the data pages were flushed.

⚠️ In production — The log is also your write amplification. Every logical byte you change is written at least twice - once to the log, once eventually to the data files. On write-heavy workloads the log device, not the table, is often the bottleneck, and a long-running transaction holding the log open prevents the engine from reclaiming space behind it.


3. Commit is a durability fence, not just a return from a function

Durability means the log reached stable storage

Durability means that once COMMIT returns successfully, the change survives the process dying, the OS panicking, or the power being pulled. To promise that, the engine must force the relevant log records out of memory and out of the OS page cache onto storage before it answers you.

That forced flush is the single most expensive moment in the transaction's life, and it is why commit latency does not scale down with how little data you changed. A transaction that updates one row and a transaction that updates fifty pay roughly the same durability tax.

⚠️ In production — This is the knob people turn when they want writes to be faster, usually without saying so out loud. Relaxed or asynchronous commit modes acknowledge before the flush completes, which trades a window of recently committed transactions for throughput. It is a legitimate choice for click telemetry and an unacceptable one for a ledger - decide it deliberately, not by inheriting a config file.


4. Recovery replays the log, which is where atomicity and durability meet

Redo the committed, undo the rest

On restart after a crash the engine scans the log. Changes belonging to committed transactions are redone so nothing durable is lost; changes belonging to transactions that never committed are undone so no half-finished unit survives.

This is the whole trick. Atomicity and durability are not two separate mechanisms - they are two consequences of having an ordered, durable record of intent that can be replayed deterministically.

⚠️ In production — Recovery time is proportional to how much log has to be replayed, which depends on checkpoint frequency. Infrequent checkpoints make steady-state writes cheaper and make startup after a crash slower. Teams discover their own recovery time during their first unplanned restart, which is the worst moment to learn it.


5. Isolation is implemented either by blocking or by versioning

Locks make you wait, MVCC makes you read the past

Isolation means concurrent transactions do not see each other's partial work. There are two families of mechanism. Lock-based control makes a conflicting reader or writer wait until the other finishes. Multi-version concurrency control (MVCC) keeps older versions of each row, so a reader sees a consistent snapshot from the moment its transaction started and never blocks on a writer.

Most widely used relational engines are MVCC-based for reads and still lock for writes to the same row. So readers scale pleasantly and two writers to one row serialise, every time.

⚠️ In production — MVCC does not make conflicts disappear, it relocates them. Old row versions accumulate and must be cleaned up by a background process, and a single long-running transaction - an analytics query, an idle session someone left open in a client - pins those versions and makes the table bloat. Open connections are not free; open transactions are expensive.


6. Isolation levels are the dial, and the default is usually not the strict one

You choose which anomalies you accept

Full serializability means the outcome is equivalent to running the transactions one after another in some order. It is the easy mental model and the costly one, so engines offer weaker levels that permit specific anomalies in exchange for less coordination.

At weaker levels you can read a row, make a decision based on it, and have that row change underneath you before you commit. That pattern - check-then-act - is the most common source of correctness bugs that survive code review, because it looks obviously fine.

-- make the read itself the lock, instead of hoping
SELECT quantity FROM inventory WHERE sku = 'X' FOR UPDATE;

⚠️ In production — Know your engine's default level by name rather than by assumption, because defaults differ between engines and are frequently weaker than engineers expect. If you raise the level to serializable, your application must handle serialization failures by retrying the whole transaction - the database will reject conflicting work rather than silently corrupt it, and an unhandled retry path turns a correctness win into a 500.


7. Consistency is your invariants, enforced at the commit point

The database holds the rules you declared

Consistency in ACID is narrower than most people assume. It does not mean your data is semantically sensible; it means the transaction moves the database from one state satisfying its declared constraints to another state satisfying them. Foreign keys, unique indexes, check constraints, not-null.

The value is that these are checked by the engine under concurrency, which your application cannot reliably do. A uniqueness check in application code is a check-then-act race; a unique index is an actual guarantee.

⚠️ In production — This is also the ACID letter most often sacrificed by accident. Teams drop foreign keys for write performance or because a migration tool struggled with them, then rebuild the same checks in application code where they no longer hold under concurrency. You can make that trade - just notice that you have made it.


8. The guarantees end at the database boundary

Two systems, no free atomicity

All of the above works because one engine owns one log and one commit decision. Write a row and publish a message to a broker, and nothing coordinates them: your process can die between the two, and there is no shared log to replay.

Distributed protocols like two-phase commit exist to extend atomicity across participants, at the price of a coordinator whose failure can leave participants holding locks while they wait to be told the outcome. The common alternative is to keep one atomic write and derive the rest: write the row and an outbox record in the same transaction, then publish from the outbox with retries and idempotent consumers.

⚠️ In production — This is the boundary where architecture diagrams lie. "The order service and the payment service are both transactional" is true of each one individually and says nothing about the pair. Any step that crosses a process boundary needs an explicit answer for what happens when it is attempted twice, because eventually it will be.

Two professionals discussing project plans at whiteboard in office setting. ## Where You Meet It
  • A double-entry ledger in a payments system. Every movement is two rows that must both exist or neither, with the sum of entries invariant. The transaction is not a performance feature here, it is the only reason the balance can be trusted, and the ledger table is append-only precisely so that correction means a new compensating entry rather than an update.
  • Checkout in an e-commerce service: decrement inventory, create the order, record the reservation. Two customers buying the last unit at the same moment is the whole problem. The transaction plus an explicit row lock on the inventory row is what stops both from succeeding, and the loser gets a clean "out of stock" instead of an oversell discovered in the warehouse.
  • The outbox pattern in a service that must both persist state and notify the outside world. The row and the pending event are written in one transaction, so the event cannot exist for a state change that rolled back. A separate worker then delivers events at-least-once, and consumers deduplicate - ACID inside the service, idempotency across the boundary.
  • A schema migration with a backfill. The DDL and a small amount of data fix-up run inside a transaction so a failure halfway does not leave a half-migrated table. The accompanying operational truth is that this transaction holds locks and log space for its duration, which is why large backfills get chunked into many small transactions instead.
  • Idempotent webhook handling. A unique index on the provider's event ID plus a transaction that inserts the dedupe row and applies the effect together means a duplicate delivery fails the insert and applies nothing. The database constraint does the work that a SELECT followed by an INSERT could not do safely.

When You Actually Need It

  • Your write path changes two or more rows that must agree, and a reader seeing only one of them would be wrong - balances, inventory and reservations, parent and child records.
  • You have an invariant you can state in one sentence ("an email appears at most once", "a seat is assigned to at most one booking") and you are currently enforcing it with a read followed by a write.
  • Losing an acknowledged write would require a human to reconstruct the truth from somewhere else. If there is no upstream source to replay from, you need the durability guarantee on commit.
  • Two concurrent requests legitimately target the same entity and the correct outcome is one winner - not last-write-wins, not both.
  • You are already on a relational database. The guarantees are present and paid for; declining to use them means hand-writing weaker versions of the same logic.
  • You are seeing data that is internally inconsistent in production and cannot explain how it got that way. Missing transaction boundaries and check-then-act races are the usual answer.

When You Don't

  • Append-only, high-volume, individually unimportant events - metrics, logs, clickstream, device telemetry. There is no multi-row invariant and no single lost record matters. Batch the inserts, accept a relaxed commit mode or a store designed for appends, and spend the durability budget on the data that needs it.
  • A long-running business process measured in minutes, hours or human approvals. Holding a transaction open across it blocks cleanup, pins row versions and will eventually hit a timeout. Model it as a state machine with explicit statuses and compensating steps - the saga pattern - and use short transactions for each state change.
  • Spanning two services or two databases. Two-phase commit buys atomicity and hands you a coordinator that can block participants when it fails. Unless you have a hard regulatory requirement, keep one atomic write plus an outbox, at-least-once delivery and idempotent consumers; it is simpler to operate and fails in ways you can reason about.
  • Reaching for a distributed SQL cluster to "get ACID at scale" before you have measured a single node. One ordinary relational instance on decent storage handles far more transactional write throughput than most products ever reach, and SQLite is fully ACID inside a single file. Distribution adds cross-node consensus to every commit, so adopt it when your measured write volume or availability target demands it, not preemptively.
  • Serializable isolation across the board because it is the strongest option. It converts contention into serialization failures that every caller must retry, which is real work in your application. Run the default level and add explicit locking or constraints at the two or three places that actually have a conflicting invariant.
  • The acid vs base database question when your workload is genuinely a cache, a search index or a derived view. BASE systems - basically available, soft state, eventually consistent - are the right fit when the record of truth lives elsewhere and staleness is recoverable by re-deriving. Requiring strict transactions there just makes a rebuildable component harder to run. Close-up of server racks in a data center highlighting modern technology infrastructure.

What People Get Wrong

"ACID versus BASE is a choice of database, and you pick a side."

It is a choice per workload, and most systems are mixed. Teams routinely keep the ledger or the orders in a transactional store and the search index, cache and activity feed in eventually consistent ones. The acid vs base database framing came from a period when NoSQL stores could not offer transactions at all; many now do within a partition or key range, so the honest question is what guarantees apply to which operation, not which camp your stack belongs to.

"If the database is ACID, my application is consistent."

ACID consistency means declared constraints hold at commit. Nothing stops you from committing business nonsense that satisfies every constraint, and nothing protects a decision made from a stale read outside the transaction. The guarantee covers the boundary you drew - if your boundaries are wrong, or if your logic reads, thinks, then writes without a lock, consistency is not enforced where you need it.

"Transactions are slow, so we avoid them."

What costs is the durability flush at commit and the contention on hot rows, not grouping statements. Wrapping three statements in one transaction is typically cheaper than three separate implicit transactions, because you pay one commit instead of three. The genuinely slow patterns are different: transactions held open across network calls or user think time, and many writers converging on the same row.

"Our replicas give us the same guarantees as the primary."

Asynchronous replication means a replica lags, so a read-your-own-write immediately after committing can return the old value. The commit on the primary was durable there; whether it is durable elsewhere, and when it becomes visible, depends on your replication mode. Synchronous replication closes the gap and adds the network round trip to every commit.

Why It Was Built This Way

The constraint is that storage devices and memory fail independently and at arbitrary moments, and a write that touches several places cannot be made instantaneous. You cannot update two data pages atomically on hardware that may stop between them. So the design gives up on making the data update atomic and instead makes a record of intent atomic: one sequential append to a log, which either made it to durable storage or did not. Everything else - rollback, crash recovery, replication - is then derived from replaying that log. Atomicity and durability stop being two hard problems and become one ordering guarantee.

What was traded away is latency at the commit point and a permanent write amplification. Every commit needs a real flush to stable storage, which is why commit cost is dominated by a fixed durability tax rather than by how much you changed, and why nearly every performance knob in this area is really a question of how much of that tax you are willing to defer. Isolation involved a second trade: strict serializability is the only level that behaves the way a programmer naturally reasons, but enforcing it requires either broad locking or conflict detection with retries. The industry's answer was to expose weaker levels as defaults and let applications opt into strictness, which is why isolation anomalies remain a live source of bugs decades later - the cost was pushed out of the engine and into your code, where it is invisible until it is concurrent.

The last trade is the one that shapes modern architecture. All of these guarantees depend on one component owning one log and making one commit decision, so they are intrinsically local. Distributing them means agreeing across machines before every commit, which costs round trips and introduces a coordinator that can stall participants while they wait for an outcome. That is the real content of the acid vs base database debate: BASE systems did not reject correctness, they rejected the coordination required to get a single global commit decision, and accepted convergence-after-the-fact in exchange for availability during partitions. Knowing that, the design question for your own system becomes narrow and answerable - which data genuinely needs a single commit decision, and which data can be re-derived from something that does.

Related Briefs

What to Read Next

  • what is MVCC in databases
  • saga pattern for distributed transactions
  • serializable vs repeatable read isolation level

Inside one database, transactions are the cheapest correctness you will ever buy - use them, and know your isolation level by name rather than by assumption. Across process boundaries you do not have them, and the useful work is deciding which single write is the atomic one and making everything downstream idempotent. Most systems need exactly one strictly transactional core and eventual consistency around it; the mistake is spreading strict guarantees everywhere, or assuming you have them where you do not.

댓글

이 블로그의 인기 게시물

What Is a Message Queue - and When You Actually Don't Need One

What Is a Bloom Filter - and When You Actually Don't Need One

When to Use GraphQL Over REST API - and When REST Is Still the Right Call