Database Transaction Mistakes and How to Avoid Them

HTTP calls inside a transaction, forgotten commits, reports without one snapshot, read-modify-write races and huge transactions that are slow to recover.

In this chapter

Transaction mistakes: too long, too big, or never finished

More on Transactions: locks and production

Keep learning

Overview

chapters · transactions, isolation and locks Transaction mistakes: too long, too big, or never finished An open transaction pays for locks and a snapshot every second, so most trouble is duration or size. Payment API Other orders stock row No slow query, nothing looks wrong, yet everyone waits row locked charge card… UPDATE stock … waits 30 s lock released

1. Time outside the database, spent inside the transaction

Move the slow step inside, then before BEGIN. Compare lock time and throughput. Slow work → BEGIN → a few statements → COMMIT → follow-up work. No humans inside Collect input first, then run a few statements. Outside work: before or after After-commit work: intent row in same tx, worker finishes (outbox). Hidden transactions Frameworks wrap whole requests. Log tx age, not query time.

2. Forgotten commits and long readers

Leave a reader idle, then switch to per-statement snapshot. How many old versions must cleanup keep? Never-ending tx keeps its locks Worse than a slow one. Per-tx snapshot blocks cleanup Of every later version: purge (MySQL), vacuum (PG). More quiet mistakes What you see No rollback on error path try/catch/finally: every path COMMIT or ROLLBACK, then release One tx across pool connections Missing rows, waits on your own locks One connection for the whole unit Retry not safe to repeat Double charges after lost connection during COMMIT Locking more than needed Writers wait on rows you never change Mixed autocommit habits Tx open for hours One convention: autocommit on + explicit tx Report from several autocommit queries Summary says 3 sales, detail shows 4 One read-only tx at REPEATABLE READ (shared snapshot), kept short Read uncommitted for speed Totals include rolled-back changes (dirty read) Trust REPEATABLE READ for read-modify-write Lost change, or cross-row rule broken (write skew) Unbounded statements UPDATE / FOR UPDATE without useful WHERE locks every row Correct retries After deadlock, lock timeout, 40001: roll back, rerun the whole tx.

3. Why one big transaction hurts in five places

rows deleted in one transaction Locks held whole run Undo keeps growing Cancel ≠ vanish Crash makes it worse DELETE every row Per-row undo for the whole table. Drop partition / TRUNCATE Skips per-row undo (some engines: TRUNCATE auto-commits). → undo · write-ahead log · version cleanup · replica lag

4. Cut it into keyset batches you can resume

Drag batch size down. Watch locks, undo and lag fall, and commits add time. Next key range id > last_id LIMIT 1000 DELETE in range Save progress Sleep 50 ms replicas catch up Indexed key, not OFFSET Idempotent batches Rerunning a committed range is harmless. Pause on replica lag Pick sizes by measurement. Not everything splits

5. Spot the misuse

Each flaw comes from a section above. Decide before you click.

Remember

Keep it short Locks, snapshot, undo cost its whole life. Huge tx Multi-query report One shared snapshot. Lock, atomic update, or retry. No waiting inside Not on people, not on other systems. Always end COMMIT or ROLLBACK, on one connection. Retry whole units Deadlock, timeout, 40001. Idempotent first. Big jobs Keyset batches, commit each, record progress, watch lag. → ACID → atomicity → anomalies → levels → snapshots → locks

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.