Harmful transactions: too large, long-running, stalled, abandoned
The four kinds of transaction that slow down or freeze a production database: symptoms, queries to find them on MySQL 8.4 and PostgreSQL 16, fixes in the code, the pool and the database, plus the details people get wrong about SET TRANSACTION and autocommit.
On this page
Part 1 showed that a long-open transaction holds locks and a snapshot: InnoDB can't purge the undo log (history list length grows) and PostgreSQL can't vacuum dead tuples. This part is the practical side: recognizing, finding and fixing those transactions, and where to put timeouts.
1. The problem
checkout() is @Transactional: it locks the order row with FOR UPDATE, calls the payment gateway, then writes the result. The gateway hangs for 30 seconds. Each request holds a connection for 30 seconds, a 20-connection pool drains after 20 requests, and the whole service stops; the DB only sees a few "idle" transactions.
2. Key idea
A transaction is like holding the meeting-room key: a long meeting, stepping out for a phone call, or forgetting to return it all keep others waiting. Each kind has its own cause and cure.
| Kind | Trait | Common cause | Cure |
|---|---|---|---|
| Too large | modifies millions of rows | one UPDATE/DELETE over the whole table |
batch by primary key |
| Long-running | too long from BEGIN to COMMIT |
missing index, N+1, lock waits | fix the cause, then add timeouts |
| Stalled | idle between statements | HTTP calls or PDF rendering inside the transaction | call out before or after the transaction |
| Abandoned | client gone, transaction still open | connection leak | try-with-resources, leak detection |
2.1 Timeouts at which layer?
| Layer | Catches | Limit |
|---|---|---|
App: @Transactional(timeout = 5) |
overdue transactions | can't catch leaks |
Pool: leakDetectionThreshold (HikariCP) |
connections borrowed too long, with a stack trace | log only |
DB: lock_timeout, statement_timeout, idle_in_transaction_session_timeout |
lock waits, slow statements, idleness | too low kills batch jobs: set per user |
| Monitoring: oldest transaction age | every kind | alerts, doesn't stop anything |
innodb_lock_wait_timeout defaults to 50 seconds, too long for web traffic. MySQL has no setting that cuts idle transactions; wait_timeout (8 hours) only closes idle connections.
2.2 Commonly confused details
- Batching gives up atomicity for the whole operation: each batch must be rerunnable (
WHERE status <> 'ARCHIVED'). SET TRANSACTION ISOLATION LEVELwithoutSESSIONapplies only to the next transaction; session-level changes in a pool "leak" into later requests.
3. In Java
public void checkout(long orderId, String idemKey) {
tx.executeWithoutResult(s -> orders.markPaying(orderId)); // short transaction 1
PaymentResult r = paymentClient.charge(orderId, idemKey); // HTTP outside any transaction
tx.executeWithoutResult(s -> orders.applyResult(orderId, r)); // short transaction 2
}
// Batching: one short transaction per batch, walking the primary key
long lastId = 0;
while (true) {
List<Long> ids = jdbc.queryForList("""
SELECT id FROM orders WHERE id > ? AND created_at < '2024-01-01' AND status <> 'ARCHIVED'
ORDER BY id LIMIT 5000""", Long.class, lastId);
if (ids.isEmpty()) break;
tx.executeWithoutResult(s -> jdbc.update(
"UPDATE orders SET status = 'ARCHIVED' WHERE id BETWEEN ? AND ? AND status <> 'ARCHIVED'",
ids.getFirst(), ids.getLast()));
lastId = ids.getLast(); // pause briefly if replicas lag
}Other languages: Go's database/sql needs defer tx.Rollback() right after BeginTx so errors don't abandon the transaction.
Queries to find abandoned transactions
-- MySQL: open transactions whose connection is Sleeping
SELECT t.trx_mysql_thread_id AS conn_id, p.user, p.host, p.time AS idle_s,
TIMESTAMPDIFF(SECOND, t.trx_started, NOW()) AS trx_age_s, t.trx_rows_locked
FROM information_schema.innodb_trx t
JOIN information_schema.processlist p ON p.id = t.trx_mysql_thread_id
WHERE p.command = 'Sleep' ORDER BY trx_age_s DESC;
-- PostgreSQL
SELECT pid, application_name, now() - xact_start AS trx_age, now() - state_change AS idle_for
FROM pg_stat_activity WHERE state = 'idle in transaction' ORDER BY xact_start;Give each service its own ApplicationName (PostgreSQL) or connectionAttributes (MySQL) and the report points straight at the leaking service. KILL is the last resort: InnoDB must roll everything back.
4. Working with AI
Give the AI: splitting a @Transactional method with HTTP calls into two short transactions, batching jobs, a report query for long-open transactions.
Check in AI-written code:
- No HTTP clients, email sending or file rendering inside
@Transactional. - Bulk
UPDATE/DELETEis batched and rerunnable. - Manually borrowed connections sit in try-with-resources.
- DB timeouts are set per user: low for the web app, higher for jobs.
5. Exercises
Exercise 1: HLL climbing all day
MySQL: history list length climbs steadily from morning to afternoon and queries slow down. innodb_trx shows a 6-hour-old transaction with trx_rows_locked = 1; processlist shows it Sleeping for 6 hours from the report service's host. Diagnose, the 15-minute action, the root fix.
Solution to Exercise 1
- Diagnosis: an abandoned transaction from a connection leak in
report. Its read view blocks purge across all tables, so HLL grows and reads slow down. - 15 minutes:
KILL <conn_id>(rolling back 1 row is fast); watch HLL fall back to baseline. - Root fix: enable
leakDetectionThreshold = 30000to get the stack trace of the unreturned borrow, then fix the code with try-with-resources or Spring-managed transactions. Alert when the oldest transaction exceeds 5 minutes; loweringwait_timeoutfor the app user is just a safety net.
Exercise 2: Archiving 20 million rows
The AI proposes UPDATE orders SET status = 'ARCHIVED' WHERE created_at < '2024-01-01' run overnight "to be quick". The table has 20 million rows and read replicas. Why is that a problem, and what do you do?
Solution to Exercise 2
One transaction locks a huge number of rows (plus gap locks under RR), generates lots of undo and redo, and replicas apply it in one go, lagging by tens of minutes; if it fails midway, the rollback takes about as long as the run.
Use the batching loop from section 3: 5,000-row batches by primary key, the condition repeated in the UPDATE, watching replica lag and shrinking the batch when lag grows.
Summary
- Four kinds: too large, long-running, stalled, abandoned.
- Batch by primary key; every batch is rerunnable.
- Move HTTP out of transactions: two short transactions and an idempotency key.
- Connection leaks hold transactions for hours; catch them with leak detection.
- Timeouts at four layers, set per user.
Read more: Locks in InnoDB.
Practice interview questions on this topic
- Why are long transactions harmful? How do "idle in transaction" and autocommit relate?
- A service occasionally slows the whole database for minutes, then recovers. How do you investigate and set timeouts?
- Which anomalies does each isolation level prevent: dirty, non-repeatable and phantom reads?
- Tell me about the most memorable bug you have debugged. How did you approach it?
All Transactions & Locking questions →All Behavioral questions →
Comments
Community rules