<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>PostgreSQL on LoomLoops</title>
    <link>https://loomloops.com/tags/postgresql/</link>
    <description>PostgreSQL guides for backend engineers: how locks work, how to build a job queue with SKIP LOCKED, and the transactional outbox pattern.</description>
    <language>en-us</language>
    <lastBuildDate>Tue, 15 Sep 2026 07:55:00 +0000</lastBuildDate>
    <atom:link href="https://loomloops.com/tags/postgresql/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>The Transactional Outbox Pattern, Explained Simply</title>
      <link>https://loomloops.com/post/transactional-outbox-pattern/</link>
      <pubDate>Tue, 15 Sep 2026 07:55:00 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/transactional-outbox-pattern/</guid>
      <description>&lt;p&gt;Your order service saves a new order and then tells the rest of the company&#xA;about it by publishing an &lt;code&gt;order_created&lt;/code&gt; event to Kafka (or RabbitMQ, or&#xA;SNS). Billing listens. Shipping listens. Email listens.&lt;/p&gt;&#xA;&lt;p&gt;That is two writes to two different systems. Sooner or later one of them&#xA;works and the other doesn&amp;rsquo;t. This is called the &lt;strong&gt;dual write problem&lt;/strong&gt;, and&#xA;the transactional outbox is the standard fix. It needs one extra table and&#xA;one small background process.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Short version:&lt;/strong&gt;&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Don&amp;rsquo;t publish the event directly. Write it to an &lt;code&gt;outbox&lt;/code&gt; table in the same&#xA;database transaction as the order.&lt;/li&gt;&#xA;&lt;li&gt;A separate process reads the outbox and publishes the events.&lt;/li&gt;&#xA;&lt;li&gt;Events are delivered at least once, so consumers must handle duplicates.&#xA;In return, no event is ever lost, and no event is sent for data that was&#xA;never saved.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;the-dual-write-problem&#34;&gt;The dual write problem&lt;/h2&gt;&#xA;&lt;p&gt;Here is the code most services start with:&lt;/p&gt;&#xA;&lt;pre tabindex=&#34;0&#34;&gt;&lt;code&gt;save order to database&#xA;publish order_created to Kafka&#xA;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Look at what can go wrong between those two lines:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/dual-write-failures.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/dual-write-failures.svg&#34; alt=&#34;Two ways the dual write fails. Failure 1, lost event: the order is saved to the database, then publishing to Kafka fails because Kafka is down, so the order exists and shipping never hears about it. Failure 2, ghost event: the event is published to Kafka, then saving the order to the database fails, so billing charges for an order that does not exist.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;328&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Swapping the order of the two lines only swaps which failure you get. The&#xA;process can also crash between the lines, which has the same effect as&#xA;Kafka being down.&lt;/p&gt;&#xA;&lt;h3 id=&#34;cant-i-publish-after-the-transaction-commits&#34;&gt;&amp;ldquo;Can&amp;rsquo;t I publish after the transaction commits?&amp;rdquo;&lt;/h3&gt;&#xA;&lt;p&gt;That is failure 1. The commit worked, then the publish failed or the&#xA;process was killed during a deploy. The event is gone and nothing will ever&#xA;retry it.&lt;/p&gt;&#xA;&lt;h3 id=&#34;cant-i-use-a-distributed-transaction&#34;&gt;&amp;ldquo;Can&amp;rsquo;t I use a distributed transaction?&amp;rdquo;&lt;/h3&gt;&#xA;&lt;p&gt;In theory, two-phase commit (2PC, also called XA) makes two systems commit&#xA;together. In practice most message brokers don&amp;rsquo;t support it, and the ones&#xA;that do make every write slower and harder to run. Almost nobody does this&#xA;for events.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-fix-write-the-event-to-your-own-database&#34;&gt;The fix: write the event to your own database&lt;/h2&gt;&#xA;&lt;p&gt;Your database can already save several rows atomically. So save the event as&#xA;a row, next to the order:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/outbox-flow.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/outbox-flow.svg&#34; alt=&#34;The service runs one database transaction that inserts into the orders table and the outbox table, so both rows or neither are saved. A relay process reads the outbox table, sends each event to Kafka and marks it sent. Kafka delivers the events to consumers.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;352&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The order and the event now live or die together. If the transaction rolls&#xA;back, there is no event. If it commits, the event is safely stored, and the&#xA;relay will send it, even if Kafka is down for an hour.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-outbox-table&#34;&gt;The outbox table&lt;/h2&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; outbox (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  id             bigserial   &lt;span style=&#34;color:#ff79c6&#34;&gt;PRIMARY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  aggregate_type &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;order&amp;#39;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  aggregate_id   &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;881&amp;#39;, also the Kafka key&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  event_type     &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;order_created&amp;#39;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  payload        jsonb       &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  created_at     timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now(),&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  sent_at        timestamptz&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INDEX&lt;/span&gt; outbox_unsent_idx &lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; outbox (id) &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;IS&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&amp;ldquo;Aggregate&amp;rdquo; is a fancy word for &amp;ldquo;the thing the event is about&amp;rdquo;. Here it is&#xA;the order. &lt;code&gt;aggregate_id&lt;/code&gt; will matter when we talk about ordering.&lt;/p&gt;&#xA;&lt;p&gt;Writing an event is a plain insert inside your existing transaction:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; orders (id, customer_id, total) &lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#bd93f9&#34;&gt;881&lt;/span&gt;, &lt;span style=&#34;color:#bd93f9&#34;&gt;42&lt;/span&gt;, &lt;span style=&#34;color:#bd93f9&#34;&gt;25&lt;/span&gt;.&lt;span style=&#34;color:#bd93f9&#34;&gt;00&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; outbox (aggregate_type, aggregate_id, event_type, payload)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;order&amp;#39;&lt;/span&gt;, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;881&amp;#39;&lt;/span&gt;, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;order_created&amp;#39;&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;{&amp;#34;order_id&amp;#34;: 881, &amp;#34;customer_id&amp;#34;: 42, &amp;#34;total&amp;#34;: &amp;#34;25.00&amp;#34;}&amp;#39;&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;the-relay-two-ways-to-read-the-outbox&#34;&gt;The relay: two ways to read the outbox&lt;/h2&gt;&#xA;&lt;h3 id=&#34;option-1-polling&#34;&gt;Option 1: polling&lt;/h3&gt;&#xA;&lt;p&gt;A small loop asks the table for unsent events every second or so:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; id, aggregate_id, event_type, payload&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; outbox&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;IS&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; id&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;LIMIT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;100&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FOR&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; SKIP LOCKED;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- publish each row to Kafka and wait for Kafka to confirm&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; outbox &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;ANY&lt;/span&gt;($sent_ids);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;code&gt;FOR UPDATE SKIP LOCKED&lt;/code&gt; lets you run more than one relay without two of&#xA;them grabbing the same rows. It is the same trick used to build a &lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;job queue&#xA;in Postgres&lt;/a&gt;, and that post explains&#xA;how it works.&lt;/p&gt;&#xA;&lt;p&gt;One detail that catches people out: don&amp;rsquo;t track progress with &amp;ldquo;give me rows&#xA;with &lt;code&gt;id&lt;/code&gt; greater than the last one I sent&amp;rdquo;. A &lt;code&gt;bigserial&lt;/code&gt; id is handed out&#xA;when the row is inserted, not when the transaction commits. A slow&#xA;transaction can commit id 100 after id 101 is already sent, and a &amp;ldquo;greater&#xA;than&amp;rdquo; relay will skip 100 forever. Querying &lt;code&gt;sent_at IS NULL&lt;/code&gt; avoids that.&lt;/p&gt;&#xA;&lt;h3 id=&#34;option-2-change-data-capture-cdc&#34;&gt;Option 2: change data capture (CDC)&lt;/h3&gt;&#xA;&lt;p&gt;Every database keeps a log of changes for crash recovery and replication:&#xA;the WAL in Postgres, the binlog in MySQL and MariaDB. A CDC tool such as&#xA;&lt;a href=&#34;https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html&#34;&gt;Debezium&lt;/a&gt;&#xA;reads that log and publishes each new outbox row as it is committed. Your&#xA;code doesn&amp;rsquo;t poll at all.&lt;/p&gt;&#xA;&lt;h3 id=&#34;which-one&#34;&gt;Which one?&lt;/h3&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;&lt;/th&gt;&#xA;          &lt;th&gt;Polling&lt;/th&gt;&#xA;          &lt;th&gt;CDC (log reading)&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Setup&lt;/td&gt;&#xA;          &lt;td&gt;A loop in your service&lt;/td&gt;&#xA;          &lt;td&gt;A separate tool to run and watch&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Delay&lt;/td&gt;&#xA;          &lt;td&gt;Your poll interval (~1 second)&lt;/td&gt;&#xA;          &lt;td&gt;Usually under a second&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Load on DB&lt;/td&gt;&#xA;          &lt;td&gt;One small query per poll&lt;/td&gt;&#xA;          &lt;td&gt;Reads the log, no queries&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Commit order&lt;/td&gt;&#xA;          &lt;td&gt;Needs care (see above)&lt;/td&gt;&#xA;          &lt;td&gt;Follows commit order&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Best for&lt;/td&gt;&#xA;          &lt;td&gt;Starting out, most services&lt;/td&gt;&#xA;          &lt;td&gt;High volume, many services&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;Start with polling. It is boring and easy to debug. Move to CDC when you can&#xA;measure that polling delay or database load is a problem.&lt;/p&gt;&#xA;&lt;h2 id=&#34;duplicates-are-part-of-the-deal&#34;&gt;Duplicates are part of the deal&lt;/h2&gt;&#xA;&lt;p&gt;Look at the relay again. It publishes to Kafka, then marks the rows as sent.&#xA;What if it crashes between those two steps?&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/duplicate-timeline.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/duplicate-timeline.svg&#34; alt=&#34;Timeline of a relay crash between three columns: relay, Kafka and outbox row 77. The relay reads row 77 and publishes it, and Kafka stores event 77. The relay crashes before marking the row sent, so sent_at stays NULL. After the restart it reads row 77 again and publishes it again, and Kafka stores a second copy of event 77. Then it marks the row sent and sent_at becomes 10:04. The event went out twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;520&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The event went out twice. You can&amp;rsquo;t fully prevent this, so the outbox gives&#xA;you &lt;strong&gt;at-least-once&lt;/strong&gt; delivery: every event arrives, maybe more than once.&lt;/p&gt;&#xA;&lt;p&gt;The answer is to make consumers safe to repeat. Include a unique event id in&#xA;the payload (the outbox &lt;code&gt;id&lt;/code&gt; works), and have each consumer remember what it&#xA;has handled:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- in the consumer&amp;#39;s database&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; processed_events (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  event_id     &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;bigint&lt;/span&gt;      &lt;span style=&#34;color:#ff79c6&#34;&gt;PRIMARY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  processed_at timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; processed_events (event_id) &lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#bd93f9&#34;&gt;77&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; CONFLICT (event_id) &lt;span style=&#34;color:#ff79c6&#34;&gt;DO&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NOTHING&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;RETURNING event_id;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- no row returned: already handled, COMMIT and stop&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- row returned: do the work in this same transaction&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This is sometimes called an &amp;ldquo;inbox&amp;rdquo; table. It is the same idea as an&#xA;&lt;a href=&#34;https://loomloops.com/post/idempotency-keys-explained/&#34;&gt;idempotency key&lt;/a&gt;: save &amp;ldquo;I am handling&#xA;this&amp;rdquo; in the same transaction as the work.&lt;/p&gt;&#xA;&lt;h2 id=&#34;ordering-same-order-same-key&#34;&gt;Ordering: same order, same key&lt;/h2&gt;&#xA;&lt;p&gt;Consumers often care about order. &lt;code&gt;order_shipped&lt;/code&gt; arriving before&#xA;&lt;code&gt;order_created&lt;/code&gt; will confuse shipping.&lt;/p&gt;&#xA;&lt;p&gt;Two rules keep the order right:&lt;/p&gt;&#xA;&lt;ol&gt;&#xA;&lt;li&gt;&lt;strong&gt;Publish with &lt;code&gt;aggregate_id&lt;/code&gt; as the message key.&lt;/strong&gt; Kafka keeps messages&#xA;with the same key in one partition, in order. Events for order 881 stay&#xA;in order, while events for different orders can be handled in parallel.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Don&amp;rsquo;t let two relays send events for the same order at the same time.&lt;/strong&gt;&#xA;With several polling relays and &lt;code&gt;SKIP LOCKED&lt;/code&gt;, relay A might hold&#xA;&lt;code&gt;order_created&lt;/code&gt; while relay B sends &lt;code&gt;order_shipped&lt;/code&gt; for the same order.&#xA;Either run one relay, or split rows between relays by&#xA;&lt;code&gt;hash(aggregate_id)&lt;/code&gt; so each order always goes through the same relay.&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/ordering-by-aggregate-id.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/ordering-by-aggregate-id.svg&#34; alt=&#34;Three orders flow through relays to Kafka partitions, each in order. Order 881 goes through relay 1 to partition p3 as created, paid, shipped. Order 882 goes through relay 2 to partition p0 as created, cancelled. Order 883 goes through relay 1 to partition p3 as created.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;272&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Order is only kept per order, not across all orders. That is almost always&#xA;what you want, and it is what lets you scale.&lt;/p&gt;&#xA;&lt;h2 id=&#34;keeping-the-outbox-small&#34;&gt;Keeping the outbox small&lt;/h2&gt;&#xA;&lt;p&gt;The outbox only needs to hold events until they are sent. Delete sent rows&#xA;on a schedule:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;DELETE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; outbox&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;interval&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;3 days&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Keeping a few days helps when you need to check what was sent. In Postgres,&#xA;a table that gets lots of inserts and deletes also needs autovacuum to keep&#xA;up. The same tuning tips from the &lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;job queue&#xA;post&lt;/a&gt; apply.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-one-metric-to-watch-outbox-lag&#34;&gt;The one metric to watch: outbox lag&lt;/h2&gt;&#xA;&lt;p&gt;If the relay stops, nothing errors. Orders save fine. Events just stop&#xA;flowing, and you find out when a customer asks where their parcel is.&lt;/p&gt;&#xA;&lt;p&gt;So watch the age of the oldest unsent event:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;min&lt;/span&gt;(created_at) &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; outbox_lag,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;       &lt;span style=&#34;color:#ff79c6&#34;&gt;count&lt;/span&gt;(&lt;span style=&#34;color:#ff79c6&#34;&gt;*&lt;/span&gt;)                &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; unsent&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; outbox&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;IS&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/outbox-lag-scale.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/outbox-lag-scale.svg&#34; alt=&#34;Outbox lag scale. Under 5 seconds: healthy. 30 seconds to a few minutes: relay slow, or broker struggling. Growing steadily: relay stopped or stuck, page someone. Unsent equals 0: fine, lag shows NULL.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;346&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Alert when the lag passes a limit that fits your business, for example two&#xA;minutes.&lt;/p&gt;&#xA;&lt;h2 id=&#34;when-you-dont-need-an-outbox&#34;&gt;When you don&amp;rsquo;t need an outbox&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Only one system is involved.&lt;/strong&gt; If the consumer reads the same database,&#xA;a &lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;job in a jobs table&lt;/a&gt; does the&#xA;same thing with less machinery.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Losing an event is fine.&lt;/strong&gt; Analytics clicks, &amp;ldquo;user viewed page&amp;rdquo; counters.&#xA;Fire and forget is simpler.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;The event is the source of truth.&lt;/strong&gt; In event sourcing, you write only the&#xA;event, so there is no second write to keep in sync.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;questions-people-ask&#34;&gt;Questions people ask&lt;/h2&gt;&#xA;&lt;p&gt;&lt;strong&gt;Is the outbox the same as event sourcing?&lt;/strong&gt;&#xA;No. With an outbox, your normal tables are the truth and events are&#xA;announcements about changes. With event sourcing, the events themselves are&#xA;the truth.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Doesn&amp;rsquo;t this double my database writes?&lt;/strong&gt;&#xA;Each event adds one insert, and later one update and one delete. For most&#xA;services that is small next to the business writes. If it ever matters, CDC&#xA;removes the update, because it doesn&amp;rsquo;t need a &lt;code&gt;sent_at&lt;/code&gt; column.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Can the relay live inside my service?&lt;/strong&gt;&#xA;Yes, and that is the easy way to start. Run it as a background loop. With&#xA;&lt;code&gt;SKIP LOCKED&lt;/code&gt;, every copy of your service can run one safely, as long as you&#xA;handle the ordering rule above.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;What about MySQL?&lt;/strong&gt;&#xA;The pattern is the same. MySQL 8.0 supports &lt;code&gt;SKIP LOCKED&lt;/code&gt; for polling, and&#xA;Debezium can read the MySQL binlog for CDC.&lt;/p&gt;&#xA;&lt;h2 id=&#34;cheat-sheet&#34;&gt;Cheat sheet&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/cheat-sheet.svg&#34; alt=&#34;Transactional outbox in one page. Problem: a database write and a broker publish cannot commit together. Fix: insert the event into the outbox table in the same transaction. Relay: poll WHERE sent_at IS NULL with SKIP LOCKED, or use CDC from the WAL or binlog. Never: track progress with id greater than last sent. Delivery: at least once, so consumers dedupe by event id. Ordering: message key is aggregate_id, one relay per key. Cleanup: delete rows sent more than a few days ago. Watch: outbox lag is now() minus the oldest unsent created_at.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;464&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;h2 id=&#34;further-reading&#34;&gt;Further reading&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://microservices.io/patterns/data/transactional-outbox&#34;&gt;microservices.io: Transactional outbox&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html&#34;&gt;AWS Prescriptive Guidance: Transactional outbox pattern&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html&#34;&gt;Debezium: Outbox Event Router&lt;/a&gt;&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;</description>
    </item>
    <item>
      <title>Idempotency Keys Explained: How to Make API Retries Safe</title>
      <link>https://loomloops.com/post/idempotency-keys-explained/</link>
      <pubDate>Thu, 04 Jun 2026 09:20:00 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/idempotency-keys-explained/</guid>
      <description>&lt;p&gt;A customer taps &amp;ldquo;Pay&amp;rdquo;. Your app sends the payment request. The phone loses&#xA;signal for a moment and the request times out. The app does the sensible&#xA;thing and tries again. The customer gets charged twice.&lt;/p&gt;&#xA;&lt;p&gt;Nothing here was a bug in the usual sense. The network did what networks do,&#xA;and the client did what clients should do. The missing piece was a way for&#xA;the server to recognise &amp;ldquo;this is the same request I already handled&amp;rdquo;.&lt;/p&gt;&#xA;&lt;p&gt;That piece is called an &lt;strong&gt;idempotency key&lt;/strong&gt;. Stripe, Shopify, Adyen, PayPal&#xA;and most banking APIs use one. This post explains the idea, then builds the&#xA;server side step by step.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Short version:&lt;/strong&gt;&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;The client makes up a unique key for each action, like &amp;ldquo;pay order 881&amp;rdquo;,&#xA;and sends it with every retry of that action.&lt;/li&gt;&#xA;&lt;li&gt;The server saves the key with the result. If the same key comes again, it&#xA;returns the saved result instead of doing the work again.&lt;/li&gt;&#xA;&lt;li&gt;Save the key before doing the work, in the same transaction when you can.&#xA;That is what makes the whole thing safe.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;the-problem-a-timeout-tells-you-nothing&#34;&gt;The problem: a timeout tells you nothing&lt;/h2&gt;&#xA;&lt;p&gt;When a request times out, the client cannot tell which of these happened:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/timeout-two-cases.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/timeout-two-cases.svg&#34; alt=&#34;Two timelines between a client and a server. Case A: the request is lost on the way, the server never sees it, the client times out, and a retry is correct. Case B: the server gets the request and charges the card, but the response is lost, the client times out, and a retry charges twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;388&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;From the client&amp;rsquo;s side, A and B look the same. If it never retries, case A&#xA;leaves a customer who wanted to pay with no order. If it always retries, case&#xA;B charges them twice. You need the server to make retries safe.&lt;/p&gt;&#xA;&lt;h2 id=&#34;what-idempotent-means&#34;&gt;What &amp;ldquo;idempotent&amp;rdquo; means&lt;/h2&gt;&#xA;&lt;p&gt;An action is idempotent when doing it twice has the same effect as doing it&#xA;once. Pressing a lift button is idempotent. Pressing it five more times does&#xA;not call five lifts.&lt;/p&gt;&#xA;&lt;p&gt;HTTP already defines some methods this way (&lt;a href=&#34;https://www.rfc-editor.org/rfc/rfc9110#name-idempotent-methods&#34;&gt;RFC 9110&lt;/a&gt;):&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Method&lt;/th&gt;&#xA;          &lt;th&gt;Idempotent?&lt;/th&gt;&#xA;          &lt;th&gt;Why&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;GET&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Yes&lt;/td&gt;&#xA;          &lt;td&gt;Reading twice changes nothing&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;PUT&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Yes&lt;/td&gt;&#xA;          &lt;td&gt;&amp;ldquo;Set the name to Sam&amp;rdquo; twice leaves the name as Sam&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;DELETE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Yes&lt;/td&gt;&#xA;          &lt;td&gt;Deleting a deleted thing leaves it deleted&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;POST&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;strong&gt;No&lt;/strong&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&amp;ldquo;Create a payment&amp;rdquo; twice creates two payments&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;PATCH&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Not always&lt;/td&gt;&#xA;          &lt;td&gt;&amp;ldquo;Add 10 to the balance&amp;rdquo; twice adds 20&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;Idempotency keys exist to make &lt;code&gt;POST&lt;/code&gt; (and risky &lt;code&gt;PATCH&lt;/code&gt;) calls behave like&#xA;the safe ones.&lt;/p&gt;&#xA;&lt;h2 id=&#34;how-an-idempotency-key-works&#34;&gt;How an idempotency key works&lt;/h2&gt;&#xA;&lt;p&gt;The client sends a header with a value it generated, usually a random UUID:&lt;/p&gt;&#xA;&lt;pre tabindex=&#34;0&#34;&gt;&lt;code&gt;POST /payments&#xA;Idempotency-Key: 6f1c2a9e-4b7d-4d3e-9a51-0c8e2f3b7d10&#xA;Content-Type: application/json&#xA;&#xA;{&amp;#34;order_id&amp;#34;: 881, &amp;#34;amount&amp;#34;: &amp;#34;25.00&amp;#34;, &amp;#34;currency&amp;#34;: &amp;#34;EUR&amp;#34;}&#xA;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The server keeps a small table of keys it has seen:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/how-a-key-works.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/how-a-key-works.svg&#34; alt=&#34;Two flows side by side. First request: the client sends POST with key K, the server checks whether K was seen before (no), saves K as started, charges the card, saves the response with K, and returns 201 Created. Retry with the same key: the server finds that K was seen before (yes), reads the saved response, and returns 201 Created with the same body, so the card is charged once.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;484&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;There is an &lt;a href=&#34;https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/&#34;&gt;IETF draft for the &lt;code&gt;Idempotency-Key&lt;/code&gt;&#xA;header&lt;/a&gt;&#xA;that writes down the common behaviour, so you don&amp;rsquo;t have to invent your own&#xA;rules.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-four-cases-your-server-must-handle&#34;&gt;The four cases your server must handle&lt;/h2&gt;&#xA;&lt;p&gt;This table is the whole design. Print it out.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/four-cases.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/four-cases.svg&#34; alt=&#34;A table of the four cases the server must handle. New key: run the request, save the result. Done key with the same body: return the saved result again, even if it was an error. Key still running: 409 Conflict, try again shortly. Key seen with a different body: 422, this key was used for a different request.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;368&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The last row catches a real bug: a client that reuses one key for two&#xA;different actions. Without the check, the second payment would silently&#xA;return the first payment&amp;rsquo;s result, and nobody would notice until the&#xA;accounts don&amp;rsquo;t add up. To check it, store a hash of the request body with&#xA;the key.&lt;/p&gt;&#xA;&lt;h2 id=&#34;building-it-in-postgres&#34;&gt;Building it in Postgres&lt;/h2&gt;&#xA;&lt;h3 id=&#34;the-table&#34;&gt;The table&lt;/h3&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; idempotency_keys (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  account_id    &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;bigint&lt;/span&gt;      &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;           &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  request_hash  &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- sha256 of method + path + body&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  status        &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;started&amp;#39; | &amp;#39;finished&amp;#39;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  response_code &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;int&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  response_body jsonb,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  created_at    timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now(),&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;PRIMARY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt; (account_id, &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The key is scoped to the account. Two customers who happen to send the same&#xA;UUID don&amp;rsquo;t clash, and one customer cannot replay another customer&amp;rsquo;s response&#xA;by guessing their key.&lt;/p&gt;&#xA;&lt;h3 id=&#34;case-1-all-the-work-happens-in-your-database&#34;&gt;Case 1: all the work happens in your database&lt;/h3&gt;&#xA;&lt;p&gt;If &amp;ldquo;do the request&amp;rdquo; only means writing rows to the same database, this is&#xA;easy. Put everything in one transaction:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; idempotency_keys (account_id, &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;, request_hash, status)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; ($account, $&lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;, $hash, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;started&amp;#39;&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; CONFLICT (account_id, &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;) &lt;span style=&#34;color:#ff79c6&#34;&gt;DO&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NOTHING&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;RETURNING &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- No row returned? The key exists. ROLLBACK, then read the saved row&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- and follow the four-case table.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; orders (account_id, order_id, amount) &lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (...);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; idempotency_keys&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;finished&amp;#39;&lt;/span&gt;, response_code &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;201&lt;/span&gt;, response_body &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $response&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; account_id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $account &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Postgres quietly handles the hard race for you here. If two copies of the&#xA;same request arrive at the same moment, the second &lt;code&gt;INSERT ... ON CONFLICT&lt;/code&gt;&#xA;waits until the first transaction ends. If the first one commits, the second&#xA;sees the key and returns the saved response. If the first one rolls back,&#xA;the second goes ahead as if it came first. No double order either way.&lt;/p&gt;&#xA;&lt;h3 id=&#34;case-2-the-work-calls-someone-else&#34;&gt;Case 2: the work calls someone else&lt;/h3&gt;&#xA;&lt;p&gt;Now the hard one. Your endpoint charges a card through a payment provider.&#xA;That call is outside your database, so you cannot roll it back.&lt;/p&gt;&#xA;&lt;p&gt;You can&amp;rsquo;t hold a transaction open across a slow network call (it ties up a&#xA;connection and can block database cleanup). So you split the work into&#xA;steps and save progress between them:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/provider-steps.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/provider-steps.svg&#34; alt=&#34;Three steps for a request that calls a payment provider. Step 1: begin, insert the key as started, commit. The decision is now saved. Step 2: call the provider, passing your key along. Step 3: begin, save the providers answer and your order, mark the key finished with the response, commit.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;316&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The important trick is in step 2: &lt;strong&gt;pass the idempotency key on to the&#xA;provider&lt;/strong&gt;. Most payment providers accept one. Now think about a crash:&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Crash happens&lt;/th&gt;&#xA;          &lt;th&gt;What the retry sees&lt;/th&gt;&#xA;          &lt;th&gt;What it does&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Before step 1 commits&lt;/td&gt;&#xA;          &lt;td&gt;No key&lt;/td&gt;&#xA;          &lt;td&gt;Starts fresh. Nothing was charged&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Between step 1 and 2&lt;/td&gt;&#xA;          &lt;td&gt;Key &lt;code&gt;started&lt;/code&gt;, old&lt;/td&gt;&#xA;          &lt;td&gt;Calls the provider. Not charged yet, so this charges once&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Between step 2 and 3&lt;/td&gt;&#xA;          &lt;td&gt;Key &lt;code&gt;started&lt;/code&gt;, old&lt;/td&gt;&#xA;          &lt;td&gt;Calls the provider again &lt;strong&gt;with the same key&lt;/strong&gt;. The provider returns the first charge instead of making a new one&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;After step 3&lt;/td&gt;&#xA;          &lt;td&gt;Key &lt;code&gt;finished&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Returns the saved response&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;Every row ends with exactly one charge. That works only because the key&#xA;travels through every system that has a side effect.&lt;/p&gt;&#xA;&lt;p&gt;How does a retry know a &lt;code&gt;started&lt;/code&gt; key is &amp;ldquo;old&amp;rdquo; and not still running? Use&#xA;&lt;code&gt;created_at&lt;/code&gt;. If it is older than your request timeout (say 60 seconds), the&#xA;first attempt is dead and the retry can take over. If it is newer, answer&#xA;409 and let the client try again in a moment.&lt;/p&gt;&#xA;&lt;p&gt;Brandur Leach wrote a longer version of this with more steps, called&#xA;&lt;a href=&#34;https://brandur.org/idempotency-keys&#34;&gt;recovery points&lt;/a&gt;. It is worth reading&#xA;if your endpoint calls more than one outside system.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-client-side&#34;&gt;The client side&lt;/h2&gt;&#xA;&lt;p&gt;The server can only help if the client sends the key correctly. The most&#xA;common mistake:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/client-keys.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/client-keys.svg&#34; alt=&#34;Two ways a client can choose keys. Wrong, a new key per attempt: attempt 1 uses key a1b2 and times out, attempt 2 uses key c3d4 and is charged, attempt 3 uses key e5f6 and is charged again. Right, one key per action: attempt 1 uses key a1b2 and times out, attempts 2 and 3 reuse a1b2 and get the saved result.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;312&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Generate the key when the user decides to act (taps &amp;ldquo;Pay&amp;rdquo;), store it with the&#xA;pending action, and reuse it for every retry. If the app restarts mid-retry,&#xA;it should pick up the same key from storage.&lt;/p&gt;&#xA;&lt;p&gt;Also:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Retry with growing waits plus a bit of randomness (for example 1s, 2s, 4s,&#xA;each plus up to 1s random). Without the randomness, thousands of clients&#xA;that failed together all retry at the same instant.&lt;/li&gt;&#xA;&lt;li&gt;Only retry on timeouts, connection errors, 409 and 5xx. A 400 or 422 will&#xA;fail the same way every time.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;how-long-to-keep-keys&#34;&gt;How long to keep keys&lt;/h2&gt;&#xA;&lt;p&gt;Keys don&amp;rsquo;t need to live forever. They only need to outlive any realistic&#xA;retry. &lt;a href=&#34;https://docs.stripe.com/api/idempotent_requests&#34;&gt;Stripe keeps them for at least 24&#xA;hours&lt;/a&gt;. Pick a window,&#xA;document it, and delete older rows with a daily job:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;DELETE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; idempotency_keys&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; created_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;interval&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;24 hours&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;mistakes-i-see-often&#34;&gt;Mistakes I see often&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Saving the key after the work.&lt;/strong&gt; If you crash in between, the retry finds&#xA;no key and does the work again. Save the decision first.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Keeping keys in a cache that can lose them.&lt;/strong&gt; If the key lives in Redis&#xA;and Redis restarts, your protection is gone. Keep the key in the same&#xA;database as the data it protects.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Not saving errors.&lt;/strong&gt; If the first attempt failed validation, a retry with&#xA;the same key should get the same error, not a fresh run. Some APIs choose&#xA;not to save 5xx errors so a retry can succeed. Either is fine if you&#xA;document it.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;No body hash.&lt;/strong&gt; Reusing a key for a different request should fail loudly,&#xA;not return the wrong result.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Global keys.&lt;/strong&gt; Scope keys to the caller, or one client can read another&#xA;client&amp;rsquo;s responses.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;you-dont-always-need-a-key&#34;&gt;You don&amp;rsquo;t always need a key&lt;/h2&gt;&#xA;&lt;p&gt;Sometimes the request already carries something unique. Then a &lt;code&gt;UNIQUE&lt;/code&gt;&#xA;constraint does the job:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;A message consumer can store each message id in a &lt;code&gt;processed_messages&lt;/code&gt;&#xA;table with a unique index, and skip ids it has seen. This is the usual&#xA;partner for the &lt;a href=&#34;https://loomloops.com/post/transactional-outbox-pattern/&#34;&gt;transactional outbox&#xA;pattern&lt;/a&gt;, which delivers messages at&#xA;least once.&lt;/li&gt;&#xA;&lt;li&gt;A background job can use the job id the same way. Jobs in a &lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;Postgres job&#xA;queue&lt;/a&gt; can run twice after a crash,&#xA;so they need this.&lt;/li&gt;&#xA;&lt;li&gt;&amp;ldquo;Create the invoice for order 881&amp;rdquo; can use &lt;code&gt;UNIQUE (order_id)&lt;/code&gt; on the&#xA;invoices table.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;An idempotency key is what you use when the request has no natural unique&#xA;value, which is the usual case for &amp;ldquo;create a new thing&amp;rdquo; endpoints.&lt;/p&gt;&#xA;&lt;h2 id=&#34;questions-people-ask&#34;&gt;Questions people ask&lt;/h2&gt;&#xA;&lt;p&gt;&lt;strong&gt;Who creates the key, client or server?&lt;/strong&gt;&#xA;The client. Only the client knows that attempt 2 is a retry of attempt 1.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Should the key be a UUID?&lt;/strong&gt;&#xA;Any random string with enough length works. UUID v4 is the easy choice. Don&amp;rsquo;t&#xA;build keys from timestamps or counters, because two devices can produce the&#xA;same one.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Is PUT enough instead of POST with a key?&lt;/strong&gt;&#xA;Sometimes. If the client can choose the new resource&amp;rsquo;s id (&lt;code&gt;PUT /payments/6f1c...&lt;/code&gt;), the id itself acts as the key. Many APIs prefer POST&#xA;plus a key so the server keeps control of ids.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does this give &amp;ldquo;exactly once&amp;rdquo;?&lt;/strong&gt;&#xA;It gives &amp;ldquo;the effect happens once&amp;rdquo;, which is what users care about. Under the&#xA;hood, requests still arrive more than once. The key makes the extra copies&#xA;harmless.&lt;/p&gt;&#xA;&lt;h2 id=&#34;cheat-sheet&#34;&gt;Cheat sheet&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/cheat-sheet.svg&#34; alt=&#34;Cheat sheet, idempotency keys in one page. Header: Idempotency-Key: uuid. Who: the client makes it, once per user action. Store: (account_id, key) PRIMARY KEY plus a body hash. New key: run, save response. Done key: return saved response. Running: 409, client retries soon. Body diff: 422, key reused for a different request. Order: save the key BEFORE the side effect. Outside: pass your key on to the payment provider. Keep: 24 hours or more, then delete.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;488&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;h2 id=&#34;further-reading&#34;&gt;Further reading&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/&#34;&gt;IETF draft: The Idempotency-Key HTTP Header Field&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://docs.stripe.com/api/idempotent_requests&#34;&gt;Stripe API docs: idempotent requests&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://brandur.org/idempotency-keys&#34;&gt;Brandur Leach: Implementing Stripe-like idempotency keys in Postgres&lt;/a&gt;&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;</description>
    </item>
    <item>
      <title>Postgres as a Job Queue: How SKIP LOCKED Works (and When It Breaks)</title>
      <link>https://loomloops.com/post/postgres-job-queue-skip-locked/</link>
      <pubDate>Tue, 17 Mar 2026 08:40:00 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/postgres-job-queue-skip-locked/</guid>
      <description>&lt;p&gt;You need background jobs. Send the welcome email, resize the photo, call the&#xA;slow partner API. The usual answer is &amp;ldquo;add Redis and a queue library&amp;rdquo;. That is&#xA;one more server to run, watch, back up and pay for.&lt;/p&gt;&#xA;&lt;p&gt;If you already use PostgreSQL, you can run a solid job queue inside it. The&#xA;key is two words in a &lt;code&gt;SELECT&lt;/code&gt;: &lt;code&gt;SKIP LOCKED&lt;/code&gt;. This post shows how it works,&#xA;gives you a schema you can copy, and then spends real time on the part most&#xA;posts skip: how it fails when traffic grows.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Short version:&lt;/strong&gt;&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;code&gt;FOR UPDATE SKIP LOCKED&lt;/code&gt; lets many workers pull jobs from one table without&#xA;ever picking the same job twice.&lt;/li&gt;&#xA;&lt;li&gt;The big win over Redis: you can add a job in the same transaction as your&#xA;business data. Either both are saved or neither is.&lt;/li&gt;&#xA;&lt;li&gt;It breaks in three ways: table bloat, long transactions, and too many&#xA;workers fighting over the same rows. All three are easy to watch for.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;the-problem-two-workers-one-job&#34;&gt;The problem: two workers, one job&lt;/h2&gt;&#xA;&lt;p&gt;Say you have a &lt;code&gt;jobs&lt;/code&gt; table and two workers. Each one runs &amp;ldquo;give me the oldest&#xA;pending job&amp;rdquo;. Without any locking, this happens:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/race-without-locks.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/race-without-locks.svg&#34; alt=&#34;Timeline: worker A reads job 42, then worker B also reads job 42 before A marks it running. Both mark it running and both send the welcome email, so the user gets it twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;400&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Both workers read the row before either one changed it. The classic fix is&#xA;&lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt;, which locks the row. Now worker B waits for worker A.&#xA;That stops the double send, but your workers now queue up behind each other.&#xA;Ten workers act like one.&lt;/p&gt;&#xA;&lt;h2 id=&#34;what-skip-locked-does&#34;&gt;What SKIP LOCKED does&lt;/h2&gt;&#xA;&lt;p&gt;&lt;code&gt;SKIP LOCKED&lt;/code&gt; tells Postgres: &amp;ldquo;if a row is already locked by someone else,&#xA;don&amp;rsquo;t wait for it. Pretend it isn&amp;rsquo;t there and give me the next one.&amp;rdquo;&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/skip-locked-workers.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/skip-locked-workers.svg&#34; alt=&#34;Three workers and a jobs table. Worker A locks job 41, worker B skips 41 and locks 42, worker C skips 41 and 42 and locks 43. Jobs 44 and 45 stay free. Each worker gets a different job and nobody waits.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;400&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;That is the whole trick. It has been in PostgreSQL since version 9.5 (2016),&#xA;so any Postgres you run today has it. The &lt;a href=&#34;https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE&#34;&gt;PostgreSQL docs on the locking&#xA;clause&lt;/a&gt;&#xA;describe it, and they say plainly that it is meant for queue-like tables,&#xA;because it gives you an inconsistent view of the data on purpose.&lt;/p&gt;&#xA;&lt;h2 id=&#34;a-schema-you-can-copy&#34;&gt;A schema you can copy&lt;/h2&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; jobs (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  id           bigserial   &lt;span style=&#34;color:#ff79c6&#34;&gt;PRIMARY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  kind         &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,          &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;send_email&amp;#39;, &amp;#39;resize_image&amp;#39;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  payload      jsonb       &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  status       &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                              &lt;span style=&#34;color:#6272a4&#34;&gt;-- pending | running | done | dead&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  run_at       timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now(),&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  attempts     &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;int&lt;/span&gt;         &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;0&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  max_attempts &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;int&lt;/span&gt;         &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;5&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  locked_until timestamptz,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  last_error   &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  created_at   timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- Only pending jobs are in this index, so it stays small&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- even when the table holds millions of finished jobs.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INDEX&lt;/span&gt; jobs_pending_idx &lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; jobs (run_at) &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;A few choices worth explaining:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;code&gt;run_at&lt;/code&gt; lets you schedule a job for later, and it is also how retries back&#xA;off. A failed job gets &lt;code&gt;run_at = now() + 1 minute&lt;/code&gt;, then 4 minutes, and so on.&lt;/li&gt;&#xA;&lt;li&gt;&lt;code&gt;locked_until&lt;/code&gt; is a lease. More on that below.&lt;/li&gt;&#xA;&lt;li&gt;The partial index (&lt;code&gt;WHERE status = &#39;pending&#39;&lt;/code&gt;) matters more than it looks.&#xA;Workers only ever search pending jobs, and there are usually few of them.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;claiming-a-job&#34;&gt;Claiming a job&lt;/h2&gt;&#xA;&lt;p&gt;There are two styles. Pick one.&lt;/p&gt;&#xA;&lt;h3 id=&#34;style-1-hold-the-transaction-open&#34;&gt;Style 1: hold the transaction open&lt;/h3&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; id, kind, payload&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; run_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;=&lt;/span&gt; now()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; run_at&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;LIMIT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FOR&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; SKIP LOCKED;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- ... the worker does the job here, while the row stays locked ...&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;done&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The nice part: if the worker crashes, its connection drops, Postgres rolls the&#xA;transaction back, and the row is free again. Crash recovery comes for free.&lt;/p&gt;&#xA;&lt;p&gt;The bad part: every running job holds a database connection and an open&#xA;transaction for as long as the job takes. A 30 second job means a 30 second&#xA;transaction. We will see why that hurts in the &amp;ldquo;when it breaks&amp;rdquo; section.&lt;/p&gt;&#xA;&lt;h3 id=&#34;style-2-take-a-lease-then-let-go&#34;&gt;Style 2: take a lease, then let go&lt;/h3&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status       &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;running&amp;#39;&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    attempts     &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; attempts &lt;span style=&#34;color:#ff79c6&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;interval&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;5 minutes&amp;#39;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; id&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; run_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;=&lt;/span&gt; now()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; run_at&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;LIMIT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;FOR&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; SKIP LOCKED&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;RETURNING id, kind, payload, attempts;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This claims the job in one short statement and commits right away. The worker&#xA;then does the job with no transaction open. When it finishes:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;done&amp;#39;&lt;/span&gt;, locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; attempts &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;;   &lt;span style=&#34;color:#6272a4&#34;&gt;-- only if we still own it&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;That &lt;code&gt;attempts = $2&lt;/code&gt; check is important. If the worker took longer than the&#xA;lease, another worker may have picked the job up again. The check stops the&#xA;slow worker from marking someone else&amp;rsquo;s attempt as done.&lt;/p&gt;&#xA;&lt;p&gt;Something has to rescue jobs whose worker died. Run this every minute from any&#xA;worker:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;, locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;running&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; now();&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Here is how a lease plays out when a worker dies:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/lease-timeline.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/lease-timeline.svg&#34; alt=&#34;Lease timeline. 10:00 worker A claims job 42 with a lease until 10:05. 10:02 worker A crashes with the job half done. 10:05 the lease expires. 10:06 the sweeper sets job 42 back to pending and worker B claims it with attempts set to 2. 10:07 worker B finishes. Job 42 ran twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;400&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Notice that job 42 ran twice, or at least partly twice. With leases, a job can&#xA;always run more than once. So write jobs that are safe to repeat. The post on&#xA;&lt;a href=&#34;https://loomloops.com/post/idempotency-keys-explained/&#34;&gt;idempotency keys&lt;/a&gt; shows how.&lt;/p&gt;&#xA;&lt;h3 id=&#34;which-style-should-you-use&#34;&gt;Which style should you use?&lt;/h3&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;&lt;/th&gt;&#xA;          &lt;th&gt;Hold transaction&lt;/th&gt;&#xA;          &lt;th&gt;Lease&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Crash recovery&lt;/td&gt;&#xA;          &lt;td&gt;Automatic&lt;/td&gt;&#xA;          &lt;td&gt;Needs a sweeper&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Connections used&lt;/td&gt;&#xA;          &lt;td&gt;One per running job&lt;/td&gt;&#xA;          &lt;td&gt;Only while claiming&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Long jobs (&amp;gt; a few seconds)&lt;/td&gt;&#xA;          &lt;td&gt;Hurts the whole database&lt;/td&gt;&#xA;          &lt;td&gt;Fine&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Can a job run twice?&lt;/td&gt;&#xA;          &lt;td&gt;Rarely&lt;/td&gt;&#xA;          &lt;td&gt;Yes, after a lease expires&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Best for&lt;/td&gt;&#xA;          &lt;td&gt;Short jobs, low volume&lt;/td&gt;&#xA;          &lt;td&gt;Most real workloads&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;My default is the lease. Jobs that call other services are slow, and slow&#xA;transactions cause the worst problems in Postgres.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-best-part-enqueue-in-the-same-transaction&#34;&gt;The best part: enqueue in the same transaction&lt;/h2&gt;&#xA;&lt;p&gt;This is the feature that a separate Redis queue cannot give you.&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; users (email) &lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;sam@example.com&amp;#39;&lt;/span&gt;) RETURNING id;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; jobs (kind, payload)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;send_welcome_email&amp;#39;&lt;/span&gt;, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;{&amp;#34;user_id&amp;#34;: 1001}&amp;#39;&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Either the user and the job are both saved, or neither is. Compare that with a&#xA;separate queue:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/same-transaction.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/same-transaction.svg&#34; alt=&#34;Two panels. With a separate queue, saving the user to the database works but pushing the job to Redis fails, so the user exists with no welcome email. With a jobs table, save user and save job sit inside one BEGIN and COMMIT, so both are saved or neither is.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;360&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The reverse also happens with a separate queue: the job is pushed, then the&#xA;database transaction rolls back, and a worker emails a user who does not&#xA;exist. The &lt;a href=&#34;https://loomloops.com/post/transactional-outbox-pattern/&#34;&gt;transactional outbox post&lt;/a&gt;&#xA;goes deeper into this &amp;ldquo;two writes&amp;rdquo; problem.&lt;/p&gt;&#xA;&lt;h2 id=&#34;waking-workers-up-polling-vs-listennotify&#34;&gt;Waking workers up: polling vs LISTEN/NOTIFY&lt;/h2&gt;&#xA;&lt;p&gt;Workers need to know when a new job shows up. Two options:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Polling.&lt;/strong&gt; Each worker runs the claim query every second or so. Simple&#xA;and reliable. With the partial index, an empty check costs very little.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;LISTEN/NOTIFY.&lt;/strong&gt; Workers run &lt;code&gt;LISTEN jobs_ready;&lt;/code&gt;. Whoever inserts a job&#xA;also runs &lt;code&gt;NOTIFY jobs_ready;&lt;/code&gt;. The notice is only sent when the transaction&#xA;commits, so a worker never wakes up for a job it can&amp;rsquo;t see yet.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;Use NOTIFY to wake workers faster, but keep a slow poll (every 5 to 10&#xA;seconds) as a safety net. Notices are not stored. A worker that was&#xA;restarting when the notice went out never gets it. Also, under heavy write&#xA;load, &lt;code&gt;NOTIFY&lt;/code&gt; takes a lock at commit time that is shared across the whole&#xA;database, and some teams have hit that at scale. If you insert thousands of&#xA;jobs a second, measure before you rely on it.&lt;/p&gt;&#xA;&lt;h2 id=&#34;retries-and-dead-jobs&#34;&gt;Retries and dead jobs&lt;/h2&gt;&#xA;&lt;p&gt;When a job fails, record the error and push it into the future:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status       &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;CASE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;WHEN&lt;/span&gt; attempts &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;gt;=&lt;/span&gt; max_attempts&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                        &lt;span style=&#34;color:#ff79c6&#34;&gt;THEN&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;dead&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;ELSE&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;END&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    run_at       &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;+&lt;/span&gt; (&lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;interval&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;1 minute&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;*&lt;/span&gt; power(&lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;, attempts)),&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    last_error   &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;With &lt;code&gt;power(2, attempts)&lt;/code&gt;, the waits are 2, 4, 8, 16 minutes. After five tries&#xA;the job is &lt;code&gt;dead&lt;/code&gt;, and a person looks at it. Dead jobs are your alarm. Put a&#xA;count of them on a dashboard.&lt;/p&gt;&#xA;&lt;h2 id=&#34;when-it-breaks&#34;&gt;When it breaks&lt;/h2&gt;&#xA;&lt;p&gt;Everything above works well for most apps. Here are the three ways it goes&#xA;wrong as you grow, and how to spot each one early.&lt;/p&gt;&#xA;&lt;h3 id=&#34;1-bloat-the-table-fills-up-with-dead-rows&#34;&gt;1. Bloat: the table fills up with dead rows&lt;/h3&gt;&#xA;&lt;p&gt;In Postgres, an &lt;code&gt;UPDATE&lt;/code&gt; does not change a row in place. It writes a new copy&#xA;and marks the old one as dead. A job that goes pending, running, done leaves&#xA;dead copies behind. A cleanup process called autovacuum removes them later.&lt;/p&gt;&#xA;&lt;p&gt;A queue table changes all day long, so dead rows pile up faster than in a&#xA;normal table. When autovacuum can&amp;rsquo;t keep up, the table and its indexes grow,&#xA;and the claim query slows down because it has to step over dead rows.&lt;/p&gt;&#xA;&lt;p&gt;What helps:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Delete finished jobs, or move them to an archive table, instead of keeping&#xA;millions of &lt;code&gt;done&lt;/code&gt; rows.&lt;/li&gt;&#xA;&lt;li&gt;Make autovacuum run more often on this one table:&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ALTER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; jobs &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  autovacuum_vacuum_scale_factor &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;0&lt;/span&gt;.&lt;span style=&#34;color:#bd93f9&#34;&gt;01&lt;/span&gt;,  &lt;span style=&#34;color:#6272a4&#34;&gt;-- start at 1% dead rows, not 20%&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  autovacuum_vacuum_cost_delay   &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;0&lt;/span&gt;      &lt;span style=&#34;color:#6272a4&#34;&gt;-- don&amp;#39;t slow it down&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h3 id=&#34;2-long-transactions-stop-the-cleanup-everywhere&#34;&gt;2. Long transactions stop the cleanup everywhere&lt;/h3&gt;&#xA;&lt;p&gt;Vacuum can only remove a dead row when no open transaction might still need&#xA;to see it. One transaction that stays open for 20 minutes blocks cleanup of&#xA;anything that changed in those 20 minutes, in every table, not only &lt;code&gt;jobs&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;This is why style 1 (hold the transaction during the job) is risky. One stuck&#xA;job, or one forgotten &lt;code&gt;BEGIN&lt;/code&gt; in a console, and the queue table bloats.&lt;/p&gt;&#xA;&lt;h3 id=&#34;3-too-many-workers-fighting-over-the-head-of-the-queue&#34;&gt;3. Too many workers fighting over the head of the queue&lt;/h3&gt;&#xA;&lt;p&gt;&lt;code&gt;SKIP LOCKED&lt;/code&gt; stops workers from waiting, but they still all look at the same&#xA;few rows at the front of the queue. With dozens of workers and a high job&#xA;rate, they spend more and more time skipping each other&amp;rsquo;s locked rows. Some&#xA;write-ups report throughput falling off a cliff at this point instead of&#xA;leveling out.&lt;/p&gt;&#xA;&lt;p&gt;As a rough rule of thumb (not a benchmark): thousands of jobs per minute is&#xA;comfortable. Hundreds of jobs per second with many workers is where you need&#xA;to test carefully, claim jobs in batches (&lt;code&gt;LIMIT 10&lt;/code&gt; instead of &lt;code&gt;LIMIT 1&lt;/code&gt;), or&#xA;look at a dedicated queue.&lt;/p&gt;&#xA;&lt;h3 id=&#34;the-health-check-card&#34;&gt;The health check card&lt;/h3&gt;&#xA;&lt;p&gt;Put these two queries on a dashboard. They catch all three problems early.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/health-check.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/health-check.svg&#34; alt=&#34;Job queue health check with four rows. 1: dead rows piling up, when n_dead_tup is much bigger than n_live_tup, vacuum is behind. 2: a transaction open for minutes, find out why. 3: pending jobs older than 5 minutes, add workers. 4: any job with status dead, a person should look.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;380&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- 1. Dead rows in the jobs table&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; n_live_tup, n_dead_tup, last_autovacuum&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; pg_stat_user_tables&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; relname &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;jobs&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- 2. The oldest open transactions&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; pid, now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; xact_start &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; open_for, &lt;span style=&#34;color:#ff79c6&#34;&gt;state&lt;/span&gt;, &lt;span style=&#34;color:#ff79c6&#34;&gt;left&lt;/span&gt;(query, &lt;span style=&#34;color:#bd93f9&#34;&gt;60&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; pg_stat_activity&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; xact_start &lt;span style=&#34;color:#ff79c6&#34;&gt;IS&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; open_for &lt;span style=&#34;color:#ff79c6&#34;&gt;DESC&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;LIMIT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;5&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- 3 and 4. Queue backlog and failures&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; status, &lt;span style=&#34;color:#ff79c6&#34;&gt;count&lt;/span&gt;(&lt;span style=&#34;color:#ff79c6&#34;&gt;*&lt;/span&gt;), &lt;span style=&#34;color:#ff79c6&#34;&gt;min&lt;/span&gt;(run_at) &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; oldest&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;IN&lt;/span&gt; (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;dead&amp;#39;&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;GROUP&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; status;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;should-you-use-postgres-redis-or-kafka&#34;&gt;Should you use Postgres, Redis or Kafka?&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/which-queue.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/which-queue.svg&#34; alt=&#34;Decision chart. If you dont already run Postgres, use what you run. If the job must be saved together with your business data, use a Postgres queue. If not, and you have under about 100 jobs a second with no other teams reading the same events, use a Postgres queue. Otherwise use a Redis queue for speed, or Kafka for many readers and replay.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;500&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Most apps land on &amp;ldquo;Postgres queue&amp;rdquo; and stay there for years. Moving later is&#xA;not hard, because the code that claims and finishes jobs is small.&lt;/p&gt;&#xA;&lt;h2 id=&#34;questions-people-ask&#34;&gt;Questions people ask&lt;/h2&gt;&#xA;&lt;p&gt;&lt;strong&gt;Is SKIP LOCKED safe? Can two workers ever get the same job?&lt;/strong&gt;&#xA;Not at the same time. A locked row is invisible to other &lt;code&gt;SKIP LOCKED&lt;/code&gt;&#xA;queries until the lock is released. A job can run twice only after a lease&#xA;expires or a transaction rolls back, which is why jobs should be safe to&#xA;repeat.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does this work in MySQL?&lt;/strong&gt;&#xA;Yes. MySQL 8.0 and MariaDB 10.6 also support &lt;code&gt;FOR UPDATE SKIP LOCKED&lt;/code&gt;. The&#xA;bloat details differ, but the pattern is the same.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Should I use a library?&lt;/strong&gt;&#xA;Often, yes. Libraries such as River (Go), Oban (Elixir), Graphile Worker&#xA;(Node) and Solid Queue (Ruby) are built on this pattern and handle retries,&#xA;scheduling and the sweeper for you. Knowing how they work helps you debug&#xA;them.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Can I use SQLite for this?&lt;/strong&gt;&#xA;SQLite allows only one writer at a time, so there is no row locking to skip.&#xA;A single worker process with a simple &lt;code&gt;UPDATE ... RETURNING&lt;/code&gt; works fine. See&#xA;&lt;a href=&#34;https://loomloops.com/post/sqlite-locks/&#34;&gt;how SQLite locks work&lt;/a&gt; for why.&lt;/p&gt;&#xA;&lt;h2 id=&#34;cheat-sheet&#34;&gt;Cheat sheet&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/cheat-sheet.svg&#34; alt=&#34;Postgres job queue cheat sheet. Claim: UPDATE where id equals a SELECT with FOR UPDATE SKIP LOCKED. Index: partial index on run_at for pending jobs. Crashes: lease with locked_until and a sweeper every minute. Finish: WHERE id = $1 AND attempts = $2. Retries: run_at = now() + 2^attempts minutes. Wake up: LISTEN/NOTIFY plus a slow poll as backup. Cleanup: delete done jobs and tune autovacuum on jobs. Watch: dead rows, old transactions, backlog, dead jobs. Rule: jobs must be safe to run twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;440&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;h2 id=&#34;further-reading&#34;&gt;Further reading&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE&#34;&gt;PostgreSQL docs: the locking clause&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/routine-vacuuming.html&#34;&gt;PostgreSQL docs: routine vacuuming&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://loomloops.com/post/understanding-postgresql-locks/&#34;&gt;Understanding PostgreSQL locks&lt;/a&gt; on this site&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;</description>
    </item>
    <item>
      <title>PostgreSQL Locks Explained: How to Find and Fix Blocking Queries</title>
      <link>https://loomloops.com/post/understanding-postgresql-locks/</link>
      <pubDate>Sun, 22 Dec 2024 17:23:09 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/understanding-postgresql-locks/</guid>
      <description>&lt;p&gt;It is 2 pm and you ship a migration. One line: &lt;code&gt;ALTER TABLE orders ADD COLUMN note text;&lt;/code&gt;.&#xA;On a table with millions of rows this takes a few milliseconds. You have run&#xA;a hundred like it.&lt;/p&gt;&#xA;&lt;p&gt;Today the site stops. Pages hang, the connection pool fills up, and the alerts&#xA;start. The &lt;code&gt;ALTER TABLE&lt;/code&gt; did not do anything wrong. It is just waiting. An&#xA;analyst started a report on &lt;code&gt;orders&lt;/code&gt; four minutes ago, and the &lt;code&gt;ALTER&lt;/code&gt; is stuck&#xA;behind it. Worse, every new query on &lt;code&gt;orders&lt;/code&gt; is now stuck behind the &lt;code&gt;ALTER&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;This outage is common, and it is always a surprise the first time. This post explains the lock rules that cause it, how to see who is&#xA;blocking whom, and how to run migrations so it cannot happen.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Short version:&lt;/strong&gt;&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;A lock request waits in line. A waiting &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; request (the lock&#xA;most &lt;code&gt;ALTER TABLE&lt;/code&gt; commands need) blocks every query that arrives after it,&#xA;even plain &lt;code&gt;SELECT&lt;/code&gt;s.&lt;/li&gt;&#xA;&lt;li&gt;Find the blocker with &lt;code&gt;pg_stat_activity&lt;/code&gt; and &lt;code&gt;pg_blocking_pids()&lt;/code&gt;. Set&#xA;&lt;code&gt;lock_timeout&lt;/code&gt; in every migration, and retry when it fires.&lt;/li&gt;&#xA;&lt;li&gt;Deadlocks come from taking locks in different orders. Lock rows in the same&#xA;order everywhere, and retry the transaction when PostgreSQL aborts one.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;the-outage-a-queue-not-a-crash&#34;&gt;The outage: a queue, not a crash&lt;/h2&gt;&#xA;&lt;p&gt;Here is the whole outage as a timeline:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/understanding-postgresql-locks/lock-queue-outage.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/understanding-postgresql-locks/lock-queue-outage.svg&#34; alt=&#34;Timeline of a lock queue outage. A report SELECT starts and holds an ACCESS SHARE lock for four minutes. An ALTER TABLE arrives and needs ACCESS EXCLUSIVE, so it waits for the report. Then application queries arrive. They do not conflict with the report, but they queue behind the waiting ALTER. The site stops until the report ends or someone cancels it.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;440&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Three facts add up to this:&lt;/p&gt;&#xA;&lt;ol&gt;&#xA;&lt;li&gt;A plain &lt;code&gt;SELECT&lt;/code&gt; takes a lock on the table (&lt;code&gt;ACCESS SHARE&lt;/code&gt;) and keeps it&#xA;until its transaction ends. A report that runs for four minutes holds it for&#xA;four minutes.&lt;/li&gt;&#xA;&lt;li&gt;&lt;code&gt;ALTER TABLE&lt;/code&gt; needs &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;. That mode conflicts with every other&#xA;mode, including &lt;code&gt;ACCESS SHARE&lt;/code&gt;. So the &lt;code&gt;ALTER&lt;/code&gt; must wait for the report.&lt;/li&gt;&#xA;&lt;li&gt;The &lt;code&gt;ALTER&lt;/code&gt; joins the line. Queries that arrive later would be fine with the&#xA;report, but they are not fine with a waiting &lt;code&gt;ALTER&lt;/code&gt; ahead of them. They wait&#xA;too.&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;p&gt;I reproduced this on PostgreSQL 17 with three sessions. This is what&#xA;&lt;code&gt;pg_locks&lt;/code&gt; showed:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt; locktype | relation |        mode         | granted | pid&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;----------+----------+---------------------+---------+-----&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt; relation | orders   | AccessShareLock     | t       |  87    &amp;lt;- the slow report&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt; relation | orders   | AccessExclusiveLock | f       |  94    &amp;lt;- the ALTER, waiting&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt; relation | orders   | AccessShareLock     | f       | 101    &amp;lt;- a plain SELECT, waiting&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The last row is the surprise. A plain read is waiting, and nothing that holds&#xA;a lock conflicts with it. It waits only because the &lt;code&gt;ALTER&lt;/code&gt; is ahead of it.&lt;/p&gt;&#xA;&lt;h2 id=&#34;table-level-lock-modes&#34;&gt;Table-level lock modes&lt;/h2&gt;&#xA;&lt;p&gt;PostgreSQL has 8 table-level lock modes. You do not need to memorise them. You&#xA;need to know which commands take which mode, and which pairs conflict.&#xA;PostgreSQL takes these locks for you. You only name one when you run&#xA;&lt;code&gt;LOCK TABLE&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Mode&lt;/th&gt;&#xA;          &lt;th&gt;Taken by (from the docs)&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;ACCESS SHARE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SELECT&lt;/code&gt;, and any query that only reads&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;ROW SHARE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt;, &lt;code&gt;FOR NO KEY UPDATE&lt;/code&gt;, &lt;code&gt;FOR SHARE&lt;/code&gt;, &lt;code&gt;FOR KEY SHARE&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;ROW EXCLUSIVE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;INSERT&lt;/code&gt;, &lt;code&gt;UPDATE&lt;/code&gt;, &lt;code&gt;DELETE&lt;/code&gt;, &lt;code&gt;MERGE&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;SHARE UPDATE EXCLUSIVE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;VACUUM&lt;/code&gt; (not &lt;code&gt;FULL&lt;/code&gt;), &lt;code&gt;ANALYZE&lt;/code&gt;, &lt;code&gt;CREATE INDEX CONCURRENTLY&lt;/code&gt;, &lt;code&gt;REINDEX CONCURRENTLY&lt;/code&gt;, &lt;code&gt;CREATE STATISTICS&lt;/code&gt;, &lt;code&gt;COMMENT ON&lt;/code&gt;, some &lt;code&gt;ALTER TABLE&lt;/code&gt; forms&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;SHARE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;CREATE INDEX&lt;/code&gt; (without &lt;code&gt;CONCURRENTLY&lt;/code&gt;)&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;SHARE ROW EXCLUSIVE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;CREATE TRIGGER&lt;/code&gt;, some &lt;code&gt;ALTER TABLE&lt;/code&gt; forms&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;EXCLUSIVE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;REFRESH MATERIALIZED VIEW CONCURRENTLY&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;DROP TABLE&lt;/code&gt;, &lt;code&gt;TRUNCATE&lt;/code&gt;, &lt;code&gt;REINDEX&lt;/code&gt;, &lt;code&gt;CLUSTER&lt;/code&gt;, &lt;code&gt;VACUUM FULL&lt;/code&gt;, &lt;code&gt;REFRESH MATERIALIZED VIEW&lt;/code&gt;, many &lt;code&gt;ALTER TABLE&lt;/code&gt; forms, and &lt;code&gt;LOCK TABLE&lt;/code&gt; with no mode&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;Here is which pairs conflict. A filled cell means two transactions cannot hold&#xA;those two modes on the same table at the same time:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/understanding-postgresql-locks/table-lock-conflicts.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/understanding-postgresql-locks/table-lock-conflicts.svg&#34; alt=&#34;Conflict matrix for the 8 table lock modes. Each row lists the modes it conflicts with. ACCESS SHARE: ACCESS EXCLUSIVE only. ROW SHARE: EXCLUSIVE, ACCESS EXCLUSIVE. ROW EXCLUSIVE: SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, ACCESS EXCLUSIVE. SHARE UPDATE EXCLUSIVE: itself, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, ACCESS EXCLUSIVE. SHARE: ROW EXCLUSIVE, SHARE UPDATE EXCLUSIVE, SHARE ROW EXCLUSIVE, EXCLUSIVE, ACCESS EXCLUSIVE. SHARE ROW EXCLUSIVE: everything except ACCESS SHARE and ROW SHARE. EXCLUSIVE: everything except ACCESS SHARE. ACCESS EXCLUSIVE: all 8.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;396&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Five patterns to remember from that grid:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Reads and writes do not block each other at table level.&lt;/strong&gt; &lt;code&gt;ACCESS SHARE&lt;/code&gt;&#xA;and &lt;code&gt;ROW EXCLUSIVE&lt;/code&gt; do not conflict, and two &lt;code&gt;ROW EXCLUSIVE&lt;/code&gt; locks do not&#xA;conflict either. Any number of &lt;code&gt;UPDATE&lt;/code&gt;s can run on one table. Two of them&#xA;only wait for each other when they touch the same row (see the next section).&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Only &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; blocks a plain &lt;code&gt;SELECT&lt;/code&gt;.&lt;/strong&gt; The docs say so&#xA;directly.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;&lt;code&gt;CREATE INDEX&lt;/code&gt; without &lt;code&gt;CONCURRENTLY&lt;/code&gt; blocks writes.&lt;/strong&gt; It takes &lt;code&gt;SHARE&lt;/code&gt;,&#xA;which conflicts with &lt;code&gt;ROW EXCLUSIVE&lt;/code&gt;. Reads still work.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Any open transaction that wrote to the table also blocks an &lt;code&gt;ALTER&lt;/code&gt;.&lt;/strong&gt;&#xA;&lt;code&gt;ROW EXCLUSIVE&lt;/code&gt; (and &lt;code&gt;ROW SHARE&lt;/code&gt;, from &lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt;) conflicts with&#xA;&lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;, and it stays until &lt;code&gt;COMMIT&lt;/code&gt;. A forgotten &lt;code&gt;BEGIN&lt;/code&gt; after an&#xA;&lt;code&gt;UPDATE&lt;/code&gt; is as bad as a slow report.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;A few modes conflict with themselves.&lt;/strong&gt; &lt;code&gt;SHARE UPDATE EXCLUSIVE&lt;/code&gt; is why&#xA;two &lt;code&gt;VACUUM&lt;/code&gt;s, or a &lt;code&gt;VACUUM&lt;/code&gt; and a &lt;code&gt;CREATE INDEX CONCURRENTLY&lt;/code&gt;, cannot run on&#xA;the same table together.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;A lock is held until the transaction ends. A transaction never conflicts with&#xA;itself.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-lock-queue&#34;&gt;The lock queue&lt;/h2&gt;&#xA;&lt;p&gt;When a lock request cannot be granted, it waits. Everything that arrives later&#xA;and conflicts with &lt;em&gt;that waiting request&lt;/em&gt; waits behind it, even if it would&#xA;have been fine with the lock holders. The PostgreSQL docs call this a &amp;ldquo;soft&#xA;block&amp;rdquo; in the page for &lt;code&gt;pg_blocking_pids()&lt;/code&gt;: a process is blocked by someone who&#xA;is waiting for a conflicting lock and is ahead of it in the wait queue.&lt;/p&gt;&#xA;&lt;p&gt;That is why the outage happens, and why it is so quick. The &lt;code&gt;ALTER&lt;/code&gt; itself is&#xA;fast. What hurts is the time it spends in line, because it holds up everybody&#xA;behind it.&lt;/p&gt;&#xA;&lt;p&gt;Some &lt;code&gt;ALTER TABLE&lt;/code&gt; forms need weaker locks, so they cause less trouble:&#xA;&lt;code&gt;ADD FOREIGN KEY&lt;/code&gt; takes &lt;code&gt;SHARE ROW EXCLUSIVE&lt;/code&gt;, and &lt;code&gt;VALIDATE CONSTRAINT&lt;/code&gt; takes&#xA;&lt;code&gt;SHARE UPDATE EXCLUSIVE&lt;/code&gt;. The docs say that &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; is the rule&#xA;unless a page says otherwise, so read the page for each command before you run&#xA;it.&lt;/p&gt;&#xA;&lt;h2 id=&#34;row-level-locks&#34;&gt;Row-level locks&lt;/h2&gt;&#xA;&lt;p&gt;Table locks are about commands that change the table&amp;rsquo;s shape. Row locks are&#xA;about two transactions that want the same row. They are separate: an &lt;code&gt;UPDATE&lt;/code&gt;&#xA;takes a &lt;code&gt;ROW EXCLUSIVE&lt;/code&gt; lock on the table &lt;em&gt;and&lt;/em&gt; a row lock on each row it&#xA;changes.&lt;/p&gt;&#xA;&lt;p&gt;There are 4 row lock modes, from strongest to weakest:&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Row lock&lt;/th&gt;&#xA;          &lt;th&gt;Taken by&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;FOR UPDATE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt;, every &lt;code&gt;DELETE&lt;/code&gt;, and an &lt;code&gt;UPDATE&lt;/code&gt; that changes a column with a unique index that a foreign key could use&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;FOR NO KEY UPDATE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SELECT ... FOR NO KEY UPDATE&lt;/code&gt;, and every other &lt;code&gt;UPDATE&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;FOR SHARE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SELECT ... FOR SHARE&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;FOR KEY SHARE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SELECT ... FOR KEY SHARE&lt;/code&gt;, and foreign key checks on the referenced row&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/understanding-postgresql-locks/row-lock-modes.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/understanding-postgresql-locks/row-lock-modes.svg&#34; alt=&#34;Conflict matrix for the 4 row lock modes. FOR KEY SHARE conflicts only with FOR UPDATE. FOR SHARE conflicts with FOR NO KEY UPDATE and FOR UPDATE. FOR NO KEY UPDATE conflicts with FOR SHARE, itself and FOR UPDATE. FOR UPDATE conflicts with all four. Plain SELECT takes no row lock and is never blocked by row locks.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;396&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The point of the two weak modes is foreign keys. When you insert a row into&#xA;&lt;code&gt;order_items&lt;/code&gt;, PostgreSQL checks that the matching row in &lt;code&gt;orders&lt;/code&gt; exists. It&#xA;takes &lt;code&gt;FOR KEY SHARE&lt;/code&gt; on that &lt;code&gt;orders&lt;/code&gt; row while it checks, so nobody can&#xA;delete the order underneath you. An &lt;code&gt;UPDATE orders SET status = &#39;paid&#39;&lt;/code&gt; only&#xA;takes &lt;code&gt;FOR NO KEY UPDATE&lt;/code&gt;, which does not conflict with &lt;code&gt;FOR KEY SHARE&lt;/code&gt;. So&#xA;updating an order never blocks inserts of its items. (This arrived in&#xA;PostgreSQL 9.3. I checked it on PostgreSQL 17: an insert into the child table&#xA;waited on a parent row held with &lt;code&gt;FOR UPDATE&lt;/code&gt;, and went straight through when&#xA;the parent row was held with &lt;code&gt;FOR NO KEY UPDATE&lt;/code&gt;.)&lt;/p&gt;&#xA;&lt;p&gt;Other things worth knowing:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Row locks do not block plain &lt;code&gt;SELECT&lt;/code&gt;s.&lt;/strong&gt; They block only writers and other&#xA;lockers of the same row.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Row locks are not in &lt;code&gt;pg_locks&lt;/code&gt;.&lt;/strong&gt; They live on disk, not in memory. A&#xA;session waiting for a row shows up as waiting for the &lt;em&gt;transaction ID&lt;/em&gt; of the&#xA;session that holds the row. That is why &lt;code&gt;wait_event&lt;/code&gt; says &lt;code&gt;transactionid&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;There is no lock escalation.&lt;/strong&gt; The docs say there is no limit on the number&#xA;of rows locked at once. Locking a million rows does not turn into a table&#xA;lock. It does cost disk writes, though.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Row locks wait forever by default.&lt;/strong&gt; &lt;code&gt;SELECT ... FOR UPDATE NOWAIT&lt;/code&gt; errors&#xA;at once instead of waiting, and &lt;code&gt;SKIP LOCKED&lt;/code&gt; skips locked rows. The&#xA;&lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;job queue post&lt;/a&gt; builds a whole&#xA;queue on &lt;code&gt;SKIP LOCKED&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;find-the-blocker&#34;&gt;Find the blocker&lt;/h2&gt;&#xA;&lt;p&gt;When the site is slow and you suspect locks, you want one answer: who is&#xA;blocking whom? &lt;code&gt;pg_locks&lt;/code&gt; has the raw rows, but the docs themselves call&#xA;joining it to itself &amp;ldquo;very difficult to get right in detail&amp;rdquo;. Use&#xA;&lt;code&gt;pg_blocking_pids()&lt;/code&gt; instead. It takes the PID of a waiting session and returns&#xA;the PIDs of the sessions in its way.&lt;/p&gt;&#xA;&lt;p&gt;Copy this query:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  blocked.pid                    &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; blocked_pid,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  blocked.wait_event_type,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  blocked.wait_event,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; blocked.query_start    &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; waiting_for,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;left&lt;/span&gt;(blocked.query, &lt;span style=&#34;color:#bd93f9&#34;&gt;40&lt;/span&gt;)        &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; blocked_query,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  blocker.pid                    &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; blocker_pid,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  blocker.&lt;span style=&#34;color:#ff79c6&#34;&gt;state&lt;/span&gt;                  &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; blocker_state,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; blocker.xact_start     &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; blocker_xact_age,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;left&lt;/span&gt;(blocker.query, &lt;span style=&#34;color:#bd93f9&#34;&gt;40&lt;/span&gt;)        &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; blocker_last_query&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; pg_stat_activity &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; blocked&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CROSS&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;JOIN&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;LATERAL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;unnest&lt;/span&gt;(pg_blocking_pids(blocked.pid)) &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; b(pid)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;LEFT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;JOIN&lt;/span&gt; pg_stat_activity &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; blocker &lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; blocker.pid &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; b.pid&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; blocked.wait_event_type &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;Lock&amp;#39;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; waiting_for &lt;span style=&#34;color:#ff79c6&#34;&gt;DESC&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This is what it printed for the outage above:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocked_pid        | 94&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;wait_event         | relation&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;waiting_for        | 00:00:03.03&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocked_query      | alter table orders add column note text;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocker_pid        | 87&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocker_state      | active&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocker_xact_age   | 00:00:04.04&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocker_last_query | select pg_sleep(20);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocked_pid        | 101&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;wait_event         | relation&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;waiting_for        | 00:00:02.01&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocked_query      | select * from orders where id=1;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocker_pid        | 94&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocker_state      | active&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;blocker_last_query | alter table orders add column note text;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/understanding-postgresql-locks/find-the-blocker.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/understanding-postgresql-locks/find-the-blocker.svg&#34; alt=&#34;Flow for finding and fixing a blocker. Step 1: run the blocker query. Step 2: find the root, the PID that blocks others but is not blocked itself. Step 3: read its state. If active, it is a slow query: cancel it with pg_cancel_backend. If idle in transaction, someone forgot to commit: end it with pg_terminate_backend. Step 4: fix the cause, with timeouts and shorter transactions.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;480&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;How to read it:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Follow the chain to the root.&lt;/strong&gt; Here 101 waits for 94, and 94 waits for 87.&#xA;The root is 87, a PID that blocks others but is not blocked. Fixing 87 frees&#xA;everyone.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Look at &lt;code&gt;blocker_state&lt;/code&gt;.&lt;/strong&gt; &lt;code&gt;active&lt;/code&gt; means a slow query. &lt;code&gt;idle in transaction&lt;/code&gt; means the session ran something, then stopped without&#xA;&lt;code&gt;COMMIT&lt;/code&gt;. For a session that is not running a query, &lt;code&gt;query&lt;/code&gt; shows the&#xA;&lt;em&gt;last&lt;/em&gt; statement it ran, which is often a hint about which code forgot to&#xA;commit.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;A blocker PID of 0 is a prepared transaction.&lt;/strong&gt; It has no row in&#xA;&lt;code&gt;pg_stat_activity&lt;/code&gt;, so the &lt;code&gt;LEFT JOIN&lt;/code&gt; keeps it in the output. Look at&#xA;&lt;code&gt;pg_prepared_xacts&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;Then you can act. Both functions need the right to signal that backend: the&#xA;same role, a role that is a member of it, or &lt;code&gt;pg_signal_backend&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; pg_cancel_backend(&lt;span style=&#34;color:#bd93f9&#34;&gt;87&lt;/span&gt;);     &lt;span style=&#34;color:#6272a4&#34;&gt;-- cancels the running query, keeps the session&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; pg_terminate_backend(&lt;span style=&#34;color:#bd93f9&#34;&gt;87&lt;/span&gt;);  &lt;span style=&#34;color:#6272a4&#34;&gt;-- ends the session and rolls back its transaction&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Cancel first. A session that is &lt;code&gt;idle in transaction&lt;/code&gt; has no query to cancel,&#xA;so that one needs &lt;code&gt;pg_terminate_backend&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;The docs warn that calling &lt;code&gt;pg_blocking_pids()&lt;/code&gt; often can slow the database a&#xA;little, because it needs short exclusive access to the lock manager&amp;rsquo;s shared&#xA;state. Run it when you investigate. Do not run it every second from a monitor.&#xA;For a lighter, always-on signal, set &lt;code&gt;log_lock_waits = on&lt;/code&gt;. It writes a log&#xA;line when a session waits longer than &lt;code&gt;deadlock_timeout&lt;/code&gt; (1 second by default).&lt;/p&gt;&#xA;&lt;h2 id=&#34;timeouts-stop-waiting-forever&#34;&gt;Timeouts: stop waiting forever&lt;/h2&gt;&#xA;&lt;p&gt;By default PostgreSQL waits forever for a lock. Three settings fix that. They&#xA;all default to &lt;code&gt;0&lt;/code&gt;, which means disabled.&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Setting&lt;/th&gt;&#xA;          &lt;th&gt;What it stops&lt;/th&gt;&#xA;          &lt;th&gt;Error you see&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;lock_timeout&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;A statement that waits too long for a lock. Only counts waiting, not running&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;canceling statement due to lock timeout&lt;/code&gt; (&lt;code&gt;55P03&lt;/code&gt;)&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;statement_timeout&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;A statement that runs too long, for any reason&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;canceling statement due to statement timeout&lt;/code&gt; (&lt;code&gt;57014&lt;/code&gt;)&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;idle_in_transaction_session_timeout&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;A session that sits in an open transaction doing nothing&lt;/td&gt;&#xA;          &lt;td&gt;The connection is closed (&lt;code&gt;25P03&lt;/code&gt;)&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;Use each one where it fits:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- At the top of every migration:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; lock_timeout &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;2s&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- For the app&amp;#39;s role: kill sessions that hold a transaction open and do nothing.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ALTER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;ROLE&lt;/span&gt; app_user &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; idle_in_transaction_session_timeout &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;60s&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- For a role that runs reports: a ceiling so one report cannot run for hours.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ALTER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;ROLE&lt;/span&gt; reporting &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; statement_timeout &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;5min&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The numbers are examples, not advice for your system. Pick them from how long&#xA;your normal queries take. Two rules from the docs:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Do not put &lt;code&gt;lock_timeout&lt;/code&gt; or &lt;code&gt;statement_timeout&lt;/code&gt; in &lt;code&gt;postgresql.conf&lt;/code&gt;. It&#xA;would hit every session, including &lt;code&gt;VACUUM&lt;/code&gt; and your own admin work. Set them&#xA;per session or per role.&lt;/li&gt;&#xA;&lt;li&gt;If &lt;code&gt;statement_timeout&lt;/code&gt; is set, a &lt;code&gt;lock_timeout&lt;/code&gt; equal to it or larger is&#xA;pointless, because the statement timeout always fires first.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;The &lt;code&gt;statement_timeout&lt;/code&gt; on the report role is what would have prevented the&#xA;outage from the start. The analyst&amp;rsquo;s query would have been cancelled after a&#xA;few minutes, instead of holding a lock until the whole site fell over.&lt;/p&gt;&#xA;&lt;h2 id=&#34;deadlocks&#34;&gt;Deadlocks&lt;/h2&gt;&#xA;&lt;p&gt;A deadlock is two transactions that each hold a lock the other one wants. No&#xA;one can ever finish by waiting.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/understanding-postgresql-locks/deadlock-cycle.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/understanding-postgresql-locks/deadlock-cycle.svg&#34; alt=&#34;Deadlock cycle. Transaction A updates account 1, then wants account 2. Transaction B updates account 2, then wants account 1. A waits for B and B waits for A, in a circle. After deadlock_timeout, PostgreSQL aborts one of them with error deadlock detected, and the other one finishes.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;430&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;You can try it with two sessions:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; accounts (id &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;int&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;PRIMARY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt;, balance &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;int&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; accounts &lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;, &lt;span style=&#34;color:#bd93f9&#34;&gt;500&lt;/span&gt;), (&lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;, &lt;span style=&#34;color:#bd93f9&#34;&gt;500&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- Session A                                       -- Session B&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;                                             &lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; accounts &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;100&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                                   &lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; accounts &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;50&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                                     &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; accounts &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;100&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;;   &lt;span style=&#34;color:#6272a4&#34;&gt;-- waits for B&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;                                                   &lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; accounts &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;50&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                                     &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;;   &lt;span style=&#34;color:#6272a4&#34;&gt;-- waits for A: deadlock&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;About a second later, one session gets this (the PIDs and transaction numbers&#xA;will differ):&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;ERROR:  deadlock detected&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;DETAIL:  Process 137 waits for ShareLock on transaction 753; blocked by process 130.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Process 130 waits for ShareLock on transaction 754; blocked by process 137.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;HINT:  See server log for query details.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;CONTEXT:  while updating tuple (0,1) in relation &amp;#34;accounts&amp;#34;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;What is going on:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;PostgreSQL does not check for a deadlock the moment a session starts to wait.&#xA;The check is costly. It waits &lt;code&gt;deadlock_timeout&lt;/code&gt; first (default 1 second) and&#xA;checks only if the lock is still not free. Most waits end sooner, so most&#xA;waits never pay for the check.&lt;/li&gt;&#xA;&lt;li&gt;The detector aborts one transaction in the cycle and lets the others go on.&#xA;The docs say you cannot predict which one, and you should not rely on it.&lt;/li&gt;&#xA;&lt;li&gt;The error code is &lt;code&gt;40P01&lt;/code&gt;. Everything the aborted transaction did is rolled&#xA;back.&lt;/li&gt;&#xA;&lt;li&gt;Deadlocks do not need &lt;code&gt;LOCK TABLE&lt;/code&gt;. Plain row updates, as above, are enough.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;How to prevent them, in order of value:&lt;/p&gt;&#xA;&lt;ol&gt;&#xA;&lt;li&gt;&#xA;&lt;p&gt;&lt;strong&gt;Take locks in the same order everywhere.&lt;/strong&gt; This is the docs&amp;rsquo; best&#xA;defence. If both sessions above had updated account 1 first, one would have&#xA;waited for the other, and there would be no cycle. When you move money&#xA;between two accounts, always touch the lower id first, or lock both rows up&#xA;front in a fixed order:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; accounts &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;IN&lt;/span&gt; (&lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;, &lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;) &lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;FOR&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NO&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/li&gt;&#xA;&lt;li&gt;&#xA;&lt;p&gt;&lt;strong&gt;Take the strongest lock you need first.&lt;/strong&gt; The docs advise that the first&#xA;lock on an object should be the most restrictive one you will need. Two&#xA;sessions that start with &lt;code&gt;FOR SHARE&lt;/code&gt; and both try to upgrade will deadlock.&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li&gt;&#xA;&lt;p&gt;&lt;strong&gt;Keep transactions short.&lt;/strong&gt; Less time holding locks means fewer chances to&#xA;meet.&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;li&gt;&#xA;&lt;p&gt;&lt;strong&gt;Retry.&lt;/strong&gt; If you cannot be sure about the order, catch &lt;code&gt;40P01&lt;/code&gt; and run the&#xA;whole transaction again. This is only safe when the transaction can run&#xA;twice without a bad effect, which is the same problem the post on&#xA;&lt;a href=&#34;https://loomloops.com/post/idempotency-keys-explained/&#34;&gt;idempotency keys&lt;/a&gt; solves.&lt;/p&gt;&#xA;&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;p&gt;Do not raise &lt;code&gt;deadlock_timeout&lt;/code&gt; to hide deadlocks. A higher value only slows&#xA;the report of real ones. The docs suggest raising it on a heavily loaded&#xA;server, so that it is longer than your usual transaction time.&lt;/p&gt;&#xA;&lt;h2 id=&#34;idle-in-transaction-the-quiet-lock-holder&#34;&gt;Idle in transaction: the quiet lock holder&lt;/h2&gt;&#xA;&lt;p&gt;A session in state &lt;code&gt;idle in transaction&lt;/code&gt; ran &lt;code&gt;BEGIN&lt;/code&gt;, ran some statements, and&#xA;is now waiting for the client to send the next command. Every lock it took is&#xA;still held. If the client forgot to commit, the locks stay until someone&#xA;notices.&lt;/p&gt;&#xA;&lt;p&gt;The usual causes:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Code that opens a transaction, then calls a slow web service before it commits.&lt;/li&gt;&#xA;&lt;li&gt;A developer who ran &lt;code&gt;BEGIN&lt;/code&gt; in a console and went to lunch.&lt;/li&gt;&#xA;&lt;li&gt;A connection pool or ORM that leaves a transaction open after an error.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;Find them:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; pid, now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; xact_start &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; open_for, &lt;span style=&#34;color:#ff79c6&#34;&gt;state&lt;/span&gt;, &lt;span style=&#34;color:#ff79c6&#34;&gt;left&lt;/span&gt;(query, &lt;span style=&#34;color:#bd93f9&#34;&gt;60&lt;/span&gt;) &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; last_query&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; pg_stat_activity&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;state&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;IN&lt;/span&gt; (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;idle in transaction&amp;#39;&lt;/span&gt;, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;idle in transaction (aborted)&amp;#39;&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; xact_start;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Set &lt;code&gt;idle_in_transaction_session_timeout&lt;/code&gt; on the app role, as shown above. The&#xA;docs say the setting exists to make sure idle sessions do not hold locks for an&#xA;unreasonable time. It also helps with bloat. An open transaction stops &lt;code&gt;VACUUM&lt;/code&gt;&#xA;from removing recently dead rows that only it can still see.&lt;/p&gt;&#xA;&lt;p&gt;The fix in code is to keep slow work outside the transaction. If you must call&#xA;another service after a write, save an event row in the same transaction and&#xA;send it later. That is the &lt;a href=&#34;https://loomloops.com/post/transactional-outbox-pattern/&#34;&gt;transactional outbox&#xA;pattern&lt;/a&gt;.&lt;/p&gt;&#xA;&lt;h2 id=&#34;safe-migrations&#34;&gt;Safe migrations&lt;/h2&gt;&#xA;&lt;p&gt;Now you can see why the dangerous part of a migration is rarely the work. It&#xA;is the wait for the lock. The recipes below keep both small.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/understanding-postgresql-locks/safe-migration.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/understanding-postgresql-locks/safe-migration.svg&#34; alt=&#34;Safe migration checklist with five rows. Always: SET lock_timeout and retry. Add a column: a constant default is fast since PostgreSQL 11, a volatile default rewrites the table. Add an index: CREATE INDEX CONCURRENTLY, never inside a transaction block. Add a constraint: ADD CONSTRAINT NOT VALID, then VALIDATE CONSTRAINT. Change a column type: it rewrites the table, so add a new column and backfill instead.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;436&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;h3 id=&#34;1-set-lock_timeout-and-retry&#34;&gt;1. Set &lt;code&gt;lock_timeout&lt;/code&gt; and retry&lt;/h3&gt;&#xA;&lt;p&gt;A short &lt;code&gt;lock_timeout&lt;/code&gt; turns &amp;ldquo;queue everyone behind me&amp;rdquo; into &amp;ldquo;give up quickly&#xA;and try again&amp;rdquo;:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-bash&#34; data-lang=&#34;bash&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;for&lt;/span&gt; i in &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;3&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;4&lt;/span&gt; 5; &lt;span style=&#34;color:#ff79c6&#34;&gt;do&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  psql -v &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;ON_ERROR_STOP&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;\&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f1fa8c&#34;&gt;&lt;/span&gt;    -c &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;SET lock_timeout = &amp;#39;2s&amp;#39;; ALTER TABLE orders ADD COLUMN note text;&amp;#34;&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;\&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f1fa8c&#34;&gt;&lt;/span&gt;    &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;break&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  sleep &lt;span style=&#34;color:#ff79c6&#34;&gt;$((&lt;/span&gt;i &lt;span style=&#34;color:#ff79c6&#34;&gt;*&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;5&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;))&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;done&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;If the table has a slow query on it, the &lt;code&gt;ALTER&lt;/code&gt; fails after 2 seconds, and&#xA;the retry loop waits and tries again. The cost is that the &lt;code&gt;ALTER&lt;/code&gt; still holds&#xA;up other queries for up to those 2 seconds. Keep the timeout small. The&#xA;numbers here are a starting point, not a rule.&lt;/p&gt;&#xA;&lt;h3 id=&#34;2-add-a-column-with-a-constant-default&#34;&gt;2. Add a column with a constant default&lt;/h3&gt;&#xA;&lt;p&gt;Since PostgreSQL 11, &lt;code&gt;ADD COLUMN ... DEFAULT&lt;/code&gt; with a constant does not rewrite&#xA;the table. The value goes into the catalog and is read back for old rows. The&#xA;current docs word it as &amp;ldquo;non-volatile&amp;rdquo;, which also covers &lt;code&gt;now()&lt;/code&gt;:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- Fast: no rewrite&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ALTER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; orders &lt;span style=&#34;color:#ff79c6&#34;&gt;ADD&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;COLUMN&lt;/span&gt; status &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;new&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- Slow: a volatile default rewrites the whole table&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ALTER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; orders &lt;span style=&#34;color:#ff79c6&#34;&gt;ADD&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;COLUMN&lt;/span&gt; token uuid &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; gen_random_uuid();&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Even the fast form takes &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt; for a moment, so it still needs&#xA;the &lt;code&gt;lock_timeout&lt;/code&gt; from recipe 1. For the volatile case, add the column with no&#xA;default, then fill it in small batches.&lt;/p&gt;&#xA;&lt;h3 id=&#34;3-create-indexes-with-concurrently&#34;&gt;3. Create indexes with &lt;code&gt;CONCURRENTLY&lt;/code&gt;&lt;/h3&gt;&#xA;&lt;p&gt;A plain &lt;code&gt;CREATE INDEX&lt;/code&gt; takes &lt;code&gt;SHARE&lt;/code&gt;, which blocks all writes for as long as&#xA;the build lasts. &lt;code&gt;CONCURRENTLY&lt;/code&gt; avoids that:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INDEX&lt;/span&gt; CONCURRENTLY orders_customer_idx &lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; orders (customer_id);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;It has a price and some limits, all from the docs:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;It scans the table twice and waits for every existing transaction that could&#xA;use the index. It takes longer and does more work than a plain build.&lt;/li&gt;&#xA;&lt;li&gt;It cannot run inside a transaction block. Some migration tools wrap each file&#xA;in a transaction, so turn that off for this file.&lt;/li&gt;&#xA;&lt;li&gt;Only one concurrent build can run on a table at a time.&lt;/li&gt;&#xA;&lt;li&gt;It is not supported on a partitioned table. Build it on each partition, then&#xA;create the index on the parent. That last step only changes metadata.&lt;/li&gt;&#xA;&lt;li&gt;If it fails (a deadlock, or a duplicate in a unique index), it leaves an&#xA;&lt;code&gt;INVALID&lt;/code&gt; index behind. Queries ignore it, but writes still pay to keep it&#xA;up to date. Drop it and try again.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;Find leftovers:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; indexrelid::regclass &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; index_name &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; pg_index &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; indisvalid;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;I tested this with a unique index on a column that had duplicates. The build&#xA;failed with &lt;code&gt;could not create unique index ... is duplicated&lt;/code&gt;, and the index&#xA;showed up in that query with &lt;code&gt;indisvalid = false&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;h3 id=&#34;4-add-constraints-with-not-valid&#34;&gt;4. Add constraints with &lt;code&gt;NOT VALID&lt;/code&gt;&lt;/h3&gt;&#xA;&lt;p&gt;A plain &lt;code&gt;ADD CONSTRAINT ... CHECK&lt;/code&gt; scans the whole table while it holds&#xA;&lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;. Split it in two:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- Instant. New and changed rows are checked from now on.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ALTER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; orders &lt;span style=&#34;color:#ff79c6&#34;&gt;ADD&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;CONSTRAINT&lt;/span&gt; status_not_empty&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;CHECK&lt;/span&gt; (status &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&amp;gt;&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;&amp;#39;&lt;/span&gt;) &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;VALID&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- Scans old rows. Takes SHARE UPDATE EXCLUSIVE, so reads and writes continue.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ALTER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; orders VALIDATE &lt;span style=&#34;color:#ff79c6&#34;&gt;CONSTRAINT&lt;/span&gt; status_not_empty;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This works for foreign keys too. &lt;code&gt;ADD FOREIGN KEY ... NOT VALID&lt;/code&gt; skips the&#xA;scan, and &lt;code&gt;VALIDATE CONSTRAINT&lt;/code&gt; does it later with weaker locks (plus a&#xA;&lt;code&gt;ROW SHARE&lt;/code&gt; lock on the referenced table).&lt;/p&gt;&#xA;&lt;p&gt;There is a related trick for &lt;code&gt;SET NOT NULL&lt;/code&gt;. The docs say the table scan is&#xA;skipped when a valid &lt;code&gt;CHECK&lt;/code&gt; constraint already proves no NULL exists. So add&#xA;&lt;code&gt;CHECK (col IS NOT NULL) NOT VALID&lt;/code&gt;, validate it, then run&#xA;&lt;code&gt;SET NOT NULL&lt;/code&gt;. That last step still takes &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;, but now it is&#xA;quick.&lt;/p&gt;&#xA;&lt;h3 id=&#34;5-do-not-change-a-column-type-in-place&#34;&gt;5. Do not change a column type in place&lt;/h3&gt;&#xA;&lt;p&gt;&lt;code&gt;ALTER COLUMN ... TYPE&lt;/code&gt; normally rewrites the whole table and its indexes while&#xA;it holds &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;. A few binary-compatible changes skip the rewrite,&#xA;but you should check the docs for the exact pair of types first. For anything&#xA;else, add a new column, copy the data in batches, and switch the code over.&lt;/p&gt;&#xA;&lt;h2 id=&#34;advisory-locks&#34;&gt;Advisory locks&lt;/h2&gt;&#xA;&lt;p&gt;Advisory locks are locks that PostgreSQL does not use itself. You pick a number,&#xA;and your code decides what it means. Typical use: make sure only one copy of a&#xA;cron job runs.&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- Returns true if you got the lock, false at once if someone else has it.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; pg_try_advisory_lock(&lt;span style=&#34;color:#bd93f9&#34;&gt;42&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Two kinds exist:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Session level&lt;/strong&gt; (&lt;code&gt;pg_advisory_lock&lt;/code&gt;). Held until you release it by hand&#xA;(each lock function has a matching release function) or the session ends. It&#xA;ignores transactions. A lock taken inside a transaction that rolls back is&#xA;still held.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Transaction level&lt;/strong&gt; (&lt;code&gt;pg_advisory_xact_lock&lt;/code&gt;). Released when the&#xA;transaction ends. There is no manual release.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;Prefer the transaction-level kind. It cannot outlive the transaction by&#xA;mistake. They show up in &lt;code&gt;pg_locks&lt;/code&gt; with &lt;code&gt;locktype = &#39;advisory&#39;&lt;/code&gt;, so the blocker&#xA;query above sees them. They share the same shared memory as normal locks, so do&#xA;not take hundreds of thousands of them.&lt;/p&gt;&#xA;&lt;h2 id=&#34;questions-people-ask&#34;&gt;Questions people ask&lt;/h2&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does a SELECT block an ALTER TABLE?&lt;/strong&gt;&#xA;Yes. A &lt;code&gt;SELECT&lt;/code&gt; holds &lt;code&gt;ACCESS SHARE&lt;/code&gt; until its transaction ends, and&#xA;&lt;code&gt;ALTER TABLE&lt;/code&gt; usually needs &lt;code&gt;ACCESS EXCLUSIVE&lt;/code&gt;, which conflicts with it. A slow&#xA;report or an &lt;code&gt;idle in transaction&lt;/code&gt; session that once ran a &lt;code&gt;SELECT&lt;/code&gt; is enough.&#xA;Use &lt;code&gt;lock_timeout&lt;/code&gt; so the &lt;code&gt;ALTER&lt;/code&gt; gives up instead of making a queue.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;How do I see which locks are held in PostgreSQL?&lt;/strong&gt;&#xA;Query &lt;code&gt;pg_locks&lt;/code&gt;. One row is one lock that is held (&lt;code&gt;granted = true&lt;/code&gt;) or&#xA;waited for (&lt;code&gt;granted = false&lt;/code&gt;). Join it to &lt;code&gt;pg_stat_activity&lt;/code&gt; on &lt;code&gt;pid&lt;/code&gt; to see&#xA;the query. To find who is blocking whom, use &lt;code&gt;pg_blocking_pids()&lt;/code&gt; as shown&#xA;above, because joining &lt;code&gt;pg_locks&lt;/code&gt; to itself is easy to get wrong.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;How do I kill a blocking query?&lt;/strong&gt;&#xA;Find the root blocker, then run &lt;code&gt;SELECT pg_cancel_backend(pid)&lt;/code&gt; to cancel its&#xA;current query. If it is &lt;code&gt;idle in transaction&lt;/code&gt;, there is no query to cancel, so&#xA;use &lt;code&gt;SELECT pg_terminate_backend(pid)&lt;/code&gt;, which ends the session and rolls back&#xA;its transaction.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;What does &amp;ldquo;deadlock detected&amp;rdquo; mean?&lt;/strong&gt;&#xA;Two or more transactions are waiting for each other in a circle. PostgreSQL&#xA;ended one of them with error &lt;code&gt;40P01&lt;/code&gt; so that the rest can go on. Retry the&#xA;failed transaction, and make all code lock rows in the same order.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does PostgreSQL turn row locks into a table lock?&lt;/strong&gt;&#xA;No. The docs say there is no limit on the number of rows locked at one time,&#xA;and there is no escalation. SQLite is different, because it locks the whole&#xA;database. See &lt;a href=&#34;https://loomloops.com/post/sqlite-locks/&#34;&gt;how SQLite locks work&lt;/a&gt;.&lt;/p&gt;&#xA;&lt;h2 id=&#34;cheat-sheet&#34;&gt;Cheat sheet&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/understanding-postgresql-locks/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/understanding-postgresql-locks/cheat-sheet.svg&#34; alt=&#34;PostgreSQL locks cheat sheet. Rule 1: a waiting ACCESS EXCLUSIVE blocks every later query on the table. Rule 2: only ACCESS EXCLUSIVE blocks a plain SELECT. Rule 3: plain UPDATE takes FOR NO KEY UPDATE, and foreign key checks take FOR KEY SHARE. Find: pg_stat_activity with pg_blocking_pids. Stop: SET lock_timeout in migrations, and retry. Cancel: pg_cancel_backend, or pg_terminate_backend for idle in transaction. Deadlock 40P01: lock in the same order, then retry. Migrate: CONCURRENTLY for indexes, NOT VALID then VALIDATE for constraints. Guard: idle_in_transaction_session_timeout on the app role.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;440&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;h2 id=&#34;further-reading&#34;&gt;Further reading&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/explicit-locking.html&#34;&gt;PostgreSQL docs: explicit locking&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/view-pg-locks.html&#34;&gt;PostgreSQL docs: the pg_locks view&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/functions-info.html&#34;&gt;PostgreSQL docs: pg_blocking_pids and other session information functions&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/runtime-config-client.html&#34;&gt;PostgreSQL docs: client connection defaults (lock_timeout, statement_timeout, idle_in_transaction_session_timeout)&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/sql-createindex.html&#34;&gt;PostgreSQL docs: CREATE INDEX, building indexes concurrently&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/sql-altertable.html&#34;&gt;PostgreSQL docs: ALTER TABLE&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;Postgres as a job queue with SKIP LOCKED&lt;/a&gt; on this site&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://loomloops.com/post/transactional-outbox-pattern/&#34;&gt;The transactional outbox pattern&lt;/a&gt; on this site&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://loomloops.com/post/idempotency-keys-explained/&#34;&gt;Idempotency keys explained&lt;/a&gt; on this site&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://loomloops.com/post/sqlite-locks/&#34;&gt;How SQLite locks work&lt;/a&gt; on this site&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;</description>
    </item>
  </channel>
</rss>
