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 for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why the two camps exist | Why it exists |
| Who coined ACID and BASE, and why BASE is not a formal model | Where it comes from |
| Atomicity, consistency, isolation, durability | Atomicity, Consistency, Isolation, Durability |
| Basically available, soft state, eventually consistent | Basically available, Soft state, Eventual consistency |
| What a BASE store really gives you | Per-key atomicity, Multi-item transactions |
| The cost of distributed ACID | Distributed ACID and 2PC |
| Building BASE correctly | Sagas, Idempotency, Read-your-writes, Reconciliation |
| ACID core with BASE edges | Hybrid architecture |
| Per-product behaviour | What each product really does |
| Numbers, knobs, error codes | Mechanics |
| Code | Go, Laravel |
| Classic failures and fixes | Solving the classic problems |
| Which contract for which data | Choosing |
| Monolith to multi-region | In architecture |
| Hands-on experiments | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
ACID: the four promises of a transaction.
| Letter | In plain words | Tiny example | What provides it |
|---|---|---|---|
| Atomicity | All the writes happen or none do | Debit and credit both apply, or neither | Write-ahead log plus rollback |
| Consistency | The data obeys your rules before and after | Stock never below zero, debits equal credits | Constraints, triggers, and your own correct code |
| Isolation | Concurrent transactions do not see each other's half-done work | Two buyers of the last item do not both succeed | Locks or snapshots (MVCC), per isolation level |
| Durability | Once committed, it survives a crash | Power cut after COMMIT returns, the row is still there | WAL flushed to disk (fsync), replication |
BASE: the three words.
| Word | In plain words | Tiny example | The price |
|---|---|---|---|
| Basically Available | Most requests get an answer even when parts are broken | One shard down, the other shards still serve | Answers may be partial or stale |
| Soft state | State may change without new input, as replicas converge | A cart count differs for a second between two replicas | Readers can see in-between values |
| Eventually consistent | If writes stop, all replicas end up equal | Two data centres agree a few hundred milliseconds later | You must design for the gap |
What each side is good at.
| Question | ACID (single database) | BASE (partitioned, replicated stores) |
|---|---|---|
| Can a user see a half-finished operation? | No | Yes, until convergence |
| What happens when the network splits? | CP: the minority side refuses writes | AP: both sides keep writing, conflicts later |
| Cost of a multi-row invariant | One transaction | Saga, compensation, reconciliation |
| Scale-out | Vertical first; sharding makes it hard | Built for horizontal partitions |
| Failure undo | ROLLBACK, automatic | Compensating action you wrote |
| Typical data | Money, stock, bookings, identity | Carts, 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".
| Pressure | ACID answer | BASE answer |
|---|---|---|
| Data no longer fits one machine | Distributed SQL with consensus, or accept a bigger machine | Partition by key, never join or transact across partitions |
| Users in several continents | Pay cross-region latency per commit | Write locally, replicate asynchronously |
| A dependency is down | The transaction waits or fails | Queue the work, answer now, finish later |
| A business rule spans services | Impossible without 2PC | Saga 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
- "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.
- "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.
- "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).
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 existsReal 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:
| Product | Scope of an atomic unit | Notes |
|---|---|---|
| PostgreSQL, MySQL (InnoDB), SQL Server, Oracle | Any statements in one transaction | Automatic rollback on error (PostgreSQL aborts the whole transaction until ROLLBACK) |
| SQLite | Any statements in one transaction, one writer | Whole database file is the unit of locking |
| MongoDB | One document always; many with a multi-document transaction | "an operation on a single document is atomic" (MongoDB docs) |
| DynamoDB | One item always; up to 100 items with TransactWriteItems | Same account and Region only |
| Cassandra | One row/partition write; LOGGED batch for several | Batch is atomic eventually, not isolated across partitions |
| Redis | A single command; MULTI/EXEC runs queued commands in one go | No 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.
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 refusesReal 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:
| Tool | Invariant it protects | Where available |
|---|---|---|
CHECK constraint | Single-row value rules | PostgreSQL, MySQL 8.0.16+, SQL Server, Oracle, SQLite |
UNIQUE and primary key | No duplicates, idempotency keys | All SQL; DynamoDB conditional write; Cassandra IF NOT EXISTS |
FOREIGN KEY | Referential integrity | SQL engines; none in DynamoDB, Cassandra or MongoDB |
Conditional update (WHERE qty >= n) | Read-modify-write without a race | Any store with a conditional write |
| Serializable isolation | Rules 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.
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:
| Product | Default level | Strongest level | Mechanism |
|---|---|---|---|
| PostgreSQL | Read Committed | Serializable (SSI) | MVCC snapshots, SSI aborts with 40001 |
| MySQL InnoDB | Repeatable Read | Serializable (locking) | MVCC plus next-key locks |
| SQL Server | Read Committed (locking) | Serializable, Snapshot | Locks or row versions |
| Oracle | Read Committed | Serializable | Undo-based read consistency |
| CockroachDB | Serializable | Serializable (Read Committed available) | Timestamp ordering, retry error 40001 |
| Spanner | Serializable (externally consistent) | same | Locks plus TrueTime commit timestamps |
| DynamoDB | Eventual single-item reads | Serializable for transactions | Between transactional and standard operations too |
| MongoDB | Snapshot within a transaction | Snapshot with majority concern | Read/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).
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 goneReal 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:
| Product | Setting | Effect |
|---|---|---|
| PostgreSQL | synchronous_commit = on (default), synchronous_standby_names | Wait for local WAL flush, optionally for a replica |
| MySQL InnoDB | innodb_flush_log_at_trx_commit = 1 | fsync the redo log at each commit |
| MongoDB | write concern w: "majority", j: true | Majority of members, journaled |
| Cassandra | commitlog_sync, consistency level QUORUM | Commit log mode plus replicas acknowledged |
| Redis | appendonly yes, appendfsync always/everysec | Per-write or per-second fsync of the AOF |
| Spanner, CockroachDB | Raft or Paxos majority | Commit 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).
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 usersReal 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:
| Technique | Product examples | Cost |
|---|---|---|
| Partition by key | DynamoDB, Cassandra, MongoDB shards | No cross-partition transaction or join |
| Multi-replica reads | Cassandra ONE/LOCAL_QUORUM, DynamoDB eventual reads | Stale reads |
| Queue instead of call | Kafka, RabbitMQ, SQS | Delayed result, more states |
| Cache fallback | Redis, CDN stale-if-error | Staleness, 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.
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:
| Mechanism | Product | Effect |
|---|---|---|
| Asynchronous replication | MongoDB secondaries, PostgreSQL async standby, MySQL replicas | Lag between primary and replica |
| Hinted handoff, read repair, anti-entropy | Cassandra, DynamoDB internals | Divergent replicas converge later |
| TTL and lease expiry | Redis keys, DynamoDB TTL, Consul sessions | State disappears without a request |
| Derived stores | Elasticsearch fed by CDC, caches | Updated 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).
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):
| Product | Default | Stronger option |
|---|---|---|
| DynamoDB | Eventually consistent reads | ConsistentRead true (strong, same Region, primary replica) |
| Cassandra | Tunable per query | QUORUM reads and writes (R + W > N) |
| MongoDB | Read from primary by default | Read concern majority or linearizable |
| Redis replication | Asynchronous | WAIT for acknowledged replicas |
| Elasticsearch | Near 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 = ?.
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 -> acceptedReal 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:
| Product | Primitive | Failure signal |
|---|---|---|
| DynamoDB | ConditionExpression on PutItem/UpdateItem/DeleteItem | ConditionalCheckFailedException |
| Cassandra | INSERT ... IF NOT EXISTS, UPDATE ... IF col = ? (Paxos) | [applied] = false in the result row |
| MongoDB | Filter in updateOne/findOneAndUpdate, $inc | matchedCount = 0 |
| Redis | SET NX, WATCH/MULTI/EXEC, Lua EVAL | nil reply or aborted EXEC |
| SQL | UPDATE ... WHERE qty >= n, version column | 0 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.
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:
| Product | API | Limits (from the docs) |
|---|---|---|
| DynamoDB | TransactWriteItems, TransactGetItems | Up to 100 actions, same account and Region, 4 MB aggregate, idempotent with a client token |
| MongoDB | Multi-document transactions on replica sets and sharded clusters | Performance cost; prefer embedding; short transactions |
| Cassandra | LOGGED BATCH; LWT IF | Batch is not isolated across partitions; LWT is per partition |
| Spanner | Read-write transactions | Serializable, externally consistent, retry on ABORTED |
| CockroachDB | BEGIN ... COMMIT | Serializable by default, retry on 40001 |
| Redis | MULTI/EXEC | No 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).
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 locksReal 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:
| Product | Distributed transaction | Notes |
|---|---|---|
| PostgreSQL | PREPARE 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 InnoDB | XA transactions | Also used internally between binlog and engine |
| SQL Server, Oracle | MSDTC, Oracle distributed transactions | Coordinator is a separate service |
| Spanner | 2PC across Paxos groups | Serializable, externally consistent |
| CockroachDB | Parallel commits over Raft ranges | Serializable, 40001 retries |
| Kafka | Transactions (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.
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.
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:
| Tool | Role | Notes |
|---|---|---|
Hand-written orchestrator (Go saga.Runner) | Journal of steps, ordered compensation | Full control; you own recovery |
Laravel Bus::chain()->catch() plus queued jobs | Chain with a failure callback that queues compensation | Per-job #[Tries], #[Backoff] |
| Temporal, AWS Step Functions, Camunda | Durable workflow engines | Retries and state persisted for you; see Durable Workflows |
| Kafka plus Debezium outbox | Choreography via events | Each 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.
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).
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 onceReal 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:
| Technique | Where | Weakness |
|---|---|---|
| Unique key in the same transaction as the effect | PostgreSQL ON CONFLICT DO NOTHING, MySQL INSERT IGNORE | Needs a shared store for dedupe and effect |
ClientRequestToken | DynamoDB TransactWriteItems | Token remembered for a limited window |
| Natural idempotent writes | Set a value, upsert by key | Not for increments |
| Version or CAS check | Conditional writes | Retries 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.
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 -> v7Real 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:
| Technique | Product examples | Cost |
|---|---|---|
| Read from the primary for N seconds after a write | Any async-replicated SQL or MongoDB | More primary load |
| Session token with minimum version/LSN | Go kv.Session; PostgreSQL LSN, Aurora, DynamoDB ConsistentRead | Plumbing per request |
| Sticky routing to one replica | Load balancer affinity | Uneven load, breaks on failover |
| Write-through the client cache | Mobile apps, SPAs | Client 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.
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 growsReal 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:
| Approach | When | Notes |
|---|---|---|
Periodic diff job (orders:reconcile, Go reconcile.Diff) | Two stores you own | Grace period for in-flight sagas |
| Settlement file match | External payment providers | Daily, authoritative |
| CDC and rebuild (Debezium, backfill) | Derived stores | Rebuild is the recovery path |
| Merkle-tree comparison | Replicated stores | See 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.
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) -> indexReal 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:
| Piece | Product | Role |
|---|---|---|
| Core | PostgreSQL, MySQL, Spanner, CockroachDB | Source of truth, constraints |
| Seam | Transactional outbox, Debezium CDC | Atomic state-plus-event |
| Transport | Kafka, RabbitMQ, SQS | At-least-once delivery |
| Edge | DynamoDB, Redis, Elasticsearch, ClickHouse | Fast, scalable, derived |
| Safety net | Reconciliation job, dead-letter queue | Repair 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.
What each product really does
| Product | Transaction scope | Default consistency | Multi-item/partition transactions | Notes |
|---|---|---|---|---|
| PostgreSQL | One node (primary) | Read Committed, ACID | Yes, locally; 2PC via PREPARE TRANSACTION for external managers | Strong ACID; scale by replicas and partitioning |
| MySQL InnoDB | One node | Repeatable Read, ACID | Yes locally; XA | Gap/next-key locks; deadlock error 1213 |
| SQL Server / Oracle | One node (RAC for cluster) | Read Committed | Yes; distributed via DTC | Mature, expensive |
| SQLite | One file | Serializable (one writer) | Yes, one file | Embedded |
| DynamoDB | One item; up to 100 items by transaction | Eventual reads; strong on request | TransactWriteItems / TransactGetItems | Conditional writes; capacity doubled for transactions |
| MongoDB | One document; multi-document on demand | Primary reads; tunable concerns | Replica sets and sharded clusters | Prefer embedding; short transactions |
| Cassandra | One partition row; LWT per partition | Tunable (ONE to ALL) | LOGGED batches (not isolated), LWT (Paxos) | AP by design |
| Redis | One command; MULTI/EXEC | Async replication | No rollback; Lua scripts for atomic logic | Cache and fast structures |
| Spanner | Global | External consistency, serializable | Yes, 2PC over Paxos groups | TrueTime; pay latency |
| CockroachDB | Global ranges | Serializable (Read Committed available) | Yes; retry error 40001 | PostgreSQL wire protocol |
| Kafka | Producer and offset transaction | Per-partition order | Atomic across partitions in one cluster | Not a database transaction |
Mechanics
Error codes and what to do
| Product | Error | Meaning | Retry? |
|---|---|---|---|
| PostgreSQL | SQLSTATE 40001 serialization_failure | Could not serialize concurrent update | Yes, whole transaction |
| PostgreSQL | SQLSTATE 40P01 deadlock_detected | Deadlock victim | Yes, whole transaction |
| PostgreSQL | SQLSTATE 23514 check_violation | Invariant refused the write | No, business error |
| PostgreSQL | SQLSTATE 23505 unique_violation | Duplicate key (often idempotency) | No, treat as already done |
| MySQL | 1213 ER_LOCK_DEADLOCK | Deadlock | Yes |
| MySQL | 1205 ER_LOCK_WAIT_TIMEOUT | Lock wait timeout | Maybe, after review |
| CockroachDB | 40001 restart transaction | Could not be placed in a serializable order | Yes (client-side retry loop) |
| Spanner | ABORTED | Transaction conflict | Yes, same session keeps lock priority |
| DynamoDB | TransactionCanceledException | An item-level condition or conflict failed | Inspect CancellationReasons first |
| DynamoDB | TransactionConflictException | A standard write collided with a transaction | Yes, with backoff |
| DynamoDB | ConditionalCheckFailedException | Condition false | No, re-read and decide |
| Cassandra | LWT [applied] = false | Condition false | No, re-read |
| MongoDB | TransientTransactionError label | Transaction can be retried as a whole | Yes (driver callback API does it) |
Retry rules
- Retry the whole transaction, never the single statement that failed; the earlier reads are stale.
- Retry only errors the engine marks as safe (40001, 40P01, 1213,
TransientTransactionError,ABORTED). Never retry a business error. - Use exponential backoff with jitter and a fixed attempt budget (Go
acid.WithRetry; Laravelattempts:argument). - Keep transactions short; no HTTP calls or sleeps inside.
- Make the transaction idempotent, because a commit whose acknowledgement was lost is indistinguishable from a failure.
Availability and latency arithmetic
| Quantity | Value | Source |
|---|---|---|
| Availability of a transaction over two 99.9% databases | 99.8%, about 43 more minutes of downtime per month | Pritchett 2008 |
Same over n required components of availability a | a to the power n | Product rule |
| Round trips in 2PC | 2 phases, at least 2 coordinator-participant exchanges each | Protocol |
| Locks held in 2PC | From prepare until the commit decision arrives | Protocol |
| DynamoDB transaction limit | 100 actions, 4 MB, same account and Region | DynamoDB docs |
| DynamoDB capacity | Transactional operations cost two reads or writes per item | DynamoDB 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
// 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:
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
}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:
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:
// 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)
}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:
// 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
}
}
}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:
// 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/sqlexposes transactions asdb.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}). The returned*sql.Txis bound to one connection; a context cancelled beforeCommitrolls the transaction back. Every statement must usetx, notdb, or it runs outside the transaction.- Go has no ambient transaction. Passing a
Txinterface into the business function (asacid.Store.InTxdoes) 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, asacid.WithRetrydoes. - 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
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
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
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
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
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
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
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$thisinside them.- Per-job attributes in Laravel 13:
#[Tries(5)]and#[Backoff([10, 30, 60])](namespaceIlluminate\Queue\Attributes). Compensation jobs get many tries and long backoff; forward steps get few. - Laravel's
failed()job method andfailed_jobstable are the hook for the "stuck" state: alert on them rather than losing the saga silently. - Idempotency in Laravel is yours:
insertOrIgnoreon a unique key (as in the jobs above),ShouldBeUnique, or theWithoutOverlappingjob middleware for per-order serialization.
Solving the classic problems
Selling the last item twice
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Conditional update | UPDATE stock SET qty = qty - 1 WHERE sku = ? AND qty >= 1 | Atomic, no lock held across a round trip | One row only |
SELECT ... FOR UPDATE | Lock the row, then decide | Allows complex logic | Holds lock, deadlock risk |
| DynamoDB condition | ConditionExpression: qty >= :n | Works at any scale | Per item only |
| Reservation with TTL | Hold the unit for 10 minutes | Fits carts and tickets | Needs expiry job |
Charge succeeded, order not recorded
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| One transaction | Same database for charge record and order | Impossible by construction | Needs one store |
| Saga with journal | Record intent first, then steps, compensate on failure | Works across services | Visible intermediate states |
| Reconciliation | Daily diff against provider | Catches everything else | Latency to repair |
Duplicate message applied twice
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Dedupe table | INSERT ... ON CONFLICT DO NOTHING with the effect | Exactly-once effect | Table growth, TTL |
| Natural idempotency | Upsert by key | No extra table | Not for increments |
| Broker dedupe | Kafka idempotent producer, SQS FIFO dedupe id | Fewer duplicates | Only inside the broker window |
Saved but not visible
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Session version token | Reject replicas older than your last write | Cheap, precise | Needs versions |
| Primary-for-a-while | Route reads of this user to the primary for N seconds | Simple | Primary load |
| Optimistic UI | Show the local state until confirmed | Instant | Needs rollback UX |
Compensation fails
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Retry with backoff, many attempts | #[Tries(20)], UndoAttempts | Handles transient outages | Delays recovery |
Journal state stuck and alert | Human work queue | No silent loss | Needs on-call |
| Semantic lock | Mark the order "pending" so users cannot act | Limits damage | UX state |
-- 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):
-- 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()
);-- 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.# 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 class | Contract | Product | Extra technique | Reason |
|---|---|---|---|---|
| Ledger, payments, wallets | ACID, serializable or FOR UPDATE | PostgreSQL, MySQL, Spanner, CockroachDB | Append-only entries, CHECK, idempotency keys, reconciliation | One anomaly costs more than any latency |
| Orders and inventory | ACID inside one service | PostgreSQL | Conditional update, outbox | Invariants across rows |
| Shopping cart | BASE, per-key atomic | DynamoDB, Redis | Version column, merge on conflict, TTL | Availability beats a stale item |
| Sessions, tokens | BASE with TTL | Redis, DynamoDB | Expiry, sticky reads | Rebuildable, high read rate |
| Product catalogue and search | BASE, derived | Elasticsearch, cache | CDC rebuild | Source of truth elsewhere |
| Likes, view counters | BASE, approximate | Redis, Cassandra counters | Sharded counters, batch flush | Exactness unneeded |
| Analytics and events | BASE, append-only | Kafka, ClickHouse, S3 | Late data handling | Throughput over freshness |
| User profile | ACID per record, replicated reads | PostgreSQL with replicas | Read-your-writes token | Rare conflicts |
| Cross-service business process | Saga | Orchestrator, Temporal | Compensations, journal | No shared transaction exists |
Which scale-out path
| Situation | Choose | Why |
|---|---|---|
| One primary is enough (most systems) | Single-database ACID | Simplest correct design |
| Writes exceed one node and invariants span keys | Distributed SQL (Spanner, CockroachDB) | Keeps transactions, pays latency |
| Writes exceed one node and invariants fit one key | DynamoDB, Cassandra, sharded store with conditional writes | Cheap, scalable |
| Process spans teams or third parties | Saga plus reconciliation | No common transaction manager |
| Need global low-latency writes, conflicts acceptable | Multi-leader or CRDTs | See Replication Topologies |
Anti-patterns
| Anti-pattern | Why it hurts | Instead |
|---|---|---|
| BASE for money (eventually consistent balance, last-write-wins on a ledger) | Lost updates and double spends | ACID core, append-only ledger |
| ACID for everything at scale (one global 2PC across services) | Availability multiplies down, locks held across the network | Local transactions plus saga |
| Saga without idempotency | Retries double-apply steps | Idempotent steps and compensations |
| Saga without reconciliation | Stuck states stay unnoticed | Scheduled diff and alerts |
| Dual write (DB then broker, no outbox) | Crash between them loses the event | Transactional outbox |
| Retrying single statements | Stale reads inside the transaction | Retry the whole transaction |
| Treating a cache as source of truth | Eviction means data loss | Cache 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:
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
| Scale | Design | Contract changes |
|---|---|---|
| 1x: one primary | Single-database ACID | None; add constraints and indexes |
| 10x: read-heavy | Read replicas, cache | Read-your-writes handling; replica lag becomes a feature to design for |
| 100x: write-heavy | Shard by key, or distributed SQL | Cross-shard invariants become sagas or distributed transactions |
| Multi-region | Regional primaries plus global replication | Pick 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).
$ 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: TestRetryGivesUpExperiment 2: the saga, including the intermediate state and a stuck compensation (run).
$ 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: TestResumeSkipsDoneStepsExperiment 3: lost update versus compare-and-swap, replica lag, session token (run).
$ 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: TestDiffIsEmptyWhenConsistentExperiment 4: double spend with and without the condition (SQL, two sessions; expected, not run).
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).
$ 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
| Belief | Reality |
|---|---|
| NoSQL has no transactions | DynamoDB, MongoDB, Cassandra (limited), Spanner and CockroachDB all do; scope and cost differ |
| BASE is a formal model | It is a design slogan from a 2008 article; the guarantees are product-specific |
| Eventual consistency means seconds at worst | The window depends on load and failures; design for hours |
| ACID consistency equals CAP consistency | One is invariants in a database, the other is linearizability across replicas |
| A saga is a distributed rollback | It is a series of committed steps with new business actions to undo them |
| Exactly-once delivery makes idempotency unnecessary | Effects on an external system still repeat; dedupe by key |
| ACID cannot scale | A single primary scales far; distributed SQL scales further at a latency cost |
| Isolation level Serializable is the default everywhere | PostgreSQL and Oracle default to Read Committed, MySQL to Repeatable Read |
| Committed means safe on several machines | Only if replication is synchronous or majority-based |
| Reconciliation is only for broken designs | Every money flow needs it; it is the last line of defence |
| 2PC is unreliable | It is correct, but blocking and low availability across independent services |
Cheat sheet
| Topic | What to remember |
|---|---|
| ACID | Atomic, Consistent (invariants), Isolated (per level), Durable (fsync, replicas) |
| BASE | Basically Available, Soft state, Eventually consistent: a stance, not a spec |
| Origin | Haerder and Reuter 1983 for ACID; Pritchett, ACM Queue 2008 for BASE |
| Availability product | Two 99.9% components in one transaction give 99.8% |
| Per-key atomicity | Safe single-item updates need a conditional write |
| Multi-item in NoSQL | DynamoDB TransactWriteItems (100 actions, 4 MB), MongoDB multi-document, Cassandra LWT and batches |
| Distributed ACID | Spanner and CockroachDB give it at latency cost; 2PC blocks if the coordinator dies |
| Saga | Local transactions plus compensations; journal progress |
| Compensation | A new business action, idempotent, retried until success |
| Idempotency | Unique key in the same transaction as the effect |
| Read-your-writes | Version token or primary reads after a write |
| Reconciliation | Scheduled diff with a grace window and alerts |
| Money | ACID, append-only ledger, idempotency keys |
| Hybrid | ACID core, outbox, idempotent BASE edges |
| Retries | Whole transaction, only for 40001, 40P01, 1213, ABORTED, transient labels |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| ACID | Atomicity, consistency, isolation, durability: the transaction contract |
| BASE | Basically available, soft state, eventually consistent: Pritchett's contrast to ACID |
| Atomicity | All writes of a transaction apply, or none |
| Consistency (ACID) | Invariants hold before and after each transaction |
| Isolation | Concurrent transactions do not see each other's partial work, per isolation level |
| Isolation level | Read Committed, Repeatable Read, Serializable, and their anomalies |
| Durability | Committed data survives crashes (log flush, replicas) |
| Basically available | The system degrades instead of stopping |
| Soft state | State may change without input while replicas converge |
| Eventually consistent | Replicas converge if updates stop |
| Pritchett | Dan Pritchett of eBay, author of "BASE: An Acid Alternative" (2008) |
| Transaction | A group of operations treated as one unit of work |
| Invariant | A rule the data must always satisfy |
| Per-key atomicity | A single key (item, row, document) is updated atomically |
| Conditional write | A write applied only if a predicate on the current value holds |
| Compare-and-swap | Conditional write using a version or expected value |
| Multi-document transaction | MongoDB transaction across several documents |
| TransactWriteItems | DynamoDB all-or-nothing write over up to 100 items |
| Cassandra LWT | Lightweight transaction: conditional write via Paxos |
| Batch | Cassandra grouped writes; LOGGED is atomic, not isolated across partitions |
| Spanner | Google's globally distributed, externally consistent SQL database |
| CockroachDB | Distributed SQL database with serializable transactions |
| Distributed transaction | A transaction spanning several nodes or databases |
| 2PC | Two-phase commit: prepare then commit, coordinated |
| Coordination | The agreement messages needed before a commit |
| Saga | A sequence of local transactions with compensations |
| Compensation | A new action that semantically undoes an earlier committed step |
| Idempotency | Repeating an operation has the same effect as doing it once |
| Read-your-writes | A session sees its own earlier writes |
| Reconciliation | A job that compares systems and repairs differences |
| Hybrid architecture | ACID core with BASE edges joined by an outbox |
| Deadlock retry | Re-running a transaction chosen as deadlock victim (DB::transaction(..., attempts: 5)) |
| Queued compensation | A compensating job placed on a queue and retried until it succeeds |
| Ledger | Append-only record of money movements |
| Shopping cart | Classic BASE data: per-key, mergeable, tolerant of staleness |
| Analytics | Append-only, eventually consistent derived data |
| DB::transaction | Laravel's closure-based transaction helper |
| Outbox | A table written in the same transaction as state to publish events reliably |
References
- Dan Pritchett, "BASE: An Acid Alternative", ACM Queue 6(3), 2008: https://queue.acm.org/detail.cfm?id=1394128 (read from an archived copy; direct fetch from this machine failed at TLS)
- ACID origin (secondary source): https://en.wikipedia.org/wiki/ACID
- PostgreSQL, Transactions tutorial: https://www.postgresql.org/docs/current/tutorial-transactions.html
- PostgreSQL, Transaction Isolation: https://www.postgresql.org/docs/current/transaction-iso.html
- PostgreSQL, PREPARE TRANSACTION: https://www.postgresql.org/docs/current/sql-prepare-transaction.html
- DynamoDB transactions: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-apis.html
- DynamoDB condition expressions: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html
- MongoDB transactions: https://www.mongodb.com/docs/manual/core/transactions/
- Cassandra guarantees: https://cassandra.apache.org/doc/latest/cassandra/architecture/guarantees.html
- Cassandra CQL data manipulation (batches, IF): https://cassandra.apache.org/doc/latest/cassandra/developing/cql/dml.html
- Spanner transactions: https://cloud.google.com/spanner/docs/transactions
- CockroachDB transactions: https://www.cockroachlabs.com/docs/stable/transactions
- Laravel 13 database (transactions): https://laravel.com/docs/13.x/database
- Laravel 13 queues: https://laravel.com/docs/13.x/queues
- Go
database/sql: https://pkg.go.dev/database/sql - microservices.io, Saga: https://microservices.io/patterns/data/saga.html