Skip to content

ACID vs BASE ​

"BASE is diametrically opposed to ACID. Where ACID is pessimistic and forces consistency at the end of every operation, BASE is optimistic and accepts that the database consistency will be in a state of flux." — Dan Pritchett, BASE: An Acid Alternative, ACM Queue 6(3), July 2008

Summary: ACID is a contract a database gives you inside one transaction: all-or-nothing writes, invariants that hold, no interference between concurrent work, and durable results. BASE is the name for the opposite bargain: stay available, tolerate temporary disagreement, converge later. Real systems mix both, by data class, with the seam between them designed on purpose. Focus: The four ACID properties, the three BASE words and where the acronym really came from, what BASE stores actually guarantee (per-key atomicity, conditional writes, tunable consistency) and how DynamoDB, MongoDB, Cassandra, Spanner and CockroachDB changed the picture, the price of distributed ACID (2PC), building BASE correctly (idempotency, sagas with compensation, read-your-writes, reconciliation), choosing per data class (ledger, cart, analytics), hybrid architectures, anti-patterns, and the same order flow in Go and Laravel 13 written both ways. Learning goal: For any piece of data in a system you can say which contract it needs, name the product feature that provides it, write the failure path (rollback or compensation), and explain what a user can observe in between.

This chapter sits in the Consistency and Distributed Data group, after CAP, PACELC and tunable consistency and Consistency Models, and before Replication Topologies. It owns the system-level decision and the trade-off tables. Mechanics live in the siblings: the four properties and BEGIN/COMMIT in ACID & Transactions, anomalies and levels in Isolation Levels, consensus and 2PC internals in Distributed SQL, Consensus & 2PC, the saga pattern in Saga Pattern, outbox in Outbox Pattern, and request deduplication in API Idempotency.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why the two camps existWhy it exists
Who coined ACID and BASE, and why BASE is not a formal modelWhere it comes from
Atomicity, consistency, isolation, durabilityAtomicity, Consistency, Isolation, Durability
Basically available, soft state, eventually consistentBasically available, Soft state, Eventual consistency
What a BASE store really gives youPer-key atomicity, Multi-item transactions
The cost of distributed ACIDDistributed ACID and 2PC
Building BASE correctlySagas, Idempotency, Read-your-writes, Reconciliation
ACID core with BASE edgesHybrid architecture
Per-product behaviourWhat each product really does
Numbers, knobs, error codesMechanics
CodeGo, Laravel
Classic failures and fixesSolving the classic problems
Which contract for which dataChoosing
Monolith to multi-regionIn architecture
Hands-on experimentsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

ACID: the four promises of a transaction.

LetterIn plain wordsTiny exampleWhat provides it
AtomicityAll the writes happen or none doDebit and credit both apply, or neitherWrite-ahead log plus rollback
ConsistencyThe data obeys your rules before and afterStock never below zero, debits equal creditsConstraints, triggers, and your own correct code
IsolationConcurrent transactions do not see each other's half-done workTwo buyers of the last item do not both succeedLocks or snapshots (MVCC), per isolation level
DurabilityOnce committed, it survives a crashPower cut after COMMIT returns, the row is still thereWAL flushed to disk (fsync), replication

BASE: the three words.

WordIn plain wordsTiny exampleThe price
Basically AvailableMost requests get an answer even when parts are brokenOne shard down, the other shards still serveAnswers may be partial or stale
Soft stateState may change without new input, as replicas convergeA cart count differs for a second between two replicasReaders can see in-between values
Eventually consistentIf writes stop, all replicas end up equalTwo data centres agree a few hundred milliseconds laterYou must design for the gap

What each side is good at.

QuestionACID (single database)BASE (partitioned, replicated stores)
Can a user see a half-finished operation?NoYes, until convergence
What happens when the network splits?CP: the minority side refuses writesAP: both sides keep writing, conflicts later
Cost of a multi-row invariantOne transactionSaga, compensation, reconciliation
Scale-outVertical first; sharding makes it hardBuilt for horizontal partitions
Failure undoROLLBACK, automaticCompensating action you wrote
Typical dataMoney, stock, bookings, identityCarts, feeds, counters, sessions, analytics

Why it exists ​

A single database server can lock rows and write one log, so it can promise that a transaction is all-or-nothing and invisible until commit. The moment the data lives on several machines, the promise costs coordination: every participant must agree before anyone commits, and agreement needs messages that can be delayed or lost. Pritchett's 2008 argument from eBay is plain arithmetic: "The availability of any system is the product of the availability of the components required for operation", so a transaction spanning two databases that are each 99.9 percent available "becomes 99.8 percent, or an additional downtime of 43 minutes per month".

PressureACID answerBASE answer
Data no longer fits one machineDistributed SQL with consensus, or accept a bigger machinePartition by key, never join or transact across partitions
Users in several continentsPay cross-region latency per commitWrite locally, replicate asynchronously
A dependency is downThe transaction waits or failsQueue the work, answer now, finish later
A business rule spans servicesImpossible without 2PCSaga with compensations

An everyday picture. A bank counter versus a notice board. At the counter, a clerk checks the balance, moves the money and stamps the slip while you wait: slow, one at a time, always right. On the notice board, many people pin updates; the board looks different from different corners for a while, but anyone can post at any time. You would not run payroll on the board, and you would not run the community noticeboard through the counter.

Three common misunderstandings, up front ​

  1. "NoSQL means no ACID." Wrong since about 2018: DynamoDB, MongoDB, Cassandra (in a limited way), Spanner and CockroachDB all offer some form of transaction. The real question is the scope: one item, one partition, one region, or the whole cluster.
  2. "BASE means the data is sometimes wrong." Wrong: BASE means the data is allowed to be stale or divergent for a bounded time, and the application must be correct anyway. A shopping cart that converges is not corrupt.
  3. "ACID is the safe choice, BASE is the fast choice." Both halves are false. ACID with a good schema scales far (one PostgreSQL primary handles thousands of writes per second), and BASE without idempotency and reconciliation is how money disappears.

Where it comes from ​

  • ACID, 1983. The acronym is credited to Theo Haerder and Andreas Reuter (Principles of Transaction-Oriented Database Recovery, ACM Computing Surveys, 1983), building on Jim Gray's earlier transaction work, which named atomicity, consistency and durability but not isolation. This attribution comes from a secondary source (the Wikipedia article on ACID, saved with the sources); the ACM paper itself could not be fetched from this machine.
  • CAP, 2000. Eric Brewer's conjecture that a web service cannot ensure consistency, availability and partition tolerance at once. Pritchett summarises it: "any horizontal scaling strategy is based on data partitioning; therefore, designers are forced to decide between consistency and availability". See CAP and PACELC.
  • BASE, 2008. Pritchett's ACM Queue article, "BASE: An Acid Alternative", written from eBay's experience, defines BASE as "basically available, soft state, eventually consistent" and sets it against ACID. He argues for splitting data and processes so that the pieces that need ACID get it locally, and the rest uses idempotent operations and asynchronous messages.
  • Why the acronym is a pun. The chemistry joke (acid versus base) shaped the name: BASE was chosen to be the opposite of ACID. It describes a design stance, not a specification. There is no formal definition of "soft state", the three words overlap, and every BASE product defines its own consistency options. Treat "BASE" as a family label for designs that choose availability, and use precise terms when you need to reason: linearizability, causal consistency, read-your-writes (see Consistency Models).
  • The line blurs, 2012 on. Google's Spanner (distributed, externally consistent), then DynamoDB transactions, MongoDB multi-document transactions and CockroachDB showed that horizontal scale and transactions can coexist when you pay the coordination cost.

The concept catalogue ​

Each block has a fixed order: plain words, a common misunderstanding, a definition, a timeline, real scenarios, what provides it, and the fix.

Atomicity Must-know ​

In plain words: A group of writes is treated as one: either every write is applied or none is. There is no "half an order".

Common misunderstanding: "Atomic means fast, or lock-free." No. Atomic means indivisible from the outside. A slow transaction can be atomic, and a lock-free operation can be non-atomic across two rows. Also: atomicity is about failure, not concurrency; hiding the half-done state from other sessions is isolation.

Definition: In Pritchett's wording, "All of the operations in the transaction will complete, or none will." The database implements it with a write-ahead log: on crash or ROLLBACK, uncommitted changes are discarded (see Durability, WAL & Crash Recovery).

text
     Session                                  Database
1    BEGIN;
2    UPDATE stock  ... qty = qty - 2          change logged, not committed
3    UPDATE accounts ... balance - 4000       ERROR: new row violates CHECK (balance_cents >= 0)
4    (transaction aborted)                    stock change is undone automatically
5    SELECT qty FROM stock                    qty is unchanged: no half order exists

Real scenario: A money transfer (debit plus credit); placing an order (stock, payment, order row); registering a user (account row, profile row, welcome-credit row); moving a task between boards (delete here, insert there).

What provides it:

ProductScope of an atomic unitNotes
PostgreSQL, MySQL (InnoDB), SQL Server, OracleAny statements in one transactionAutomatic rollback on error (PostgreSQL aborts the whole transaction until ROLLBACK)
SQLiteAny statements in one transaction, one writerWhole database file is the unit of locking
MongoDBOne document always; many with a multi-document transaction"an operation on a single document is atomic" (MongoDB docs)
DynamoDBOne item always; up to 100 items with TransactWriteItemsSame account and Region only
CassandraOne row/partition write; LOGGED batch for severalBatch is atomic eventually, not isolated across partitions
RedisA single command; MULTI/EXEC runs queued commands in one goNo rollback of commands that already ran

Fix / how to use it: Put every write that must stand or fall together in one transaction. Do not open the transaction in one function and write in another that uses a different connection (the hidden-connection bug). See the SQL in Go and PHP in Laravel.

Consistency, as invariants Must-know ​

In plain words: "Consistent" in ACID means the data obeys your business rules after every transaction: no negative stock, every order has a customer, debits equal credits.

Common misunderstanding: "ACID consistency is the same as the C in CAP, or as replicas agreeing." No. The C in ACID is about invariants inside one database. The C in CAP is linearizability across replicas. The database offers the tools; your application defines the rules.

Definition: A transaction takes the database from one state that satisfies all declared and implicit invariants to another. The engine enforces what you declare (CHECK, UNIQUE, FOREIGN KEY, NOT NULL, exclusion constraints); everything you do not declare is only as safe as your code.

text
     Rule: stock.qty >= 0 and sum(ledger) = 0 per transfer
1    app reads qty = 1, decides "enough"
2    another transaction sets qty = 0
3    app writes qty = qty - 1   -> without CHECK: qty = -1, rule broken silently
4    with CHECK (qty >= 0) or UPDATE ... WHERE qty >= 1: the engine refuses

Real scenario: Inventory that must not oversell; unique usernames and emails; one active subscription per customer; ledger entries that sum to zero; a booking that must not overlap another (PostgreSQL exclusion constraint).

What provides it:

ToolInvariant it protectsWhere available
CHECK constraintSingle-row value rulesPostgreSQL, MySQL 8.0.16+, SQL Server, Oracle, SQLite
UNIQUE and primary keyNo duplicates, idempotency keysAll SQL; DynamoDB conditional write; Cassandra IF NOT EXISTS
FOREIGN KEYReferential integritySQL engines; none in DynamoDB, Cassandra or MongoDB
Conditional update (WHERE qty >= n)Read-modify-write without a raceAny store with a conditional write
Serializable isolationRules across several rows (write skew)PostgreSQL SSI, CockroachDB, Spanner

Fix / how to use it: Encode rules as constraints first, conditional updates second, application checks last. In BASE stores that have no cross-item constraints, the invariant moves into the application and the reconciliation job.

Isolation Must-know ​

In plain words: Transactions that run at the same time should not trip over each other. The strongest form makes it look as if they ran one after another.

Common misunderstanding: "Isolation is on or off." It is a dial with named levels (Read Committed, Repeatable Read, Serializable) and the defaults differ per product: PostgreSQL defaults to Read Committed, MySQL InnoDB to Repeatable Read, Spanner and CockroachDB to Serializable. The ACID promise as taught is the Serializable end; most systems run weaker for speed.

Definition: The PostgreSQL manual describes the goal of the strongest level: Serializable "emulates serial transaction execution for all committed transactions; as if transactions had been executed one after another, serially, rather than concurrently". The anomalies each level allows are covered in Isolation Levels; here is the summary.

text
     Level               Dirty read  Non-repeatable  Phantom   Lost update / write skew
1    Read Committed      no (PG)     possible        possible  possible
2    Repeatable Read     no          no              no (PG)   write skew possible
3    Serializable        no          no              no        no (retry on 40001)

Real scenario: Two checkouts for the last ticket; two admins editing the same profile; a report that runs while nightly batch inserts; two doctors both going off call (write skew).

What provides it:

ProductDefault levelStrongest levelMechanism
PostgreSQLRead CommittedSerializable (SSI)MVCC snapshots, SSI aborts with 40001
MySQL InnoDBRepeatable ReadSerializable (locking)MVCC plus next-key locks
SQL ServerRead Committed (locking)Serializable, SnapshotLocks or row versions
OracleRead CommittedSerializableUndo-based read consistency
CockroachDBSerializableSerializable (Read Committed available)Timestamp ordering, retry error 40001
SpannerSerializable (externally consistent)sameLocks plus TrueTime commit timestamps
DynamoDBEventual single-item readsSerializable for transactionsBetween transactional and standard operations too
MongoDBSnapshot within a transactionSnapshot with majority concernRead/write concerns

Fix / how to use it: Keep the default for ordinary reads, protect hot invariants with an atomic conditional update or SELECT ... FOR UPDATE, and use Serializable plus a retry loop when the rule spans rows. Retries are in Mechanics.

Durability Important ​

In plain words: When the database says "committed", a crash or power loss will not take that data back.

Common misunderstanding: "Committed means on disk on several machines." Not by default. A commit on one server means its log was flushed (when fsync is on). Whether a replica has it depends on synchronous versus asynchronous replication; a failover to a lagging replica can lose recent commits.

Definition: The effects of a committed transaction survive crashes. The mechanism is the log forced to stable storage before the commit returns (Durability, WAL & Crash Recovery). Across machines, durability becomes "acknowledged by how many replicas" (Replication, Read Replicas & Failover).

text
     Client                       Primary                    Replica (async)
1    COMMIT ------------------>   write WAL, fsync
2    <------------ OK             (replicates in background)
3                                 primary dies
4    failover promotes replica ------------------------------> lacks the last commits
5    the client was told OK, the data is gone

Real scenario: Payments acknowledged then lost after a failover; a Redis cache with default appendfsync everysec losing one second of writes; a DynamoDB write acknowledged by a quorum of storage nodes (durable by design).

What provides it:

ProductSettingEffect
PostgreSQLsynchronous_commit = on (default), synchronous_standby_namesWait for local WAL flush, optionally for a replica
MySQL InnoDBinnodb_flush_log_at_trx_commit = 1fsync the redo log at each commit
MongoDBwrite concern w: "majority", j: trueMajority of members, journaled
Cassandracommitlog_sync, consistency level QUORUMCommit log mode plus replicas acknowledged
Redisappendonly yes, appendfsync always/everysecPer-write or per-second fsync of the AOF
Spanner, CockroachDBRaft or Paxos majorityCommit is durable on a majority before returning

Fix / how to use it: For money, require the strongest local setting plus at least one synchronous replica or a majority-replicated store; accept weaker durability only for data you can rebuild.

Basically available Must-know ​

In plain words: When something breaks, the system still answers most requests instead of going dark.

Common misunderstanding: "Basically available means high availability with a guarantee." It is the opposite of a guarantee: it means the system degrades, perhaps serving stale or partial data, instead of refusing. Pritchett's point is that availability of a system is the product of the availability of the components it requires, so you reduce the components a request requires.

Definition: Partial failure should degrade the service, not stop it. Mechanisms: partitioning (a failed shard hurts only its keys), replication (another node serves the read), asynchronous work (queue it, answer now), and degraded modes (see Bulkheads & Graceful Degradation).

text
     User                    API                  Cart shard A      Cart shard B
1    GET /cart (user 17) --> hash(17) -> A ------> down
2                            retry replica of A -> A2 (stale by 300 ms)
3    <-- 200 cart, maybe slightly stale
     User 42 -> shard B -> normal; the outage touched only a slice of users

Real scenario: A product page served from cache when the pricing service is down; a social feed served with a stale ranking; a search index that lags the primary; DynamoDB returning a read from any replica in an eventually consistent read.

What provides it:

TechniqueProduct examplesCost
Partition by keyDynamoDB, Cassandra, MongoDB shardsNo cross-partition transaction or join
Multi-replica readsCassandra ONE/LOCAL_QUORUM, DynamoDB eventual readsStale reads
Queue instead of callKafka, RabbitMQ, SQSDelayed result, more states
Cache fallbackRedis, CDN stale-if-errorStaleness, invalidation

Fix / how to use it: For each user-facing path list the components it requires, then remove, queue or cache the ones that are not essential to answering.

Soft state Important ​

In plain words: The state of the system can change over time even if nobody sends it a new request, because replicas are still catching up or timers are expiring.

Common misunderstanding: "Soft state means the data is temporary or not saved." No. Data is stored durably. "Soft" means the agreement between copies is not settled; a read may return an in-between value. It also covers state that must be refreshed or it expires, such as leases and cache entries.

Definition: There is no point at which all copies are guaranteed identical; the system moves toward agreement in the background (anti-entropy, read repair, replication). Applications must be written so that reading an in-between value is harmless or detectable. See Merkle Trees & Anti-Entropy.

text
     Replica 1               Replica 2               Replica 3
1    cart = [A]              cart = [A]              cart = [A]
2    write cart = [A,B] lands here only
3    cart = [A,B]            cart = [A]              cart = [A]       (soft: copies differ)
4    replicate ----------->  cart = [A,B]
5    anti-entropy -------------------------------->  cart = [A,B]    (converged)

Real scenario: A like counter that differs by region for a few seconds; a Cassandra row read at ONE from a replica that missed a write; a DNS record cached with a TTL; a materialised view built from events.

What provides it:

MechanismProductEffect
Asynchronous replicationMongoDB secondaries, PostgreSQL async standby, MySQL replicasLag between primary and replica
Hinted handoff, read repair, anti-entropyCassandra, DynamoDB internalsDivergent replicas converge later
TTL and lease expiryRedis keys, DynamoDB TTL, Consul sessionsState disappears without a request
Derived storesElasticsearch fed by CDC, cachesUpdated after the source

Fix / how to use it: Show state that may be stale as "pending" in the UI, version every record, and give consumers a way to ask "is this at least as new as my write" (see Read-your-writes).

Eventual consistency Must-know ​

In plain words: If you stop writing, every copy will end up with the same value. It does not say when, and it does not say what you see in the meantime.

Common misunderstanding: "Eventually consistent means it is fixed in a few milliseconds, so I can ignore it." The window is a property of load, failures and configuration. It can be milliseconds in the normal case and minutes or hours after an outage. Design for the worst, not the median. Also: "eventually" without a conflict rule can converge to the wrong value, for example when last-write-wins discards an update.

Definition: A liveness guarantee: in the absence of new updates, all replicas converge. Everything else (monotonic reads, read-your-writes, causal order) is a session guarantee you must ask for separately (Consistency Models).

text
     Writer A            Writer B             Replica X            Replica Y
1    set n = 5 ---------------------------->  n = 5
2                        set n = 7 -------------------------------> n = 7
3    replicate -------------------------------------------------->  n = 5 (timestamp lower: ignored)
4    replicate ------------------------------> n = 7
5    both converge to 7; A's write was lost without any error (last-write-wins)

Real scenario: DynamoDB default reads after a write; Cassandra ONE reads; a search index after a product change; analytics dashboards behind the event stream; DNS.

What provides it (and how to tighten it):

ProductDefaultStronger option
DynamoDBEventually consistent readsConsistentRead true (strong, same Region, primary replica)
CassandraTunable per queryQUORUM reads and writes (R + W > N)
MongoDBRead from primary by defaultRead concern majority or linearizable
Redis replicationAsynchronousWAIT for acknowledged replicas
ElasticsearchNear real time (refresh interval)Explicit refresh, or read from the source of truth

Fix / how to use it: Use conditional writes for read-modify-write, version numbers for staleness, and a conflict rule appropriate to the data (CRDTs, merge, or reject; see CRDTs).

Per-key atomicity and conditional writes Must-know ​

In plain words: Most BASE stores promise that a single key (one item, one document, one partition row) is updated atomically, and that you can say "only write if the value is still what I read".

Common misunderstanding: "No transactions means no safe updates." A conditional write (compare-and-set) is the safe update primitive; most "NoSQL" counters, inventories and locks are built from it. What you lose is atomicity across two keys.

Definition: A write on one key either fully applies or not, and a conditional write applies only if a predicate on the current item holds: DynamoDB ConditionExpression, Cassandra IF (lightweight transaction), MongoDB findOneAndUpdate with a filter, Redis WATCH or a Lua script, SQL UPDATE ... WHERE version = ?.

text
     Client 1                                  Client 2                       Item cart#1
1    GET cart#1 -> version 3 ---------------------------------------------->  v3
2                                              GET cart#1 -> version 3
3    PUT v4  IF version = 3 ---------------------------------------------->   v4 (accepted)
4                                              PUT v4' IF version = 3         ConditionalCheckFailedException
5                                              re-read v4, merge, PUT v5 IF version = 4 -> accepted

Real scenario: A cart that two devices edit; an inventory counter decremented with qty >= n; a username claim (IF NOT EXISTS); an idempotency key insert; a distributed lock with a fencing token.

What provides it:

ProductPrimitiveFailure signal
DynamoDBConditionExpression on PutItem/UpdateItem/DeleteItemConditionalCheckFailedException
CassandraINSERT ... IF NOT EXISTS, UPDATE ... IF col = ? (Paxos)[applied] = false in the result row
MongoDBFilter in updateOne/findOneAndUpdate, $incmatchedCount = 0
RedisSET NX, WATCH/MULTI/EXEC, Lua EVALnil reply or aborted EXEC
SQLUPDATE ... WHERE qty >= n, version column0 rows affected

Fix / how to use it: See kv/kv.go in Go (compare-and-swap with retry) and the DynamoDB and Cassandra forms in the SQL block below. For optimistic versions in SQL see Optimistic vs Pessimistic Locking.

Multi-item transactions in NoSQL stores Important ​

In plain words: BASE stores historically had no multi-item transactions. Most now have an opt-in version, with limits and a price.

Common misunderstanding: "Now that DynamoDB and MongoDB have transactions, use them everywhere." The documentation itself warns against it. MongoDB's manual says "In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design." DynamoDB doubles the capacity cost of transactional operations.

Definition: An opt-in API that groups writes across items, partitions or documents with all-or-nothing semantics and serializable (DynamoDB) or snapshot (MongoDB) isolation, at higher latency and with size and count limits.

text
     App                         DynamoDB
1    TransactWriteItems(ClientRequestToken = "order-o1", [
2       Update stock  ConditionExpression "qty >= 2",
3       Update accounts ConditionExpression "balance >= 4000",
4       Put orders ConditionExpression "attribute_not_exists(id)" ])
5    -> either all three commit, or TransactionCanceledException with CancellationReasons per item
6    timeout? resend the same token: "subsequent calls with the same client token return successfully"

Real scenario: Moving a small order across three items in one table family; creating a user and its unique-email item together; MongoDB moving money between two documents when the schema cannot embed them.

What provides it:

ProductAPILimits (from the docs)
DynamoDBTransactWriteItems, TransactGetItemsUp to 100 actions, same account and Region, 4 MB aggregate, idempotent with a client token
MongoDBMulti-document transactions on replica sets and sharded clustersPerformance cost; prefer embedding; short transactions
CassandraLOGGED BATCH; LWT IFBatch is not isolated across partitions; LWT is per partition
SpannerRead-write transactionsSerializable, externally consistent, retry on ABORTED
CockroachDBBEGIN ... COMMITSerializable by default, retry on 40001
RedisMULTI/EXECNo rollback; single node or one hash slot in Cluster

Fix / how to use it: Model so that the invariant lives in one item or one partition; use multi-item transactions for the few operations that cannot; keep them short and idempotent.

Distributed ACID and two-phase commit Must-know ​

In plain words: To commit one transaction on several machines, a coordinator asks everyone "can you commit?" and only then says "commit". It works, but everyone waits for the slowest and the unluckiest.

Common misunderstanding: "2PC is a solved problem, so cross-service ACID is free." 2PC is correct but blocking: if the coordinator dies after the participants voted yes, they hold locks and wait. It also needs every participant to support the protocol, which a REST API or a third-party payment provider does not.

Definition: Two-phase commit: phase 1 the coordinator asks each participant to prepare (make the transaction durable and promise to commit); phase 2 it tells all to commit or roll back. Pritchett: "The transaction coordinator asks each database involved to precommit the operation and indicate whether commit is possible. If all databases agree the commit can proceed, then phase 2 begins." Consensus-based systems (Spanner, CockroachDB) layer 2PC over Paxos or Raft groups so that the coordinator and participants are replicated and do not block forever (Distributed SQL, Consensus & 2PC).

text
     Coordinator                 Database A                Database B
1    PREPARE ------------------> prepare (log, lock)
2    PREPARE ------------------------------------------>   prepare (log, lock)
3    <---------------- yes       <------------------------ yes
4    log decision: COMMIT
5    COMMIT -------------------> commit, release locks
6    COMMIT -------------------------------------------->  commit, release locks
     coordinator crash between 3 and 5: A and B stay "in doubt", holding locks

Real scenario: PostgreSQL PREPARE TRANSACTION driven by an external transaction manager (XA-style Java/Narayana); MySQL XA; Spanner or CockroachDB transactions touching several ranges; a legacy ERP with two databases.

What provides it:

ProductDistributed transactionNotes
PostgreSQLPREPARE TRANSACTION / COMMIT PREPARED"Unless you're writing a transaction manager, you probably shouldn't be using PREPARE TRANSACTION"; leave max_prepared_transactions at 0 otherwise
MySQL InnoDBXA transactionsAlso used internally between binlog and engine
SQL Server, OracleMSDTC, Oracle distributed transactionsCoordinator is a separate service
Spanner2PC across Paxos groupsSerializable, externally consistent
CockroachDBParallel commits over Raft rangesSerializable, 40001 retries
KafkaTransactions (producer + offsets)Atomic across partitions of one cluster, not across a database

Fix / how to use it: Use it where one product gives it to you inside its own cluster (Spanner, CockroachDB, a single PostgreSQL). Across services and third parties, use a saga. The cost shows in the diagram below.

CoordinatorDatabase ADatabase B1. PREPAREvotes: yes (durable)decision logged2. COMMITackslocks held, in doubtcoordinator dies here= participants blockAvailabilityA 99.9% x B 99.9%= 99.8%+43 min/monthdown (Pritchett)+ 2 round trips,+ 2 log forces,+ held row locks

Sagas and compensation Must-know ​

In plain words: Replace one big transaction by a sequence of small local ones. If a later step fails, run the undo for each earlier step.

Common misunderstanding: "A compensation is a rollback." It is not. A rollback erases an uncommitted change; a compensation is a new business action after the original was committed and possibly seen: a refund after a charge, a "cancelled" status after "confirmed". A refund may take days, an email cannot be unsent, and a shipment may already have left.

Definition: A saga is a sequence of local transactions where each step has a compensating transaction. microservices.io states it as: "If a local transaction fails because it violates a business rule then the saga executes a series of compensating transactions that undo the changes that were made by the preceding local transactions." Coordination is either choreography (events) or orchestration (a coordinator tells participants what to do). Mechanics and variants: Saga Pattern and Outbox Pattern.

text
     Orchestrator        Inventory           Payments            Shipping
1    reserve(o1) ------> hold 2 units, commit
2    charge(o1) ------------------------------> DECLINED
3    compensate: refund(o1) ------------------> no charge: no-op
4    compensate: release(o1) -> units returned
5    outcome = compensated; between steps 1 and 4 other users saw 2 fewer units (no isolation)

Real scenario: Booking a trip (flight, hotel, car); marketplace checkout (stock, payment, shipment); onboarding (account, billing, welcome email).

What provides it:

ToolRoleNotes
Hand-written orchestrator (Go saga.Runner)Journal of steps, ordered compensationFull control; you own recovery
Laravel Bus::chain()->catch() plus queued jobsChain with a failure callback that queues compensationPer-job #[Tries], #[Backoff]
Temporal, AWS Step Functions, CamundaDurable workflow enginesRetries and state persisted for you; see Durable Workflows
Kafka plus Debezium outboxChoreography via eventsEach service reacts and emits

Fix / how to use it: Make every step and every compensation idempotent, journal progress, retry compensations until they succeed, order steps so the hardest-to-undo comes last (charge before you ship, not after), and add a human queue for stuck. Code: saga/saga.go and the Laravel jobs below.

ACID: one transactionBEGIN ... COMMIT (one database)UPDATE stock (qty >= n)UPDATE accounts (balance >= n)INSERT ordersall three apply, or none; no one sees halfBASE style: saga, local commitsInventoryreserve (commit)Paymentscharge (commit)Payments declinesstep failsInventoryrelease stockPaymentsrefund if chargedbetween commits other readers see half the orderundo is a new business action, not a rollback

Idempotency Must-know ​

In plain words: Doing the same operation twice has the same effect as doing it once. In an at-least-once world every message and request will be delivered twice eventually.

Common misunderstanding: "My queue is exactly-once, so I do not need it." No broker gives end-to-end exactly-once effects on an external system; it gives at-least-once plus, sometimes, deduplication inside its own boundary (Delivery Guarantees). Pritchett: "An operation is considered idempotent if it can be applied one time or multiple times with the same result." He also notes that "Update operations are rarely idempotent" (an increment applied twice counts twice).

Definition: Make effects idempotent by key: a unique constraint on (consumer, message_id), a charge row keyed by order id, a ClientRequestToken on a DynamoDB transaction, or an idempotency key on an API (API Idempotency, Idempotent Consumers & the Inbox Pattern).

text
     Broker          Consumer                     Database
1    deliver m-123 -> BEGIN
2                     INSERT processed(m-123)  --> ok (first time)
3                     apply effect: charge 40.00
4                     COMMIT;  crash before ack
5    redeliver m-123 -> BEGIN
6                     INSERT processed(m-123)  --> conflict, 0 rows: skip effect
7                     COMMIT; ack  -> charged exactly once

Real scenario: A payment webhook delivered three times; a retry after a gateway timeout; a saga step repeated after an orchestrator restart; a mobile client resending a POST on a flaky network.

What provides it:

TechniqueWhereWeakness
Unique key in the same transaction as the effectPostgreSQL ON CONFLICT DO NOTHING, MySQL INSERT IGNORENeeds a shared store for dedupe and effect
ClientRequestTokenDynamoDB TransactWriteItemsToken remembered for a limited window
Natural idempotent writesSet a value, upsert by keyNot for increments
Version or CAS checkConditional writesRetries after conflict need re-read

Fix / how to use it: processed_messages in the SQL below; insertOrIgnore in the Laravel jobs; keyed operations in every Go service method.

Read-your-writes Important ​

In plain words: After I save something, I must see it on my next read, even if other people still see the old value.

Common misunderstanding: "Eventual consistency means nobody sees it until later." The writer sees nothing wrong on the primary but is served by a lagging replica on the next click, and thinks the save failed. It is the commonest user-visible symptom of BASE.

Definition: A session guarantee: a read in a session reflects all earlier writes of that session. It is cheaper than strong consistency for everyone: only the writer's reads need care. See Consistency Models for the client-centric family.

text
     Browser            API                  Primary             Replica (lag 400 ms)
1    POST /profile ---> write ---------------> v7
2    <-- 200 (token: profile@v7)
3    GET /profile ----> read replica ----------------------------> v6   (stale!)
4                       replica version 6 < token 7 -> read primary instead -> v7

Real scenario: Posting a comment and not seeing it; updating an address then seeing the old one at checkout; a "Saved" toast followed by stale data; a cart after "add".

What provides it:

TechniqueProduct examplesCost
Read from the primary for N seconds after a writeAny async-replicated SQL or MongoDBMore primary load
Session token with minimum version/LSNGo kv.Session; PostgreSQL LSN, Aurora, DynamoDB ConsistentReadPlumbing per request
Sticky routing to one replicaLoad balancer affinityUneven load, breaks on failover
Write-through the client cacheMobile apps, SPAsClient holds derived state

Fix / how to use it: kv.Session in Go; in Laravel use the sticky option of the database connection or read from the write connection for a short window after a write.

Reconciliation Important ​

In plain words: A scheduled job that compares two systems and fixes the differences, because sooner or later they will disagree.

Common misunderstanding: "Reconciliation means my design is broken." It is the safety net of every serious distributed money flow: card networks, banks and marketplaces reconcile daily. The design is broken if there is no reconciliation.

Definition: A periodic, read-mostly process that computes the difference between two sources of truth (orders versus charges, ledger versus bank statement, source table versus search index) and emits idempotent repair actions or alerts.

text
     Scheduler        Orders service          Payments service         Repair queue
1    every 5 min -->  list confirmed orders
2                     ---------------------->  list charges older than 15 min
3    diff: o3 confirmed, no charge ; o9 charge, no order
4    enqueue cancel-order(o3), refund(o9) ---------------------------> idempotent jobs
5    metric drift_total{kind=...} exported; alert if it grows

Real scenario: Stripe or bank settlement files compared with your ledger; a search index rebuilt nightly and diffed against the database; inventory counts versus warehouse scans; webhooks missed during an outage.

What provides it:

ApproachWhenNotes
Periodic diff job (orders:reconcile, Go reconcile.Diff)Two stores you ownGrace period for in-flight sagas
Settlement file matchExternal payment providersDaily, authoritative
CDC and rebuild (Debezium, backfill)Derived storesRebuild is the recovery path
Merkle-tree comparisonReplicated storesSee Merkle Trees

Fix / how to use it: reconcile/reconcile.go and ReconcileOrders.php below. Always add a grace window so you do not fight a saga that is still running.

Hybrid architecture: ACID core, BASE edges Important ​

In plain words: Keep the money and the source of truth in a transactional database, and let everything derived from it be eventually consistent.

Common misunderstanding: "Pick one model for the whole system." Mature systems choose per data class, and the seam between them is the design: an outbox row written in the same ACID transaction as the change, a relay that publishes it, and idempotent consumers on the other side.

Definition: A transactional core owns invariants and writes events atomically with state (transactional outbox); edge services consume the events and maintain their own eventually consistent views (cart, search, analytics, caches). A reconciliation job watches the seam.

text
     Checkout service            PostgreSQL (core)          Relay            Broker        Search / Analytics
1    place order --------------> BEGIN
2                                INSERT orders, UPDATE stock
3                                INSERT outbox(order_placed)
4                                COMMIT   (state and event are atomic)
5                                                  poll/CDC ----> publish --> topic
6                                                                                consume (idempotent) -> index

Real scenario: An e-commerce order pipeline (orders in a transactional store, recommendations and search fed asynchronously); a bank (core ledger ACID, notifications and statements BASE); a ticketing system (seat inventory ACID, "tickets left" counter eventual).

What provides it:

PieceProductRole
CorePostgreSQL, MySQL, Spanner, CockroachDBSource of truth, constraints
SeamTransactional outbox, Debezium CDCAtomic state-plus-event
TransportKafka, RabbitMQ, SQSAt-least-once delivery
EdgeDynamoDB, Redis, Elasticsearch, ClickHouseFast, scalable, derived
Safety netReconciliation job, dead-letter queueRepair and visibility

Fix / how to use it: Start with the diagram; write the outbox in the same transaction as the state (Outbox Pattern); keep consumers idempotent and add the reconciliation job before launch.

ACID core (PostgreSQL)orders, ledger, stockoutbox row, same commitCHECK, UNIQUE, FK enforcedbrokerKafka / RabbitMQat-least-onceCart store (DynamoDB, Redis)Search index (Elasticsearch)Analytics warehouseRead caches, projectionsreconciliation job compares both sides, repairs driftBASE edges: idempotent consumers

What each product really does ​

ProductTransaction scopeDefault consistencyMulti-item/partition transactionsNotes
PostgreSQLOne node (primary)Read Committed, ACIDYes, locally; 2PC via PREPARE TRANSACTION for external managersStrong ACID; scale by replicas and partitioning
MySQL InnoDBOne nodeRepeatable Read, ACIDYes locally; XAGap/next-key locks; deadlock error 1213
SQL Server / OracleOne node (RAC for cluster)Read CommittedYes; distributed via DTCMature, expensive
SQLiteOne fileSerializable (one writer)Yes, one fileEmbedded
DynamoDBOne item; up to 100 items by transactionEventual reads; strong on requestTransactWriteItems / TransactGetItemsConditional writes; capacity doubled for transactions
MongoDBOne document; multi-document on demandPrimary reads; tunable concernsReplica sets and sharded clustersPrefer embedding; short transactions
CassandraOne partition row; LWT per partitionTunable (ONE to ALL)LOGGED batches (not isolated), LWT (Paxos)AP by design
RedisOne command; MULTI/EXECAsync replicationNo rollback; Lua scripts for atomic logicCache and fast structures
SpannerGlobalExternal consistency, serializableYes, 2PC over Paxos groupsTrueTime; pay latency
CockroachDBGlobal rangesSerializable (Read Committed available)Yes; retry error 40001PostgreSQL wire protocol
KafkaProducer and offset transactionPer-partition orderAtomic across partitions in one clusterNot a database transaction

Mechanics ​

Error codes and what to do ​

ProductErrorMeaningRetry?
PostgreSQLSQLSTATE 40001 serialization_failureCould not serialize concurrent updateYes, whole transaction
PostgreSQLSQLSTATE 40P01 deadlock_detectedDeadlock victimYes, whole transaction
PostgreSQLSQLSTATE 23514 check_violationInvariant refused the writeNo, business error
PostgreSQLSQLSTATE 23505 unique_violationDuplicate key (often idempotency)No, treat as already done
MySQL1213 ER_LOCK_DEADLOCKDeadlockYes
MySQL1205 ER_LOCK_WAIT_TIMEOUTLock wait timeoutMaybe, after review
CockroachDB40001 restart transactionCould not be placed in a serializable orderYes (client-side retry loop)
SpannerABORTEDTransaction conflictYes, same session keeps lock priority
DynamoDBTransactionCanceledExceptionAn item-level condition or conflict failedInspect CancellationReasons first
DynamoDBTransactionConflictExceptionA standard write collided with a transactionYes, with backoff
DynamoDBConditionalCheckFailedExceptionCondition falseNo, re-read and decide
CassandraLWT [applied] = falseCondition falseNo, re-read
MongoDBTransientTransactionError labelTransaction can be retried as a wholeYes (driver callback API does it)

Retry rules ​

  1. Retry the whole transaction, never the single statement that failed; the earlier reads are stale.
  2. Retry only errors the engine marks as safe (40001, 40P01, 1213, TransientTransactionError, ABORTED). Never retry a business error.
  3. Use exponential backoff with jitter and a fixed attempt budget (Go acid.WithRetry; Laravel attempts: argument).
  4. Keep transactions short; no HTTP calls or sleeps inside.
  5. Make the transaction idempotent, because a commit whose acknowledgement was lost is indistinguishable from a failure.

Availability and latency arithmetic ​

QuantityValueSource
Availability of a transaction over two 99.9% databases99.8%, about 43 more minutes of downtime per monthPritchett 2008
Same over n required components of availability aa to the power nProduct rule
Round trips in 2PC2 phases, at least 2 coordinator-participant exchanges eachProtocol
Locks held in 2PCFrom prepare until the commit decision arrivesProtocol
DynamoDB transaction limit100 actions, 4 MB, same account and RegionDynamoDB docs
DynamoDB capacityTransactional operations cost two reads or writes per itemDynamoDB docs

Go ​

The same order flow written twice: place an order that reserves stock, charges the customer and records the order. Package acid uses one transaction; package saga uses three services with their own stores, compensations and a journal.

Before: one transaction ​

go
// Package acid places an order inside ONE database transaction: stock,
// payment and the order row commit together or not at all.
package acid

import (
	"context"
	"errors"
	"time"
)

var (
	ErrOutOfStock        = errors.New("acid: out of stock")
	ErrInsufficientFunds = errors.New("acid: insufficient funds")
)

// Order is the unit of work the transaction protects.
type Order struct {
	ID      string
	SKU     string
	Qty     int
	Account string
	Cents   int64
}

// Tx is what code may do while a transaction is open.
type Tx interface {
	// ReserveStock fails with ErrOutOfStock instead of going below zero.
	ReserveStock(sku string, qty int) error
	// Debit fails with ErrInsufficientFunds instead of going below zero.
	Debit(account string, cents int64) error
	InsertOrder(o Order) error
}

// Store runs fn in a transaction: nil commits, an error rolls back.
type Store interface {
	InTx(ctx context.Context, fn func(Tx) error) error
}

// RetryableError marks a failure the database says is safe to retry
// (PostgreSQL 40001 serialization_failure, 40P01 deadlock_detected,
// MySQL 1213 deadlock).
type RetryableError struct{ Err error }

func (e *RetryableError) Error() string { return "acid: retryable: " + e.Err.Error() }
func (e *RetryableError) Unwrap() error { return e.Err }

// PlaceOrder is the whole business operation. Three writes, one commit.
func PlaceOrder(ctx context.Context, s Store, o Order) error {
	return s.InTx(ctx, func(tx Tx) error {
		if err := tx.ReserveStock(o.SKU, o.Qty); err != nil {
			return err
		}
		if err := tx.Debit(o.Account, o.Cents); err != nil {
			return err // rolls back the stock reservation too
		}
		return tx.InsertOrder(o)
	})
}

// WithRetry re-runs the WHOLE transaction when it fails with a
// RetryableError. Business errors are never retried.
func WithRetry(ctx context.Context, attempts int, base time.Duration, fn func(context.Context) error) error {
	var err error
	for i := 0; i < attempts; i++ {
		if err = fn(ctx); err == nil {
			return nil
		}
		var re *RetryableError
		if !errors.As(err, &re) {
			return err
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(base << i):
		}
	}
	return err
}

The in-memory store gives the tests snapshot-rollback semantics, and sqlstore.go is the production shape over database/sql:

go
package acid

import (
	"context"
	"database/sql"
	"errors"
)

// SQLStore is the production shape: database/sql with a real driver
// (pgx stdlib, lib/pq, go-sql-driver/mysql). Importing a driver is the
// caller's job, so this file compiles without one.
type SQLStore struct{ DB *sql.DB }

type sqlTx struct {
	ctx context.Context
	tx  *sql.Tx
}

func (t sqlTx) ReserveStock(sku string, qty int) error {
	// Atomic conditional update: no read-modify-write race, no negative stock.
	res, err := t.tx.ExecContext(t.ctx,
		`UPDATE stock SET qty = qty - $2 WHERE sku = $1 AND qty >= $2`, sku, qty)
	return oneRow(res, err, ErrOutOfStock)
}

func (t sqlTx) Debit(acct string, cents int64) error {
	res, err := t.tx.ExecContext(t.ctx,
		`UPDATE accounts SET balance_cents = balance_cents - $2 WHERE id = $1 AND balance_cents >= $2`, acct, cents)
	return oneRow(res, err, ErrInsufficientFunds)
}

func (t sqlTx) InsertOrder(o Order) error {
	_, err := t.tx.ExecContext(t.ctx,
		`INSERT INTO orders (id, sku, qty, account_id, cents) VALUES ($1,$2,$3,$4,$5)`,
		o.ID, o.SKU, o.Qty, o.Account, o.Cents)
	return err
}

func oneRow(res sql.Result, err error, onZero error) error {
	if err != nil {
		return classify(err)
	}
	n, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if n == 0 {
		return onZero
	}
	return nil
}

// sqlStater is implemented by pgconn.PgError (SQLState()) and similar.
type sqlStater interface{ SQLState() string }

// classify wraps retryable server errors so WithRetry can see them.
func classify(err error) error {
	var st sqlStater
	if errors.As(err, &st) {
		switch st.SQLState() {
		case "40001", "40P01":
			return &RetryableError{Err: err}
		}
	}
	return err
}

func (s SQLStore) InTx(ctx context.Context, fn func(Tx) error) error {
	tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
	if err != nil {
		return err
	}
	if err := fn(sqlTx{ctx, tx}); err != nil {
		_ = tx.Rollback()
		return err
	}
	if err := tx.Commit(); err != nil {
		return classify(err) // 40001 can surface at COMMIT under SERIALIZABLE
	}
	return nil
}
go
package acid

import (
	"context"
	"errors"
	"testing"
	"time"
)

func seeded() *MemStore {
	s := NewMemStore()
	s.Stock["sku-1"] = 5
	s.Balances["acct-1"] = 10_000
	return s
}

func TestCommitAppliesAllThreeWrites(t *testing.T) {
	s := seeded()
	o := Order{ID: "o1", SKU: "sku-1", Qty: 2, Account: "acct-1", Cents: 4_000}
	if err := PlaceOrder(context.Background(), s, o); err != nil {
		t.Fatal(err)
	}
	if s.Stock["sku-1"] != 3 || s.Balances["acct-1"] != 6_000 || len(s.Orders) != 1 {
		t.Fatalf("unexpected state: %+v %+v %+v", s.Stock, s.Balances, s.Orders)
	}
}

func TestAtomicityPaymentFailureUndoesStock(t *testing.T) {
	s := seeded()
	o := Order{ID: "o1", SKU: "sku-1", Qty: 2, Account: "acct-1", Cents: 99_999}
	err := PlaceOrder(context.Background(), s, o)
	if !errors.Is(err, ErrInsufficientFunds) {
		t.Fatalf("want ErrInsufficientFunds, got %v", err)
	}
	if s.Stock["sku-1"] != 5 || len(s.Orders) != 0 {
		t.Fatalf("rollback failed: stock=%d orders=%d", s.Stock["sku-1"], len(s.Orders))
	}
}

func TestAtomicityCommitFailureUndoesEverything(t *testing.T) {
	s := seeded()
	s.FailCommit = func() error { return errors.New("disk full") }
	o := Order{ID: "o1", SKU: "sku-1", Qty: 1, Account: "acct-1", Cents: 100}
	if err := PlaceOrder(context.Background(), s, o); err == nil {
		t.Fatal("expected error")
	}
	if s.Stock["sku-1"] != 5 || s.Balances["acct-1"] != 10_000 {
		t.Fatal("partial effects leaked")
	}
}

func TestInvariantStockNeverNegative(t *testing.T) {
	s := seeded()
	ctx := context.Background()
	var ok int
	for i := 0; i < 8; i++ {
		o := Order{ID: string(rune('a' + i)), SKU: "sku-1", Qty: 1, Account: "acct-1", Cents: 10}
		if PlaceOrder(ctx, s, o) == nil {
			ok++
		}
	}
	if ok != 5 || s.Stock["sku-1"] != 0 {
		t.Fatalf("ok=%d stock=%d", ok, s.Stock["sku-1"])
	}
}

func TestRetryOnSerializationFailure(t *testing.T) {
	calls := 0
	err := WithRetry(context.Background(), 5, time.Millisecond, func(context.Context) error {
		calls++
		if calls < 3 {
			return &RetryableError{Err: errors.New("40001")}
		}
		return nil
	})
	if err != nil || calls != 3 {
		t.Fatalf("err=%v calls=%d", err, calls)
	}
}

func TestRetryDoesNotRepeatBusinessErrors(t *testing.T) {
	calls := 0
	err := WithRetry(context.Background(), 5, time.Millisecond, func(context.Context) error {
		calls++
		return ErrOutOfStock
	})
	if !errors.Is(err, ErrOutOfStock) || calls != 1 {
		t.Fatalf("err=%v calls=%d", err, calls)
	}
}

func TestRetryGivesUp(t *testing.T) {
	calls := 0
	err := WithRetry(context.Background(), 3, time.Millisecond, func(context.Context) error {
		calls++
		return &RetryableError{Err: errors.New("40P01")}
	})
	var re *RetryableError
	if !errors.As(err, &re) || calls != 3 {
		t.Fatalf("err=%v calls=%d", err, calls)
	}
}

After: a saga across services ​

Each service owns its data and every operation is idempotent per order id:

go
package saga

import (
	"context"
	"errors"
	"sync"
)

// Each service owns its own data. There is no shared transaction between
// them; every operation is idempotent per order ID so it can be retried.

var (
	ErrOutOfStock = errors.New("inventory: out of stock")
	ErrDeclined   = errors.New("payments: card declined")
)

// Inventory is service A's private store.
type Inventory struct {
	mu    sync.Mutex
	Stock map[string]int
	holds map[string]hold
	Fault func(op string) error // test hook: inject failures
}

type hold struct {
	sku string
	qty int
}

func NewInventory(stock map[string]int) *Inventory {
	return &Inventory{Stock: stock, holds: map[string]hold{}}
}

func (s *Inventory) Reserve(_ context.Context, orderID, sku string, qty int) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.Fault != nil {
		if err := s.Fault("reserve"); err != nil {
			return err
		}
	}
	if _, done := s.holds[orderID]; done {
		return nil // duplicate delivery: same result, no second decrement
	}
	if s.Stock[sku] < qty {
		return ErrOutOfStock
	}
	s.Stock[sku] -= qty
	s.holds[orderID] = hold{sku, qty}
	return nil
}

// Release is the compensation for Reserve. Releasing something never
// reserved (or already released) is a no-op, never an error.
func (s *Inventory) Release(_ context.Context, orderID string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.Fault != nil {
		if err := s.Fault("release"); err != nil {
			return err
		}
	}
	h, ok := s.holds[orderID]
	if !ok {
		return nil
	}
	s.Stock[h.sku] += h.qty
	delete(s.holds, orderID)
	return nil
}

// Payments is service B's private store.
type Payments struct {
	mu       sync.Mutex
	Balances map[string]int64
	charges  map[string]charge
	Fault    func(op string) error
}

type charge struct {
	acct  string
	cents int64
}

func NewPayments(b map[string]int64) *Payments {
	return &Payments{Balances: b, charges: map[string]charge{}}
}

func (p *Payments) Charge(_ context.Context, orderID, acct string, cents int64) error {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.Fault != nil {
		if err := p.Fault("charge"); err != nil {
			return err
		}
	}
	if _, done := p.charges[orderID]; done {
		return nil
	}
	if p.Balances[acct] < cents {
		return ErrDeclined
	}
	p.Balances[acct] -= cents
	p.charges[orderID] = charge{acct, cents}
	return nil
}

func (p *Payments) Refund(_ context.Context, orderID string) error {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.Fault != nil {
		if err := p.Fault("refund"); err != nil {
			return err
		}
	}
	c, ok := p.charges[orderID]
	if !ok {
		return nil
	}
	p.Balances[c.acct] += c.cents
	delete(p.charges, orderID)
	return nil
}

// Charged reports whether a charge exists for the order (used by reconcile).
func (p *Payments) Charged(orderID string) bool {
	p.mu.Lock()
	defer p.mu.Unlock()
	_, ok := p.charges[orderID]
	return ok
}

// Shipping is service C's private store.
type Shipping struct {
	mu      sync.Mutex
	shipped map[string]bool
	Fault   func(op string) error
}

func NewShipping() *Shipping { return &Shipping{shipped: map[string]bool{}} }

func (s *Shipping) Create(_ context.Context, orderID string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.Fault != nil {
		if err := s.Fault("ship"); err != nil {
			return err
		}
	}
	s.shipped[orderID] = true
	return nil
}

func (s *Shipping) Cancel(_ context.Context, orderID string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.shipped, orderID)
	return nil
}

func (s *Shipping) Has(orderID string) bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.shipped[orderID]
}

The orchestrator journals progress, compensates in reverse, retries compensation and reports stuck when it cannot:

go
// Package saga runs the same order flow as package acid, but across three
// services with no shared transaction. Atomicity is replaced by forward
// steps plus compensations; isolation is gone (other readers can see the
// stock held while the payment is still pending).
package saga

import (
	"context"
	"errors"
	"fmt"
	"sync"
)

// Step is one local transaction and its semantic undo.
type Step struct {
	Name string
	Do   func(context.Context) error
	Undo func(context.Context) error // must be idempotent
}

type State string

const (
	StateDone        State = "done"
	StateCompensated State = "compensated"
)

type Outcome string

const (
	Completed   Outcome = "completed"
	Compensated Outcome = "compensated"
	Stuck       Outcome = "stuck" // compensation kept failing: page a human
)

// Journal persists progress so a crashed orchestrator can resume.
// In production this is a table written in the orchestrator's own DB.
type Journal interface {
	Record(orderID, step string, s State)
	Steps(orderID string) map[string]State
	SetOutcome(orderID string, o Outcome)
	Outcome(orderID string) (Outcome, bool)
}

type MemJournal struct {
	mu       sync.Mutex
	steps    map[string]map[string]State
	outcomes map[string]Outcome
}

func NewMemJournal() *MemJournal {
	return &MemJournal{steps: map[string]map[string]State{}, outcomes: map[string]Outcome{}}
}

func (j *MemJournal) Record(id, step string, s State) {
	j.mu.Lock()
	defer j.mu.Unlock()
	if j.steps[id] == nil {
		j.steps[id] = map[string]State{}
	}
	j.steps[id][step] = s
}

func (j *MemJournal) Steps(id string) map[string]State {
	j.mu.Lock()
	defer j.mu.Unlock()
	out := map[string]State{}
	for k, v := range j.steps[id] {
		out[k] = v
	}
	return out
}

func (j *MemJournal) SetOutcome(id string, o Outcome) {
	j.mu.Lock()
	defer j.mu.Unlock()
	j.outcomes[id] = o
}

func (j *MemJournal) Outcome(id string) (Outcome, bool) {
	j.mu.Lock()
	defer j.mu.Unlock()
	o, ok := j.outcomes[id]
	return o, ok
}

// Runner is a minimal orchestrator.
type Runner struct {
	J            Journal
	UndoAttempts int // retries per compensation before giving up
}

// Run executes steps in order. On the first failure it compensates every
// step that may have taken effect, in reverse order. Calling Run again
// for the same order resumes or returns the recorded outcome.
func (r *Runner) Run(ctx context.Context, orderID string, steps []Step) (Outcome, error) {
	if o, ok := r.J.Outcome(orderID); ok && o != Stuck {
		return o, nil
	}
	done := r.J.Steps(orderID)
	for i, st := range steps {
		if done[st.Name] == StateDone {
			continue
		}
		if err := st.Do(ctx); err != nil {
			// Include the failed step itself: Do may have applied partially
			// before the error (a timeout does not mean "did not happen").
			o := r.compensate(ctx, orderID, steps[:i+1])
			return o, fmt.Errorf("saga %s: step %s: %w", orderID, st.Name, err)
		}
		r.J.Record(orderID, st.Name, StateDone)
	}
	r.J.SetOutcome(orderID, Completed)
	return Completed, nil
}

func (r *Runner) compensate(ctx context.Context, orderID string, steps []Step) Outcome {
	for i := len(steps) - 1; i >= 0; i-- {
		st := steps[i]
		var err error
		for a := 0; a < max(r.UndoAttempts, 1); a++ {
			if err = st.Undo(ctx); err == nil {
				break
			}
		}
		if err != nil {
			r.J.SetOutcome(orderID, Stuck)
			return Stuck
		}
		r.J.Record(orderID, st.Name, StateCompensated)
	}
	r.J.SetOutcome(orderID, Compensated)
	return Compensated
}

// OrderRequest is the same business input as acid.Order.
type OrderRequest struct {
	ID      string
	SKU     string
	Qty     int
	Account string
	Cents   int64
}

// OrderSteps wires the three services into saga steps.
func OrderSteps(inv *Inventory, pay *Payments, ship *Shipping, o OrderRequest) []Step {
	return []Step{
		{"reserve-stock",
			func(c context.Context) error { return inv.Reserve(c, o.ID, o.SKU, o.Qty) },
			func(c context.Context) error { return inv.Release(c, o.ID) }},
		{"charge-payment",
			func(c context.Context) error { return pay.Charge(c, o.ID, o.Account, o.Cents) },
			func(c context.Context) error { return pay.Refund(c, o.ID) }},
		{"create-shipment",
			func(c context.Context) error { return ship.Create(c, o.ID) },
			func(c context.Context) error { return ship.Cancel(c, o.ID) }},
	}
}

// IsBusinessError tells a declined/out-of-stock apart from an outage.
func IsBusinessError(err error) bool {
	return errors.Is(err, ErrOutOfStock) || errors.Is(err, ErrDeclined)
}
go
package saga

import (
	"context"
	"errors"
	"testing"
)

func world() (*Inventory, *Payments, *Shipping, *Runner) {
	return NewInventory(map[string]int{"sku-1": 5}),
		NewPayments(map[string]int64{"acct-1": 10_000}),
		NewShipping(),
		&Runner{J: NewMemJournal(), UndoAttempts: 3}
}

var req = OrderRequest{ID: "o1", SKU: "sku-1", Qty: 2, Account: "acct-1", Cents: 4_000}

func TestHappyPath(t *testing.T) {
	inv, pay, ship, r := world()
	out, err := r.Run(context.Background(), req.ID, OrderSteps(inv, pay, ship, req))
	if err != nil || out != Completed {
		t.Fatalf("out=%s err=%v", out, err)
	}
	if inv.Stock["sku-1"] != 3 || pay.Balances["acct-1"] != 6_000 || !ship.Has("o1") {
		t.Fatal("unexpected end state")
	}
}

func TestPaymentDeclinedReleasesStock(t *testing.T) {
	inv, pay, ship, r := world()
	big := req
	big.Cents = 99_999
	out, err := r.Run(context.Background(), big.ID, OrderSteps(inv, pay, ship, big))
	if out != Compensated || !errors.Is(err, ErrDeclined) {
		t.Fatalf("out=%s err=%v", out, err)
	}
	if inv.Stock["sku-1"] != 5 || pay.Balances["acct-1"] != 10_000 || ship.Has("o1") {
		t.Fatal("compensation did not restore state")
	}
}

func TestIntermediateStateIsVisible(t *testing.T) {
	// No isolation: while the charge is in flight, stock is already gone.
	inv, pay, ship, r := world()
	var seen int
	pay.Fault = func(op string) error {
		seen = inv.Stock["sku-1"] // another reader looks mid-saga
		return nil
	}
	if _, err := r.Run(context.Background(), req.ID, OrderSteps(inv, pay, ship, req)); err != nil {
		t.Fatal(err)
	}
	if seen != 3 {
		t.Fatalf("expected the reservation to be visible mid-saga, saw %d", seen)
	}
}

func TestCompensationIsRetried(t *testing.T) {
	inv, pay, ship, r := world()
	ship.Fault = func(string) error { return errors.New("shipping down") }
	fails := 2
	pay.Fault = func(op string) error {
		if op == "refund" && fails > 0 {
			fails--
			return errors.New("payments timeout")
		}
		return nil
	}
	out, _ := r.Run(context.Background(), req.ID, OrderSteps(inv, pay, ship, req))
	if out != Compensated {
		t.Fatalf("out=%s", out)
	}
	if pay.Balances["acct-1"] != 10_000 || inv.Stock["sku-1"] != 5 {
		t.Fatal("not fully compensated")
	}
}

func TestStuckWhenCompensationNeverSucceeds(t *testing.T) {
	inv, pay, ship, r := world()
	ship.Fault = func(string) error { return errors.New("shipping down") }
	pay.Fault = func(op string) error {
		if op == "refund" {
			return errors.New("payments down")
		}
		return nil
	}
	out, _ := r.Run(context.Background(), req.ID, OrderSteps(inv, pay, ship, req))
	if out != Stuck {
		t.Fatalf("out=%s", out)
	}
}

func TestDuplicateDeliveryDoesNotDoubleCharge(t *testing.T) {
	inv, pay, _, _ := world()
	ctx := context.Background()
	for i := 0; i < 3; i++ {
		if err := pay.Charge(ctx, "o1", "acct-1", 4_000); err != nil {
			t.Fatal(err)
		}
		if err := inv.Reserve(ctx, "o1", "sku-1", 2); err != nil {
			t.Fatal(err)
		}
	}
	if pay.Balances["acct-1"] != 6_000 || inv.Stock["sku-1"] != 3 {
		t.Fatal("duplicates were applied twice")
	}
}

func TestReRunReturnsRecordedOutcome(t *testing.T) {
	inv, pay, ship, r := world()
	steps := OrderSteps(inv, pay, ship, req)
	if _, err := r.Run(context.Background(), req.ID, steps); err != nil {
		t.Fatal(err)
	}
	out, err := r.Run(context.Background(), req.ID, steps)
	if err != nil || out != Completed || pay.Balances["acct-1"] != 6_000 {
		t.Fatalf("out=%s err=%v", out, err)
	}
}

func TestResumeSkipsDoneSteps(t *testing.T) {
	inv, pay, ship, r := world()
	r.J.Record(req.ID, "reserve-stock", StateDone) // crash happened after step 1
	_ = inv.Reserve(context.Background(), req.ID, req.SKU, req.Qty)
	if _, err := r.Run(context.Background(), req.ID, OrderSteps(inv, pay, ship, req)); err != nil {
		t.Fatal(err)
	}
	if inv.Stock["sku-1"] != 3 {
		t.Fatalf("stock=%d, step 1 ran twice", inv.Stock["sku-1"])
	}
}

BASE building blocks ​

Conditional write, replica lag and a session that restores read-your-writes:

go
// Package kv models what BASE stores really give you: atomicity per key,
// a conditional write (compare-and-set), lagging replicas, and a session
// token that restores read-your-writes.
package kv

import (
	"errors"
	"sync"
)

var ErrConflict = errors.New("kv: version conflict")

type Item struct {
	Value   string
	Version int64
}

// Primary accepts writes. Each key is atomic; there is NO multi-key transaction.
type Primary struct {
	mu   sync.Mutex
	data map[string]Item
	log  []entry // replication log
}

type entry struct {
	key  string
	item Item
}

func NewPrimary() *Primary { return &Primary{data: map[string]Item{}} }

func (p *Primary) Get(key string) Item {
	p.mu.Lock()
	defer p.mu.Unlock()
	return p.data[key]
}

// Put is last-writer-wins: unconditional, silently overwrites (lost update).
func (p *Primary) Put(key, value string) Item {
	p.mu.Lock()
	defer p.mu.Unlock()
	it := Item{Value: value, Version: p.data[key].Version + 1}
	p.data[key] = it
	p.log = append(p.log, entry{key, it})
	return it
}

// CompareAndSwap is the conditional write (DynamoDB ConditionExpression,
// Cassandra IF, MongoDB filter on a version field): it applies only if the
// stored version still equals expect.
func (p *Primary) CompareAndSwap(key, value string, expect int64) (Item, error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.data[key].Version != expect {
		return Item{}, ErrConflict
	}
	it := Item{Value: value, Version: expect + 1}
	p.data[key] = it
	p.log = append(p.log, entry{key, it})
	return it, nil
}

// Replica applies the primary's log with lag (eventual consistency).
type Replica struct {
	mu      sync.Mutex
	data    map[string]Item
	applied int
	src     *Primary
}

func NewReplica(src *Primary) *Replica { return &Replica{data: map[string]Item{}, src: src} }

// Sync applies up to n pending log entries (simulates replication lag).
func (r *Replica) Sync(n int) {
	r.src.mu.Lock()
	pending := append([]entry(nil), r.src.log[r.applied:]...)
	r.src.mu.Unlock()
	if n < len(pending) {
		pending = pending[:n]
	}
	r.mu.Lock()
	defer r.mu.Unlock()
	for _, e := range pending {
		r.data[e.key] = e.item
		r.applied++
	}
}

func (r *Replica) Get(key string) Item {
	r.mu.Lock()
	defer r.mu.Unlock()
	return r.data[key]
}

// Session gives read-your-writes on top of lagging replicas: it remembers
// the highest version it wrote per key and refuses to read anything older.
type Session struct {
	P       *Primary
	R       *Replica
	written map[string]int64
}

func NewSession(p *Primary, r *Replica) *Session {
	return &Session{P: p, R: r, written: map[string]int64{}}
}

func (s *Session) Put(key, value string) {
	it := s.P.Put(key, value)
	s.written[key] = it.Version
}

func (s *Session) Get(key string) Item {
	if it := s.R.Get(key); it.Version >= s.written[key] {
		return it
	}
	return s.P.Get(key) // replica is behind this session's own write
}

// Incr adds delta using CAS in a retry loop (no lost updates).
func Incr(p *Primary, key string, delta int, parse func(string) int, format func(int) string) {
	for {
		cur := p.Get(key)
		if _, err := p.CompareAndSwap(key, format(parse(cur.Value)+delta), cur.Version); err == nil {
			return
		}
	}
}
go
package kv

import (
	"strconv"
	"sync"
	"testing"
)

func atoi(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}

func TestReplicaIsStaleUntilSynced(t *testing.T) {
	p := NewPrimary()
	r := NewReplica(p)
	p.Put("cart:1", "[apple]")
	if got := r.Get("cart:1").Version; got != 0 {
		t.Fatalf("replica should lag, version=%d", got)
	}
	r.Sync(10)
	if got := r.Get("cart:1").Value; got != "[apple]" {
		t.Fatalf("converged value = %q", got)
	}
}

func TestSessionReadsItsOwnWrites(t *testing.T) {
	p := NewPrimary()
	r := NewReplica(p)
	s := NewSession(p, r)
	s.Put("cart:1", "[apple]")
	if got := s.Get("cart:1").Value; got != "[apple]" {
		t.Fatalf("read-your-writes violated: %q", got)
	}
	other := NewSession(p, r)
	if got := other.Get("cart:1").Value; got != "" {
		t.Fatalf("another session may still see stale data, got %q", got)
	}
}

func TestLastWriterWinsLosesAnUpdate(t *testing.T) {
	p := NewPrimary()
	p.Put("n", "0")
	a, b := p.Get("n"), p.Get("n") // both read 0
	p.Put("n", strconv.Itoa(atoi(a.Value)+1))
	p.Put("n", strconv.Itoa(atoi(b.Value)+1))
	if p.Get("n").Value != "1" {
		t.Fatal("expected the lost update (1, not 2)")
	}
}

func TestCompareAndSwapRejectsStaleVersion(t *testing.T) {
	p := NewPrimary()
	it := p.Put("k", "a")
	if _, err := p.CompareAndSwap("k", "b", it.Version); err != nil {
		t.Fatal(err)
	}
	if _, err := p.CompareAndSwap("k", "c", it.Version); err != ErrConflict {
		t.Fatalf("want ErrConflict, got %v", err)
	}
}

func TestConcurrentIncrementWithCASIsExact(t *testing.T) {
	p := NewPrimary()
	p.Put("n", "0")
	var wg sync.WaitGroup
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			Incr(p, "n", 1, atoi, strconv.Itoa)
		}()
	}
	wg.Wait()
	if p.Get("n").Value != "50" {
		t.Fatalf("n=%s", p.Get("n").Value)
	}
}

The safety net:

go
// Package reconcile is the safety net of a BASE design: a periodic job that
// compares two services' views and emits the repairs that converge them.
package reconcile

import "sort"

type OrderStatus string

const (
	OrderConfirmed OrderStatus = "confirmed"
	OrderCancelled OrderStatus = "cancelled"
)

type Action struct {
	OrderID string
	Fix     string // "refund" | "cancel-order" | "mark-confirmed"
}

// Diff compares orders (service A) with charges (service B).
//   - charged but cancelled or unknown order -> refund (money taken, no goods)
//   - confirmed order without a charge       -> cancel-order (goods without money)
//
// It only reads; applying the Action list is a separate, idempotent step.
func Diff(orders map[string]OrderStatus, charged map[string]bool) []Action {
	var out []Action
	for id, ok := range charged {
		if !ok {
			continue
		}
		if st, known := orders[id]; !known || st == OrderCancelled {
			out = append(out, Action{id, "refund"})
		}
	}
	for id, st := range orders {
		if st == OrderConfirmed && !charged[id] {
			out = append(out, Action{id, "cancel-order"})
		}
	}
	sort.Slice(out, func(i, j int) bool {
		if out[i].OrderID != out[j].OrderID {
			return out[i].OrderID < out[j].OrderID
		}
		return out[i].Fix < out[j].Fix
	})
	return out
}

The Go angle ​

  • database/sql exposes transactions as db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}). The returned *sql.Tx is bound to one connection; a context cancelled before Commit rolls the transaction back. Every statement must use tx, not db, or it runs outside the transaction.
  • Go has no ambient transaction. Passing a Tx interface into the business function (as acid.Store.InTx does) keeps the transaction boundary visible and the function testable without a database.
  • Retry loops are your job: classify the driver error by SQLSTATE (pgconn.PgError.SQLState() for pgx) and re-run the whole closure, as acid.WithRetry does.
  • Across services there is no transaction type at all; the saga code is plain functions plus a journal. Dedicated engines (Temporal's Go SDK) persist this state for you.

Laravel ​

Before: one transaction ​

php
<?php

namespace App\Orders;

use Illuminate\Support\Facades\DB;
use RuntimeException;

/**
 * ACID version: one database, one transaction, one commit.
 * DB::transaction retries the whole closure when the database reports a
 * deadlock (attempts: 5). Business failures throw and roll everything back.
 */
final class PlaceOrderAcid
{
    public function handle(string $orderId, string $sku, int $qty, string $account, int $cents): void
    {
        DB::transaction(function () use ($orderId, $sku, $qty, $account, $cents) {
            // Atomic conditional updates: no read-modify-write race.
            $stock = DB::table('stock')
                ->where('sku', $sku)->where('qty', '>=', $qty)
                ->decrement('qty', $qty);
            if ($stock === 0) {
                throw new RuntimeException('out of stock');
            }

            $paid = DB::table('accounts')
                ->where('id', $account)->where('balance_cents', '>=', $cents)
                ->decrement('balance_cents', $cents);
            if ($paid === 0) {
                throw new RuntimeException('insufficient funds'); // rolls back the stock too
            }

            DB::table('orders')->insert([
                'id' => $orderId, 'sku' => $sku, 'qty' => $qty,
                'account_id' => $account, 'cents' => $cents,
            ]);
        }, attempts: 5);
    }
}

After: queued steps and compensation ​

php
<?php

namespace App\Orders\Saga;

use Illuminate\Support\Facades\Bus;
use Throwable;

/**
 * BASE version: the same business flow as PlaceOrderAcid, as a chain of
 * queued local transactions. If any job exhausts its tries the catch
 * callback queues the compensation. No $this inside the callback: it is
 * serialized and run later by a worker.
 */
final class StartOrderSaga
{
    public function __invoke(string $orderId, string $sku, int $qty, string $account, int $cents): void
    {
        Bus::chain([
            new ReserveStockJob($orderId, $sku, $qty),
            new ChargePaymentJob($orderId, $account, $cents),
            new ConfirmOrderJob($orderId, $sku, $qty, $account, $cents),
        ])->catch(function (Throwable $e) use ($orderId) {
            CompensateOrderJob::dispatch($orderId);
        })->dispatch();
    }
}
php
<?php

namespace App\Orders\Saga;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\DB;
use RuntimeException;

/** Step 1 of the saga. Idempotent per order id: a redelivery changes nothing. */
#[Tries(5)]
#[Backoff([5, 15, 60])]
final class ReserveStockJob implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public string $orderId,
        public string $sku,
        public int $qty,
    ) {
    }

    public function handle(): void
    {
        DB::transaction(function () {
            // Dedupe row and effect commit together (a local ACID transaction).
            $first = DB::table('stock_holds')->insertOrIgnore([
                'order_id' => $this->orderId, 'sku' => $this->sku, 'qty' => $this->qty,
            ]);
            if ($first === 0) {
                return; // already reserved for this order
            }
            $ok = DB::table('stock')
                ->where('sku', $this->sku)->where('qty', '>=', $this->qty)
                ->decrement('qty', $this->qty);
            if ($ok === 0) {
                throw new RuntimeException('out of stock'); // rolls back the hold row
            }
        });
    }
}
php
<?php

namespace App\Orders\Saga;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\DB;
use RuntimeException;

/** Step 2 of the saga. The unique charges.order_id makes it idempotent. */
#[Tries(3)]
#[Backoff([5, 30])]
final class ChargePaymentJob implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public string $orderId,
        public string $account,
        public int $cents,
    ) {
    }

    public function handle(): void
    {
        DB::transaction(function () {
            $first = DB::table('charges')->insertOrIgnore([
                'order_id' => $this->orderId, 'account_id' => $this->account, 'cents' => $this->cents,
            ]);
            if ($first === 0) {
                return;
            }
            $ok = DB::table('accounts')
                ->where('id', $this->account)->where('balance_cents', '>=', $this->cents)
                ->decrement('balance_cents', $this->cents);
            if ($ok === 0) {
                throw new RuntimeException('card declined');
            }
        });
    }
}
php
<?php

namespace App\Orders\Saga;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;

/** Last step: record the order as confirmed (idempotent upsert). */
final class ConfirmOrderJob implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public string $orderId,
        public string $sku,
        public int $qty,
        public string $account,
        public int $cents,
    ) {
    }

    public function handle(): void
    {
        DB::table('orders')->updateOrInsert(
            ['id' => $this->orderId],
            ['sku' => $this->sku, 'qty' => $this->qty, 'account_id' => $this->account,
             'cents' => $this->cents, 'status' => 'confirmed'],
        );
    }
}
php
<?php

namespace App\Orders\Saga;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\DB;

/**
 * Queued compensation: undo whatever of steps 1-2 took effect.
 * Safe to run any number of times; releasing nothing is a no-op.
 * Many tries and a long backoff: compensation must eventually succeed.
 */
#[Tries(20)]
#[Backoff([10, 30, 60, 300])]
final class CompensateOrderJob implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $orderId)
    {
    }

    public function handle(): void
    {
        DB::transaction(function () {
            $hold = DB::table('stock_holds')->where('order_id', $this->orderId)->lockForUpdate()->first();
            if ($hold) {
                DB::table('stock')->where('sku', $hold->sku)->increment('qty', $hold->qty);
                DB::table('stock_holds')->where('order_id', $this->orderId)->delete();
            }

            $charge = DB::table('charges')->where('order_id', $this->orderId)->lockForUpdate()->first();
            if ($charge) {
                DB::table('accounts')->where('id', $charge->account_id)->increment('balance_cents', $charge->cents);
                DB::table('charges')->where('order_id', $this->orderId)->delete();
            }

            DB::table('orders')->where('id', $this->orderId)->update(['status' => 'cancelled']);
        });
    }
}
php
<?php

namespace App\Console\Commands;

use App\Orders\Saga\CompensateOrderJob;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * Reconciliation job (schedule it every few minutes). Finds charges whose
 * order is missing or cancelled, and confirmed orders without a charge,
 * and queues the idempotent compensation for them.
 */
final class ReconcileOrders extends Command
{
    protected $signature = 'orders:reconcile';

    protected $description = 'Repair orders and charges that disagree';

    public function handle(): int
    {
        $stray = DB::table('charges')
            ->leftJoin('orders', 'orders.id', '=', 'charges.order_id')
            ->where('charges.created_at', '<', now()->subMinutes(15)) // give live sagas time
            ->where(fn ($q) => $q->whereNull('orders.id')->orWhere('orders.status', 'cancelled'))
            ->pluck('charges.order_id');

        $unpaid = DB::table('orders')
            ->leftJoin('charges', 'charges.order_id', '=', 'orders.id')
            ->where('orders.status', 'confirmed')
            ->whereNull('charges.order_id')
            ->pluck('orders.id');

        foreach ($stray->merge($unpaid)->unique() as $orderId) {
            CompensateOrderJob::dispatch($orderId);
        }

        $this->info($stray->count().' stray charges, '.$unpaid->count().' unpaid orders');

        return self::SUCCESS;
    }
}

The Laravel angle ​

  • DB::transaction(Closure, attempts: 5): the Laravel database documentation says the method "accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs"; after the attempts are used up, an exception is thrown. The closure may therefore run more than once, so keep side effects out of it.
  • Dispatch jobs after the transaction commits: ProcessPodcast::dispatch($podcast)->afterCommit() waits "until all open database transactions have been committed" (queues documentation); otherwise a worker may pick up the job before the row exists.
  • Bus::chain([...])->catch(function (Throwable $e) {...})->dispatch() runs jobs in sequence and calls the callback when one fails; chain callbacks are serialized, so do not use $this inside them.
  • Per-job attributes in Laravel 13: #[Tries(5)] and #[Backoff([10, 30, 60])] (namespace Illuminate\Queue\Attributes). Compensation jobs get many tries and long backoff; forward steps get few.
  • Laravel's failed() job method and failed_jobs table are the hook for the "stuck" state: alert on them rather than losing the saga silently.
  • Idempotency in Laravel is yours: insertOrIgnore on a unique key (as in the jobs above), ShouldBeUnique, or the WithoutOverlapping job middleware for per-order serialization.

Solving the classic problems ​

Selling the last item twice ​

SolutionHowAdvantageCost or limit
Conditional updateUPDATE stock SET qty = qty - 1 WHERE sku = ? AND qty >= 1Atomic, no lock held across a round tripOne row only
SELECT ... FOR UPDATELock the row, then decideAllows complex logicHolds lock, deadlock risk
DynamoDB conditionConditionExpression: qty >= :nWorks at any scalePer item only
Reservation with TTLHold the unit for 10 minutesFits carts and ticketsNeeds expiry job

Charge succeeded, order not recorded ​

SolutionHowAdvantageCost or limit
One transactionSame database for charge record and orderImpossible by constructionNeeds one store
Saga with journalRecord intent first, then steps, compensate on failureWorks across servicesVisible intermediate states
ReconciliationDaily diff against providerCatches everything elseLatency to repair

Duplicate message applied twice ​

SolutionHowAdvantageCost or limit
Dedupe tableINSERT ... ON CONFLICT DO NOTHING with the effectExactly-once effectTable growth, TTL
Natural idempotencyUpsert by keyNo extra tableNot for increments
Broker dedupeKafka idempotent producer, SQS FIFO dedupe idFewer duplicatesOnly inside the broker window

Saved but not visible ​

SolutionHowAdvantageCost or limit
Session version tokenReject replicas older than your last writeCheap, preciseNeeds versions
Primary-for-a-whileRoute reads of this user to the primary for N secondsSimplePrimary load
Optimistic UIShow the local state until confirmedInstantNeeds rollback UX

Compensation fails ​

SolutionHowAdvantageCost or limit
Retry with backoff, many attempts#[Tries(20)], UndoAttemptsHandles transient outagesDelays recovery
Journal state stuck and alertHuman work queueNo silent lossNeeds on-call
Semantic lockMark the order "pending" so users cannot actLimits damageUX state
sql
-- Idempotent debit with an invariant, in one transaction (PostgreSQL)
BEGIN;
INSERT INTO processed_messages (consumer, message_id) VALUES ('billing', 'm-123') ON CONFLICT DO NOTHING;
-- if 0 rows inserted: duplicate, stop here
UPDATE accounts SET balance_cents = balance_cents - 2500 WHERE id = 'A' AND balance_cents >= 2500;
COMMIT;

SQL used by the examples (schema, transfer and idempotent consume, and NoSQL conditional forms):

sql
-- ACID core: one database, invariants enforced by the engine.
CREATE TABLE stock (
  sku text PRIMARY KEY,
  qty integer NOT NULL CHECK (qty >= 0)
);
CREATE TABLE accounts (
  id text PRIMARY KEY,
  balance_cents bigint NOT NULL CHECK (balance_cents >= 0)
);
CREATE TABLE orders (
  id text PRIMARY KEY,
  sku text NOT NULL REFERENCES stock (sku),
  qty integer NOT NULL CHECK (qty > 0),
  account_id text NOT NULL REFERENCES accounts (id),
  cents bigint NOT NULL CHECK (cents > 0),
  status text NOT NULL DEFAULT 'confirmed'
);

-- Append-only ledger: every balance change is a row; the sum of a transfer is zero.
CREATE TABLE ledger_entries (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  transfer_id text NOT NULL,
  account_id text NOT NULL,
  amount_cents bigint NOT NULL,
  UNIQUE (transfer_id, account_id)      -- idempotency: replaying a transfer cannot double-post
);

-- BASE edge: dedupe table so a redelivered message is applied once.
CREATE TABLE processed_messages (
  consumer text NOT NULL,
  message_id text NOT NULL,
  processed_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (consumer, message_id)
);

-- Saga support tables (per-service, idempotency by order id).
CREATE TABLE stock_holds (
  order_id text PRIMARY KEY,
  sku text NOT NULL,
  qty integer NOT NULL
);
CREATE TABLE charges (
  order_id text PRIMARY KEY,              -- one charge per order, ever
  account_id text NOT NULL,
  cents bigint NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
sql
-- One transaction, two rows, one invariant. SERIALIZABLE + retry on 40001/40P01.
BEGIN ISOLATION LEVEL SERIALIZABLE;
UPDATE accounts SET balance_cents = balance_cents - 2500 WHERE id = 'A' AND balance_cents >= 2500;
-- 0 rows updated => insufficient funds => ROLLBACK, do not continue
UPDATE accounts SET balance_cents = balance_cents + 2500 WHERE id = 'B';
INSERT INTO ledger_entries (transfer_id, account_id, amount_cents) VALUES ('t-77', 'A', -2500), ('t-77', 'B', 2500);
COMMIT;

-- Idempotent consume (BASE edge): apply the effect only the first time.
-- Run inside the same transaction as the effect.
INSERT INTO processed_messages (consumer, message_id) VALUES ('billing', 'm-123')
ON CONFLICT DO NOTHING;
-- affected rows = 0 => duplicate delivery => skip the effect, still ack the message.
txt
# DynamoDB conditional write (per-item atomic compare-and-set), AWS CLI shape:
aws dynamodb put-item --table-name carts \
  --item '{"pk":{"S":"cart#1"},"version":{"N":"4"},"items":{"S":"[apple,pear]"}}' \
  --condition-expression "attribute_not_exists(pk) OR version = :v" \
  --expression-attribute-values '{":v":{"N":"3"}}'
# fails with ConditionalCheckFailedException when someone else wrote version 4 first

# DynamoDB multi-item ACID transaction: all actions succeed or none; ClientRequestToken makes it idempotent.
aws dynamodb transact-write-items --client-request-token order-o1 --transact-items file://items.json

-- Cassandra lightweight transaction (Paxos): conditional, linearizable per partition.
INSERT INTO usernames (name, user_id) VALUES ('ada', 42) IF NOT EXISTS;
UPDATE carts SET items = 'x', version = 4 WHERE cart_id = 1 IF version = 3;
-- A LOGGED batch is atomic (eventually all or none) but NOT isolated across partitions.
BEGIN BATCH
  INSERT INTO orders_by_id (order_id, user_id) VALUES (1, 7);
  INSERT INTO orders_by_user (user_id, order_id) VALUES (7, 1);
APPLY BATCH;

Choosing ​

Per data class ​

Data classContractProductExtra techniqueReason
Ledger, payments, walletsACID, serializable or FOR UPDATEPostgreSQL, MySQL, Spanner, CockroachDBAppend-only entries, CHECK, idempotency keys, reconciliationOne anomaly costs more than any latency
Orders and inventoryACID inside one servicePostgreSQLConditional update, outboxInvariants across rows
Shopping cartBASE, per-key atomicDynamoDB, RedisVersion column, merge on conflict, TTLAvailability beats a stale item
Sessions, tokensBASE with TTLRedis, DynamoDBExpiry, sticky readsRebuildable, high read rate
Product catalogue and searchBASE, derivedElasticsearch, cacheCDC rebuildSource of truth elsewhere
Likes, view countersBASE, approximateRedis, Cassandra countersSharded counters, batch flushExactness unneeded
Analytics and eventsBASE, append-onlyKafka, ClickHouse, S3Late data handlingThroughput over freshness
User profileACID per record, replicated readsPostgreSQL with replicasRead-your-writes tokenRare conflicts
Cross-service business processSagaOrchestrator, TemporalCompensations, journalNo shared transaction exists

Which scale-out path ​

SituationChooseWhy
One primary is enough (most systems)Single-database ACIDSimplest correct design
Writes exceed one node and invariants span keysDistributed SQL (Spanner, CockroachDB)Keeps transactions, pays latency
Writes exceed one node and invariants fit one keyDynamoDB, Cassandra, sharded store with conditional writesCheap, scalable
Process spans teams or third partiesSaga plus reconciliationNo common transaction manager
Need global low-latency writes, conflicts acceptableMulti-leader or CRDTsSee Replication Topologies

Anti-patterns ​

Anti-patternWhy it hurtsInstead
BASE for money (eventually consistent balance, last-write-wins on a ledger)Lost updates and double spendsACID core, append-only ledger
ACID for everything at scale (one global 2PC across services)Availability multiplies down, locks held across the networkLocal transactions plus saga
Saga without idempotencyRetries double-apply stepsIdempotent steps and compensations
Saga without reconciliationStuck states stay unnoticedScheduled diff and alerts
Dual write (DB then broker, no outbox)Crash between them loses the eventTransactional outbox
Retrying single statementsStale reads inside the transactionRetry the whole transaction
Treating a cache as source of truthEviction means data lossCache is derived

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One PostgreSQL primary and DB::transaction or db.BeginTx give you everything ACID. Orders, stock, payment records and users live in one schema with constraints. A single node does thousands of write transactions per second; most products never leave this stage. Example: a Laravel shop where PlaceOrderAcid is the whole checkout. The only BASE-like thing is the browser cache.

Modular monolith: boundaries without the network ​

Modules own their tables but share one database, so a use case that crosses modules still runs in one transaction. Rule: a module writes only its own tables and calls others through interfaces, so the shared transaction can be split later. Prepare the seam now: write domain events to an outbox table inside the same transaction, and consume them in-process. See Modular Monolith.

Microservices: no shared transaction ​

Each service owns its database, so cross-service rules become sagas. Example flow:

text
     Client    Order svc            Inventory svc        Payment svc          Shipping svc
1    POST /orders (Idempotency-Key k1)
2             INSERT order(pending) + outbox       (ACID, local)
3             -> OrderPlaced ----> reserve (dedupe by order id)
4                               -> StockReserved --> charge (dedupe by order id)
5                                                  -> PaymentFailed --> Order svc: cancel
6                               <- ReleaseStock (compensation, idempotent)
7    GET /orders/o1 -> status "pending" ... then "cancelled"  (eventual; show it honestly)

Costs: users see pending, every step needs an idempotency key, and you need a reconciliation job. See Service Communication and Saga Pattern.

Distributed data: replicas, caches, regions ​

Replicas make reads cheap and stale: use read-your-writes tokens for the writer and accept lag for everyone else (Replication, Read Replicas & Failover). A cache in front of the database adds a second source of staleness (Caching). Multi-region: distributed ACID (Spanner, CockroachDB) pays a cross-region round trip per commit, while per-region writes with asynchronous replication (DynamoDB global tables, Cassandra multi-DC) keep latency local and need a conflict rule. Under a partition the choice is explicit: refuse writes (CP) or accept divergence (AP); see CAP and PACELC.

Scaling path: 1x, 10x, 100x ​

ScaleDesignContract changes
1x: one primarySingle-database ACIDNone; add constraints and indexes
10x: read-heavyRead replicas, cacheRead-your-writes handling; replica lag becomes a feature to design for
100x: write-heavyShard by key, or distributed SQLCross-shard invariants become sagas or distributed transactions
Multi-regionRegional primaries plus global replicationPick CP or AP per data class; reconciliation everywhere

Lab: ACID rollback versus saga compensation ​

The Go experiments run on the host (the tests below were run). The SQL and NoSQL experiments are expected output, not run.

Experiment 1: atomicity and invariant in one transaction (run).

text
$ cd docs/snippets/system-design/acid-vs-base/go && go test -v ./acid
--- PASS: TestCommitAppliesAllThreeWrites
--- PASS: TestAtomicityPaymentFailureUndoesStock
--- PASS: TestAtomicityCommitFailureUndoesEverything
--- PASS: TestInvariantStockNeverNegative
--- PASS: TestRetryOnSerializationFailure
--- PASS: TestRetryDoesNotRepeatBusinessErrors
--- PASS: TestRetryGivesUp

Experiment 2: the saga, including the intermediate state and a stuck compensation (run).

text
$ go test -v ./saga
--- PASS: TestHappyPath
--- PASS: TestPaymentDeclinedReleasesStock
--- PASS: TestIntermediateStateIsVisible        <- other readers see the stock held mid-saga
--- PASS: TestCompensationIsRetried
--- PASS: TestStuckWhenCompensationNeverSucceeds
--- PASS: TestDuplicateDeliveryDoesNotDoubleCharge
--- PASS: TestReRunReturnsRecordedOutcome
--- PASS: TestResumeSkipsDoneSteps

Experiment 3: lost update versus compare-and-swap, replica lag, session token (run).

text
$ go test -v ./kv ./reconcile
--- PASS: TestReplicaIsStaleUntilSynced
--- PASS: TestSessionReadsItsOwnWrites
--- PASS: TestLastWriterWinsLosesAnUpdate         <- final value 1, not 2
--- PASS: TestCompareAndSwapRejectsStaleVersion
--- PASS: TestConcurrentIncrementWithCASIsExact   <- 50 goroutines, exactly 50
--- PASS: TestDiffFindsBothDirections
--- PASS: TestDiffIsEmptyWhenConsistent

Experiment 4: double spend with and without the condition (SQL, two sessions; expected, not run).

text
     Session 1                                       Session 2
1    BEGIN;                                          BEGIN;
2    UPDATE accounts SET balance_cents = balance_cents - 8000 WHERE id='A' AND balance_cents >= 8000;  -- 1 row (balance was 10000)
3                                                    UPDATE accounts SET balance_cents = balance_cents - 8000 WHERE id='A' AND balance_cents >= 8000;  -- waits for session 1
4    COMMIT;
5                                                    -- re-evaluates the WHERE on the new row: 0 rows updated -> insufficient funds
6                                                    ROLLBACK;

Experiment 5: DynamoDB conditional write and idempotent transaction (expected, not run).

text
$ aws dynamodb put-item ... --condition-expression "version = :v" ... :v=3     -> ok
$ aws dynamodb put-item ... --condition-expression "version = :v" ... :v=3     -> ConditionalCheckFailedException
$ aws dynamodb transact-write-items --client-request-token order-o1 ...         -> ok
$ aws dynamodb transact-write-items --client-request-token order-o1 ...         -> ok (same result, applied once)

Experiment 6: kill the orchestrator mid-saga (Laravel, expected, not run). Start php artisan queue:work, dispatch StartOrderSaga, stop the worker after ReserveStockJob, restart it: the chain continues; run php artisan orders:reconcile and check stock_holds and charges agree with orders.

Common misconceptions ​

BeliefReality
NoSQL has no transactionsDynamoDB, MongoDB, Cassandra (limited), Spanner and CockroachDB all do; scope and cost differ
BASE is a formal modelIt is a design slogan from a 2008 article; the guarantees are product-specific
Eventual consistency means seconds at worstThe window depends on load and failures; design for hours
ACID consistency equals CAP consistencyOne is invariants in a database, the other is linearizability across replicas
A saga is a distributed rollbackIt is a series of committed steps with new business actions to undo them
Exactly-once delivery makes idempotency unnecessaryEffects on an external system still repeat; dedupe by key
ACID cannot scaleA single primary scales far; distributed SQL scales further at a latency cost
Isolation level Serializable is the default everywherePostgreSQL and Oracle default to Read Committed, MySQL to Repeatable Read
Committed means safe on several machinesOnly if replication is synchronous or majority-based
Reconciliation is only for broken designsEvery money flow needs it; it is the last line of defence
2PC is unreliableIt is correct, but blocking and low availability across independent services

Cheat sheet ​

TopicWhat to remember
ACIDAtomic, Consistent (invariants), Isolated (per level), Durable (fsync, replicas)
BASEBasically Available, Soft state, Eventually consistent: a stance, not a spec
OriginHaerder and Reuter 1983 for ACID; Pritchett, ACM Queue 2008 for BASE
Availability productTwo 99.9% components in one transaction give 99.8%
Per-key atomicitySafe single-item updates need a conditional write
Multi-item in NoSQLDynamoDB TransactWriteItems (100 actions, 4 MB), MongoDB multi-document, Cassandra LWT and batches
Distributed ACIDSpanner and CockroachDB give it at latency cost; 2PC blocks if the coordinator dies
SagaLocal transactions plus compensations; journal progress
CompensationA new business action, idempotent, retried until success
IdempotencyUnique key in the same transaction as the effect
Read-your-writesVersion token or primary reads after a write
ReconciliationScheduled diff with a grace window and alerts
MoneyACID, append-only ledger, idempotency keys
HybridACID core, outbox, idempotent BASE edges
RetriesWhole transaction, only for 40001, 40P01, 1213, ABORTED, transient labels

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Which of the four ACID properties are guaranteed when a crash happens between two UPDATE statements, and which mechanism provides it? Must-know ​

Answer

Answer: Atomicity (and durability of earlier commits). The write-ahead log lets the database discard the uncommitted changes on recovery, so neither update survives.

2 — Why is "consistency" in ACID different from consistency in CAP? Must-know ​

Answer

Answer: ACID consistency means invariants (constraints, rules) hold after a transaction. CAP consistency means linearizability: every read sees the latest write across replicas.

3 — Who coined BASE, when, and why is it better described as a stance than a model? Good to know ​

Answer

Answer: Dan Pritchett, ACM Queue, 2008. It has no formal definition and each product defines its own consistency options; the three words overlap.

4 — A DynamoDB TransactWriteItems call times out. How do you retry safely? Important ​

Answer

Answer: Resend with the same ClientRequestToken; the docs say repeated calls with the same token return successfully without applying twice (within the token window).

5 — Why does 2PC reduce availability, with numbers? Important ​

Answer

Answer: The transaction requires both databases, so availability is the product: 99.9% times 99.9% is about 99.8%, roughly 43 more minutes of downtime per month (Pritchett). Also locks are held while participants are in doubt.

6 — What is the difference between a rollback and a compensation? Must-know ​

Answer

Answer: Rollback discards uncommitted changes invisibly. A compensation is a new committed action (refund, cancel) after the original effect was committed and possibly observed.

7 — Name three things a saga step must be. Important ​

Answer

Answer: Idempotent, retryable, and paired with an idempotent compensation (plus journaled progress and an alert for the stuck state).

8 — A user saves a profile and sees the old data on the next page. What is happening and what are two fixes? Must-know ​

Answer

Answer: A lagging replica served the read (no read-your-writes). Fixes: route the user's reads to the primary for a few seconds, or pass a version token and reject replicas older than it.

9 — When is BASE the wrong choice? Must-know ​

Answer

Answer: For money and any invariant spanning several entities that must never be violated (ledgers, balances, inventory that cannot oversell), unless an ACID core enforces the invariant.

10 — Why dispatch a Laravel job with afterCommit() inside a transaction? Important ​

Answer

Answer: So the worker cannot run before the transaction commits and look for rows that do not exist yet, and a rollback does not leave a job behind.

11 — What does the reconciliation job in this chapter compare, and why the 15-minute grace window? Good to know ​

Answer

Answer: Charges versus orders. The window avoids "repairing" a saga that is still in progress.

12 — Which errors may you retry for a SQL transaction and what do you retry? Important ​

Answer

Answer: 40001, 40P01 (MySQL 1213) and similar engine-marked transient errors; retry the whole transaction, never a business error and never a single statement.

Glossary ​

TermMeaning
ACIDAtomicity, consistency, isolation, durability: the transaction contract
BASEBasically available, soft state, eventually consistent: Pritchett's contrast to ACID
AtomicityAll writes of a transaction apply, or none
Consistency (ACID)Invariants hold before and after each transaction
IsolationConcurrent transactions do not see each other's partial work, per isolation level
Isolation levelRead Committed, Repeatable Read, Serializable, and their anomalies
DurabilityCommitted data survives crashes (log flush, replicas)
Basically availableThe system degrades instead of stopping
Soft stateState may change without input while replicas converge
Eventually consistentReplicas converge if updates stop
PritchettDan Pritchett of eBay, author of "BASE: An Acid Alternative" (2008)
TransactionA group of operations treated as one unit of work
InvariantA rule the data must always satisfy
Per-key atomicityA single key (item, row, document) is updated atomically
Conditional writeA write applied only if a predicate on the current value holds
Compare-and-swapConditional write using a version or expected value
Multi-document transactionMongoDB transaction across several documents
TransactWriteItemsDynamoDB all-or-nothing write over up to 100 items
Cassandra LWTLightweight transaction: conditional write via Paxos
BatchCassandra grouped writes; LOGGED is atomic, not isolated across partitions
SpannerGoogle's globally distributed, externally consistent SQL database
CockroachDBDistributed SQL database with serializable transactions
Distributed transactionA transaction spanning several nodes or databases
2PCTwo-phase commit: prepare then commit, coordinated
CoordinationThe agreement messages needed before a commit
SagaA sequence of local transactions with compensations
CompensationA new action that semantically undoes an earlier committed step
IdempotencyRepeating an operation has the same effect as doing it once
Read-your-writesA session sees its own earlier writes
ReconciliationA job that compares systems and repairs differences
Hybrid architectureACID core with BASE edges joined by an outbox
Deadlock retryRe-running a transaction chosen as deadlock victim (DB::transaction(..., attempts: 5))
Queued compensationA compensating job placed on a queue and retried until it succeeds
LedgerAppend-only record of money movements
Shopping cartClassic BASE data: per-key, mergeable, tolerant of staleness
AnalyticsAppend-only, eventually consistent derived data
DB::transactionLaravel's closure-based transaction helper
OutboxA table written in the same transaction as state to publish events reliably

References ​

Built by Morteza Negahi