<?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>SQLite on LoomLoops</title>
    <link>https://loomloops.com/tags/sqlite/</link>
    <description>SQLite guides: how its locks work, how to pick indexes, and how to run it on a busy website.</description>
    <language>en-us</language>
    <lastBuildDate>Sat, 04 Jan 2025 10:22:22 +0000</lastBuildDate>
    <atom:link href="https://loomloops.com/tags/sqlite/index.xml" rel="self" type="application/rss+xml" />
    <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>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>
