Postgres: Why One ALTER TABLE Froze Every Query

Outline

Transcript

0:00 Imagine a checkout service on Postgres. A deploy adds one empty column to the orders table. The moment that migration starts, every checkout that reads orders hangs, and it stays hung for as long as some unrelated report keeps its transaction open. My first guess is the table is huge, or the new column is secretly rewriting it, so the migration is just slow. And a report only reads, so it can't be the report, right? That's the usual reasoning, and here it misses. Adding that column rewrites nothing.

0:33 In the run we'll trace, a plain SELECT waited 2.7 seconds, right up until a 3-second report finished, while the ALTER itself did almost no work. Huh. So the read was waiting on something, just not on the ALTER's work. And if that report had sat open for 10 minutes, that's 10 minutes of frozen checkouts. Exactly, and why it waited comes straight from the PostgreSQL documentation, the lock manager's source code, and a reproduction we ran on a throwaway database. Source links are in the description.

1:05 Okay, let's hear it. Walk me through the run. So, the setup. One table of orders, 1,000 rows, and three connections: a report, a migration and a checkout. Let me guess: the report starts first, begins a transaction, runs one SELECT on orders, and then just sits there with it open? Yep. And that SELECT took the weakest table lock Postgres has, access share. The docs list exactly one mode it conflicts with: access exclusive, the lock that keeps everyone else out, even readers. Which is the one the migration needs.

1:38 Adding a column is one of the ALTER TABLE forms that takes access exclusive, so the migration has to wait until the report's transaction ends. Right. Now the checkout arrives, just reading orders. It only wants access share too, the same lock the report already holds, and two of those never conflict. Then the checkout should just walk in. You'd think so. But it sat there until the report finished. And it can't conflict with the report, so it was waiting on the migration, not the report. Wait. The migration isn't even doing anything yet, so why would a read wait on it?

2:11 So it comes down to how Postgres grants a lock. When a request arrives, it checks two things, In this order. First, whether it conflicts with anything already waiting in line. Only then, whether it clashes with a lock someone already holds. Okay, the checkout would pass the held-lock check easily. But does the migration even count, if it hasn't been granted anything yet? It counts. There's a short comment in Postgres's lock code: if the request conflicts with locks requested by waiters, it must join the wait queue.

2:42 Hold on. So a lock nobody has even been granted can block you. The checkout never gets as far as checking the report. Yeah. The lock README says conflicting requests are granted in order of arrival. Which makes sense. Without that order, readers could keep arriving and overlapping, and the migration might never get its turn. So nobody ever cuts the line? Almost nobody. The one exception is about deadlocks. Suppose the report, still holding its read lock, now updates a row. The migration is already waiting on the report, so if the report joined the back of the line, they'd wait on each other.

3:20 Postgres lets the report in just ahead of the migration instead. Fair enough. That's a deadlock escape hatch, and the checkout holds nothing, so it gets no pass. So the fairness that keeps the migration from starving is really what froze the checkouts. And that's fair to the migration but brutal on checkout. You can actually watch that line form during an incident. While the checkout is stuck, pg locks, the view of every lock in the server, shows the report's lock granted, and the migration's and the checkout's requests marked not granted.

3:53 And when someone pings the channel, "who is blocking checkout?", we all blame the migration. It's the thing that just shipped. And Postgres agrees, at first. Ask pg blocking pids about the checkout, and it names the migration. Ask it about the migration, and it names the report. Right, and the docs have a name for each. The report holds a lock that conflicts with what the migration wants: a hard block. The migration holds nothing yet, it's just ahead of the checkout in line, wanting a conflicting lock: a soft block.

4:26 Exactly. So keep asking until you reach a session that isn't waiting on anyone. That's usually the oldest open transaction, not the migration everyone is staring at. And for the postmortem, when the line is long gone, I'd want log lock waits turned on. Then any lock wait longer than the deadlock timeout leaves a log line with the process holding the lock and the whole wait queue. That timeout is how long Postgres waits before checking for deadlocks, 1 second by default. Yeah. That's the receipt, instead of a hunch about the migration.

4:58 But here's what bugs me. The migration only adds an empty column. Why does it need the strongest table lock there is? Postgres's own code comment gives two reasons. The change is visible to every query on the table, so no reader can be partway through a query while it changes. And with some defaults, Postgres has to rewrite the whole table. But per the docs, when that column has no default, or a default that's the same for every row, Postgres only changes the table's definition. This one is cheap.

5:30 Cheap, but still visible to every SELECT, so readers still have to be out. And ALTER TABLE picks its lock before it even opens the table, so it couldn't go lighter if it wanted to. For a column add, that's access exclusive, every time. Then what you actually pay is: wait for every transaction that got there first, then a quick definition change. Yeah, and that first part has no upper bound by default. Take a transaction that read once and then sat idle. It still holds its lock the whole time. Which, honestly, describes half the connection pools I've debugged.

6:06 Only half? The other half, I caused. Let's say a checkout worker opens a transaction, reads the order, then calls a payment service that takes 10 seconds. If the migration lands in that window, every checkout behind it is blocked for the rest of those 10 seconds, which means one slow payment call turns into a checkout outage. Now the fix changes how long the migration is allowed to wait, not how fast it runs. Before the ALTER, set lock timeout, for example to 100 milliseconds. In our run, the migration gave up right on schedule, with "canceling statement due to lock timeout".

6:42 And the checkout that was already stuck in line behind it? Does it still wait out the whole report? No. Postgres pulls the quitter out of the line and immediately re-checks who's left, so that checkout, which showed up about 40 milliseconds after the migration, waited about 60 milliseconds instead of 2.7 seconds. Oh, nice. So the timeout rescues the reads already stuck behind it, not just the ones that arrive later. And the first thing a reviewer will ask is, "So now my deploy fails randomly?" Sometimes, yes, and that's the tradeoff.

7:14 On a busy table it might take a few attempts, so the retry needs a backoff and a limit. The timeout is the stall budget you choose for everyone else, and honestly, I think a failed deploy is the cheaper outage. And that timeout has to live somewhere, and not in postgresql dot conf. The docs warn a global lock timeout would affect every session. It belongs in the migration itself. Say it's a Django migration. What does that look like? Django runs each migration as one transaction on Postgres, so the first step can be a Run SQL step, a raw SQL statement, that sets a short local lock timeout.

7:50 Local means it ends with that transaction. And if the ALTER times out? The whole migration rolls back cleanly, nothing half applied, so you just rerun it. And once the ALTER does get its lock, it keeps it until everything in that migration commits, so keep slow backfills out of it. I'll admit, I always counted our statement timeout as covering this. Doesn't it? Only partly. It does count the wait, but say yours is 30 seconds: the migration can still hold the line for 30 seconds. Lock timeout caps just the wait, so you can make it tiny without ever cutting off the work itself.

8:26 Oh, man. So the statement timeout I trusted is really a 30-second stall budget for everyone in line. Right. And then there's that worker from earlier. Before a migration, I'd look in pg stat activity, the view of every connection and what it's doing, for anything sitting idle in a transaction. And in the code, commit before that 10-second payment call, not after. And Postgres even has a backstop, idle in transaction session timeout, which is off by default. Set it, and a session that sits idle inside a transaction too long gets ended instead of holding the line.

9:01 So if a quick migration freezes reads, the migration isn't slow. It's waiting, and everything behind it waits too. Yeah. Give every schema change a lock timeout, and look for the oldest open transaction first. Thanks for listening to Learning Podcasts.