Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 150/ 160
08. Backend

Transactions and ACID

Atomic multi-step writes for billing, quotas, and agent side effects.

IntermediateACID · Isolation3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

A transaction is a way to make several changes happen together or not at all, so a crash or a second user can't leave your data half-updated.

Think of it like…

A bank counter with a sealed envelope. The teller moves money between accounts inside one envelope that is either filed completely or thrown away, and nobody else can peek at the half-moved state; but if the teller keeps the envelope open while waiting for a phone call to finish, the whole queue stands still.

Where you’ve seen it

A usage-billed assistant stores each tenant's balance in credits(tenant_id, balance) plus an append-only ledger. Naive code reads the balance, checks balance >= cost in the application and then writes the new value. With a balance of 10 and two concurrent 8-credit calls, both reads see 10, both pass the check and the final balance is 10 − 8 − 8 = −6. The fix is an atomic conditional update inside a transaction: UPDATE credits SET balance = balance - 8 WHERE tenant_id = $1 AND balance >= 8 followed by an INSERT INTO ledger ...; the second request finds 0 affected rows and returns a clear "insufficient credits" error. The second rule is to keep locks short. If the handler holds the row lock while the model call runs for 3.4 seconds, that tenant's requests are serialised: one row can process at most 1 / 3.4 ≈ 0.29 transactions per second, whereas a 5 ms transaction allows 200 per second. So the service uses reserve, call, settle: transaction 1 reserves the worst-case cost ($0.02) and writes a pending ledger row; the model call runs with no transaction open; transaction 2 settles the actual cost ($0.01195) and releases the difference ($0.00805), marking the ledger row settled. A sweeper releases reservations still pending after 10 minutes, covering crashed workers. Side effects outside the database use the outbox pattern: the order record and an outbox row are written in one transaction, and a worker publishes the event, so the state change and the message can't diverge. Idempotency keys make a retried request return the stored result instead of charging twice. Isolation is read committed (the PostgreSQL default) for most paths, with SELECT ... FOR UPDATE or serializable transactions for the few multi-row invariants, and deadlocks are avoided by always locking rows in a consistent order.

Words you’ll hear

Atomicity
All operations in a transaction commit together or none do.
Isolation level
How strongly concurrent transactions are kept from seeing each other's changes.
Conditional update
An UPDATE whose WHERE clause enforces a rule atomically, such as balance >= cost.
Outbox pattern
Writing an event row in the same transaction as the data change, then publishing it asynchronously.

Visual diagram

Loading interactive diagram

Theory & deep dive

ACID, isolation and anomalies

Atomicity and durability come from the write-ahead log: changes are logged before they are applied and a commit is acknowledged only after the log is safely on disk, so a crash either replays or discards a whole transaction. Consistency means constraints (foreign keys, CHECK balance >= 0, unique keys) hold at commit, which is why encoding rules in the schema beats trusting every code path. Isolation is the hard part. At read committed (default in PostgreSQL) each statement sees only committed data, so two statements in one transaction can see different values (non-repeatable read). Repeatable read gives a stable snapshot. Serializable makes concurrent transactions behave as if run one at a time, at the cost of aborts you must retry.

The credits bug is a lost update or write skew: both transactions read the same state and each makes a decision that is valid alone but invalid together. Fixes in rising order of strength: make the check and the change one atomic statement (UPDATE ... WHERE balance >= cost), lock the row you read (SELECT ... FOR UPDATE), or use serializable isolation and retry on serialization failure. Unique constraints and INSERT ... ON CONFLICT are the best tools for idempotency and dedupe. Choose the weakest level that preserves your invariants and test them with concurrent load, since single-threaded tests won't reveal races.

The lost-update race

Balance 10. Request A reads 10, request B reads 10. A: 10 ≥ 8, writes 2. B: 10 ≥ 8, writes 2 from its stale read, or subtracts again to reach −6. With UPDATE credits SET balance = balance - 8 WHERE tenant_id = $1 AND balance >= 8, B's update sees balance 2 and affects 0 rows.

Key takeaway: Encode invariants in constraints and conditional updates, and pick an isolation level that prevents the anomaly you care about.

Short transactions, AI side effects and distributed work

A transaction holds locks until it ends, so never call an LLM, a payment provider or any slow service inside one. If the handler locks a tenant's balance row for the 3.4-second model call, that row can process at most 1 / 3.4 ≈ 0.29 transactions per second versus 200 per second at 5 ms, and other requests queue or deadlock. Use reserve, call, settle: reserve the worst-case cost in a short transaction, run the model call with no transaction open, then settle the actual cost and refund the difference ($0.02 reserved, $0.01195 used, $0.00805 returned). Handle failure paths: if the call fails, release the reservation; if the worker crashes, a sweeper expires reservations pending beyond a timeout. Keep transactions small, touch rows in a consistent order to avoid deadlocks and retry on deadlock or serialization errors.

Across services you cannot rely on one ACID transaction. Use the outbox pattern (write the business row and an outbox event in one transaction, publish from the outbox with retries), idempotency keys and consumers that tolerate duplicates, and sagas (a sequence of local transactions with compensating actions) for multi-step workflows such as an agent booking, charging and emailing. For agent actions with external side effects, record intent first (pending), perform the action with an idempotency key and then mark it done, so a retry after a crash neither repeats nor loses the action. Monitor lock waits, deadlocks, long-running transactions and serialization failures as production signals.

Lock-hold throughput

Transaction holds the tenant row for 3.4 s (model call inside): max 1 / 3.4 = 0.29 tx/s per tenant. Reserve and settle at 5 ms each: 1 / 0.005 = 200 tx/s per transaction phase. Same correctness, roughly 700 times the contention headroom.

Key takeaway: Keep transactions short and free of slow I/O, use outbox and idempotency for side effects, and compensate rather than assume distributed ACID.

How it works, step by step

Step 1 of 4
Backend engineer

1. List invariants that must hold

Identify rules such as balance never negative and ledger matching balance, and encode them as constraints.

CHECK balance >= 0
Key numbers at this step
Prefer
database-enforced rules

When to use it & trade-offs

What it is

A transaction groups several database operations into one unit that either fully happens or doesn't happen at all. ACID names its guarantees: atomicity (all or nothing), consistency (constraints hold before and after), isolation (concurrent transactions don't see each other's half-finished work, to a chosen degree) and durability (committed data survives a crash). Isolation comes in levels (read committed, repeatable read, serializable) that trade strictness for concurrency and allow or prevent anomalies such as non-repeatable reads, phantoms and write skew. For AI backends the transactional core protects credits and quotas, billing ledgers, job state and agent side effects, while slow work such as model calls must stay outside the transaction.

Why it matters: Money and permissions break in subtle ways under concurrency. Two parallel requests can both read a balance of 10 credits, both decide an 8-credit call is affordable and drive the balance to −6. A crash between "charge the customer" and "record the usage" produces a ledger that doesn't add up. Meanwhile a transaction held open across a 3-second LLM call serialises everyone touching the same row. Knowing which operations must be atomic, how to lock or use conditional updates and how to keep transactions short is central to correct and fast AI services.

When to reach for it

  • Credit, quota and ledger updates
  • Job state transitions and claiming work
  • Outbox writes for reliable events

When to avoid or be careful

  • Model or HTTP calls inside open transactions
  • Read-then-write balance checks in application code
  • Assuming cross-service ACID

Isolation approaches

Read committed with conditional updates
Best for: Most counters, quotas and balances

Strengths: High concurrency; simple.

Watch out: Multi-row invariants need care.

SELECT … FOR UPDATE
Best for: Read-modify-write on specific rows

Strengths: Explicit mutual exclusion.

Watch out: Locks block others; deadlock risk.

Serializable isolation
Best for: Complex multi-row invariants

Strengths: Strongest correctness guarantees.

Watch out: Aborts and retries; lower throughput.

Interview signals & numbers to know

When this topic comes up

  • “How do you prevent double-spending credits?”
  • Isolation levels and anomalies
  • Why not call the LLM inside a transaction
  • Outbox and saga patterns
  • Deadlock avoidance

Benchmarks & rules of thumb

10 − 8 − 8 = −6 -
overdraft from two racing 8-credit requests
0.29 tx/s vs 200 tx/s -
per-row throughput with a 3.4 s lock versus a 5 ms lock
$0.02 → $0.01195 -
reserved worst case versus actual cost, refunding $0.00805

Common mistakes & follow-ups

Common interview mistakes

  • Checking a balance in code and updating it in a separate statement.
  • Locking rows in different orders in different code paths.
  • Never testing invariants under concurrent load.

Likely interviewer follow-ups

  • How would you charge a tenant for an LLM call safely?
  • What happens if the worker crashes after reserving credits?
  • When would you choose serializable isolation?
Interview tip: Quote the 3.4 s lock-hold arithmetic; it shows you know why slow work stays outside transactions.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Transactions and ACID with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Database Indexing
Next topic
Caching with Redis