<?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>Reliable backends with just your database on LoomLoops</title>
    <link>https://loomloops.com/series/reliable-backends/</link>
    <description>A three-part series on building reliable backends with one database: a job queue, safe API retries and a transactional outbox.</description>
    <language>en-us</language>
    <lastBuildDate>Tue, 15 Sep 2026 07:55:00 +0000</lastBuildDate>
    <atom:link href="https://loomloops.com/series/reliable-backends/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>The Transactional Outbox Pattern, Explained Simply</title>
      <link>https://loomloops.com/post/transactional-outbox-pattern/</link>
      <pubDate>Tue, 15 Sep 2026 07:55:00 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/transactional-outbox-pattern/</guid>
      <description>&lt;p&gt;Your order service saves a new order and then tells the rest of the company&#xA;about it by publishing an &lt;code&gt;order_created&lt;/code&gt; event to Kafka (or RabbitMQ, or&#xA;SNS). Billing listens. Shipping listens. Email listens.&lt;/p&gt;&#xA;&lt;p&gt;That is two writes to two different systems. Sooner or later one of them&#xA;works and the other doesn&amp;rsquo;t. This is called the &lt;strong&gt;dual write problem&lt;/strong&gt;, and&#xA;the transactional outbox is the standard fix. It needs one extra table and&#xA;one small background process.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Short version:&lt;/strong&gt;&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Don&amp;rsquo;t publish the event directly. Write it to an &lt;code&gt;outbox&lt;/code&gt; table in the same&#xA;database transaction as the order.&lt;/li&gt;&#xA;&lt;li&gt;A separate process reads the outbox and publishes the events.&lt;/li&gt;&#xA;&lt;li&gt;Events are delivered at least once, so consumers must handle duplicates.&#xA;In return, no event is ever lost, and no event is sent for data that was&#xA;never saved.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;the-dual-write-problem&#34;&gt;The dual write problem&lt;/h2&gt;&#xA;&lt;p&gt;Here is the code most services start with:&lt;/p&gt;&#xA;&lt;pre tabindex=&#34;0&#34;&gt;&lt;code&gt;save order to database&#xA;publish order_created to Kafka&#xA;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Look at what can go wrong between those two lines:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/dual-write-failures.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/dual-write-failures.svg&#34; alt=&#34;Two ways the dual write fails. Failure 1, lost event: the order is saved to the database, then publishing to Kafka fails because Kafka is down, so the order exists and shipping never hears about it. Failure 2, ghost event: the event is published to Kafka, then saving the order to the database fails, so billing charges for an order that does not exist.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;328&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Swapping the order of the two lines only swaps which failure you get. The&#xA;process can also crash between the lines, which has the same effect as&#xA;Kafka being down.&lt;/p&gt;&#xA;&lt;h3 id=&#34;cant-i-publish-after-the-transaction-commits&#34;&gt;&amp;ldquo;Can&amp;rsquo;t I publish after the transaction commits?&amp;rdquo;&lt;/h3&gt;&#xA;&lt;p&gt;That is failure 1. The commit worked, then the publish failed or the&#xA;process was killed during a deploy. The event is gone and nothing will ever&#xA;retry it.&lt;/p&gt;&#xA;&lt;h3 id=&#34;cant-i-use-a-distributed-transaction&#34;&gt;&amp;ldquo;Can&amp;rsquo;t I use a distributed transaction?&amp;rdquo;&lt;/h3&gt;&#xA;&lt;p&gt;In theory, two-phase commit (2PC, also called XA) makes two systems commit&#xA;together. In practice most message brokers don&amp;rsquo;t support it, and the ones&#xA;that do make every write slower and harder to run. Almost nobody does this&#xA;for events.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-fix-write-the-event-to-your-own-database&#34;&gt;The fix: write the event to your own database&lt;/h2&gt;&#xA;&lt;p&gt;Your database can already save several rows atomically. So save the event as&#xA;a row, next to the order:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/outbox-flow.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/outbox-flow.svg&#34; alt=&#34;The service runs one database transaction that inserts into the orders table and the outbox table, so both rows or neither are saved. A relay process reads the outbox table, sends each event to Kafka and marks it sent. Kafka delivers the events to consumers.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;352&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The order and the event now live or die together. If the transaction rolls&#xA;back, there is no event. If it commits, the event is safely stored, and the&#xA;relay will send it, even if Kafka is down for an hour.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-outbox-table&#34;&gt;The outbox table&lt;/h2&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; outbox (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  id             bigserial   &lt;span style=&#34;color:#ff79c6&#34;&gt;PRIMARY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  aggregate_type &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;order&amp;#39;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  aggregate_id   &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;881&amp;#39;, also the Kafka key&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  event_type     &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;order_created&amp;#39;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  payload        jsonb       &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  created_at     timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now(),&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  sent_at        timestamptz&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INDEX&lt;/span&gt; outbox_unsent_idx &lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; outbox (id) &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;IS&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&amp;ldquo;Aggregate&amp;rdquo; is a fancy word for &amp;ldquo;the thing the event is about&amp;rdquo;. Here it is&#xA;the order. &lt;code&gt;aggregate_id&lt;/code&gt; will matter when we talk about ordering.&lt;/p&gt;&#xA;&lt;p&gt;Writing an event is a plain insert inside your existing transaction:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; orders (id, customer_id, total) &lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#bd93f9&#34;&gt;881&lt;/span&gt;, &lt;span style=&#34;color:#bd93f9&#34;&gt;42&lt;/span&gt;, &lt;span style=&#34;color:#bd93f9&#34;&gt;25&lt;/span&gt;.&lt;span style=&#34;color:#bd93f9&#34;&gt;00&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; outbox (aggregate_type, aggregate_id, event_type, payload)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;order&amp;#39;&lt;/span&gt;, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;881&amp;#39;&lt;/span&gt;, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;order_created&amp;#39;&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;{&amp;#34;order_id&amp;#34;: 881, &amp;#34;customer_id&amp;#34;: 42, &amp;#34;total&amp;#34;: &amp;#34;25.00&amp;#34;}&amp;#39;&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;the-relay-two-ways-to-read-the-outbox&#34;&gt;The relay: two ways to read the outbox&lt;/h2&gt;&#xA;&lt;h3 id=&#34;option-1-polling&#34;&gt;Option 1: polling&lt;/h3&gt;&#xA;&lt;p&gt;A small loop asks the table for unsent events every second or so:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; id, aggregate_id, event_type, payload&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; outbox&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;IS&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; id&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;LIMIT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;100&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FOR&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; SKIP LOCKED;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- publish each row to Kafka and wait for Kafka to confirm&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; outbox &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;ANY&lt;/span&gt;($sent_ids);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;code&gt;FOR UPDATE SKIP LOCKED&lt;/code&gt; lets you run more than one relay without two of&#xA;them grabbing the same rows. It is the same trick used to build a &lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;job queue&#xA;in Postgres&lt;/a&gt;, and that post explains&#xA;how it works.&lt;/p&gt;&#xA;&lt;p&gt;One detail that catches people out: don&amp;rsquo;t track progress with &amp;ldquo;give me rows&#xA;with &lt;code&gt;id&lt;/code&gt; greater than the last one I sent&amp;rdquo;. A &lt;code&gt;bigserial&lt;/code&gt; id is handed out&#xA;when the row is inserted, not when the transaction commits. A slow&#xA;transaction can commit id 100 after id 101 is already sent, and a &amp;ldquo;greater&#xA;than&amp;rdquo; relay will skip 100 forever. Querying &lt;code&gt;sent_at IS NULL&lt;/code&gt; avoids that.&lt;/p&gt;&#xA;&lt;h3 id=&#34;option-2-change-data-capture-cdc&#34;&gt;Option 2: change data capture (CDC)&lt;/h3&gt;&#xA;&lt;p&gt;Every database keeps a log of changes for crash recovery and replication:&#xA;the WAL in Postgres, the binlog in MySQL and MariaDB. A CDC tool such as&#xA;&lt;a href=&#34;https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html&#34;&gt;Debezium&lt;/a&gt;&#xA;reads that log and publishes each new outbox row as it is committed. Your&#xA;code doesn&amp;rsquo;t poll at all.&lt;/p&gt;&#xA;&lt;h3 id=&#34;which-one&#34;&gt;Which one?&lt;/h3&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;&lt;/th&gt;&#xA;          &lt;th&gt;Polling&lt;/th&gt;&#xA;          &lt;th&gt;CDC (log reading)&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Setup&lt;/td&gt;&#xA;          &lt;td&gt;A loop in your service&lt;/td&gt;&#xA;          &lt;td&gt;A separate tool to run and watch&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Delay&lt;/td&gt;&#xA;          &lt;td&gt;Your poll interval (~1 second)&lt;/td&gt;&#xA;          &lt;td&gt;Usually under a second&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Load on DB&lt;/td&gt;&#xA;          &lt;td&gt;One small query per poll&lt;/td&gt;&#xA;          &lt;td&gt;Reads the log, no queries&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Commit order&lt;/td&gt;&#xA;          &lt;td&gt;Needs care (see above)&lt;/td&gt;&#xA;          &lt;td&gt;Follows commit order&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Best for&lt;/td&gt;&#xA;          &lt;td&gt;Starting out, most services&lt;/td&gt;&#xA;          &lt;td&gt;High volume, many services&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;Start with polling. It is boring and easy to debug. Move to CDC when you can&#xA;measure that polling delay or database load is a problem.&lt;/p&gt;&#xA;&lt;h2 id=&#34;duplicates-are-part-of-the-deal&#34;&gt;Duplicates are part of the deal&lt;/h2&gt;&#xA;&lt;p&gt;Look at the relay again. It publishes to Kafka, then marks the rows as sent.&#xA;What if it crashes between those two steps?&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/duplicate-timeline.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/duplicate-timeline.svg&#34; alt=&#34;Timeline of a relay crash between three columns: relay, Kafka and outbox row 77. The relay reads row 77 and publishes it, and Kafka stores event 77. The relay crashes before marking the row sent, so sent_at stays NULL. After the restart it reads row 77 again and publishes it again, and Kafka stores a second copy of event 77. Then it marks the row sent and sent_at becomes 10:04. The event went out twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;520&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The event went out twice. You can&amp;rsquo;t fully prevent this, so the outbox gives&#xA;you &lt;strong&gt;at-least-once&lt;/strong&gt; delivery: every event arrives, maybe more than once.&lt;/p&gt;&#xA;&lt;p&gt;The answer is to make consumers safe to repeat. Include a unique event id in&#xA;the payload (the outbox &lt;code&gt;id&lt;/code&gt; works), and have each consumer remember what it&#xA;has handled:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- in the consumer&amp;#39;s database&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; processed_events (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  event_id     &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;bigint&lt;/span&gt;      &lt;span style=&#34;color:#ff79c6&#34;&gt;PRIMARY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  processed_at timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; processed_events (event_id) &lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#bd93f9&#34;&gt;77&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; CONFLICT (event_id) &lt;span style=&#34;color:#ff79c6&#34;&gt;DO&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NOTHING&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;RETURNING event_id;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- no row returned: already handled, COMMIT and stop&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- row returned: do the work in this same transaction&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This is sometimes called an &amp;ldquo;inbox&amp;rdquo; table. It is the same idea as an&#xA;&lt;a href=&#34;https://loomloops.com/post/idempotency-keys-explained/&#34;&gt;idempotency key&lt;/a&gt;: save &amp;ldquo;I am handling&#xA;this&amp;rdquo; in the same transaction as the work.&lt;/p&gt;&#xA;&lt;h2 id=&#34;ordering-same-order-same-key&#34;&gt;Ordering: same order, same key&lt;/h2&gt;&#xA;&lt;p&gt;Consumers often care about order. &lt;code&gt;order_shipped&lt;/code&gt; arriving before&#xA;&lt;code&gt;order_created&lt;/code&gt; will confuse shipping.&lt;/p&gt;&#xA;&lt;p&gt;Two rules keep the order right:&lt;/p&gt;&#xA;&lt;ol&gt;&#xA;&lt;li&gt;&lt;strong&gt;Publish with &lt;code&gt;aggregate_id&lt;/code&gt; as the message key.&lt;/strong&gt; Kafka keeps messages&#xA;with the same key in one partition, in order. Events for order 881 stay&#xA;in order, while events for different orders can be handled in parallel.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Don&amp;rsquo;t let two relays send events for the same order at the same time.&lt;/strong&gt;&#xA;With several polling relays and &lt;code&gt;SKIP LOCKED&lt;/code&gt;, relay A might hold&#xA;&lt;code&gt;order_created&lt;/code&gt; while relay B sends &lt;code&gt;order_shipped&lt;/code&gt; for the same order.&#xA;Either run one relay, or split rows between relays by&#xA;&lt;code&gt;hash(aggregate_id)&lt;/code&gt; so each order always goes through the same relay.&lt;/li&gt;&#xA;&lt;/ol&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/ordering-by-aggregate-id.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/ordering-by-aggregate-id.svg&#34; alt=&#34;Three orders flow through relays to Kafka partitions, each in order. Order 881 goes through relay 1 to partition p3 as created, paid, shipped. Order 882 goes through relay 2 to partition p0 as created, cancelled. Order 883 goes through relay 1 to partition p3 as created.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;272&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Order is only kept per order, not across all orders. That is almost always&#xA;what you want, and it is what lets you scale.&lt;/p&gt;&#xA;&lt;h2 id=&#34;keeping-the-outbox-small&#34;&gt;Keeping the outbox small&lt;/h2&gt;&#xA;&lt;p&gt;The outbox only needs to hold events until they are sent. Delete sent rows&#xA;on a schedule:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;DELETE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; outbox&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;interval&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;3 days&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Keeping a few days helps when you need to check what was sent. In Postgres,&#xA;a table that gets lots of inserts and deletes also needs autovacuum to keep&#xA;up. The same tuning tips from the &lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;job queue&#xA;post&lt;/a&gt; apply.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-one-metric-to-watch-outbox-lag&#34;&gt;The one metric to watch: outbox lag&lt;/h2&gt;&#xA;&lt;p&gt;If the relay stops, nothing errors. Orders save fine. Events just stop&#xA;flowing, and you find out when a customer asks where their parcel is.&lt;/p&gt;&#xA;&lt;p&gt;So watch the age of the oldest unsent event:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;min&lt;/span&gt;(created_at) &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; outbox_lag,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;       &lt;span style=&#34;color:#ff79c6&#34;&gt;count&lt;/span&gt;(&lt;span style=&#34;color:#ff79c6&#34;&gt;*&lt;/span&gt;)                &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; unsent&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; outbox&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; sent_at &lt;span style=&#34;color:#ff79c6&#34;&gt;IS&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/outbox-lag-scale.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/outbox-lag-scale.svg&#34; alt=&#34;Outbox lag scale. Under 5 seconds: healthy. 30 seconds to a few minutes: relay slow, or broker struggling. Growing steadily: relay stopped or stuck, page someone. Unsent equals 0: fine, lag shows NULL.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;346&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Alert when the lag passes a limit that fits your business, for example two&#xA;minutes.&lt;/p&gt;&#xA;&lt;h2 id=&#34;when-you-dont-need-an-outbox&#34;&gt;When you don&amp;rsquo;t need an outbox&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Only one system is involved.&lt;/strong&gt; If the consumer reads the same database,&#xA;a &lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;job in a jobs table&lt;/a&gt; does the&#xA;same thing with less machinery.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Losing an event is fine.&lt;/strong&gt; Analytics clicks, &amp;ldquo;user viewed page&amp;rdquo; counters.&#xA;Fire and forget is simpler.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;The event is the source of truth.&lt;/strong&gt; In event sourcing, you write only the&#xA;event, so there is no second write to keep in sync.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;questions-people-ask&#34;&gt;Questions people ask&lt;/h2&gt;&#xA;&lt;p&gt;&lt;strong&gt;Is the outbox the same as event sourcing?&lt;/strong&gt;&#xA;No. With an outbox, your normal tables are the truth and events are&#xA;announcements about changes. With event sourcing, the events themselves are&#xA;the truth.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Doesn&amp;rsquo;t this double my database writes?&lt;/strong&gt;&#xA;Each event adds one insert, and later one update and one delete. For most&#xA;services that is small next to the business writes. If it ever matters, CDC&#xA;removes the update, because it doesn&amp;rsquo;t need a &lt;code&gt;sent_at&lt;/code&gt; column.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Can the relay live inside my service?&lt;/strong&gt;&#xA;Yes, and that is the easy way to start. Run it as a background loop. With&#xA;&lt;code&gt;SKIP LOCKED&lt;/code&gt;, every copy of your service can run one safely, as long as you&#xA;handle the ordering rule above.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;What about MySQL?&lt;/strong&gt;&#xA;The pattern is the same. MySQL 8.0 supports &lt;code&gt;SKIP LOCKED&lt;/code&gt; for polling, and&#xA;Debezium can read the MySQL binlog for CDC.&lt;/p&gt;&#xA;&lt;h2 id=&#34;cheat-sheet&#34;&gt;Cheat sheet&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/transactional-outbox-pattern/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/transactional-outbox-pattern/cheat-sheet.svg&#34; alt=&#34;Transactional outbox in one page. Problem: a database write and a broker publish cannot commit together. Fix: insert the event into the outbox table in the same transaction. Relay: poll WHERE sent_at IS NULL with SKIP LOCKED, or use CDC from the WAL or binlog. Never: track progress with id greater than last sent. Delivery: at least once, so consumers dedupe by event id. Ordering: message key is aggregate_id, one relay per key. Cleanup: delete rows sent more than a few days ago. Watch: outbox lag is now() minus the oldest unsent created_at.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;464&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;h2 id=&#34;further-reading&#34;&gt;Further reading&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://microservices.io/patterns/data/transactional-outbox&#34;&gt;microservices.io: Transactional outbox&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html&#34;&gt;AWS Prescriptive Guidance: Transactional outbox pattern&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html&#34;&gt;Debezium: Outbox Event Router&lt;/a&gt;&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;</description>
    </item>
    <item>
      <title>Idempotency Keys Explained: How to Make API Retries Safe</title>
      <link>https://loomloops.com/post/idempotency-keys-explained/</link>
      <pubDate>Thu, 04 Jun 2026 09:20:00 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/idempotency-keys-explained/</guid>
      <description>&lt;p&gt;A customer taps &amp;ldquo;Pay&amp;rdquo;. Your app sends the payment request. The phone loses&#xA;signal for a moment and the request times out. The app does the sensible&#xA;thing and tries again. The customer gets charged twice.&lt;/p&gt;&#xA;&lt;p&gt;Nothing here was a bug in the usual sense. The network did what networks do,&#xA;and the client did what clients should do. The missing piece was a way for&#xA;the server to recognise &amp;ldquo;this is the same request I already handled&amp;rdquo;.&lt;/p&gt;&#xA;&lt;p&gt;That piece is called an &lt;strong&gt;idempotency key&lt;/strong&gt;. Stripe, Shopify, Adyen, PayPal&#xA;and most banking APIs use one. This post explains the idea, then builds the&#xA;server side step by step.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Short version:&lt;/strong&gt;&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;The client makes up a unique key for each action, like &amp;ldquo;pay order 881&amp;rdquo;,&#xA;and sends it with every retry of that action.&lt;/li&gt;&#xA;&lt;li&gt;The server saves the key with the result. If the same key comes again, it&#xA;returns the saved result instead of doing the work again.&lt;/li&gt;&#xA;&lt;li&gt;Save the key before doing the work, in the same transaction when you can.&#xA;That is what makes the whole thing safe.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;the-problem-a-timeout-tells-you-nothing&#34;&gt;The problem: a timeout tells you nothing&lt;/h2&gt;&#xA;&lt;p&gt;When a request times out, the client cannot tell which of these happened:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/timeout-two-cases.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/timeout-two-cases.svg&#34; alt=&#34;Two timelines between a client and a server. Case A: the request is lost on the way, the server never sees it, the client times out, and a retry is correct. Case B: the server gets the request and charges the card, but the response is lost, the client times out, and a retry charges twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;388&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;From the client&amp;rsquo;s side, A and B look the same. If it never retries, case A&#xA;leaves a customer who wanted to pay with no order. If it always retries, case&#xA;B charges them twice. You need the server to make retries safe.&lt;/p&gt;&#xA;&lt;h2 id=&#34;what-idempotent-means&#34;&gt;What &amp;ldquo;idempotent&amp;rdquo; means&lt;/h2&gt;&#xA;&lt;p&gt;An action is idempotent when doing it twice has the same effect as doing it&#xA;once. Pressing a lift button is idempotent. Pressing it five more times does&#xA;not call five lifts.&lt;/p&gt;&#xA;&lt;p&gt;HTTP already defines some methods this way (&lt;a href=&#34;https://www.rfc-editor.org/rfc/rfc9110#name-idempotent-methods&#34;&gt;RFC 9110&lt;/a&gt;):&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Method&lt;/th&gt;&#xA;          &lt;th&gt;Idempotent?&lt;/th&gt;&#xA;          &lt;th&gt;Why&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;GET&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Yes&lt;/td&gt;&#xA;          &lt;td&gt;Reading twice changes nothing&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;PUT&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Yes&lt;/td&gt;&#xA;          &lt;td&gt;&amp;ldquo;Set the name to Sam&amp;rdquo; twice leaves the name as Sam&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;DELETE&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Yes&lt;/td&gt;&#xA;          &lt;td&gt;Deleting a deleted thing leaves it deleted&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;POST&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&lt;strong&gt;No&lt;/strong&gt;&lt;/td&gt;&#xA;          &lt;td&gt;&amp;ldquo;Create a payment&amp;rdquo; twice creates two payments&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;&lt;code&gt;PATCH&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Not always&lt;/td&gt;&#xA;          &lt;td&gt;&amp;ldquo;Add 10 to the balance&amp;rdquo; twice adds 20&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;Idempotency keys exist to make &lt;code&gt;POST&lt;/code&gt; (and risky &lt;code&gt;PATCH&lt;/code&gt;) calls behave like&#xA;the safe ones.&lt;/p&gt;&#xA;&lt;h2 id=&#34;how-an-idempotency-key-works&#34;&gt;How an idempotency key works&lt;/h2&gt;&#xA;&lt;p&gt;The client sends a header with a value it generated, usually a random UUID:&lt;/p&gt;&#xA;&lt;pre tabindex=&#34;0&#34;&gt;&lt;code&gt;POST /payments&#xA;Idempotency-Key: 6f1c2a9e-4b7d-4d3e-9a51-0c8e2f3b7d10&#xA;Content-Type: application/json&#xA;&#xA;{&amp;#34;order_id&amp;#34;: 881, &amp;#34;amount&amp;#34;: &amp;#34;25.00&amp;#34;, &amp;#34;currency&amp;#34;: &amp;#34;EUR&amp;#34;}&#xA;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The server keeps a small table of keys it has seen:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/how-a-key-works.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/how-a-key-works.svg&#34; alt=&#34;Two flows side by side. First request: the client sends POST with key K, the server checks whether K was seen before (no), saves K as started, charges the card, saves the response with K, and returns 201 Created. Retry with the same key: the server finds that K was seen before (yes), reads the saved response, and returns 201 Created with the same body, so the card is charged once.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;484&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;There is an &lt;a href=&#34;https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/&#34;&gt;IETF draft for the &lt;code&gt;Idempotency-Key&lt;/code&gt;&#xA;header&lt;/a&gt;&#xA;that writes down the common behaviour, so you don&amp;rsquo;t have to invent your own&#xA;rules.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-four-cases-your-server-must-handle&#34;&gt;The four cases your server must handle&lt;/h2&gt;&#xA;&lt;p&gt;This table is the whole design. Print it out.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/four-cases.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/four-cases.svg&#34; alt=&#34;A table of the four cases the server must handle. New key: run the request, save the result. Done key with the same body: return the saved result again, even if it was an error. Key still running: 409 Conflict, try again shortly. Key seen with a different body: 422, this key was used for a different request.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;368&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The last row catches a real bug: a client that reuses one key for two&#xA;different actions. Without the check, the second payment would silently&#xA;return the first payment&amp;rsquo;s result, and nobody would notice until the&#xA;accounts don&amp;rsquo;t add up. To check it, store a hash of the request body with&#xA;the key.&lt;/p&gt;&#xA;&lt;h2 id=&#34;building-it-in-postgres&#34;&gt;Building it in Postgres&lt;/h2&gt;&#xA;&lt;h3 id=&#34;the-table&#34;&gt;The table&lt;/h3&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; idempotency_keys (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  account_id    &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;bigint&lt;/span&gt;      &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;           &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  request_hash  &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- sha256 of method + path + body&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  status        &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,   &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;started&amp;#39; | &amp;#39;finished&amp;#39;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  response_code &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;int&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  response_body jsonb,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  created_at    timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now(),&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;PRIMARY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt; (account_id, &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The key is scoped to the account. Two customers who happen to send the same&#xA;UUID don&amp;rsquo;t clash, and one customer cannot replay another customer&amp;rsquo;s response&#xA;by guessing their key.&lt;/p&gt;&#xA;&lt;h3 id=&#34;case-1-all-the-work-happens-in-your-database&#34;&gt;Case 1: all the work happens in your database&lt;/h3&gt;&#xA;&lt;p&gt;If &amp;ldquo;do the request&amp;rdquo; only means writing rows to the same database, this is&#xA;easy. Put everything in one transaction:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; idempotency_keys (account_id, &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;, request_hash, status)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; ($account, $&lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;, $hash, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;started&amp;#39;&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; CONFLICT (account_id, &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;) &lt;span style=&#34;color:#ff79c6&#34;&gt;DO&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NOTHING&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;RETURNING &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- No row returned? The key exists. ROLLBACK, then read the saved row&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- and follow the four-case table.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; orders (account_id, order_id, amount) &lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (...);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; idempotency_keys&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;finished&amp;#39;&lt;/span&gt;, response_code &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;201&lt;/span&gt;, response_body &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $response&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; account_id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $account &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#ff79c6&#34;&gt;key&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Postgres quietly handles the hard race for you here. If two copies of the&#xA;same request arrive at the same moment, the second &lt;code&gt;INSERT ... ON CONFLICT&lt;/code&gt;&#xA;waits until the first transaction ends. If the first one commits, the second&#xA;sees the key and returns the saved response. If the first one rolls back,&#xA;the second goes ahead as if it came first. No double order either way.&lt;/p&gt;&#xA;&lt;h3 id=&#34;case-2-the-work-calls-someone-else&#34;&gt;Case 2: the work calls someone else&lt;/h3&gt;&#xA;&lt;p&gt;Now the hard one. Your endpoint charges a card through a payment provider.&#xA;That call is outside your database, so you cannot roll it back.&lt;/p&gt;&#xA;&lt;p&gt;You can&amp;rsquo;t hold a transaction open across a slow network call (it ties up a&#xA;connection and can block database cleanup). So you split the work into&#xA;steps and save progress between them:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/provider-steps.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/provider-steps.svg&#34; alt=&#34;Three steps for a request that calls a payment provider. Step 1: begin, insert the key as started, commit. The decision is now saved. Step 2: call the provider, passing your key along. Step 3: begin, save the providers answer and your order, mark the key finished with the response, commit.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;316&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The important trick is in step 2: &lt;strong&gt;pass the idempotency key on to the&#xA;provider&lt;/strong&gt;. Most payment providers accept one. Now think about a crash:&lt;/p&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;Crash happens&lt;/th&gt;&#xA;          &lt;th&gt;What the retry sees&lt;/th&gt;&#xA;          &lt;th&gt;What it does&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Before step 1 commits&lt;/td&gt;&#xA;          &lt;td&gt;No key&lt;/td&gt;&#xA;          &lt;td&gt;Starts fresh. Nothing was charged&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Between step 1 and 2&lt;/td&gt;&#xA;          &lt;td&gt;Key &lt;code&gt;started&lt;/code&gt;, old&lt;/td&gt;&#xA;          &lt;td&gt;Calls the provider. Not charged yet, so this charges once&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Between step 2 and 3&lt;/td&gt;&#xA;          &lt;td&gt;Key &lt;code&gt;started&lt;/code&gt;, old&lt;/td&gt;&#xA;          &lt;td&gt;Calls the provider again &lt;strong&gt;with the same key&lt;/strong&gt;. The provider returns the first charge instead of making a new one&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;After step 3&lt;/td&gt;&#xA;          &lt;td&gt;Key &lt;code&gt;finished&lt;/code&gt;&lt;/td&gt;&#xA;          &lt;td&gt;Returns the saved response&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;Every row ends with exactly one charge. That works only because the key&#xA;travels through every system that has a side effect.&lt;/p&gt;&#xA;&lt;p&gt;How does a retry know a &lt;code&gt;started&lt;/code&gt; key is &amp;ldquo;old&amp;rdquo; and not still running? Use&#xA;&lt;code&gt;created_at&lt;/code&gt;. If it is older than your request timeout (say 60 seconds), the&#xA;first attempt is dead and the retry can take over. If it is newer, answer&#xA;409 and let the client try again in a moment.&lt;/p&gt;&#xA;&lt;p&gt;Brandur Leach wrote a longer version of this with more steps, called&#xA;&lt;a href=&#34;https://brandur.org/idempotency-keys&#34;&gt;recovery points&lt;/a&gt;. It is worth reading&#xA;if your endpoint calls more than one outside system.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-client-side&#34;&gt;The client side&lt;/h2&gt;&#xA;&lt;p&gt;The server can only help if the client sends the key correctly. The most&#xA;common mistake:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/client-keys.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/client-keys.svg&#34; alt=&#34;Two ways a client can choose keys. Wrong, a new key per attempt: attempt 1 uses key a1b2 and times out, attempt 2 uses key c3d4 and is charged, attempt 3 uses key e5f6 and is charged again. Right, one key per action: attempt 1 uses key a1b2 and times out, attempts 2 and 3 reuse a1b2 and get the saved result.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;312&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Generate the key when the user decides to act (taps &amp;ldquo;Pay&amp;rdquo;), store it with the&#xA;pending action, and reuse it for every retry. If the app restarts mid-retry,&#xA;it should pick up the same key from storage.&lt;/p&gt;&#xA;&lt;p&gt;Also:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Retry with growing waits plus a bit of randomness (for example 1s, 2s, 4s,&#xA;each plus up to 1s random). Without the randomness, thousands of clients&#xA;that failed together all retry at the same instant.&lt;/li&gt;&#xA;&lt;li&gt;Only retry on timeouts, connection errors, 409 and 5xx. A 400 or 422 will&#xA;fail the same way every time.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;how-long-to-keep-keys&#34;&gt;How long to keep keys&lt;/h2&gt;&#xA;&lt;p&gt;Keys don&amp;rsquo;t need to live forever. They only need to outlive any realistic&#xA;retry. &lt;a href=&#34;https://docs.stripe.com/api/idempotent_requests&#34;&gt;Stripe keeps them for at least 24&#xA;hours&lt;/a&gt;. Pick a window,&#xA;document it, and delete older rows with a daily job:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;DELETE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; idempotency_keys&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; created_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;interval&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;24 hours&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;mistakes-i-see-often&#34;&gt;Mistakes I see often&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Saving the key after the work.&lt;/strong&gt; If you crash in between, the retry finds&#xA;no key and does the work again. Save the decision first.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Keeping keys in a cache that can lose them.&lt;/strong&gt; If the key lives in Redis&#xA;and Redis restarts, your protection is gone. Keep the key in the same&#xA;database as the data it protects.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Not saving errors.&lt;/strong&gt; If the first attempt failed validation, a retry with&#xA;the same key should get the same error, not a fresh run. Some APIs choose&#xA;not to save 5xx errors so a retry can succeed. Either is fine if you&#xA;document it.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;No body hash.&lt;/strong&gt; Reusing a key for a different request should fail loudly,&#xA;not return the wrong result.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;Global keys.&lt;/strong&gt; Scope keys to the caller, or one client can read another&#xA;client&amp;rsquo;s responses.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;you-dont-always-need-a-key&#34;&gt;You don&amp;rsquo;t always need a key&lt;/h2&gt;&#xA;&lt;p&gt;Sometimes the request already carries something unique. Then a &lt;code&gt;UNIQUE&lt;/code&gt;&#xA;constraint does the job:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;A message consumer can store each message id in a &lt;code&gt;processed_messages&lt;/code&gt;&#xA;table with a unique index, and skip ids it has seen. This is the usual&#xA;partner for the &lt;a href=&#34;https://loomloops.com/post/transactional-outbox-pattern/&#34;&gt;transactional outbox&#xA;pattern&lt;/a&gt;, which delivers messages at&#xA;least once.&lt;/li&gt;&#xA;&lt;li&gt;A background job can use the job id the same way. Jobs in a &lt;a href=&#34;https://loomloops.com/post/postgres-job-queue-skip-locked/&#34;&gt;Postgres job&#xA;queue&lt;/a&gt; can run twice after a crash,&#xA;so they need this.&lt;/li&gt;&#xA;&lt;li&gt;&amp;ldquo;Create the invoice for order 881&amp;rdquo; can use &lt;code&gt;UNIQUE (order_id)&lt;/code&gt; on the&#xA;invoices table.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;An idempotency key is what you use when the request has no natural unique&#xA;value, which is the usual case for &amp;ldquo;create a new thing&amp;rdquo; endpoints.&lt;/p&gt;&#xA;&lt;h2 id=&#34;questions-people-ask&#34;&gt;Questions people ask&lt;/h2&gt;&#xA;&lt;p&gt;&lt;strong&gt;Who creates the key, client or server?&lt;/strong&gt;&#xA;The client. Only the client knows that attempt 2 is a retry of attempt 1.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Should the key be a UUID?&lt;/strong&gt;&#xA;Any random string with enough length works. UUID v4 is the easy choice. Don&amp;rsquo;t&#xA;build keys from timestamps or counters, because two devices can produce the&#xA;same one.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Is PUT enough instead of POST with a key?&lt;/strong&gt;&#xA;Sometimes. If the client can choose the new resource&amp;rsquo;s id (&lt;code&gt;PUT /payments/6f1c...&lt;/code&gt;), the id itself acts as the key. Many APIs prefer POST&#xA;plus a key so the server keeps control of ids.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does this give &amp;ldquo;exactly once&amp;rdquo;?&lt;/strong&gt;&#xA;It gives &amp;ldquo;the effect happens once&amp;rdquo;, which is what users care about. Under the&#xA;hood, requests still arrive more than once. The key makes the extra copies&#xA;harmless.&lt;/p&gt;&#xA;&lt;h2 id=&#34;cheat-sheet&#34;&gt;Cheat sheet&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/idempotency-keys-explained/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/idempotency-keys-explained/cheat-sheet.svg&#34; alt=&#34;Cheat sheet, idempotency keys in one page. Header: Idempotency-Key: uuid. Who: the client makes it, once per user action. Store: (account_id, key) PRIMARY KEY plus a body hash. New key: run, save response. Done key: return saved response. Running: 409, client retries soon. Body diff: 422, key reused for a different request. Order: save the key BEFORE the side effect. Outside: pass your key on to the payment provider. Keep: 24 hours or more, then delete.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;488&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;h2 id=&#34;further-reading&#34;&gt;Further reading&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/&#34;&gt;IETF draft: The Idempotency-Key HTTP Header Field&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://docs.stripe.com/api/idempotent_requests&#34;&gt;Stripe API docs: idempotent requests&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://brandur.org/idempotency-keys&#34;&gt;Brandur Leach: Implementing Stripe-like idempotency keys in Postgres&lt;/a&gt;&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;</description>
    </item>
    <item>
      <title>Postgres as a Job Queue: How SKIP LOCKED Works (and When It Breaks)</title>
      <link>https://loomloops.com/post/postgres-job-queue-skip-locked/</link>
      <pubDate>Tue, 17 Mar 2026 08:40:00 +0000</pubDate>
      <dc:creator>Rafi Loom</dc:creator>
      <guid>https://loomloops.com/post/postgres-job-queue-skip-locked/</guid>
      <description>&lt;p&gt;You need background jobs. Send the welcome email, resize the photo, call the&#xA;slow partner API. The usual answer is &amp;ldquo;add Redis and a queue library&amp;rdquo;. That is&#xA;one more server to run, watch, back up and pay for.&lt;/p&gt;&#xA;&lt;p&gt;If you already use PostgreSQL, you can run a solid job queue inside it. The&#xA;key is two words in a &lt;code&gt;SELECT&lt;/code&gt;: &lt;code&gt;SKIP LOCKED&lt;/code&gt;. This post shows how it works,&#xA;gives you a schema you can copy, and then spends real time on the part most&#xA;posts skip: how it fails when traffic grows.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Short version:&lt;/strong&gt;&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;code&gt;FOR UPDATE SKIP LOCKED&lt;/code&gt; lets many workers pull jobs from one table without&#xA;ever picking the same job twice.&lt;/li&gt;&#xA;&lt;li&gt;The big win over Redis: you can add a job in the same transaction as your&#xA;business data. Either both are saved or neither is.&lt;/li&gt;&#xA;&lt;li&gt;It breaks in three ways: table bloat, long transactions, and too many&#xA;workers fighting over the same rows. All three are easy to watch for.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;the-problem-two-workers-one-job&#34;&gt;The problem: two workers, one job&lt;/h2&gt;&#xA;&lt;p&gt;Say you have a &lt;code&gt;jobs&lt;/code&gt; table and two workers. Each one runs &amp;ldquo;give me the oldest&#xA;pending job&amp;rdquo;. Without any locking, this happens:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/race-without-locks.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/race-without-locks.svg&#34; alt=&#34;Timeline: worker A reads job 42, then worker B also reads job 42 before A marks it running. Both mark it running and both send the welcome email, so the user gets it twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;400&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Both workers read the row before either one changed it. The classic fix is&#xA;&lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt;, which locks the row. Now worker B waits for worker A.&#xA;That stops the double send, but your workers now queue up behind each other.&#xA;Ten workers act like one.&lt;/p&gt;&#xA;&lt;h2 id=&#34;what-skip-locked-does&#34;&gt;What SKIP LOCKED does&lt;/h2&gt;&#xA;&lt;p&gt;&lt;code&gt;SKIP LOCKED&lt;/code&gt; tells Postgres: &amp;ldquo;if a row is already locked by someone else,&#xA;don&amp;rsquo;t wait for it. Pretend it isn&amp;rsquo;t there and give me the next one.&amp;rdquo;&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/skip-locked-workers.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/skip-locked-workers.svg&#34; alt=&#34;Three workers and a jobs table. Worker A locks job 41, worker B skips 41 and locks 42, worker C skips 41 and 42 and locks 43. Jobs 44 and 45 stay free. Each worker gets a different job and nobody waits.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;400&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;That is the whole trick. It has been in PostgreSQL since version 9.5 (2016),&#xA;so any Postgres you run today has it. The &lt;a href=&#34;https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE&#34;&gt;PostgreSQL docs on the locking&#xA;clause&lt;/a&gt;&#xA;describe it, and they say plainly that it is meant for queue-like tables,&#xA;because it gives you an inconsistent view of the data on purpose.&lt;/p&gt;&#xA;&lt;h2 id=&#34;a-schema-you-can-copy&#34;&gt;A schema you can copy&lt;/h2&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; jobs (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  id           bigserial   &lt;span style=&#34;color:#ff79c6&#34;&gt;PRIMARY&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;KEY&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  kind         &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,          &lt;span style=&#34;color:#6272a4&#34;&gt;-- &amp;#39;send_email&amp;#39;, &amp;#39;resize_image&amp;#39;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  payload      jsonb       &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  status       &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;        &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                              &lt;span style=&#34;color:#6272a4&#34;&gt;-- pending | running | done | dead&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  run_at       timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now(),&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  attempts     &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;int&lt;/span&gt;         &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;0&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  max_attempts &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;int&lt;/span&gt;         &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;5&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  locked_until timestamptz,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  last_error   &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;text&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  created_at   timestamptz &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;DEFAULT&lt;/span&gt; now()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- Only pending jobs are in this index, so it stays small&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- even when the table holds millions of finished jobs.&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;CREATE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INDEX&lt;/span&gt; jobs_pending_idx &lt;span style=&#34;color:#ff79c6&#34;&gt;ON&lt;/span&gt; jobs (run_at) &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;A few choices worth explaining:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;code&gt;run_at&lt;/code&gt; lets you schedule a job for later, and it is also how retries back&#xA;off. A failed job gets &lt;code&gt;run_at = now() + 1 minute&lt;/code&gt;, then 4 minutes, and so on.&lt;/li&gt;&#xA;&lt;li&gt;&lt;code&gt;locked_until&lt;/code&gt; is a lease. More on that below.&lt;/li&gt;&#xA;&lt;li&gt;The partial index (&lt;code&gt;WHERE status = &#39;pending&#39;&lt;/code&gt;) matters more than it looks.&#xA;Workers only ever search pending jobs, and there are usually few of them.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;h2 id=&#34;claiming-a-job&#34;&gt;Claiming a job&lt;/h2&gt;&#xA;&lt;p&gt;There are two styles. Pick one.&lt;/p&gt;&#xA;&lt;h3 id=&#34;style-1-hold-the-transaction-open&#34;&gt;Style 1: hold the transaction open&lt;/h3&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; id, kind, payload&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; run_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;=&lt;/span&gt; now()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; run_at&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;LIMIT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FOR&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; SKIP LOCKED;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- ... the worker does the job here, while the row stays locked ...&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;done&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The nice part: if the worker crashes, its connection drops, Postgres rolls the&#xA;transaction back, and the row is free again. Crash recovery comes for free.&lt;/p&gt;&#xA;&lt;p&gt;The bad part: every running job holds a database connection and an open&#xA;transaction for as long as the job takes. A 30 second job means a 30 second&#xA;transaction. We will see why that hurts in the &amp;ldquo;when it breaks&amp;rdquo; section.&lt;/p&gt;&#xA;&lt;h3 id=&#34;style-2-take-a-lease-then-let-go&#34;&gt;Style 2: take a lease, then let go&lt;/h3&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status       &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;running&amp;#39;&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    attempts     &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; attempts &lt;span style=&#34;color:#ff79c6&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;interval&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;5 minutes&amp;#39;&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; id&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; run_at &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;=&lt;/span&gt; now()&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; run_at&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;LIMIT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#ff79c6&#34;&gt;FOR&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; SKIP LOCKED&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;RETURNING id, kind, payload, attempts;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This claims the job in one short statement and commits right away. The worker&#xA;then does the job with no transaction open. When it finishes:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;done&amp;#39;&lt;/span&gt;, locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; attempts &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;;   &lt;span style=&#34;color:#6272a4&#34;&gt;-- only if we still own it&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;That &lt;code&gt;attempts = $2&lt;/code&gt; check is important. If the worker took longer than the&#xA;lease, another worker may have picked the job up again. The check stops the&#xA;slow worker from marking someone else&amp;rsquo;s attempt as done.&lt;/p&gt;&#xA;&lt;p&gt;Something has to rescue jobs whose worker died. Run this every minute from any&#xA;worker:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;, locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;running&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;AND&lt;/span&gt; locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;lt;&lt;/span&gt; now();&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Here is how a lease plays out when a worker dies:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/lease-timeline.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/lease-timeline.svg&#34; alt=&#34;Lease timeline. 10:00 worker A claims job 42 with a lease until 10:05. 10:02 worker A crashes with the job half done. 10:05 the lease expires. 10:06 the sweeper sets job 42 back to pending and worker B claims it with attempts set to 2. 10:07 worker B finishes. Job 42 ran twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;400&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Notice that job 42 ran twice, or at least partly twice. With leases, a job can&#xA;always run more than once. So write jobs that are safe to repeat. The post on&#xA;&lt;a href=&#34;https://loomloops.com/post/idempotency-keys-explained/&#34;&gt;idempotency keys&lt;/a&gt; shows how.&lt;/p&gt;&#xA;&lt;h3 id=&#34;which-style-should-you-use&#34;&gt;Which style should you use?&lt;/h3&gt;&#xA;&lt;table&gt;&#xA;  &lt;thead&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;th&gt;&lt;/th&gt;&#xA;          &lt;th&gt;Hold transaction&lt;/th&gt;&#xA;          &lt;th&gt;Lease&lt;/th&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/thead&gt;&#xA;  &lt;tbody&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Crash recovery&lt;/td&gt;&#xA;          &lt;td&gt;Automatic&lt;/td&gt;&#xA;          &lt;td&gt;Needs a sweeper&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Connections used&lt;/td&gt;&#xA;          &lt;td&gt;One per running job&lt;/td&gt;&#xA;          &lt;td&gt;Only while claiming&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Long jobs (&amp;gt; a few seconds)&lt;/td&gt;&#xA;          &lt;td&gt;Hurts the whole database&lt;/td&gt;&#xA;          &lt;td&gt;Fine&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Can a job run twice?&lt;/td&gt;&#xA;          &lt;td&gt;Rarely&lt;/td&gt;&#xA;          &lt;td&gt;Yes, after a lease expires&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;      &lt;tr&gt;&#xA;          &lt;td&gt;Best for&lt;/td&gt;&#xA;          &lt;td&gt;Short jobs, low volume&lt;/td&gt;&#xA;          &lt;td&gt;Most real workloads&lt;/td&gt;&#xA;      &lt;/tr&gt;&#xA;  &lt;/tbody&gt;&#xA;&lt;/table&gt;&#xA;&lt;p&gt;My default is the lease. Jobs that call other services are slow, and slow&#xA;transactions cause the worst problems in Postgres.&lt;/p&gt;&#xA;&lt;h2 id=&#34;the-best-part-enqueue-in-the-same-transaction&#34;&gt;The best part: enqueue in the same transaction&lt;/h2&gt;&#xA;&lt;p&gt;This is the feature that a separate Redis queue cannot give you.&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;BEGIN&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; users (email) &lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;sam@example.com&amp;#39;&lt;/span&gt;) RETURNING id;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;INSERT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;INTO&lt;/span&gt; jobs (kind, payload)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;VALUES&lt;/span&gt; (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;send_welcome_email&amp;#39;&lt;/span&gt;, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;{&amp;#34;user_id&amp;#34;: 1001}&amp;#39;&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;COMMIT&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Either the user and the job are both saved, or neither is. Compare that with a&#xA;separate queue:&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/same-transaction.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/same-transaction.svg&#34; alt=&#34;Two panels. With a separate queue, saving the user to the database works but pushing the job to Redis fails, so the user exists with no welcome email. With a jobs table, save user and save job sit inside one BEGIN and COMMIT, so both are saved or neither is.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;360&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;The reverse also happens with a separate queue: the job is pushed, then the&#xA;database transaction rolls back, and a worker emails a user who does not&#xA;exist. The &lt;a href=&#34;https://loomloops.com/post/transactional-outbox-pattern/&#34;&gt;transactional outbox post&lt;/a&gt;&#xA;goes deeper into this &amp;ldquo;two writes&amp;rdquo; problem.&lt;/p&gt;&#xA;&lt;h2 id=&#34;waking-workers-up-polling-vs-listennotify&#34;&gt;Waking workers up: polling vs LISTEN/NOTIFY&lt;/h2&gt;&#xA;&lt;p&gt;Workers need to know when a new job shows up. Two options:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;strong&gt;Polling.&lt;/strong&gt; Each worker runs the claim query every second or so. Simple&#xA;and reliable. With the partial index, an empty check costs very little.&lt;/li&gt;&#xA;&lt;li&gt;&lt;strong&gt;LISTEN/NOTIFY.&lt;/strong&gt; Workers run &lt;code&gt;LISTEN jobs_ready;&lt;/code&gt;. Whoever inserts a job&#xA;also runs &lt;code&gt;NOTIFY jobs_ready;&lt;/code&gt;. The notice is only sent when the transaction&#xA;commits, so a worker never wakes up for a job it can&amp;rsquo;t see yet.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;p&gt;Use NOTIFY to wake workers faster, but keep a slow poll (every 5 to 10&#xA;seconds) as a safety net. Notices are not stored. A worker that was&#xA;restarting when the notice went out never gets it. Also, under heavy write&#xA;load, &lt;code&gt;NOTIFY&lt;/code&gt; takes a lock at commit time that is shared across the whole&#xA;database, and some teams have hit that at scale. If you insert thousands of&#xA;jobs a second, measure before you rely on it.&lt;/p&gt;&#xA;&lt;h2 id=&#34;retries-and-dead-jobs&#34;&gt;Retries and dead jobs&lt;/h2&gt;&#xA;&lt;p&gt;When a job fails, record the error and push it into the future:&lt;/p&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;UPDATE&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; status       &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;CASE&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;WHEN&lt;/span&gt; attempts &lt;span style=&#34;color:#ff79c6&#34;&gt;&amp;gt;=&lt;/span&gt; max_attempts&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                        &lt;span style=&#34;color:#ff79c6&#34;&gt;THEN&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;dead&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;ELSE&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;END&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    run_at       &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; now() &lt;span style=&#34;color:#ff79c6&#34;&gt;+&lt;/span&gt; (&lt;span style=&#34;color:#8be9fd;font-style:italic&#34;&gt;interval&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;1 minute&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;*&lt;/span&gt; power(&lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;, attempts)),&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    locked_until &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;,&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    last_error   &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;2&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; id &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; $&lt;span style=&#34;color:#bd93f9&#34;&gt;1&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;With &lt;code&gt;power(2, attempts)&lt;/code&gt;, the waits are 2, 4, 8, 16 minutes. After five tries&#xA;the job is &lt;code&gt;dead&lt;/code&gt;, and a person looks at it. Dead jobs are your alarm. Put a&#xA;count of them on a dashboard.&lt;/p&gt;&#xA;&lt;h2 id=&#34;when-it-breaks&#34;&gt;When it breaks&lt;/h2&gt;&#xA;&lt;p&gt;Everything above works well for most apps. Here are the three ways it goes&#xA;wrong as you grow, and how to spot each one early.&lt;/p&gt;&#xA;&lt;h3 id=&#34;1-bloat-the-table-fills-up-with-dead-rows&#34;&gt;1. Bloat: the table fills up with dead rows&lt;/h3&gt;&#xA;&lt;p&gt;In Postgres, an &lt;code&gt;UPDATE&lt;/code&gt; does not change a row in place. It writes a new copy&#xA;and marks the old one as dead. A job that goes pending, running, done leaves&#xA;dead copies behind. A cleanup process called autovacuum removes them later.&lt;/p&gt;&#xA;&lt;p&gt;A queue table changes all day long, so dead rows pile up faster than in a&#xA;normal table. When autovacuum can&amp;rsquo;t keep up, the table and its indexes grow,&#xA;and the claim query slows down because it has to step over dead rows.&lt;/p&gt;&#xA;&lt;p&gt;What helps:&lt;/p&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;Delete finished jobs, or move them to an archive table, instead of keeping&#xA;millions of &lt;code&gt;done&lt;/code&gt; rows.&lt;/li&gt;&#xA;&lt;li&gt;Make autovacuum run more often on this one table:&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ALTER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;TABLE&lt;/span&gt; jobs &lt;span style=&#34;color:#ff79c6&#34;&gt;SET&lt;/span&gt; (&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  autovacuum_vacuum_scale_factor &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;0&lt;/span&gt;.&lt;span style=&#34;color:#bd93f9&#34;&gt;01&lt;/span&gt;,  &lt;span style=&#34;color:#6272a4&#34;&gt;-- start at 1% dead rows, not 20%&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;  autovacuum_vacuum_cost_delay   &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;0&lt;/span&gt;      &lt;span style=&#34;color:#6272a4&#34;&gt;-- don&amp;#39;t slow it down&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;);&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h3 id=&#34;2-long-transactions-stop-the-cleanup-everywhere&#34;&gt;2. Long transactions stop the cleanup everywhere&lt;/h3&gt;&#xA;&lt;p&gt;Vacuum can only remove a dead row when no open transaction might still need&#xA;to see it. One transaction that stays open for 20 minutes blocks cleanup of&#xA;anything that changed in those 20 minutes, in every table, not only &lt;code&gt;jobs&lt;/code&gt;.&lt;/p&gt;&#xA;&lt;p&gt;This is why style 1 (hold the transaction during the job) is risky. One stuck&#xA;job, or one forgotten &lt;code&gt;BEGIN&lt;/code&gt; in a console, and the queue table bloats.&lt;/p&gt;&#xA;&lt;h3 id=&#34;3-too-many-workers-fighting-over-the-head-of-the-queue&#34;&gt;3. Too many workers fighting over the head of the queue&lt;/h3&gt;&#xA;&lt;p&gt;&lt;code&gt;SKIP LOCKED&lt;/code&gt; stops workers from waiting, but they still all look at the same&#xA;few rows at the front of the queue. With dozens of workers and a high job&#xA;rate, they spend more and more time skipping each other&amp;rsquo;s locked rows. Some&#xA;write-ups report throughput falling off a cliff at this point instead of&#xA;leveling out.&lt;/p&gt;&#xA;&lt;p&gt;As a rough rule of thumb (not a benchmark): thousands of jobs per minute is&#xA;comfortable. Hundreds of jobs per second with many workers is where you need&#xA;to test carefully, claim jobs in batches (&lt;code&gt;LIMIT 10&lt;/code&gt; instead of &lt;code&gt;LIMIT 1&lt;/code&gt;), or&#xA;look at a dedicated queue.&lt;/p&gt;&#xA;&lt;h3 id=&#34;the-health-check-card&#34;&gt;The health check card&lt;/h3&gt;&#xA;&lt;p&gt;Put these two queries on a dashboard. They catch all three problems early.&lt;/p&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/health-check.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/health-check.svg&#34; alt=&#34;Job queue health check with four rows. 1: dead rows piling up, when n_dead_tup is much bigger than n_live_tup, vacuum is behind. 2: a transaction open for minutes, find out why. 3: pending jobs older than 5 minutes, add workers. 4: any job with status dead, a person should look.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;380&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#282a36;-moz-tab-size:2;-o-tab-size:2;tab-size:2;&#34;&gt;&lt;code class=&#34;language-sql&#34; data-lang=&#34;sql&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- 1. Dead rows in the jobs table&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; n_live_tup, n_dead_tup, last_autovacuum&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; pg_stat_user_tables&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; relname &lt;span style=&#34;color:#ff79c6&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;jobs&amp;#39;&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- 2. The oldest open transactions&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; pid, now() &lt;span style=&#34;color:#ff79c6&#34;&gt;-&lt;/span&gt; xact_start &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; open_for, &lt;span style=&#34;color:#ff79c6&#34;&gt;state&lt;/span&gt;, &lt;span style=&#34;color:#ff79c6&#34;&gt;left&lt;/span&gt;(query, &lt;span style=&#34;color:#bd93f9&#34;&gt;60&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; pg_stat_activity&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; xact_start &lt;span style=&#34;color:#ff79c6&#34;&gt;IS&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NOT&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;NULL&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;ORDER&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; open_for &lt;span style=&#34;color:#ff79c6&#34;&gt;DESC&lt;/span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;LIMIT&lt;/span&gt; &lt;span style=&#34;color:#bd93f9&#34;&gt;5&lt;/span&gt;;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;-- 3 and 4. Queue backlog and failures&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#6272a4&#34;&gt;&lt;/span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;SELECT&lt;/span&gt; status, &lt;span style=&#34;color:#ff79c6&#34;&gt;count&lt;/span&gt;(&lt;span style=&#34;color:#ff79c6&#34;&gt;*&lt;/span&gt;), &lt;span style=&#34;color:#ff79c6&#34;&gt;min&lt;/span&gt;(run_at) &lt;span style=&#34;color:#ff79c6&#34;&gt;AS&lt;/span&gt; oldest&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;FROM&lt;/span&gt; jobs&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;WHERE&lt;/span&gt; status &lt;span style=&#34;color:#ff79c6&#34;&gt;IN&lt;/span&gt; (&lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;pending&amp;#39;&lt;/span&gt;, &lt;span style=&#34;color:#f1fa8c&#34;&gt;&amp;#39;dead&amp;#39;&lt;/span&gt;)&#xA;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#ff79c6&#34;&gt;GROUP&lt;/span&gt; &lt;span style=&#34;color:#ff79c6&#34;&gt;BY&lt;/span&gt; status;&#xA;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;should-you-use-postgres-redis-or-kafka&#34;&gt;Should you use Postgres, Redis or Kafka?&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/which-queue.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/which-queue.svg&#34; alt=&#34;Decision chart. If you dont already run Postgres, use what you run. If the job must be saved together with your business data, use a Postgres queue. If not, and you have under about 100 jobs a second with no other teams reading the same events, use a Postgres queue. Otherwise use a Redis queue for speed, or Kafka for many readers and replay.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;500&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;p&gt;Most apps land on &amp;ldquo;Postgres queue&amp;rdquo; and stay there for years. Moving later is&#xA;not hard, because the code that claims and finishes jobs is small.&lt;/p&gt;&#xA;&lt;h2 id=&#34;questions-people-ask&#34;&gt;Questions people ask&lt;/h2&gt;&#xA;&lt;p&gt;&lt;strong&gt;Is SKIP LOCKED safe? Can two workers ever get the same job?&lt;/strong&gt;&#xA;Not at the same time. A locked row is invisible to other &lt;code&gt;SKIP LOCKED&lt;/code&gt;&#xA;queries until the lock is released. A job can run twice only after a lease&#xA;expires or a transaction rolls back, which is why jobs should be safe to&#xA;repeat.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Does this work in MySQL?&lt;/strong&gt;&#xA;Yes. MySQL 8.0 and MariaDB 10.6 also support &lt;code&gt;FOR UPDATE SKIP LOCKED&lt;/code&gt;. The&#xA;bloat details differ, but the pattern is the same.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Should I use a library?&lt;/strong&gt;&#xA;Often, yes. Libraries such as River (Go), Oban (Elixir), Graphile Worker&#xA;(Node) and Solid Queue (Ruby) are built on this pattern and handle retries,&#xA;scheduling and the sweeper for you. Knowing how they work helps you debug&#xA;them.&lt;/p&gt;&#xA;&lt;p&gt;&lt;strong&gt;Can I use SQLite for this?&lt;/strong&gt;&#xA;SQLite allows only one writer at a time, so there is no row locking to skip.&#xA;A single worker process with a simple &lt;code&gt;UPDATE ... RETURNING&lt;/code&gt; works fine. See&#xA;&lt;a href=&#34;https://loomloops.com/post/sqlite-locks/&#34;&gt;how SQLite locks work&lt;/a&gt; for why.&lt;/p&gt;&#xA;&lt;h2 id=&#34;cheat-sheet&#34;&gt;Cheat sheet&lt;/h2&gt;&#xA;&lt;figure&gt;&#xA;  &lt;a href=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/cheat-sheet.svg&#34;&gt;&lt;img src=&#34;https://loomloops.com/images/postgres-job-queue-skip-locked/cheat-sheet.svg&#34; alt=&#34;Postgres job queue cheat sheet. Claim: UPDATE where id equals a SELECT with FOR UPDATE SKIP LOCKED. Index: partial index on run_at for pending jobs. Crashes: lease with locked_until and a sweeper every minute. Finish: WHERE id = $1 AND attempts = $2. Retries: run_at = now() + 2^attempts minutes. Wake up: LISTEN/NOTIFY plus a slow poll as backup. Cleanup: delete done jobs and tune autovacuum on jobs. Watch: dead rows, old transactions, backlog, dead jobs. Rule: jobs must be safe to run twice.&#34; loading=&#34;lazy&#34; decoding=&#34;async&#34; width=&#34;640&#34; height=&#34;440&#34;&gt;&lt;/a&gt;&#xA;&lt;/figure&gt;&lt;h2 id=&#34;further-reading&#34;&gt;Further reading&lt;/h2&gt;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE&#34;&gt;PostgreSQL docs: the locking clause&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://www.postgresql.org/docs/current/routine-vacuuming.html&#34;&gt;PostgreSQL docs: routine vacuuming&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;&lt;a href=&#34;https://loomloops.com/post/understanding-postgresql-locks/&#34;&gt;Understanding PostgreSQL locks&lt;/a&gt; on this site&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;</description>
    </item>
  </channel>
</rss>
