4.5 The Danger of Long Transactions

The shorter a transaction, the better, because while a transaction is open it holds three resources.

First, locks. Rows modified by a transaction are locked so that other transactions cannot modify the same rows at the same time. These locks are held until commit or rollback. If a transaction that changed Hong Gildong's balance stays open for 10 minutes without committing, every other transaction that tries to modify Hong Gildong's balance waits 10 minutes. This is why a design that keeps a transaction open while waiting for the user to press a "Confirm" button on the screen is dangerous. Lock behavior is covered in Section 7.2. It is reasonable to start the transaction after the user finally presses the confirm button.

Second, the log. As Chapter 5 shows, the database records every change in the log, and log that has not been finally applied to disk cannot be deleted. A failure in which a single long transaction keeps occupying log space until the disk fills up is not rare in production. This phenomenon is covered in detail in Chapter 10.

Third, old record versions. Section 1.4 explained that when PostgreSQL modifies a row, it adds a new version and leaves the old version in place. MS SQL Server also creates per-version snapshots of records when the snapshot isolation level is enabled. Old versions are kept because a transaction that started earlier may still be referring to them. If even one long-open transaction exists, no old record version created after that transaction's start can be deleted. This is because, to finally apply changes to disk, they must be applied starting from the oldest record.

In this case the table's data bloats and queries slow down. Why this happens is explained in Section 7.9, after the snapshot concept of Chapter 7.

Figure 4-3. Timeline of a long transaction

block-beta
  columns 8
  space ax<["time  t0  ->  t1"]>(right):6 space
  tx["TX1"] tb["BEGIN"] to["open"]:4 tc["COMMIT"] space
  s1["(1) locks"]:8
  l0["TX1"] lk["row lock held by TX1"]:6 lr["released"]
  l2["TX2"] w2["TX2 waits"]:6 r2["runs"]
  l3["TX3"] space w3["TX3 waits"]:5 r3["runs"]
  l4["TX4"] space:2 w4["TX4 waits"]:4 r4["runs"]
  s2["(2) log written since t0"]:8
  g0["log"] g1["kept"]:2 space:4 gr["removable"]
  space g2["cannot be removed"]:4 space:2 space
  space g3["cannot be removed"]:6 space
  s3["(3) old row versions created since t0"]:8
  v0["versions"] v1["kept"]:2 space:4 vr["cleanable"]
  space v2["cannot be cleaned up"]:6 space
  class ax,s1,s2,s3,tx,l0,l2,l3,l4,g0,v0 plain
  class tb,tc meta
  class to,lk slot
  class w2,w3,w4 warn
  class r2,r3,r4,lr,gr,vr data
  class g1,g2,g3,v1,v2 hot

The horizontal axis is time. TX1 in the top row is a transaction that starts with BEGIN at t0 and stays open for a long time until it issues COMMIT at t1. The three groups below are the three resources that accumulate together during the t0-t1 interval while TX1 is open, and the horizontal bars are the intervals during which each resource is held.

(1) Lock wait queue. The lock on the row TX1 modified is held until the commit at t1. Meanwhile TX2, TX3, and TX4, which try to modify the same row, pile up in the queue in order of arrival, and the earlier TX2 arrived, the longer it waits. Only at t1, when TX1 commits and releases the lock, do the waiting transactions proceed.

(2) Log range that cannot be deleted. The database records every change in the log. While TX1 has not ended, log written after t0 cannot be deleted, so, as the bars that grow longer toward the bottom show, the space the log occupies keeps growing over time. If this range fills the disk, it becomes a failure.

(3) Old versions that cannot be cleaned up. Every time a row is updated, an old version is left behind. Since TX1 may still be referring to old versions, none of the old versions created after t0 can be deleted, and they keep piling up. This causes table bloat and slow queries.

All three groups are released at once at t1. The length of the interval during which resources are held equals the time TX1 stayed open, so the sooner a transaction finishes, the shorter all three intervals become.

The three are different resources but serve the same purpose. Until a transaction ends, the database does not know "whether this work will be finalized or cancelled", so it must hold all the resources needed to prepare for both outcomes. Finishing a transaction quickly has the effect of occupying resources to a minimum.

The same applies to read-only transactions. A transaction that only reads takes almost no locks on rows or pages, but if another transaction changed rows after it started, it is referring to the old versions of those rows. This delays the final application of the log to disk, and with a slow query it can fill the log disk. If a query that generates an analytics report runs for hours with a transaction left open on a connection with autocommit off, the database's log files keep accumulating during that time, and once they pass the threshold the server stops.