<?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>Databases on LoomLoops</title>
    <link>https://loomloops.com/tags/databases/</link>
    <description>Rafi Loom&#39;s blog. Anything I find interesting.</description>
    <language>en-us</language>
    <lastBuildDate>Tue, 15 Sep 2026 07:55:00 +0000</lastBuildDate>
    <atom:link href="https://loomloops.com/tags/databases/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>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>SQLite in Production: Settings for a High-Traffic Website</title>
      <link>https://loomloops.com/post/sqlite-for-high-traffic-websites/</link>
      <pubDate>Sat, 04 Jan 2025 10:22:22 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/sqlite-for-high-traffic-websites/</guid>
      <description>&lt;p&gt;A small site gets shared in a big chat group on a Tuesday evening. The pages&#xA;stay fast. Then the error log fills up with &lt;code&gt;database is locked&lt;/code&gt;, and a couple&#xA;of form submissions vanish.&lt;/p&gt;&#xA;&lt;p&gt;The database is SQLite, running on its default settings. The fix is about five&#xA;lines of setup and one habit. SQLite does not need replacing. It needs to be&#xA;used the way it expects. For anything that moves money I would pick Postgres,&#xA;but for a read-heavy site on one server, SQLite is a strong first choice.&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;SQLite is fast on a busy site because there is no network hop. A page that&#xA;runs 200 queries makes 200 function calls, not 200 round trips.&lt;/li&gt;&#xA;&lt;li&gt;Turn on WAL mode, set a busy timeout, use one write connection and a pool of&#xA;read connections, and keep write transactions short.&lt;/li&gt;&#xA;&lt;li&gt;Never copy a live database file with &lt;code&gt;cp&lt;/code&gt;. Use the backup API,&#xA;&lt;code&gt;VACUUM INTO&lt;/code&gt;, or Litestream, and test a restore.&lt;/li&gt;&#xA;&lt;li&gt;It stops being the right choice when you need more than one app server,&#xA;a network drive, or many writers at once.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;why-sqlite-can-serve-a-busy-site&#34;&gt;Why SQLite can serve a busy site&lt;/h2&gt;&#xA;&lt;p&gt;A client/server database sits across a network. Every SQL statement is a&#xA;message there and back. SQLite is a library inside your app process. A query&#xA;is a function call that reads a local file.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/request-path.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/request-path.svg&#34; alt=&#34;Two request paths for a page that runs about 200 SQL statements. With SQLite the statements are function calls inside the app process, with no network. With a database server each statement is a network round trip, so 200 statements mean 200 round trips.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;418&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The SQLite team makes the same point on their page about&#xA;&lt;a href=&#34;https://www.sqlite.org/np1queryprob.html&#34;&gt;many small queries&lt;/a&gt;. Doing over 200&#xA;round trips in a row &amp;ldquo;can be a serious performance drag&amp;rdquo; with a database&#xA;server, while in SQLite a query is only a function call. That is why code that&#xA;runs a query per row on a page is fine here.&lt;/p&gt;&#xA;&lt;p&gt;How much traffic is that? The SQLite docs say a site with fewer than 100K&#xA;hits a day &amp;ldquo;should work fine&amp;rdquo;, and call that figure a conservative estimate.&#xA;They say SQLite has been shown to work with 10 times that. Their own site, as&#xA;of 2015, handled about 400K to 500K requests a day on one small VM. About&#xA;15% to 20% of those were dynamic pages that touched the database.&lt;/p&gt;&#xA;&lt;p&gt;Treat all of that as a rule of thumb, not a benchmark for your app. It depends&#xA;on how much of your traffic writes. Reads scale well. Writes are the thing to&#xA;watch.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-settings-i-start-with&#34;&gt;The settings I start with&lt;/h2&gt;&#xA;&lt;p&gt;Run these when you open a database. The first one is stored in the file. The&#xA;rest belong to the connection, so a new connection starts with the defaults&#xA;again.&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;PRAGMA journal_mode &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; WAL;      &lt;span style=&#34;color:#6272a4&#34;&gt;-- stored in the file, set once&#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;PRAGMA synchronous &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; NORMAL;    &lt;span style=&#34;color:#6272a4&#34;&gt;-- from here down: every new connection&#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;PRAGMA busy_timeout &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;5000&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;PRAGMA foreign_keys &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;PRAGMA cache_size &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt;&lt;span style=&#34;color:#bd93f9&#34;&gt;64000&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;PRAGMA temp_store &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; MEMORY;&#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;-- optional, measure first:&#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;PRAGMA mmap_size &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;268435456&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/sqlite-for-high-traffic-websites/pragma-card.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/pragma-card.svg&#34; alt=&#34;PRAGMA settings card. journal_mode = WAL is stored in the file: readers and the writer stop blocking each other, same machine only. The other six apply per connection, so set them on every new connection. synchronous = NORMAL syncs at checkpoints only and a power cut can drop the latest commits. busy_timeout = 5000 waits up to 5 seconds for a lock. foreign_keys = ON is off by default. cache_size = -64000 is about 64 MB of page cache. temp_store = MEMORY keeps temporary tables in memory. mmap_size = 268435456 is optional, measure first.&#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;p&gt;What each one does:&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;&lt;code&gt;journal_mode = WAL&lt;/code&gt;.&lt;/strong&gt; The default journal is a rollback journal, where&#xA;readers and the writer get in each other&amp;rsquo;s way. In&#xA;&lt;a href=&#34;https://www.sqlite.org/wal.html&#34;&gt;WAL mode&lt;/a&gt; the writer appends changes to a&#xA;separate &lt;code&gt;-wal&lt;/code&gt; file, and readers keep reading the main file plus the WAL.&#xA;Readers do not block the writer and the writer does not block readers. This is&#xA;the one setting I would not skip. It is persistent: once set, the database&#xA;comes back in WAL mode every time it is opened. The catch is that every process&#xA;using the database must be on the same machine. WAL does not work over a&#xA;network filesystem.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;&lt;code&gt;synchronous = NORMAL&lt;/code&gt;.&lt;/strong&gt; This is a durability trade, so read it twice. With&#xA;&lt;code&gt;FULL&lt;/code&gt;, SQLite syncs the WAL to disk on every commit. With &lt;code&gt;NORMAL&lt;/code&gt; it skips&#xA;that and syncs only at checkpoints. The SQLite docs say that in WAL mode the&#xA;database is always consistent, but a transaction committed with &lt;code&gt;NORMAL&lt;/code&gt; &amp;ldquo;might&#xA;roll back following a power loss or system crash&amp;rdquo;. Commits are still safe if&#xA;only your app crashes. My rule: if losing the last few commits after a power&#xA;cut would cost money or trust, use &lt;code&gt;FULL&lt;/code&gt; and accept slower writes. For a blog,&#xA;a catalog or a dashboard, &lt;code&gt;NORMAL&lt;/code&gt; is the usual choice.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;&lt;code&gt;busy_timeout = 5000&lt;/code&gt;.&lt;/strong&gt; Without it, a connection that finds the database&#xA;locked fails at once with &lt;code&gt;SQLITE_BUSY&lt;/code&gt;. With it, SQLite retries for up to 5000&#xA;ms first. Five seconds is also what the Litestream docs recommend. A&#xA;connection has only one busy handler, so if your driver sets its own, check&#xA;which one wins.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;&lt;code&gt;foreign_keys = ON&lt;/code&gt;.&lt;/strong&gt; Foreign keys are off by default, for old-code&#xA;compatibility, and must be turned on for each connection. The pragma does&#xA;nothing inside a transaction, so run it right after you connect.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;&lt;code&gt;cache_size = -64000&lt;/code&gt;.&lt;/strong&gt; A positive number means pages. A negative number&#xA;means KiB, so &lt;code&gt;-64000&lt;/code&gt; is about 64 MB. The default is &lt;code&gt;-2000&lt;/code&gt;, about 2 MB. The&#xA;cache is per connection, so 5 connections at 64 MB can use 320 MB. Size it for&#xA;your pool, not for one connection.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;&lt;code&gt;temp_store = MEMORY&lt;/code&gt;.&lt;/strong&gt; Temporary tables and indexes stay in RAM instead of&#xA;temp files. Fine for most sites. Watch memory if you run large sorts.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;&lt;code&gt;mmap_size&lt;/code&gt;.&lt;/strong&gt; Optional. It lets SQLite read the database through memory&#xA;mapping instead of &lt;code&gt;read()&lt;/code&gt; calls. The limit is in bytes, and &lt;code&gt;0&lt;/code&gt; turns it off.&#xA;I only enable it after measuring on real data, because the gain depends on&#xA;your disk and OS.&lt;/p&gt;&#xA;&lt;p&gt;One more: &lt;code&gt;page_size&lt;/code&gt; cannot change after the database enters WAL mode. The&#xA;default (4096 bytes since SQLite 3.12) is fine for most sites, so I leave it.&lt;/p&gt;&#xA;&lt;h2 id=&#34;one-writer-many-readers&#34;&gt;One writer, many readers&lt;/h2&gt;&#xA;&lt;p&gt;WAL allows many readers and one writer at a time. A second writer has to wait.&#xA;So do not fight that. Build the app around it: one write connection, and a&#xA;pool of read connections.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/one-writer-pool.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/one-writer-pool.svg&#34; alt=&#34;One writer and a pool of readers. Web requests go to the app. Reads use a pool of four read-only connections that run in parallel. Writes go through a lock to one write connection that runs BEGIN IMMEDIATE and COMMIT. Both paths end at the local files app.db, app.db-wal and app.db-shm.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;466&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Here is the whole idea in Python. It uses only the standard library, and the&#xA;same shape works in any language.&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-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;import&lt;/span&gt; sqlite3&#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;import&lt;/span&gt; threading&#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; contextlib &lt;span style=&#34;color:#ff79c6&#34;&gt;import&lt;/span&gt; contextmanager&#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; queue &lt;span style=&#34;color:#ff79c6&#34;&gt;import&lt;/span&gt; Queue&#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;DB_PATH &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;app.db&amp;#34;&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;# Per connection. Run these on every new connection.&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;CONNECTION_PRAGMAS &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;&amp;#34;&amp;#34;&#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;    PRAGMA synchronous = NORMAL;&#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;    PRAGMA busy_timeout = 5000;&#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;    PRAGMA foreign_keys = 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:#f1fa8c&#34;&gt;    PRAGMA cache_size = -64000;&#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;    PRAGMA temp_store = MEMORY;&#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;&amp;#34;&amp;#34;&amp;#34;&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;&#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;def&lt;/span&gt; &lt;span style=&#34;color:#50fa7b&#34;&gt;connect&lt;/span&gt;(mode):&#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;# isolation_level=None: we send BEGIN and COMMIT ourselves.&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    conn &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; sqlite3&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;connect(&lt;span style=&#34;color:#f1fa8c&#34;&gt;f&lt;/span&gt;&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;file:&lt;/span&gt;&lt;span style=&#34;color:#f1fa8c&#34;&gt;{&lt;/span&gt;DB_PATH&lt;span style=&#34;color:#f1fa8c&#34;&gt;}&lt;/span&gt;&lt;span style=&#34;color:#f1fa8c&#34;&gt;?mode=&lt;/span&gt;&lt;span style=&#34;color:#f1fa8c&#34;&gt;{&lt;/span&gt;mode&lt;span style=&#34;color:#f1fa8c&#34;&gt;}&lt;/span&gt;&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;&lt;/span&gt;, uri&lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;True&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                           isolation_level&lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;None&lt;/span&gt;, check_same_thread&lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;False&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    conn&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;executescript(CONNECTION_PRAGMAS)&#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;return&lt;/span&gt; conn&#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;# One connection does all the writing, behind a lock.&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;writer &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; connect(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;rwc&amp;#34;&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;writer&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;PRAGMA journal_mode = WAL&amp;#34;&lt;/span&gt;)  &lt;span style=&#34;color:#6272a4&#34;&gt;# stored in the file&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;write_lock &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; threading&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;Lock()&#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;# Create tables here, before the readers open a read-only connection.&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;writer&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;CREATE TABLE IF NOT EXISTS hits (id INTEGER PRIMARY KEY, path TEXT NOT NULL)&amp;#34;&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;# A small pool of read-only connections.&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;readers &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; Queue()&#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;in&lt;/span&gt; &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;range&lt;/span&gt;(&lt;span style=&#34;color:#bd93f9&#34;&gt;4&lt;/span&gt;):&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    readers&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;put(connect(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;ro&amp;#34;&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;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;@contextmanager&#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;def&lt;/span&gt; &lt;span style=&#34;color:#50fa7b&#34;&gt;write_tx&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;with&lt;/span&gt; write_lock:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        writer&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;BEGIN IMMEDIATE&amp;#34;&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;try&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;yield&lt;/span&gt; writer&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            writer&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;COMMIT&amp;#34;&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;except&lt;/span&gt; BaseException:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            writer&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;ROLLBACK&amp;#34;&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;raise&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;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;@contextmanager&#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;def&lt;/span&gt; &lt;span style=&#34;color:#50fa7b&#34;&gt;read_conn&lt;/span&gt;():&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    conn &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; readers&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;get()&#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;try&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;yield&lt;/span&gt; conn&#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;finally&lt;/span&gt;:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        readers&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;put(conn)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Use it like this:&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-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;with&lt;/span&gt; write_tx() &lt;span style=&#34;color:#ff79c6&#34;&gt;as&lt;/span&gt; db:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    db&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;INSERT INTO hits (path) VALUES (?)&amp;#34;&lt;/span&gt;, (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;/pricing&amp;#34;&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;with&lt;/span&gt; read_conn() &lt;span style=&#34;color:#ff79c6&#34;&gt;as&lt;/span&gt; db:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    total &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; db&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;SELECT count(*) FROM hits&amp;#34;&lt;/span&gt;)&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;fetchone()[&lt;span style=&#34;color:#bd93f9&#34;&gt;0&lt;/span&gt;]&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;A few details matter here:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;The lock is the write queue.&lt;/strong&gt; Threads wait on &lt;code&gt;write_lock&lt;/code&gt; in line, so&#xA;SQLite never has to decide who goes next. In Go, open a second &lt;code&gt;sql.DB&lt;/code&gt; for&#xA;writes and call &lt;code&gt;SetMaxOpenConns(1)&lt;/code&gt; on it.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Readers open with &lt;code&gt;mode=ro&lt;/code&gt;.&lt;/strong&gt; A read-only connection cannot write by&#xA;mistake. It needs the database file to exist, so create tables with the&#xA;writer first.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;&lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt; takes the write lock at the start.&lt;/strong&gt; The default&#xA;&lt;code&gt;BEGIN&lt;/code&gt; is deferred. If it starts with a &lt;code&gt;SELECT&lt;/code&gt; and writes later, SQLite&#xA;tries to upgrade it. If another connection changed the database in the&#xA;meantime, the upgrade fails with &lt;code&gt;SQLITE_BUSY&lt;/code&gt;. SQLite may also skip the busy&#xA;handler there, to avoid a deadlock. Starting with &lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt; means you&#xA;wait for the lock once, up front, and never fail halfway through. In WAL mode&#xA;&lt;code&gt;BEGIN EXCLUSIVE&lt;/code&gt; behaves the same, so use &lt;code&gt;IMMEDIATE&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;How the lock states work inside is covered in&#xA;&lt;a href=&#34;https://loomloops.com/post/sqlite-locks/&#34;&gt;how SQLite locks work&lt;/a&gt;, so I will not repeat it here.&lt;/p&gt;&#xA;&lt;h2 id=&#34;keep-write-transactions-short&#34;&gt;Keep write transactions short&lt;/h2&gt;&#xA;&lt;p&gt;Writers take turns, so the time each one holds the lock is your write&#xA;capacity. The SQLite docs describe the healthy picture: writers queue up, each&#xA;does its work quickly and moves on, and no lock lasts more than a few dozen&#xA;milliseconds.&lt;/p&gt;&#xA;&lt;p&gt;The most common mistake is doing slow work inside the 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-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;# Wrong: every other write waits while we call a partner API&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;with&lt;/span&gt; write_tx() &lt;span style=&#34;color:#ff79c6&#34;&gt;as&lt;/span&gt; db:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    rate &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; fetch_exchange_rate()      &lt;span style=&#34;color:#6272a4&#34;&gt;# network call, maybe seconds&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    db&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;INSERT INTO quotes (rate) VALUES (?)&amp;#34;&lt;/span&gt;, (rate,))&#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;# Better: slow work first, then a short transaction&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rate &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; fetch_exchange_rate()&#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;with&lt;/span&gt; write_tx() &lt;span style=&#34;color:#ff79c6&#34;&gt;as&lt;/span&gt; db:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    db&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;INSERT INTO quotes (rate) VALUES (?)&amp;#34;&lt;/span&gt;, (rate,))&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Some other habits:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Put many small inserts in one transaction instead of committing each one.&lt;/li&gt;&#xA;&lt;li&gt;Do not wait on a user, a network call or a sleep while a transaction is open.&lt;/li&gt;&#xA;&lt;li&gt;A slow &lt;code&gt;UPDATE&lt;/code&gt; holds the lock for as long as it runs. Fix it with an index&#xA;first, see &lt;a href=&#34;https://loomloops.com/post/sqlite-index-optimisation/&#34;&gt;SQLite index optimisation&lt;/a&gt;.&lt;/li&gt;&#xA;&lt;li&gt;Long read transactions have a cost too. They keep an old snapshot alive, and&#xA;that is how checkpoints get stuck, as the next section shows.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;wal-checkpoints-the-part-people-forget&#34;&gt;WAL checkpoints: the part people forget&lt;/h2&gt;&#xA;&lt;p&gt;In WAL mode, a commit does not touch the main file. It appends pages to the&#xA;&lt;code&gt;app.db-wal&lt;/code&gt; file. A &lt;strong&gt;checkpoint&lt;/strong&gt; copies those pages back into &lt;code&gt;app.db&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/wal-checkpoint.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/wal-checkpoint.svg&#34; alt=&#34;How WAL mode works in four steps. 1: the writer appends changed pages to the app.db-wal file. 2: readers check the WAL for newer pages, then the main app.db file. 3: a checkpoint copies pages from the WAL back into app.db. 4: when no reader needs the old WAL, the writer starts again at the top. A reader that never stops blocks the reset and the WAL keeps growing.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;468&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;By default SQLite runs a checkpoint on its own when a commit pushes the WAL to&#xA;1000 pages or more. With the default 4096 byte page, that is about 4 MB. You&#xA;can change the threshold with &lt;code&gt;PRAGMA wal_autocheckpoint&lt;/code&gt;. Automatic&#xA;checkpoints are always the gentle kind, called PASSIVE: they do as much as&#xA;they can without waiting for anyone, and may stop early if readers or writers&#xA;are busy.&lt;/p&gt;&#xA;&lt;h3 id=&#34;checkpoint-starvation&#34;&gt;Checkpoint starvation&lt;/h3&gt;&#xA;&lt;p&gt;The WAL file can only be reset when no connection is still using it. The SQLite&#xA;docs spell out the bad case. If there are many overlapping readers and &amp;ldquo;there&#xA;is always at least one active reader&amp;rdquo;, no checkpoint can finish and the WAL&#xA;file &amp;ldquo;will grow without bound&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-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;reader A  |------------------------|&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;reader B            |------------------------|&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;reader C                       |------------------------|&#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;          there is never a gap with zero readers,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;          so the WAL cannot be reset and keeps growing&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;A bigger WAL also makes reads slower. Every reader has to check the WAL, and&#xA;the time that takes grows with its size. So a runaway WAL hurts twice: disk&#xA;space and read speed.&lt;/p&gt;&#xA;&lt;p&gt;What helps:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Keep reads short.&lt;/strong&gt; Finish and close cursors. An unfinished statement&#xA;keeps a read transaction open.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Leave &lt;code&gt;wal_autocheckpoint&lt;/code&gt; on&lt;/strong&gt; unless you run checkpoints yourself.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Cap the file size&lt;/strong&gt; with &lt;code&gt;PRAGMA journal_size_limit = 67108864;&lt;/code&gt; (64 MiB).&#xA;A checkpoint does not normally shrink the WAL file unless this limit is set.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Run a stronger checkpoint at a quiet moment&lt;/strong&gt; from the write connection:&#xA;&lt;code&gt;PRAGMA wal_checkpoint(TRUNCATE);&lt;/code&gt;. It waits for readers to finish, then&#xA;truncates the WAL to zero bytes. The waiting is bounded by your busy timeout.&#xA;If it was blocked, the first number it returns is &lt;code&gt;1&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;To see how the WAL is doing, run a passive checkpoint and read the result:&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;PRAGMA wal_checkpoint(PASSIVE);&#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;-- returns three numbers, for example: 0 | 807 | 807&#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;--   busy | frames in the WAL | frames already checkpointed&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;If the second number keeps growing while the third falls behind, something is&#xA;holding a reader open.&lt;/p&gt;&#xA;&lt;h2 id=&#34;backups-never-cp-a-live-database&#34;&gt;Backups: never &lt;code&gt;cp&lt;/code&gt; a live database&lt;/h2&gt;&#xA;&lt;p&gt;This is where people lose data. It feels harmless to run &lt;code&gt;cp app.db backup.db&lt;/code&gt;&#xA;from a cron job. With WAL it is wrong in two ways. Recent commits may still be&#xA;in &lt;code&gt;app.db-wal&lt;/code&gt;, so the copy of &lt;code&gt;app.db&lt;/code&gt; alone can miss them. And the copy may&#xA;land in the middle of a checkpoint. The SQLite docs also note that the &lt;code&gt;-wal&lt;/code&gt;&#xA;file is part of the database state and should be kept with it when you copy or&#xA;move it. The only safe way to remove one is to open the database and close it&#xA;again.&lt;/p&gt;&#xA;&lt;p&gt;You have three safe options.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/backup-options.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/backup-options.svg&#34; alt=&#34;Backup options for a live SQLite database. Never: cp app.db, because a live copy can miss data in app.db-wal or catch a checkpoint midway. Online backup API: one consistent snapshot, copy in one step or writes can restart it. VACUUM INTO: one SQL statement, a consistent compact copy, needs SQLite 3.27 or newer, the target must not exist. Litestream: ships WAL changes to object storage, every second by default for S3, asynchronous so a crash loses what was not shipped yet. Whatever you pick, restore it somewhere else and run PRAGMA integrity_check.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;508&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;h3 id=&#34;1-the-online-backup-api&#34;&gt;1. The online backup API&lt;/h3&gt;&#xA;&lt;p&gt;It makes a copy that is a snapshot of the database as it was when the copy&#xA;started. Most languages wrap it. In Python:&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-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;import&lt;/span&gt; sqlite3&#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;src &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; sqlite3&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;connect(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;app.db&amp;#34;&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;dst &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; sqlite3&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;connect(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;backup.db&amp;#34;&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;src&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;backup(dst)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;dst&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;close()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;src&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;close()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The &lt;code&gt;sqlite3&lt;/code&gt; command line has &lt;code&gt;.backup backup.db&lt;/code&gt; for the same job. One&#xA;warning from the docs: if the copy is done in many small steps and another&#xA;connection writes between steps, the backup restarts, and on a very busy&#xA;database it may never finish. Copying in one step, which is the Python&#xA;default, leaves no gap between steps for a write to land in.&lt;/p&gt;&#xA;&lt;h3 id=&#34;2-vacuum-into&#34;&gt;2. &lt;code&gt;VACUUM INTO&lt;/code&gt;&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;VACUUM&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;/backups/app-2026-11-26.db&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;One SQL statement. It writes a transactionally consistent, compact copy, with&#xA;free pages removed. It exists since SQLite 3.27.0 (2019). The target file must&#xA;not exist, or must be empty. And if the statement is cut short by a power&#xA;loss, the output may be corrupt. So write to a temporary name and rename the&#xA;file after it finishes.&lt;/p&gt;&#xA;&lt;h3 id=&#34;3-litestream-continuous-copies&#34;&gt;3. Litestream: continuous copies&lt;/h3&gt;&#xA;&lt;p&gt;&lt;a href=&#34;https://litestream.io/how-it-works/&#34;&gt;Litestream&lt;/a&gt; runs as a separate process&#xA;next to your app. It watches the WAL and copies changes to object storage,&#xA;such as S3. It does this by taking over checkpointing, and it holds a long&#xA;read transaction to keep other processes from checkpointing. To restore, it&#xA;fetches the latest snapshot and replays the changes after it.&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-sh&#34; data-lang=&#34;sh&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;# keep this running next to your app&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;litestream replicate /var/lib/app/app.db s3://my-bucket/app.db&#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;# restore on a new machine&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;litestream restore -o /var/lib/app/app.db s3://my-bucket/app.db&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Things to know before you rely on it:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;The copy is &lt;strong&gt;asynchronous&lt;/strong&gt;. By default it ships to S3 every second. If the&#xA;server dies, you lose what was not shipped yet, as with async replication in&#xA;Postgres or MySQL. It is disaster recovery, not instant failover.&lt;/li&gt;&#xA;&lt;li&gt;It needs WAL mode.&lt;/li&gt;&#xA;&lt;li&gt;It needs short write locks when it checkpoints, so set &lt;code&gt;busy_timeout&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;li&gt;Only one app should replicate into one bucket path. Two writers into the same&#xA;place can make a restore impossible.&lt;/li&gt;&#xA;&lt;li&gt;Defaults can change between versions. The Litestream docs for 0.5 describe&#xA;compaction levels, a daily snapshot and 24 hours of retention by default.&#xA;Check the docs for the version you run.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;My default is Litestream for a continuous copy, plus a nightly &lt;code&gt;VACUUM INTO&lt;/code&gt;&#xA;file stored somewhere else. The nightly file is a plain database that any&#xA;SQLite can open, even if the Litestream setup breaks.&lt;/p&gt;&#xA;&lt;h3 id=&#34;test-the-restore&#34;&gt;Test the restore&lt;/h3&gt;&#xA;&lt;p&gt;A backup you have never restored is a hope. Once a month, and after every&#xA;change to the backup setup, do this on another machine:&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-sh&#34; data-lang=&#34;sh&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;litestream restore -o /tmp/restored.db s3://my-bucket/app.db&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;sqlite3 /tmp/restored.db &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;PRAGMA integrity_check;&amp;#34;&lt;/span&gt;   &lt;span style=&#34;color:#6272a4&#34;&gt;# should print: ok&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;sqlite3 /tmp/restored.db &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;SELECT count(*) FROM hits;&amp;#34;&lt;/span&gt;  &lt;span style=&#34;color:#6272a4&#34;&gt;# does the count look right?&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Write down how long the restore took. That number is your real downtime after&#xA;a disk failure.&lt;/p&gt;&#xA;&lt;h2 id=&#34;upkeep-pragma-optimize&#34;&gt;Upkeep: &lt;code&gt;PRAGMA optimize&lt;/code&gt;&lt;/h2&gt;&#xA;&lt;p&gt;SQLite&amp;rsquo;s query planner uses statistics about your tables. &lt;code&gt;PRAGMA optimize&lt;/code&gt;&#xA;refreshes them, but only where it is likely to help. The docs give three&#xA;rules:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;With short-lived connections, run &lt;code&gt;PRAGMA optimize;&lt;/code&gt; just before closing.&lt;/li&gt;&#xA;&lt;li&gt;With long-lived connections, run &lt;code&gt;PRAGMA optimize=0x10002;&lt;/code&gt; when the&#xA;connection opens, then &lt;code&gt;PRAGMA optimize;&lt;/code&gt; now and then, say every few hours.&lt;/li&gt;&#xA;&lt;li&gt;Run it after a schema change, especially after &lt;code&gt;CREATE INDEX&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;Advice to run &lt;code&gt;REINDEX&lt;/code&gt; and &lt;code&gt;VACUUM&lt;/code&gt; on a schedule is not needed for most&#xA;sites. A full &lt;code&gt;VACUUM&lt;/code&gt; rewrites the whole file and can need up to twice&#xA;the database size in free disk space. I only run it after deleting a large&#xA;amount of data.&lt;/p&gt;&#xA;&lt;h2 id=&#34;what-to-monitor&#34;&gt;What to monitor&lt;/h2&gt;&#xA;&lt;p&gt;Most of these cost nothing to track.&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Signal&lt;/th&gt;&#xA;          &lt;th&gt;How to check&lt;/th&gt;&#xA;          &lt;th&gt;What it tells you&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;WAL file size&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;ls -l app.db-wal&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Growing means a checkpoint is stuck behind a reader&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Checkpoint result&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;PRAGMA wal_checkpoint(PASSIVE)&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Frames in the WAL vs frames checkpointed&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;SQLITE_BUSY&lt;/code&gt; errors&lt;/td&gt;&#xA;          &lt;td&gt;Count &amp;ldquo;database is locked&amp;rdquo; in the app log&lt;/td&gt;&#xA;          &lt;td&gt;Should be zero. Each one is a bug to fix&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Write transaction time&lt;/td&gt;&#xA;          &lt;td&gt;Time &lt;code&gt;write_tx&lt;/code&gt; in the app&lt;/td&gt;&#xA;          &lt;td&gt;The longest one is your write ceiling&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Wait for the write lock&lt;/td&gt;&#xA;          &lt;td&gt;Time spent waiting in &lt;code&gt;write_lock&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Rising means you are nearing the one-writer limit&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Free disk space&lt;/td&gt;&#xA;          &lt;td&gt;Disk usage on the data volume&lt;/td&gt;&#xA;          &lt;td&gt;Backups, &lt;code&gt;VACUUM&lt;/code&gt; and a big WAL all need room&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Last good backup, last restore test&lt;/td&gt;&#xA;          &lt;td&gt;Timestamp of each&lt;/td&gt;&#xA;          &lt;td&gt;Backups fail quietly&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;h2 id=&#34;where-sqlite-stops&#34;&gt;Where SQLite stops&lt;/h2&gt;&#xA;&lt;p&gt;SQLite is a good fit until one of these is true. They come from the SQLite&#xA;team&amp;rsquo;s own pages on &lt;a href=&#34;https://www.sqlite.org/whentouse.html&#34;&gt;when to use it&lt;/a&gt; and&#xA;on &lt;a href=&#34;https://www.sqlite.org/useovernet.html&#34;&gt;using it over a network&lt;/a&gt;.&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;One machine.&lt;/strong&gt; All processes must be on the same host to use WAL. If you&#xA;need two or more app servers on the same data, SQLite is the wrong tool.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;No network filesystems.&lt;/strong&gt; NFS and similar drives have buggy file locking in&#xA;many implementations. The SQLite docs say that has led to database&#xA;corruption, and that WAL does not work over a network filesystem at all.&#xA;Check what a &amp;ldquo;shared volume&amp;rdquo; in your cloud really is.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;One writer at a time.&lt;/strong&gt; Writers queue. That is fine while each write takes&#xA;milliseconds. If writes pile up and users wait, or you need many writers at&#xA;once, move on. The docs say that if a site is write-intensive or needs&#xA;multiple servers, use a client/server database.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Very large data.&lt;/strong&gt; The limit is 281 terabytes, but long before that the&#xA;docs suggest looking at a client/server database. Backups and restores also&#xA;get slower as the file grows.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;No instant failover.&lt;/strong&gt; Litestream restores a file onto a new machine. You&#xA;wait as long as the restore takes, and you lose the unshipped tail.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;A disk that disappears.&lt;/strong&gt; If your containers restart with a fresh disk, you&#xA;need a persistent volume attached to exactly one instance.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/sqlite-or-postgres.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/sqlite-or-postgres.svg&#34; alt=&#34;SQLite or Postgres? If two or more app servers need the same database, use Postgres. If the file would sit on NFS or another network drive, use a local disk or Postgres. If writes queue up so users wait, or many writers must run at once, use Postgres. If the data is heading for terabytes or you need instant failover, use Postgres. Otherwise use SQLite with WAL, one writer and Litestream.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;526&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;If you do outgrow it, the move is easier than it sounds when you kept to plain&#xA;SQL. Postgres swaps the one big write lock for locks on single rows. The post&#xA;on &lt;a href=&#34;https://loomloops.com/post/understanding-postgresql-locks/&#34;&gt;understanding PostgreSQL locks&lt;/a&gt;&#xA;explains how that works. And if the part that hurts is a job queue, see&#xA;&lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;Postgres as a job queue&lt;/a&gt;.&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 SQLite good enough for production?&lt;/strong&gt;&#xA;Yes, for the right job. The SQLite docs say it works great for most low to&#xA;medium traffic websites. It is a good fit when one machine serves the site,&#xA;reads dominate and writes are short. It is a poor fit when you need several&#xA;app servers or many concurrent writers.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;How many requests can SQLite handle?&lt;/strong&gt;&#xA;The docs give a rule of thumb: a site under about 100K hits a day should be&#xA;fine, and 10 times that has been shown to work. Your real limit depends on how&#xA;many requests write and how long each write takes. Measure your own write&#xA;times before you trust a number from someone else.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does WAL mode fix &amp;ldquo;database is locked&amp;rdquo;?&lt;/strong&gt;&#xA;It fixes most of it, because readers and the writer stop blocking each other.&#xA;You can still see the error when two connections try to write at once, or when&#xA;a read transaction tries to upgrade to a write. Set &lt;code&gt;busy_timeout&lt;/code&gt;, use one&#xA;write connection, and start writes with &lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Can two servers share one SQLite file?&lt;/strong&gt;&#xA;Not safely over a network drive. File locking on network filesystems is&#xA;unreliable, and WAL needs every process on the same machine. Use Postgres, or&#xA;put one app in front of the file and have the other servers call it.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;How do I back up a SQLite database that is in use?&lt;/strong&gt;&#xA;Use the online backup API, &lt;code&gt;VACUUM INTO&lt;/code&gt;, or Litestream. Do not use &lt;code&gt;cp&lt;/code&gt; on a&#xA;live file. Then restore the backup on another machine and run&#xA;&lt;code&gt;PRAGMA integrity_check&lt;/code&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/sqlite-for-high-traffic-websites/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-for-high-traffic-websites/cheat-sheet.svg&#34; alt=&#34;SQLite in production cheat sheet. Reads: no network hop, so many small queries are fine. Open: WAL, NORMAL sync, busy_timeout 5000, foreign_keys ON. Writes: one write connection, BEGIN IMMEDIATE, keep it short. Readers: a pool of read-only connections with short reads. Checkpoints: leave autocheckpoint on and watch the -wal file size. Backups: never cp a live file, use the backup API, VACUUM INTO or Litestream. Restore: test it by restoring elsewhere and running integrity_check. Upkeep: PRAGMA optimize after CREATE INDEX and every few hours. Limits: one machine, no NFS, one writer at a time, otherwise Postgres.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;444&#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.sqlite.org/wal.html&#34;&gt;SQLite docs: Write-Ahead Logging&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/pragma.html&#34;&gt;SQLite docs: PRAGMA statements&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/whentouse.html&#34;&gt;SQLite docs: appropriate uses for SQLite&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/backup.html&#34;&gt;SQLite docs: the online backup API&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/lang_vacuum.html&#34;&gt;SQLite docs: VACUUM and VACUUM INTO&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/useovernet.html&#34;&gt;SQLite docs: SQLite over a network&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/lang_transaction.html&#34;&gt;SQLite docs: transactions&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://litestream.io/how-it-works/&#34;&gt;Litestream: how it works&lt;/a&gt; and &lt;a href=&#34;https://litestream.io/tips/&#34;&gt;tips and caveats&lt;/a&gt;&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;li&gt;&lt;a href=&#34;https://loomloops.com/post/sqlite-index-optimisation/&#34;&gt;SQLite index optimisation&lt;/a&gt; on this site&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&lt;/a&gt; and &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>
    <item>
      <title>SQLite Indexes Explained: How to Find and Fix Slow Queries</title>
      <link>https://loomloops.com/post/sqlite-index-optimisation/</link>
      <pubDate>Fri, 30 Aug 2024 22:20:09 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/sqlite-index-optimisation/</guid>
      <description>&lt;p&gt;The &amp;ldquo;my orders&amp;rdquo; page was fast for months. Then the shop grew. The table went&#xA;from a few thousand orders to a couple of hundred thousand, and the same page&#xA;started to feel slow. Nobody touched the query. The data just got bigger.&lt;/p&gt;&#xA;&lt;p&gt;Most of the time the fix is one &lt;code&gt;CREATE INDEX&lt;/code&gt;. The hard part is knowing which&#xA;one, and knowing that it worked. SQLite will tell you, if you ask. This post&#xA;takes one slow query, asks SQLite how it runs it, and fixes it in four steps.&#xA;Every plan below is real output from SQLite 3.51 on 200,000 generated orders.&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;EXPLAIN QUERY PLAN&lt;/code&gt; shows how SQLite runs a query. &lt;code&gt;SCAN&lt;/code&gt; means it reads&#xA;every row. &lt;code&gt;SEARCH ... USING INDEX&lt;/code&gt; means it jumps straight to the rows.&lt;/li&gt;&#xA;&lt;li&gt;For a composite index, put the &lt;code&gt;=&lt;/code&gt; columns first, then one range column, then&#xA;the &lt;code&gt;ORDER BY&lt;/code&gt; column. Add the columns you select at the end to skip the table.&lt;/li&gt;&#xA;&lt;li&gt;An index is not free. It slows every write, and one on a column with few&#xA;distinct values often does nothing. Run &lt;code&gt;PRAGMA optimize&lt;/code&gt; so SQLite knows&#xA;your data.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;the-slow-query&#34;&gt;The slow query&lt;/h2&gt;&#xA;&lt;p&gt;Here is the table. The &lt;code&gt;orders&lt;/code&gt; table has one row per order, and the page asks&#xA;for the 20 newest paid orders of one customer.&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; orders (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  id          &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;INTEGER&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;  customer_id &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;INTEGER&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;  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;pending&amp;#39;, &amp;#39;paid&amp;#39; or &amp;#39;refunded&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;  total_cents &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;INTEGER&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;  created_at  &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;2025-01-14 09:30:00&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;  note        &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;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;To follow along, fill it with random data. The numbers will differ from mine,&#xA;but the plans will match.&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;WITH&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;RECURSIVE&lt;/span&gt; n(i) &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; (&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;UNION&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;ALL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; i &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;FROM&lt;/span&gt; n &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; i &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;200000&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 (customer_id, status, total_cents, created_at, note)&#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; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;abs&lt;/span&gt;(random()) &lt;span style=&#34;color:#ff79c6&#34;&gt;%&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1000&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;CASE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;WHEN&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;abs&lt;/span&gt;(random()) &lt;span style=&#34;color:#ff79c6&#34;&gt;%&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;100&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;2&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;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:#ff79c6&#34;&gt;WHEN&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;abs&lt;/span&gt;(random()) &lt;span style=&#34;color:#ff79c6&#34;&gt;%&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;100&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;10&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;refunded&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;ELSE&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;paid&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;       &lt;span style=&#34;color:#ff79c6&#34;&gt;abs&lt;/span&gt;(random()) &lt;span style=&#34;color:#ff79c6&#34;&gt;%&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;50000&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;       datetime(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;2025-01-01&amp;#39;&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;||&lt;/span&gt; (i &lt;span style=&#34;color:#ff79c6&#34;&gt;%&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;500&lt;/span&gt;) &lt;span style=&#34;color:#ff79c6&#34;&gt;||&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39; hours&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;note for order &amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;||&lt;/span&gt; i&#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; n;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The slow query, with &lt;code&gt;EXPLAIN QUERY PLAN&lt;/code&gt; in front:&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;EXPLAIN&lt;/span&gt; QUERY PLAN&#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, total_cents, created_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;FROM&lt;/span&gt; orders&#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; customer_id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;42&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&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;paid&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; created_at &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;20&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&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-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;QUERY PLAN&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;|--SCAN orders&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;`--USE TEMP B-TREE FOR ORDER BY&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Two lines, two problems. &lt;code&gt;SCAN orders&lt;/code&gt; means SQLite reads all 200,000 rows to&#xA;find the few that belong to customer 42. &lt;code&gt;USE TEMP B-TREE FOR ORDER BY&lt;/code&gt; means it&#xA;then sorts what it found, because nothing hands the rows over in order.&lt;/p&gt;&#xA;&lt;p&gt;In the SQLite shell, &lt;code&gt;.eqp on&lt;/code&gt; prints the plan before every query result, which&#xA;saves typing. The &lt;a href=&#34;https://www.sqlite.org/eqp.html&#34;&gt;SQLite docs&lt;/a&gt; say the plan&#xA;text is for people, and its format can change between releases, so do not parse&#xA;it in your code.&lt;/p&gt;&#xA;&lt;h2 id=&#34;what-an-index-is&#34;&gt;What an index is&lt;/h2&gt;&#xA;&lt;p&gt;An index is a sorted copy of some columns, plus the rowid of each row. The&#xA;rowid is the number SQLite uses to find the row in the table. The&#xA;&lt;a href=&#34;https://www.sqlite.org/queryplanner.html&#34;&gt;query planner docs&lt;/a&gt; describe it as&#xA;another table with the indexed content stored in front of the rowid and all rows&#xA;in content order.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-index-optimisation/scan-vs-search.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-index-optimisation/scan-vs-search.svg&#34; alt=&#34;Two strips of customer ids. Without an index SQLite reads every row to find customer 42. With an index the ids are sorted, so SQLite jumps to the first 42, reads the three matches and stops.&#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;Because the copy is sorted, SQLite can use a binary search: look at the middle,&#xA;decide which half to keep, repeat. The cost grows with the logarithm of the row&#xA;count, not with the row count. The table itself is also a sorted tree, keyed by&#xA;rowid, so once the index gives a rowid, a second search finds the row.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-index-optimisation/how-an-index-works.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-index-optimisation/how-an-index-works.svg&#34; alt=&#34;How an index finds a row. SQLite compares 42 with the keys in the root page, follows the middle branch to a leaf page, finds the entry for customer 42 with rowid 8812, then uses that rowid to read the row from the orders table.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;452&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The &lt;a href=&#34;https://www.sqlite.org/fileformat2.html&#34;&gt;file format docs&lt;/a&gt; call this a&#xA;B-tree. Each index entry is the indexed column values followed by the rowid.&#xA;You never build it by hand. &lt;code&gt;CREATE INDEX&lt;/code&gt; does it, and SQLite keeps it in step&#xA;with the table on every write.&lt;/p&gt;&#xA;&lt;h2 id=&#34;reading-explain-query-plan&#34;&gt;Reading EXPLAIN QUERY PLAN&lt;/h2&gt;&#xA;&lt;p&gt;Five phrases cover almost every plan you will see.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-index-optimisation/read-query-plan.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-index-optimisation/read-query-plan.svg&#34; alt=&#34;How to read EXPLAIN QUERY PLAN. SCAN orders: reads every row. SCAN orders USING COVERING INDEX: reads every entry of a smaller index. SEARCH orders USING INDEX with (customer_id=?): jumps to matching entries, then reads table rows. SEARCH USING COVERING INDEX: the index has every column, so the table is not read. USE TEMP B-TREE FOR ORDER BY: collects rows and sorts them. The text in brackets shows which index columns narrowed the search.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;508&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;&lt;code&gt;SCAN&lt;/code&gt;&lt;/strong&gt; reads every row, or every entry of an index. &lt;strong&gt;&lt;code&gt;SEARCH&lt;/code&gt;&lt;/strong&gt; reads&#xA;only a subset. This is the first word to look at.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;&lt;code&gt;USING INDEX name&lt;/code&gt;&lt;/strong&gt; means SQLite finds rows through the index, then reads&#xA;the table for the other columns.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;&lt;code&gt;USING COVERING INDEX name&lt;/code&gt;&lt;/strong&gt; means the index has every column the query&#xA;needs, so the table is never read.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;&lt;code&gt;(customer_id=? AND status=?)&lt;/code&gt;&lt;/strong&gt; lists the conditions that the index&#xA;handles. If a column you expected is missing here, it is not helping.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;&lt;code&gt;USE TEMP B-TREE FOR ORDER BY&lt;/code&gt;&lt;/strong&gt; means a separate sort step. The same&#xA;phrase appears for &lt;code&gt;GROUP BY&lt;/code&gt; and &lt;code&gt;DISTINCT&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;A trap: &lt;code&gt;SCAN orders USING COVERING INDEX idx_x&lt;/code&gt; is still a full scan. SQLite&#xA;reads every entry in the index. It is cheaper than reading the table, because&#xA;the index is smaller, but the work still grows with the table.&lt;/p&gt;&#xA;&lt;h2 id=&#34;fix-1-index-the-column-in-where&#34;&gt;Fix 1: index the column in WHERE&lt;/h2&gt;&#xA;&lt;p&gt;The query filters on &lt;code&gt;customer_id&lt;/code&gt;, so index 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; idx_orders_customer &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;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;QUERY PLAN&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;|--SEARCH orders USING INDEX idx_orders_customer (customer_id=?)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;`--USE TEMP B-TREE FOR ORDER BY&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;code&gt;SCAN&lt;/code&gt; became &lt;code&gt;SEARCH&lt;/code&gt;. SQLite now finds the roughly 200 orders of customer 42&#xA;without touching the other 199,800. Two things are still wrong. It reads all&#xA;200 table rows to test &lt;code&gt;status&lt;/code&gt;, and it still sorts them. A customer with&#xA;10,000 orders would pay for 10,000 rows and a sort on every page view.&lt;/p&gt;&#xA;&lt;h2 id=&#34;fix-2-one-composite-index&#34;&gt;Fix 2: one composite index&lt;/h2&gt;&#xA;&lt;p&gt;A composite index has more than one column. SQLite sorts it by the first&#xA;column, uses the second to break ties, and so on. The&#xA;&lt;a href=&#34;https://www.sqlite.org/optoverview.html&#34;&gt;docs&lt;/a&gt; give the rules for using it:&#xA;the first columns must be tested with &lt;code&gt;=&lt;/code&gt;, &lt;code&gt;IN&lt;/code&gt; or &lt;code&gt;IS&lt;/code&gt;, the last column used&#xA;may have range tests (&lt;code&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;BETWEEN&lt;/code&gt;), and there can be no gaps.&lt;/p&gt;&#xA;&lt;p&gt;That gives a recipe for column order:&lt;/p&gt;&#xA;&lt;ol&gt;&#xA;&lt;li&gt;&lt;strong&gt;Equality columns first.&lt;/strong&gt; Here &lt;code&gt;customer_id&lt;/code&gt; and &lt;code&gt;status&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;One range column next&lt;/strong&gt;, if the query has one.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;The &lt;code&gt;ORDER BY&lt;/code&gt; column last.&lt;/strong&gt; Rows with the same &lt;code&gt;customer_id&lt;/code&gt; and&#xA;&lt;code&gt;status&lt;/code&gt; are already stored in &lt;code&gt;created_at&lt;/code&gt; order, so no sort is needed.&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-index-optimisation/composite-column-order.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-index-optimisation/composite-column-order.svg&#34; alt=&#34;Composite index on customer_id, status, created_at. Rows are sorted by customer_id, then status, then created_at. The query for customer 42 and status paid lands on one block of rows that is already sorted by created_at, so no sort step is needed. Rule: equality columns first, then one range column, then the ORDER BY column.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;470&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Replace the single-column index with a composite one:&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;DROP&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INDEX&lt;/span&gt; idx_orders_customer;&#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; idx_orders_customer_status_created&#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; orders (customer_id, status, created_at);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&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-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;QUERY PLAN&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;`--SEARCH orders USING INDEX idx_orders_customer_status_created (customer_id=? AND status=?)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The temp B-tree line is gone. SQLite walks the matching block of the index&#xA;from the end (that is what &lt;code&gt;DESC&lt;/code&gt; asks for) and stops after 20 rows. We dropped&#xA;the old index because it is a prefix of the new one. The planner docs give the&#xA;rule: never keep two indexes where one is a prefix of the other, and drop the&#xA;shorter one.&lt;/p&gt;&#xA;&lt;h3 id=&#34;the-left-most-prefix-rule&#34;&gt;The left-most prefix rule&lt;/h3&gt;&#xA;&lt;p&gt;The composite index serves every query that starts with its first columns, and&#xA;stops helping where the chain breaks. These are real plans for the index above:&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Query filters on&lt;/th&gt;&#xA;          &lt;th&gt;Plan&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;customer_id&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SEARCH ... (customer_id=?)&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;customer_id&lt;/code&gt; and &lt;code&gt;status&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SEARCH ... (customer_id=? AND status=?)&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;customer_id&lt;/code&gt; and &lt;code&gt;created_at &amp;gt;= ?&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SEARCH ... (customer_id=?)&lt;/code&gt;, the gap at &lt;code&gt;status&lt;/code&gt; stops it&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;status&lt;/code&gt; only&lt;/td&gt;&#xA;          &lt;td&gt;cannot &lt;code&gt;SEARCH&lt;/code&gt;, falls back to a &lt;code&gt;SCAN&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;The third row is the one that bites. &lt;code&gt;created_at&lt;/code&gt; is in the index, but because&#xA;&lt;code&gt;status&lt;/code&gt; is skipped, it cannot narrow the search. SQLite finds the customer&amp;rsquo;s&#xA;rows and filters the dates one by one.&lt;/p&gt;&#xA;&lt;p&gt;The same rule explains why column order matters for a range. Take a query with&#xA;&lt;code&gt;customer_id = ?&lt;/code&gt; and &lt;code&gt;created_at &amp;gt;= ?&lt;/code&gt;:&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Index&lt;/th&gt;&#xA;          &lt;th&gt;What narrows the search&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;(created_at, customer_id)&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(created_at&amp;gt;?)&lt;/code&gt;, only the range&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;(customer_id, created_at)&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(customer_id=? AND created_at&amp;gt;?)&lt;/code&gt;, both&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;Put the range column after the equality columns. A range column ends the&#xA;chain, so anything to its right cannot help narrow the search.&lt;/p&gt;&#xA;&lt;p&gt;Two more gotchas, both from real plans:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;&lt;code&gt;IN&lt;/code&gt; on an earlier column brings the sort back.&lt;/strong&gt; With&#xA;&lt;code&gt;status IN (&#39;paid&#39;, &#39;refunded&#39;) ORDER BY created_at&lt;/code&gt;, SQLite searches two&#xA;blocks. Each block is in &lt;code&gt;created_at&lt;/code&gt; order, but the two together are not, so&#xA;you see &lt;code&gt;USE TEMP B-TREE FOR ORDER BY&lt;/code&gt; again.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;A range on a middle column breaks the order too.&lt;/strong&gt; With&#xA;&lt;code&gt;status &amp;gt; &#39;a&#39; ORDER BY created_at&lt;/code&gt;, the rows are no longer in &lt;code&gt;created_at&lt;/code&gt;&#xA;order. You cannot get both a range and an &lt;code&gt;ORDER BY&lt;/code&gt; on different columns from&#xA;one index. Pick the one that removes more rows and measure.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;One composite index is also better than two single-column ones. SQLite does not&#xA;intersect two indexes for an &lt;code&gt;AND&lt;/code&gt;. The planner docs say plainly that it does&#xA;not implement that technique. (For &lt;code&gt;OR&lt;/code&gt; it can use one index per branch.)&lt;/p&gt;&#xA;&lt;h2 id=&#34;fix-3-a-covering-index&#34;&gt;Fix 3: a covering index&lt;/h2&gt;&#xA;&lt;p&gt;Look at the plan again. It says &lt;code&gt;USING INDEX&lt;/code&gt;, not &lt;code&gt;USING COVERING INDEX&lt;/code&gt;. The&#xA;query selects &lt;code&gt;total_cents&lt;/code&gt;, which is not in the index, so for each of the 20&#xA;rows SQLite goes back to the table. Add &lt;code&gt;total_cents&lt;/code&gt; at the end:&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;DROP&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INDEX&lt;/span&gt; idx_orders_customer_status_created;&#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; idx_orders_customer_status_created_total&#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; orders (customer_id, status, created_at, total_cents);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&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-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;QUERY PLAN&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;`--SEARCH orders USING COVERING INDEX idx_orders_customer_status_created_total (customer_id=? AND status=?)&#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/sqlite-index-optimisation/covering-index.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-index-optimisation/covering-index.svg&#34; alt=&#34;Two plans side by side. With USING INDEX, SQLite finds the rowid in the index and then reads the table row to get total_cents: two lookups. With USING COVERING INDEX the index already holds total_cents, so the table is never read: one lookup.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;372&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;&lt;code&gt;id&lt;/code&gt; is free, because it is the rowid and every index entry holds the rowid.&#xA;The docs say a covering index can make many queries run about twice as fast.&#xA;That is a constant factor, not a change in how the cost grows. A covering index&#xA;has a price: it is a bigger index, so it uses more disk and slows writes a bit&#xA;more.&lt;/p&gt;&#xA;&lt;p&gt;It only works if the query selects columns that are all in the index. Change&#xA;the query to &lt;code&gt;SELECT *&lt;/code&gt; on this table and the plan goes back to&#xA;&lt;code&gt;SEARCH ... USING INDEX&lt;/code&gt;, because &lt;code&gt;note&lt;/code&gt; is not in the index. Select only the&#xA;columns you need. That is better for covering indexes and for everything else.&lt;/p&gt;&#xA;&lt;h2 id=&#34;partial-indexes-index-only-the-rows-you-ask-for&#34;&gt;Partial indexes: index only the rows you ask for&lt;/h2&gt;&#xA;&lt;p&gt;A partial index has a &lt;code&gt;WHERE&lt;/code&gt; clause and holds entries only for the rows where&#xA;it is true. Say a back-office job looks for orders still &lt;code&gt;pending&lt;/code&gt;. In my data&#xA;that is about 2% of the table.&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; idx_orders_pending_customer&#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; orders (customer_id) &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;The index is small, so it is cheap to keep and quick to search. It is used&#xA;only when SQLite can prove that the query&amp;rsquo;s &lt;code&gt;WHERE&lt;/code&gt; implies the index&amp;rsquo;s&#xA;&lt;code&gt;WHERE&lt;/code&gt;. Here are the plans for the same index:&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Query&lt;/th&gt;&#xA;          &lt;th&gt;Plan&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;WHERE customer_id = 42 AND status = &#39;pending&#39;&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SEARCH orders USING COVERING INDEX idx_orders_pending_customer (customer_id=?)&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;WHERE customer_id = 42 AND status = &#39;paid&#39;&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SCAN orders&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;WHERE customer_id = 42&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SCAN orders&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;WHERE customer_id = 42 AND status = ?1&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;SCAN orders&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;The last row is the surprise. A bound parameter is fine in a query, but SQLite&#xA;does not know at planning time that &lt;code&gt;?1&lt;/code&gt; will be &lt;code&gt;&#39;pending&#39;&lt;/code&gt;, so it cannot use&#xA;the index. Write the literal in the query text.&lt;/p&gt;&#xA;&lt;p&gt;The &lt;a href=&#34;https://www.sqlite.org/partialindex.html&#34;&gt;partial index docs&lt;/a&gt; explain that&#xA;SQLite has no general theorem prover. It uses two simple rules. First, a term&#xA;in the query&amp;rsquo;s &lt;code&gt;WHERE&lt;/code&gt; has to match a term in the index&amp;rsquo;s &lt;code&gt;WHERE&lt;/code&gt; exactly:&#xA;&lt;code&gt;b=6&lt;/code&gt; matches &lt;code&gt;b=6&lt;/code&gt;, but not &lt;code&gt;b=3+3&lt;/code&gt; or &lt;code&gt;b BETWEEN 6 AND 6&lt;/code&gt;. Second, if the&#xA;index says &lt;code&gt;z IS NOT NULL&lt;/code&gt;, a query that compares &lt;code&gt;z&lt;/code&gt; with an operator other&#xA;than &lt;code&gt;IS&lt;/code&gt; (&lt;code&gt;=&lt;/code&gt;, &lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;&amp;gt;&lt;/code&gt;, &lt;code&gt;IN&lt;/code&gt;, &lt;code&gt;LIKE&lt;/code&gt;) matches. When you are unsure,&#xA;run &lt;code&gt;EXPLAIN QUERY PLAN&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;The &lt;code&gt;WHERE&lt;/code&gt; of the index itself cannot use subqueries, other tables,&#xA;non-deterministic functions or bound parameters. A partial index can also be&#xA;&lt;code&gt;UNIQUE&lt;/code&gt;, which gives you &amp;ldquo;only one per group&amp;rdquo; rules, for example one default&#xA;address per user. Partial indexes need SQLite 3.8.0 (2013) or newer, and a&#xA;database that has one cannot be opened by older versions.&lt;/p&gt;&#xA;&lt;h2 id=&#34;indexes-on-expressions&#34;&gt;Indexes on expressions&lt;/h2&gt;&#xA;&lt;p&gt;Users type their email in any case, so the login query looks like this:&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; users &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;lower&lt;/span&gt;(email) &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;user42@example.com&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 plain index on &lt;code&gt;email&lt;/code&gt; does not help. The index is sorted by &lt;code&gt;email&lt;/code&gt;, not by&#xA;&lt;code&gt;lower(email)&lt;/code&gt;, so SQLite reads the whole index:&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;QUERY PLAN&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;`--SCAN users USING COVERING INDEX idx_users_email&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Index the expression itself:&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; idx_users_email_lower &lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; users (&lt;span style=&#34;color:#ff79c6&#34;&gt;lower&lt;/span&gt;(email));&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&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-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;QUERY PLAN&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;`--SEARCH users USING COVERING INDEX idx_users_email_lower (&amp;lt;expr&amp;gt;=?)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The query has to use the same expression. The&#xA;&lt;a href=&#34;https://www.sqlite.org/expridx.html&#34;&gt;expression index docs&lt;/a&gt; say the planner&#xA;&amp;ldquo;does not do algebra&amp;rdquo;: an index on &lt;code&gt;x+y&lt;/code&gt; is not used for &lt;code&gt;y+x=22&lt;/code&gt;. In my test,&#xA;&lt;code&gt;lower(trim(email))&lt;/code&gt; also falls back to a scan.&lt;/p&gt;&#xA;&lt;p&gt;Expression indexes only accept deterministic functions (same input, same&#xA;output), so &lt;code&gt;random()&lt;/code&gt; is out. They need SQLite 3.9.0 (2015) or newer.&lt;/p&gt;&#xA;&lt;p&gt;Often you can fix the query instead. Take &lt;code&gt;WHERE date(created_at) = &#39;2025-01-10&#39;&lt;/code&gt;.&#xA;With an index on &lt;code&gt;created_at&lt;/code&gt; (&lt;code&gt;CREATE INDEX idx_orders_created ON orders (created_at)&lt;/code&gt;),&#xA;it is a scan, because the column is wrapped in a function. Written as a range,&#xA;it uses the index:&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;WHERE&lt;/span&gt; created_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;2025-01-10&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; created_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;2025-01-11&amp;#39;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&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-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;QUERY PLAN&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;`--SEARCH orders USING COVERING INDEX idx_orders_created (created_at&amp;gt;? AND created_at&amp;lt;?)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;like-and-upper-and-lower-case&#34;&gt;LIKE and upper and lower case&lt;/h2&gt;&#xA;&lt;p&gt;&lt;code&gt;LIKE&lt;/code&gt; can use an index, but only if the pattern does not start with a wildcard&#xA;and the index uses the right collation (the rule for comparing text). By&#xA;default &lt;code&gt;LIKE&lt;/code&gt; ignores case for plain English letters. The optimizer docs&#xA;say that with the default setting, the column must be indexed with &lt;code&gt;COLLATE NOCASE&lt;/code&gt;. If you turn on &lt;code&gt;PRAGMA case_sensitive_like&lt;/code&gt;, it must be the default&#xA;&lt;code&gt;BINARY&lt;/code&gt; collation instead.&lt;/p&gt;&#xA;&lt;p&gt;My &lt;code&gt;users.email&lt;/code&gt; has an ordinary index, which is &lt;code&gt;BINARY&lt;/code&gt;. So this scans:&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; users &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; email &lt;span style=&#34;color:#ff79c6&#34;&gt;LIKE&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;user42%&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&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-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;QUERY PLAN&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;`--SCAN users USING COVERING INDEX idx_users_email&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Add a &lt;code&gt;NOCASE&lt;/code&gt; index and the same query searches a range:&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; idx_users_email_nocase &lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; users (email &lt;span style=&#34;color:#ff79c6&#34;&gt;COLLATE&lt;/span&gt; NOCASE);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&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-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;QUERY PLAN&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;`--SEARCH users USING COVERING INDEX idx_users_email_nocase (email&amp;gt;? AND email&amp;lt;?)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;SQLite turns &lt;code&gt;LIKE &#39;user42%&#39;&lt;/code&gt; into a range test between &lt;code&gt;user42&lt;/code&gt; and the next&#xA;string up. &lt;code&gt;email LIKE &#39;%example.com&#39;&lt;/code&gt;, with a wildcard at the start, cannot do&#xA;that and scans. Equality works too: &lt;code&gt;email = ? COLLATE NOCASE&lt;/code&gt; uses the&#xA;&lt;code&gt;NOCASE&lt;/code&gt; index.&lt;/p&gt;&#xA;&lt;h2 id=&#34;analyze-and-pragma-optimize&#34;&gt;ANALYZE and PRAGMA optimize&lt;/h2&gt;&#xA;&lt;p&gt;SQLite has to guess how many rows each index will return. &lt;code&gt;ANALYZE&lt;/code&gt; counts and&#xA;stores the answer in a table called &lt;code&gt;sqlite_stat1&lt;/code&gt;. The&#xA;&lt;a href=&#34;https://www.sqlite.org/lang_analyze.html&#34;&gt;ANALYZE docs&lt;/a&gt; describe it. The&#xA;planner docs say that without it, the choice between indexes is arbitrary.&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;ANALYZE&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; &lt;span style=&#34;color:#ff79c6&#34;&gt;*&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; sqlite_stat1;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;With one index on &lt;code&gt;customer_id&lt;/code&gt; and one on &lt;code&gt;status&lt;/code&gt;, the table holds this:&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;orders|idx_customer|200000 200&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;orders|idx_status|200000 66667&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Read the &lt;code&gt;stat&lt;/code&gt; column as: the index has about 200,000 entries, and each&#xA;&lt;code&gt;customer_id&lt;/code&gt; matches about 200 of them. It is an average, a single number per&#xA;column. That is also why it cannot tell a common value from a rare one.&lt;/p&gt;&#xA;&lt;p&gt;You should not have to remember to run &lt;code&gt;ANALYZE&lt;/code&gt;. The docs recommend&#xA;&lt;code&gt;PRAGMA optimize&lt;/code&gt;, which runs it only when it is likely to help, and quickly:&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;-- short-lived connection: run once, just before closing&#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;PRAGMA optimize;&#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;-- long-lived connection: run when it opens, then now and then&#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;PRAGMA optimize &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;0&lt;/span&gt;x10002;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;PRAGMA optimize;   &lt;span style=&#34;color:#6272a4&#34;&gt;-- for example once a day&#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:#6272a4&#34;&gt;-- after any schema change, especially CREATE INDEX&#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;PRAGMA optimize;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;code&gt;PRAGMA optimize(-1)&lt;/code&gt; shows what it would do without doing it. Since SQLite&#xA;3.46.0 you do not need to set &lt;code&gt;analysis_limit&lt;/code&gt; yourself, because optimize does&#xA;it.&lt;/p&gt;&#xA;&lt;p&gt;Statistics also switch on one more trick. With an index on&#xA;&lt;code&gt;(status, created_at)&lt;/code&gt; and a query that only filters on &lt;code&gt;created_at&lt;/code&gt;, SQLite&#xA;may use a skip-scan, which tries each value of the first column. It only does&#xA;that when it knows the first column has many repeats, and it only knows after&#xA;&lt;code&gt;ANALYZE&lt;/code&gt;. In my test the plan changed from&#xA;&lt;code&gt;SCAN orders USING COVERING INDEX idx_status_created&lt;/code&gt; to&#xA;&lt;code&gt;SEARCH ... (ANY(status) AND created_at&amp;gt;?)&lt;/code&gt; after running &lt;code&gt;ANALYZE&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;h2 id=&#34;when-an-index-hurts&#34;&gt;When an index hurts&lt;/h2&gt;&#xA;&lt;p&gt;Every index is a second copy of your data, and SQLite keeps it in step.&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Writes get slower.&lt;/strong&gt; Each &lt;code&gt;INSERT&lt;/code&gt; and &lt;code&gt;DELETE&lt;/code&gt; changes every index, and an&#xA;&lt;code&gt;UPDATE&lt;/code&gt; does too when it changes an indexed column. As a rough check, I&#xA;inserted 200,000 rows in one transaction on my laptop: about 0.11 seconds&#xA;with no extra indexes, about 0.47 seconds with four. Your numbers will&#xA;differ, but the direction will not.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Indexes on columns with few distinct values rarely help.&lt;/strong&gt; An index on&#xA;&lt;code&gt;status&lt;/code&gt; has three values. For &lt;code&gt;status = &#39;paid&#39;&lt;/code&gt;, which is 90% of my table,&#xA;SQLite still picked the index, and the query was no faster than a scan in my&#xA;test. The stat row above shows why: it knows 66,667 rows per value on average,&#xA;not that &lt;code&gt;paid&lt;/code&gt; is most of them.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Redundant indexes waste space and slow writes.&lt;/strong&gt; If you have&#xA;&lt;code&gt;(customer_id)&lt;/code&gt; and &lt;code&gt;(customer_id, status)&lt;/code&gt;, the first is not needed.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;An index nobody uses still costs.&lt;/strong&gt; To check, run &lt;code&gt;EXPLAIN QUERY PLAN&lt;/code&gt; on&#xA;your real queries. If no plan names an index, it is a candidate to drop.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Building one takes the write lock.&lt;/strong&gt; &lt;code&gt;CREATE INDEX&lt;/code&gt; on a big table is a&#xA;write for as long as it takes. Do it when it is quiet. A related point from&#xA;&lt;a href=&#34;https://loomloops.com/post/sqlite-locks/&#34;&gt;how SQLite locks work&lt;/a&gt;: a query that needs less time&#xA;also holds its locks for less time, so a good index helps writers too.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;For settings that matter in production, such as WAL mode and busy timeouts,&#xA;see &lt;a href=&#34;https://loomloops.com/post/sqlite-for-high-traffic-websites/&#34;&gt;SQLite for high-traffic websites&lt;/a&gt;.&#xA;If you also run PostgreSQL, the lock side of the same story is in&#xA;&lt;a href=&#34;https://loomloops.com/post/understanding-postgresql-locks/&#34;&gt;Understanding PostgreSQL locks&lt;/a&gt;.&lt;/p&gt;&#xA;&lt;h2 id=&#34;which-index-should-i-add&#34;&gt;Which index should I add?&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-index-optimisation/which-index.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-index-optimisation/which-index.svg&#34; alt=&#34;Which index should I add. Question 1: does the plan show SCAN or USE TEMP B-TREE FOR ORDER BY on a query you run often? If no, leave it alone. Question 2: does the query wrap the column in a function, like lower(email)? If yes, index that same expression. Question 3: does the query only touch a small slice of rows, like status = pending? If yes, use a partial index. Question 4: does a hot query read only a few columns? If yes, add them at the end to make the index covering. Otherwise add a composite index: equality columns, one range column, then the ORDER BY column. Then read the plan again.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;604&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;And as a table, for the common query shapes:&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Query shape&lt;/th&gt;&#xA;          &lt;th&gt;Index&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;WHERE a = ?&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(a)&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;WHERE a = ? AND b = ?&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(a, b)&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;WHERE a = ? AND c &amp;gt; ?&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(a, c)&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;WHERE a = ? ORDER BY c&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(a, c)&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;WHERE a = ? AND b = ? ORDER BY c&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(a, b, c)&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;the same, selecting &lt;code&gt;d&lt;/code&gt; too&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(a, b, c, d)&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;WHERE lower(a) = ?&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(lower(a))&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;WHERE status = &#39;pending&#39;&lt;/code&gt; on a big table&lt;/td&gt;&#xA;          &lt;td&gt;&lt;code&gt;(a) WHERE status = &#39;pending&#39;&lt;/code&gt;&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;h2 id=&#34;questions-people-ask&#34;&gt;Questions people ask&lt;/h2&gt;&#xA;&lt;p&gt;&lt;strong&gt;How do I know if SQLite is using my index?&lt;/strong&gt;&#xA;Put &lt;code&gt;EXPLAIN QUERY PLAN&lt;/code&gt; in front of the query and look for the index name.&#xA;&lt;code&gt;SEARCH ... USING INDEX name&lt;/code&gt; or &lt;code&gt;USING COVERING INDEX name&lt;/code&gt; means yes. &lt;code&gt;SCAN&lt;/code&gt;&#xA;with no index means no. In the SQLite shell, &lt;code&gt;.eqp on&lt;/code&gt; does this for every&#xA;query.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Why does SQLite ignore my index?&lt;/strong&gt;&#xA;The usual causes: the column is wrapped in a function (&lt;code&gt;lower(email)&lt;/code&gt;), a&#xA;&lt;code&gt;LIKE&lt;/code&gt; pattern starts with &lt;code&gt;%&lt;/code&gt;, the &lt;code&gt;LIKE&lt;/code&gt; collation does not match the index,&#xA;a column earlier in the composite index is missing from the &lt;code&gt;WHERE&lt;/code&gt;, or a&#xA;partial index&amp;rsquo;s &lt;code&gt;WHERE&lt;/code&gt; is not implied by the query. Without &lt;code&gt;ANALYZE&lt;/code&gt; the&#xA;planner is also guessing, so run &lt;code&gt;PRAGMA optimize&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does column order in a composite index matter?&lt;/strong&gt;&#xA;Yes. Equality columns first, then one range column, then the &lt;code&gt;ORDER BY&lt;/code&gt;&#xA;column. The index can only be used from its left-most column, with no gaps.&#xA;&lt;code&gt;(a, b)&lt;/code&gt; serves &lt;code&gt;WHERE a = ?&lt;/code&gt;, but not &lt;code&gt;WHERE b = ?&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Do I need to index the primary key?&lt;/strong&gt;&#xA;Not an &lt;code&gt;INTEGER PRIMARY KEY&lt;/code&gt;. That column is the rowid, and a lookup shows&#xA;&lt;code&gt;SEARCH orders USING INTEGER PRIMARY KEY (rowid=?)&lt;/code&gt;. Other &lt;code&gt;PRIMARY KEY&lt;/code&gt; and&#xA;&lt;code&gt;UNIQUE&lt;/code&gt; constraints get an index created for them automatically.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Can SQLite use two indexes for one table?&lt;/strong&gt;&#xA;Usually one per table in a query. The main exception is &lt;code&gt;OR&lt;/code&gt;, where each side&#xA;can use its own index. It does not intersect two indexes for &lt;code&gt;AND&lt;/code&gt;, so build&#xA;one composite index instead.&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/sqlite-index-optimisation/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-index-optimisation/cheat-sheet.svg&#34; alt=&#34;SQLite index cheat sheet. Read: EXPLAIN QUERY PLAN SELECT. Good: SEARCH using an index or covering index. Bad: SCAN on a big table, USE TEMP B-TREE FOR ORDER BY. Order: equality columns first, one range column, then ORDER BY. Prefix: index on a, b, c helps a, a and b, a and b and c. Gap: WHERE a and c uses only a because b is missing. Covering: put the columns you select at the end. Partial: the query WHERE must imply the index WHERE. Expression: write the same expression in the query. Stats: PRAGMA optimize before closing and after CREATE INDEX. LIKE: needs a NOCASE index and no leading percent sign. Cost: each index slows writes and takes space. Rule: change one thing, then read the plan again.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;572&#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.sqlite.org/queryplanner.html&#34;&gt;SQLite docs: the query planner&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/eqp.html&#34;&gt;SQLite docs: EXPLAIN QUERY PLAN&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/optoverview.html&#34;&gt;SQLite docs: the query optimizer overview&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/partialindex.html&#34;&gt;SQLite docs: partial indexes&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/expridx.html&#34;&gt;SQLite docs: indexes on expressions&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/lang_analyze.html&#34;&gt;SQLite docs: ANALYZE&lt;/a&gt; and &lt;a href=&#34;https://www.sqlite.org/pragma.html#pragma_optimize&#34;&gt;PRAGMA optimize&lt;/a&gt;&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;li&gt;&lt;a href=&#34;https://loomloops.com/post/sqlite-for-high-traffic-websites/&#34;&gt;SQLite for high-traffic websites&lt;/a&gt; on this site&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>SQLite Locking: Why You Get &#39;database is locked&#39; and How to Fix It</title>
      <link>https://loomloops.com/post/sqlite-locks/</link>
      <pubDate>Sat, 13 Jan 2024 21:22:09 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/sqlite-locks/</guid>
      <description>&lt;p&gt;It is a common story. A small service uses SQLite and runs fine for weeks.&#xA;Then one afternoon the logs start to fill with &lt;code&gt;database is locked&lt;/code&gt;. Not all&#xA;the time. A few times an hour, always on writes, always when two requests land&#xA;together.&lt;/p&gt;&#xA;&lt;p&gt;The usual advice is to set a busy timeout of five seconds. The errors go down,&#xA;but they don&amp;rsquo;t go away. Some of them still come back after a few&#xA;microseconds, not after five seconds. That is the confusing part, and it is&#xA;the part most guides skip. A timeout that does not wait looks like a bug until&#xA;you know how SQLite hands out locks.&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;SQLite locks the whole database file. There are no row locks and no table&#xA;locks in normal use. Many connections can read, but only one can write.&lt;/li&gt;&#xA;&lt;li&gt;A second writer gets &lt;code&gt;SQLITE_BUSY&lt;/code&gt; (&amp;ldquo;database is locked&amp;rdquo;). The default busy&#xA;timeout is 0, so it fails at once. Set &lt;code&gt;PRAGMA busy_timeout&lt;/code&gt; on every&#xA;connection.&lt;/li&gt;&#xA;&lt;li&gt;A transaction that reads first and writes later can fail right away, even&#xA;with a timeout. Start every transaction that will write with&#xA;&lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;the-problem-one-writer-per-database-file&#34;&gt;The problem: one writer per database file&lt;/h2&gt;&#xA;&lt;p&gt;SQLite is a library that runs inside your process. There is no server to queue&#xA;requests for you. Each connection talks to the same file on disk, and the&#xA;connections agree on who goes first by taking locks on that file.&lt;/p&gt;&#xA;&lt;p&gt;The rule is simple. Any number of connections can read at the same time. Only&#xA;one can write at a time. When a connection asks for a lock that another&#xA;connection holds, SQLite has two options. It can return &lt;code&gt;SQLITE_BUSY&lt;/code&gt;&#xA;straight away, or it can call a &lt;strong&gt;busy handler&lt;/strong&gt; that sleeps and tries again.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-locks/busy-timeline.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-locks/busy-timeline.svg&#34; alt=&#34;Timeline: connection A runs BEGIN IMMEDIATE and holds the write lock. Connection B tries the same. With busy_timeout 0, B gets SQLITE_BUSY at once. With busy_timeout 5000, B sleeps and retries, and gets in right after A commits, unless A holds the lock for more than 5 seconds.&#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;The busy handler is what &lt;code&gt;busy_timeout&lt;/code&gt; turns on. The docs say it plainly: the&#xA;default busy callback is NULL, and then &lt;code&gt;SQLITE_BUSY&lt;/code&gt; is returned immediately&#xA;when SQLite meets the lock. So out of the box a second writer does not wait.&lt;/p&gt;&#xA;&lt;p&gt;Some drivers set their own default. Python&amp;rsquo;s &lt;code&gt;sqlite3&lt;/code&gt; module waits up to 5&#xA;seconds. The &lt;code&gt;sqlite3&lt;/code&gt; command line tool waits 0 seconds. Check what your&#xA;connection really uses:&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;PRAGMA busy_timeout;          &lt;span style=&#34;color:#6272a4&#34;&gt;-- 0 means &amp;#34;fail at once&amp;#34;&#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;PRAGMA busy_timeout &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;5000&lt;/span&gt;;   &lt;span style=&#34;color:#6272a4&#34;&gt;-- wait up to 5000 ms&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The setting belongs to the connection, not to the file. Every connection in&#xA;your pool needs it.&lt;/p&gt;&#xA;&lt;h3 id=&#34;what-database-is-locked-actually-means&#34;&gt;What &amp;ldquo;database is locked&amp;rdquo; actually means&lt;/h3&gt;&#xA;&lt;p&gt;The message is the text for the result code &lt;code&gt;SQLITE_BUSY&lt;/code&gt; (code 5). The docs&#xA;say it means the file could not be written, or sometimes read, because of&#xA;another connection, usually one in a separate process.&lt;/p&gt;&#xA;&lt;p&gt;There is a second, similar code, &lt;code&gt;SQLITE_LOCKED&lt;/code&gt; (code 6). It means a conflict&#xA;inside the same connection, or with another connection that shares a cache.&#xA;Shared-cache mode is the one place where SQLite does lock per table. The docs&#xA;call that mode obsolete and discourage it, and say WAL mode serves most of&#xA;those use cases better. So for normal use, think &amp;ldquo;one lock for the whole&#xA;file&amp;rdquo;.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-five-lock-states-rollback-journal-mode&#34;&gt;The five lock states (rollback journal mode)&lt;/h2&gt;&#xA;&lt;p&gt;By default, SQLite uses a rollback journal. In this mode a connection moves&#xA;through five lock states. This is the part of&#xA;&lt;a href=&#34;https://www.sqlite.org/lockingv3.html&#34;&gt;the locking docs&lt;/a&gt; worth knowing by&#xA;heart.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-locks/lock-states.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-locks/lock-states.svg&#34; alt=&#34;The five SQLite lock states in rollback-journal mode. Idle: not using the file. SHARED: reading, many at once, blocks any write to the file. RESERVED: plans to write, only one at a time, new readers still allowed. PENDING: wants to commit, no new readers, current readers can finish. EXCLUSIVE: writing the file, nothing else can coexist.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;460&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Here is the order a write takes, with what each step blocks:&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;UNLOCKED   idle, nobody is blocked&#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;SHARED     reading. Many at once. Blocks: any write to the file&#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;RESERVED   &amp;#34;I will write soon&amp;#34;. Only ONE at a time.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;   |       Blocks: a second RESERVED. New readers are still let in.&#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;PENDING    &amp;#34;I want to commit now&amp;#34;. Waits for readers to finish.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;   |       Blocks: new SHARED locks. Old readers may finish.&#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;EXCLUSIVE  writing the file. Blocks: everything, even readers.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;While a connection holds &lt;code&gt;RESERVED&lt;/code&gt;, it can already change pages, but at&#xA;first only in memory. The database file stays as it was, so other connections&#xA;keep reading.&#xA;The connection needs &lt;code&gt;EXCLUSIVE&lt;/code&gt; only at commit time, when it writes the&#xA;changes into the file. &lt;code&gt;PENDING&lt;/code&gt; is there to stop a steady stream of new&#xA;readers from starving the writer.&lt;/p&gt;&#xA;&lt;p&gt;Two things follow from this:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Only one connection can get &lt;code&gt;RESERVED&lt;/code&gt;.&lt;/strong&gt; That is the &amp;ldquo;one writer&amp;rdquo; rule.&#xA;A second connection that asks for it gets &lt;code&gt;SQLITE_BUSY&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;A reader can stop a commit.&lt;/strong&gt; Commit needs &lt;code&gt;EXCLUSIVE&lt;/code&gt;, and that waits for&#xA;every &lt;code&gt;SHARED&lt;/code&gt; lock to go. A connection that read something and never&#xA;finished its transaction keeps writers from committing. The docs say a&#xA;&lt;code&gt;COMMIT&lt;/code&gt; can return &lt;code&gt;SQLITE_BUSY&lt;/code&gt; for this reason, and that you can retry it&#xA;later.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;wal-mode-readers-and-the-writer-stop-blocking-each-other&#34;&gt;WAL mode: readers and the writer stop blocking each other&lt;/h2&gt;&#xA;&lt;p&gt;Write-ahead logging (WAL) is the fix most people reach for first. Turn it on&#xA;once:&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;PRAGMA journal_mode &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; WAL;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;It is saved in the database file, so it stays on after you close and reopen&#xA;the database. In WAL mode, changes go to a separate &lt;code&gt;-wal&lt;/code&gt; file instead of&#xA;overwriting the main file. The &lt;a href=&#34;https://www.sqlite.org/wal.html&#34;&gt;WAL docs&lt;/a&gt;&#xA;state the result: readers do not block the writer, and the writer does not&#xA;block readers. Each reader sees the database as it was when its transaction&#xA;began.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-locks/rollback-vs-wal.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-locks/rollback-vs-wal.svg&#34; alt=&#34;Rollback journal versus WAL. Rollback journal (default): a reader can block a commit, a commit blocks new readers for a short moment, one writer at a time, extra file is the journal. WAL: readers never block the writer, the writer never blocks readers, still one writer at a time, extra files are -wal and -shm, same machine only. Both: a second writer gets SQLITE_BUSY.&#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;WAL does &lt;strong&gt;not&lt;/strong&gt; give you more than one writer. The docs are clear: there is&#xA;only one WAL file, so there can only be one writer at a time. A second writer&#xA;still gets &lt;code&gt;SQLITE_BUSY&lt;/code&gt;. WAL only removes the readers from the fight.&lt;/p&gt;&#xA;&lt;p&gt;WAL has costs:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;All processes must run on the same machine. WAL does not work over a network&#xA;file system, because it needs shared memory.&lt;/li&gt;&#xA;&lt;li&gt;There are two extra files next to the database, &lt;code&gt;-wal&lt;/code&gt; and &lt;code&gt;-shm&lt;/code&gt;. Keep them&#xA;together with the database if you copy or move it.&lt;/li&gt;&#xA;&lt;li&gt;&lt;code&gt;SQLITE_BUSY&lt;/code&gt; can still appear for readers in a few cases: another&#xA;connection uses exclusive locking mode, the last connection is cleaning up&#xA;the WAL files while you open the database, or a connection is running crash&#xA;recovery.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;My production defaults, including the other pragmas that go with WAL, are in&#xA;&lt;a href=&#34;https://loomloops.com/post/sqlite-for-high-traffic-websites/&#34;&gt;the SQLite for high-traffic websites post&lt;/a&gt;.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-trap-a-deferred-transaction-that-reads-then-writes&#34;&gt;The trap: a deferred transaction that reads, then writes&lt;/h2&gt;&#xA;&lt;p&gt;This is the confusing case. A plain &lt;code&gt;BEGIN&lt;/code&gt; starts a &lt;strong&gt;deferred&lt;/strong&gt;&#xA;transaction. It takes no lock when it starts. The docs say it begins when the&#xA;database is first used: if the first statement is a &lt;code&gt;SELECT&lt;/code&gt;, it is a read&#xA;transaction. A later write &amp;ldquo;will upgrade the transaction to a write&#xA;transaction if possible, or return SQLITE_BUSY&amp;rdquo;.&lt;/p&gt;&#xA;&lt;p&gt;The words &amp;ldquo;if possible&amp;rdquo; hide the trap. Look at two connections that both read&#xA;first:&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;-- connection A                 -- connection 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;SELECT&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; accounts    &lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; balance &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; accounts&#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;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; ...;        &lt;span style=&#34;color:#6272a4&#34;&gt;-- A holds RESERVED&#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; ...;&#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;-- B: SQLITE_BUSY, at once&#xA;&lt;/span&gt;&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/sqlite-locks/deferred-trap.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-locks/deferred-trap.svg&#34; alt=&#34;Deferred transaction trap in rollback mode. A and B both run BEGIN and SELECT, so both hold SHARED locks. A updates and takes RESERVED. B updates and gets SQLITE_BUSY at once, without using the busy timeout. A tries to commit and waits for Bs read lock. B rolls back, then A commits. The fix is BEGIN IMMEDIATE, so B waits at its BEGIN instead.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;540&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Why does B not wait? Think about what would happen if it did. A needs B&amp;rsquo;s&#xA;&lt;code&gt;SHARED&lt;/code&gt; lock to go away before it can commit. B would be waiting for A to&#xA;finish. Neither can move. The &lt;code&gt;sqlite3_busy_handler&lt;/code&gt; docs describe exactly this&#xA;case: one process holds a read lock it wants to promote, another holds a&#xA;reserved lock it wants to make exclusive. If both called their busy handlers,&#xA;neither would make progress. So SQLite returns &lt;code&gt;SQLITE_BUSY&lt;/code&gt; to the first one&#xA;and hopes it gives up its read lock. It does not call the busy handler at all.&lt;/p&gt;&#xA;&lt;p&gt;This is the answer to &amp;ldquo;I set busy_timeout and it still fails right away&amp;rdquo;.&#xA;There is no deadlock detector that picks a victim. SQLite avoids the deadlock&#xA;by failing one side early.&lt;/p&gt;&#xA;&lt;p&gt;I ran it to be sure. With SQLite 3.51.0 and a 5000 ms timeout on both&#xA;connections, B failed in 0.0 seconds. The same test in WAL mode also failed at&#xA;once, which fits the docs: if another connection &amp;ldquo;has already modified the&#xA;database or is already in the process of modifying the database&amp;rdquo;, the upgrade&#xA;is not possible.&lt;/p&gt;&#xA;&lt;h3 id=&#34;the-wal-version-sqlite_busy_snapshot&#34;&gt;The WAL version: SQLITE_BUSY_SNAPSHOT&lt;/h3&gt;&#xA;&lt;p&gt;WAL mode has its own form of the trap. The extended result code is&#xA;&lt;code&gt;SQLITE_BUSY_SNAPSHOT&lt;/code&gt; (517). The docs say it happens when a connection tries&#xA;to promote a read transaction into a write transaction, but another connection&#xA;has already written and so made its earlier reads out of date.&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;-- connection A                 -- connection 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;;&#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; n &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; t;                &lt;span style=&#34;color:#6272a4&#34;&gt;-- A reads the old snapshot&#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;IMMEDIATE&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; t &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; n &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; n &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;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; t &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; n &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; n &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:#6272a4&#34;&gt;-- A: SQLITE_BUSY (BUSY_SNAPSHOT)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Waiting cannot help here. A&amp;rsquo;s reads are stale, and A made a decision on them.&#xA;The only fix is to start the transaction over.&lt;/p&gt;&#xA;&lt;h3 id=&#34;the-fix-begin-immediate&#34;&gt;The fix: BEGIN IMMEDIATE&lt;/h3&gt;&#xA;&lt;p&gt;If you know a transaction will write, say so at the start:&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; &lt;span style=&#34;color:#ff79c6&#34;&gt;IMMEDIATE&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; balance &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;=&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;10&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;&lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt; takes the write lock right away. The docs note it can fail&#xA;with &lt;code&gt;SQLITE_BUSY&lt;/code&gt; if another write transaction is active, and that is the&#xA;point: now the failure happens at the very start, &lt;strong&gt;before you read anything&lt;/strong&gt;,&#xA;where the busy handler is allowed to wait. In my test, the first connection&#xA;held the lock for one second. The second connection waited about one second,&#xA;then ran, in both rollback and WAL mode. Both updates were kept.&lt;/p&gt;&#xA;&lt;p&gt;Here it is in Python. &lt;code&gt;isolation_level=None&lt;/code&gt; stops the module from managing&#xA;transactions, so the &lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt; you write is the one that 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-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;import&lt;/span&gt; sqlite3&#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;con &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; sqlite3&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;connect(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;app.db&amp;#34;&lt;/span&gt;, timeout&lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#bd93f9&#34;&gt;5&lt;/span&gt;, isolation_level&lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;None&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;con&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;PRAGMA journal_mode=WAL&amp;#34;&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;con&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;BEGIN IMMEDIATE&amp;#34;&lt;/span&gt;)      &lt;span style=&#34;color:#6272a4&#34;&gt;# waits up to 5 s for the write lock&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;try&lt;/span&gt;:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    (balance,) &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; con&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&#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;#34;SELECT balance FROM accounts WHERE id = 1&amp;#34;&lt;/span&gt;)&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;fetchone()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    con&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&#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;#34;UPDATE accounts SET balance = ? WHERE id = 1&amp;#34;&lt;/span&gt;, (balance &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;10&lt;/span&gt;,))&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    con&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;COMMIT&amp;#34;&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;except&lt;/span&gt; Exception:&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    con&lt;span style=&#34;color:#ff79c6&#34;&gt;.&lt;/span&gt;execute(&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#34;ROLLBACK&amp;#34;&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;raise&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Watch out for drivers that open transactions for you. Python&amp;rsquo;s &lt;code&gt;sqlite3&lt;/code&gt;&#xA;module, in its default mode, only sends &lt;code&gt;BEGIN&lt;/code&gt; right before the first write,&#xA;so a &lt;code&gt;SELECT&lt;/code&gt; before it runs outside the transaction. Setting&#xA;&lt;code&gt;isolation_level=&amp;quot;IMMEDIATE&amp;quot;&lt;/code&gt; changes that &lt;code&gt;BEGIN&lt;/code&gt; to &lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt;, but the&#xA;read still happens first, outside it. That is why the example above takes&#xA;control with &lt;code&gt;isolation_level=None&lt;/code&gt;. Some drivers have a proper setting, such&#xA;as &lt;code&gt;_txlock=immediate&lt;/code&gt; in Go&amp;rsquo;s &lt;code&gt;mattn/go-sqlite3&lt;/code&gt;. Check your driver&amp;rsquo;s docs.&#xA;What matters is the SQL it sends, and when.&lt;/p&gt;&#xA;&lt;p&gt;&lt;code&gt;BEGIN EXCLUSIVE&lt;/code&gt; is also there. In WAL mode it is the same as &lt;code&gt;IMMEDIATE&lt;/code&gt;. In&#xA;rollback mode it also stops other connections from reading, so I almost never&#xA;use it.&lt;/p&gt;&#xA;&lt;p&gt;If a transaction still fails with &lt;code&gt;SQLITE_BUSY&lt;/code&gt; after &lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt;, the&#xA;timeout ran out. Retry the whole transaction, not only the last statement.&lt;/p&gt;&#xA;&lt;h2 id=&#34;long-transactions-and-checkpoints&#34;&gt;Long transactions and checkpoints&lt;/h2&gt;&#xA;&lt;p&gt;Locks last as long as the transaction does. The most common real cause of&#xA;&lt;code&gt;database is locked&lt;/code&gt; that I see is not two fast writers. It is one slow&#xA;transaction.&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;A write transaction that calls the network.&lt;/strong&gt; It holds the write lock the&#xA;whole time. Every other writer waits, then fails when the timeout ends. Do&#xA;slow work outside the transaction.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;A read that never finishes.&lt;/strong&gt; An implicit transaction ends when its last&#xA;statement finishes, and a statement only reliably finishes when you reset or&#xA;finalize it. A cursor left half read, or a forgotten &lt;code&gt;BEGIN&lt;/code&gt;, can hold a&#xA;read lock for as long as the connection lives. In rollback mode that stops&#xA;every commit.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;In WAL mode a long reader does not block the writer, but it causes a&#xA;different problem. Changes pile up in the &lt;code&gt;-wal&lt;/code&gt; file until a &lt;strong&gt;checkpoint&lt;/strong&gt;&#xA;copies them back into the main file. SQLite runs one automatically when the&#xA;WAL reaches 1000 pages. That automatic checkpoint is the PASSIVE kind: it does&#xA;as much as it can without getting in the way, and it may not finish if readers&#xA;are active.&lt;/p&gt;&#xA;&lt;p&gt;The docs warn about the bad case. A checkpoint can only run to completion, and&#xA;reset the WAL, when no connection is using the old data. If there is always at&#xA;least one active reader, with overlapping transactions and no gap, no&#xA;checkpoint finishes and the WAL file grows without bound.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-locks/wal-checkpoint.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-locks/wal-checkpoint.svg&#34; alt=&#34;Why the WAL file grows. Two read transactions overlap in time, so there is never a gap with no reader. Writers keep committing into the WAL. Checkpoints run but cannot reset the WAL while readers are always active. The WAL file keeps growing. The fix is to keep read transactions short so gaps appear.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;470&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;What helps:&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;PRAGMA wal_checkpoint(&lt;span style=&#34;color:#ff79c6&#34;&gt;TRUNCATE&lt;/span&gt;);   &lt;span style=&#34;color:#6272a4&#34;&gt;-- run a checkpoint now and shrink the WAL&#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;PRAGMA journal_size_limit &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;67108864&lt;/span&gt;;  &lt;span style=&#34;color:#6272a4&#34;&gt;-- cut the WAL back to 64 MB after resets&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Run the TRUNCATE checkpoint at a quiet moment. The docs warn that readers&#xA;might block while such a checkpoint runs, and the pragma tells you if it was&#xA;blocked. The size limit is only a cap on the leftover file. It does not fix&#xA;the reader that causes the growth. The real fix is short read transactions.&lt;/p&gt;&#xA;&lt;p&gt;Faster queries also mean shorter locks. See&#xA;&lt;a href=&#34;https://loomloops.com/post/sqlite-index-optimisation/&#34;&gt;SQLite index optimisation&lt;/a&gt; for how to find&#xA;the slow ones.&lt;/p&gt;&#xA;&lt;h2 id=&#34;database-is-locked-checklist&#34;&gt;&amp;ldquo;database is locked&amp;rdquo; checklist&lt;/h2&gt;&#xA;&lt;p&gt;Work through these in order. The diagram is the same list.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/sqlite-locks/troubleshooting.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-locks/troubleshooting.svg&#34; alt=&#34;Troubleshooting chart. Is busy_timeout set on every connection? If no, set it to 5000. Does a transaction read first, then write? If yes, start it with BEGIN IMMEDIATE. Is any transaction open for seconds or never closed? If yes, shorten it and do slow work outside. Still on the rollback journal? If yes, try WAL mode on a local disk. Still locked: too many writers for one file, so queue writes through one connection or use Postgres.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;580&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;ol&gt;&#xA;&lt;li&gt;&lt;strong&gt;Check the timeout on the connection that fails.&lt;/strong&gt; Run&#xA;&lt;code&gt;PRAGMA busy_timeout;&lt;/code&gt; there. A pool can contain connections that were&#xA;opened without it.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Find the read-then-write transactions.&lt;/strong&gt; Look in your code or ORM for a&#xA;&lt;code&gt;SELECT&lt;/code&gt; followed by an &lt;code&gt;UPDATE&lt;/code&gt; inside one transaction. Switch it to&#xA;&lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt;.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Find the long transactions.&lt;/strong&gt; Log how long each write transaction stays&#xA;open. Anything over a second or so is a suspect. Look for network calls,&#xA;file work or user waits inside the transaction.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Look for forgotten readers.&lt;/strong&gt; A script, an admin tool or a debugger&#xA;session left open on the same file can hold a read lock. On Linux or macOS,&#xA;&lt;code&gt;lsof app.db&lt;/code&gt; shows which processes have the file open.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Check the journal mode.&lt;/strong&gt; &lt;code&gt;PRAGMA journal_mode;&lt;/code&gt; should say &lt;code&gt;wal&lt;/code&gt; for most&#xA;web apps.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Check the file system.&lt;/strong&gt; A database on a network share or a shared volume&#xA;breaks locking. WAL does not work there at all.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Look at your backups.&lt;/strong&gt; A copy of the file while a write is running can be&#xA;inconsistent, and a long dump holds a read lock. Use SQLite&amp;rsquo;s own backup&#xA;tools.&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;p&gt;If all of that is clean and writes still collide, you have more write traffic&#xA;than one file can take. Send writes through one connection (a small queue in&#xA;your app is enough), or use a database that has real row locks. I wrote about&#xA;how &lt;a href=&#34;https://loomloops.com/post/understanding-postgresql-locks/&#34;&gt;Postgres locks work&lt;/a&gt; and how to&#xA;build &lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;a job queue in Postgres&lt;/a&gt; if you&#xA;get there.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-result-codes-at-a-glance&#34;&gt;The result codes at a glance&lt;/h2&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Code&lt;/th&gt;&#xA;          &lt;th&gt;Number&lt;/th&gt;&#xA;          &lt;th&gt;Meaning&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;SQLITE_BUSY&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;5&lt;/td&gt;&#xA;          &lt;td&gt;Another connection, usually in another process, holds a lock you need&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;SQLITE_BUSY_SNAPSHOT&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;517&lt;/td&gt;&#xA;          &lt;td&gt;WAL: you tried to write after another connection wrote since your read began&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;SQLITE_BUSY_RECOVERY&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;261&lt;/td&gt;&#xA;          &lt;td&gt;WAL: another process is recovering the database after a crash&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;SQLITE_LOCKED&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;6&lt;/td&gt;&#xA;          &lt;td&gt;A conflict inside one connection, or with a shared-cache connection&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&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 &lt;code&gt;busy_timeout&lt;/code&gt; fix &amp;ldquo;database is locked&amp;rdquo;?&lt;/strong&gt;&#xA;It fixes the plain case, where a writer has to wait for another writer. It&#xA;does not help in a read-then-write upgrade that SQLite cannot allow, because&#xA;SQLite returns &lt;code&gt;SQLITE_BUSY&lt;/code&gt; there without calling the busy handler. For that&#xA;case you need &lt;code&gt;BEGIN IMMEDIATE&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does SQLite have deadlocks?&lt;/strong&gt;&#xA;Not in the usual sense. SQLite does not detect a deadlock and pick a victim.&#xA;It sees that two waits could block each other, and it fails one side early with&#xA;&lt;code&gt;SQLITE_BUSY&lt;/code&gt;. Your code is expected to roll back and retry.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does SQLite lock tables or rows?&lt;/strong&gt;&#xA;No, not in normal use. In rollback mode the locks cover the whole database&#xA;file. In WAL mode there is one writer at a time. Only the obsolete shared-cache&#xA;mode has table locks.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Can SQLite handle concurrent writes?&lt;/strong&gt;&#xA;Many connections can ask at the same time, but SQLite runs the writes one&#xA;after another. For short transactions that is often fast enough. The limit is&#xA;how long each write holds the lock, not how many connections you open.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Is WAL mode safe to use everywhere?&lt;/strong&gt;&#xA;Use it on a local disk. It does not work over a network file system, and it&#xA;adds the &lt;code&gt;-wal&lt;/code&gt; and &lt;code&gt;-shm&lt;/code&gt; files you must keep with the database.&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/sqlite-locks/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/sqlite-locks/cheat-sheet.svg&#34; alt=&#34;SQLite locking cheat sheet. Writers: one writer per database file, in every mode. Rollback: readers block commits, SHARED to EXCLUSIVE. WAL: readers and the writer dont block each other. Timeout: PRAGMA busy_timeout = 5000, default 0. Write: BEGIN IMMEDIATE when the transaction writes. Trap: a deferred read then write fails with no wait. Long: short transactions, close readers, watch the WAL. Errors: BUSY is another connection, LOCKED is the same connection. Rule: short write transactions, one writer at a time.&#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.sqlite.org/lockingv3.html&#34;&gt;SQLite docs: file locking and concurrency&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/wal.html&#34;&gt;SQLite docs: write-ahead logging&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/lang_transaction.html&#34;&gt;SQLite docs: BEGIN, COMMIT and ROLLBACK&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/c3ref/busy_timeout.html&#34;&gt;SQLite docs: sqlite3_busy_timeout()&lt;/a&gt; and &lt;a href=&#34;https://www.sqlite.org/c3ref/busy_handler.html&#34;&gt;sqlite3_busy_handler()&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/rescode.html&#34;&gt;SQLite docs: result and error codes&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.sqlite.org/sharedcache.html&#34;&gt;SQLite docs: shared-cache mode&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://loomloops.com/post/sqlite-for-high-traffic-websites/&#34;&gt;SQLite for high-traffic websites&lt;/a&gt; on this site&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://loomloops.com/post/sqlite-index-optimisation/&#34;&gt;SQLite index optimisation&lt;/a&gt; on this site&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;li&gt;&lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;Postgres as a job queue&lt;/a&gt; on this site&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;</description>
    </item>
  </channel>
</rss>
