<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://yuhruh.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://yuhruh.github.io/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-11-25T22:18:13+08:00</updated><id>https://yuhruh.github.io/feed.xml</id><title type="html">Rita Huang</title><subtitle>Rita Huang is a full-stack engineer in Taiwan (remote) building production software across API, web and mobile with TypeScript, NestJS, React, React Native and Ruby on Rails.</subtitle><author><name>Rita Huang</name></author><entry><title type="html">One reminder a day, even when the job runs twice</title><link href="https://yuhruh.github.io/notes/one-reminder-a-day/" rel="alternate" type="text/html" title="One reminder a day, even when the job runs twice" /><published>2026-11-24T00:00:00+08:00</published><updated>2026-11-24T00:00:00+08:00</updated><id>https://yuhruh.github.io/notes/one-reminder-a-day</id><content type="html" xml:base="https://yuhruh.github.io/notes/one-reminder-a-day/"><![CDATA[<p>Household Tracker reminds my family about bills before they’re due. Every member gets one digest
a day, at the hour they chose and in their own time zone, through up to three channels: the
in-app inbox, email and Web Push.</p>

<p>“One a day” sounds simple. It’s easy to get wrong in both directions:</p>

<ul>
  <li><strong>Twice.</strong> The hourly job can overlap with itself: a retry, a slow run that’s still going when
the next one starts, or two workers after a deploy. If both decide “Alex hasn’t been reminded
today”, Alex gets two emails.</li>
  <li><strong>Never.</strong> The process can die after deciding to send and before sending. If the system has
already written down “reminded”, nobody tries again.</li>
  <li><strong>Lying.</strong> A push service answering <code class="language-plaintext highlighter-rouge">201 Created</code> doesn’t mean the phone showed anything. If
that counts as “sent”, the status page is wrong exactly when it matters.</li>
</ul>

<p>Here is how the app handles each one.</p>

<h2 id="1-let-the-database-decide-who-wins">1. Let the database decide who wins</h2>

<p>The obvious version is check-then-insert (a sketch, not the app’s code):</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">unless</span> <span class="no">ReminderDelivery</span><span class="p">.</span><span class="nf">exists?</span><span class="p">(</span><span class="n">user</span><span class="p">:,</span> <span class="n">channel</span><span class="p">:,</span> <span class="ss">run_on: </span><span class="n">today</span><span class="p">)</span>
  <span class="no">ReminderDelivery</span><span class="p">.</span><span class="nf">create!</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>   <span class="c1"># two overlapping runs both get here</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Two runs that start at the same moment both see “nothing yet”, and both send. A Ruby-level mutex
doesn’t help across processes or machines.</p>

<p>Instead, the rule “one per day” lives in PostgreSQL as unique indexes, at two levels:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># One claim per bill, member, reminder stage, channel and day</span>
<span class="n">t</span><span class="p">.</span><span class="nf">index</span> <span class="p">[</span><span class="s2">"record_id"</span><span class="p">,</span> <span class="s2">"user_id"</span><span class="p">,</span> <span class="s2">"kind"</span><span class="p">,</span> <span class="s2">"channel"</span><span class="p">,</span> <span class="s2">"scheduled_on"</span><span class="p">],</span>
        <span class="ss">name: </span><span class="s2">"index_reminder_logs_claim"</span><span class="p">,</span> <span class="ss">unique: </span><span class="kp">true</span>

<span class="c1"># One digest per household, member, channel and local day (plus at most one same-day addition)</span>
<span class="n">t</span><span class="p">.</span><span class="nf">index</span> <span class="p">[</span><span class="s2">"household_id"</span><span class="p">,</span> <span class="s2">"user_id"</span><span class="p">,</span> <span class="s2">"channel"</span><span class="p">,</span> <span class="s2">"run_on"</span><span class="p">,</span> <span class="s2">"addition"</span><span class="p">],</span>
        <span class="ss">name: </span><span class="s2">"index_reminder_deliveries_one_per_day"</span><span class="p">,</span> <span class="ss">unique: </span><span class="kp">true</span>
</code></pre></div></div>

<p>Each run tries to <em>claim</em> every item it wants to remind about by inserting a row. The insert
either succeeds, and this run owns that reminder, or raises <code class="language-plaintext highlighter-rouge">RecordNotUnique</code>, and another run
already owns it:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">claim</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">user</span><span class="p">,</span> <span class="n">channel</span><span class="p">)</span>
  <span class="no">ReminderLog</span><span class="p">.</span><span class="nf">transaction</span><span class="p">(</span><span class="ss">requires_new: </span><span class="kp">true</span><span class="p">)</span> <span class="k">do</span>
    <span class="no">ReminderLog</span><span class="p">.</span><span class="nf">create!</span><span class="p">(</span><span class="ss">record: </span><span class="n">item</span><span class="p">.</span><span class="nf">record</span><span class="p">,</span> <span class="n">user</span><span class="p">:,</span> <span class="ss">kind: </span><span class="n">item</span><span class="p">.</span><span class="nf">kind</span><span class="p">,</span> <span class="n">channel</span><span class="p">:,</span>
                        <span class="ss">scheduled_on: </span><span class="n">item</span><span class="p">.</span><span class="nf">scheduled_on</span><span class="p">,</span> <span class="ss">snoozed: </span><span class="n">item</span><span class="p">.</span><span class="nf">snoozed</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">rescue</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">RecordNotUnique</span>
  <span class="kp">nil</span>
<span class="k">end</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">requires_new: true</code> matters. In PostgreSQL, a failed statement aborts the whole transaction it’s
in. The nested transaction becomes a savepoint, so losing one claim rolls back only that insert,
and the run carries on with the items it did win.</p>

<p>The claims and the digest row are created in one transaction. If a second run gets as far as
creating the same day’s digest, the second unique index stops it, and the whole attempt rolls back:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">rescue</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">RecordNotUnique</span>
  <span class="kp">nil</span> <span class="c1"># a concurrent run created today's delivery; its claims won</span>
</code></pre></div></div>

<p>The index is the lock. There’s no lock table, no advisory lock, no Redis. The database already has
to keep the data consistent, so I let it enforce the rule as well.</p>

<h2 id="2-recover-from-a-run-that-died-halfway">2. Recover from a run that died halfway</h2>

<p>Claiming and sending are separate steps. The run writes the claims and a <code class="language-plaintext highlighter-rouge">pending</code> digest in one
transaction, then queues a job to send it. If the process dies after that commit, the digest
exists but nothing is sending it.</p>

<p>Each run starts by picking those up:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Claimed but never dispatched (the run died in between): dispatch on the next run</span>
<span class="k">def</span> <span class="nf">recover_stuck_deliveries</span>
  <span class="no">ReminderDelivery</span><span class="p">.</span><span class="nf">pending</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">channel: </span><span class="sx">%w[email web_push]</span><span class="p">,</span> <span class="ss">dispatched_at: </span><span class="kp">nil</span><span class="p">)</span>
    <span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">created_at: </span><span class="o">...</span><span class="p">(</span><span class="vi">@now</span> <span class="o">-</span> <span class="no">STUCK_AFTER</span><span class="p">))</span>
    <span class="p">.</span><span class="nf">find_each</span> <span class="p">{</span> <span class="o">|</span><span class="n">delivery</span><span class="o">|</span> <span class="no">DeliverReminderJob</span><span class="p">.</span><span class="nf">perform_later</span><span class="p">(</span><span class="n">delivery</span><span class="p">.</span><span class="nf">id</span><span class="p">)</span> <span class="p">}</span>
<span class="k">end</span>
</code></pre></div></div>

<p>The send job is safe to run again: it returns straight away unless the digest is still <code class="language-plaintext highlighter-rouge">pending</code>.</p>

<p>To be honest about the limits: the <em>decision</em> to remind happens exactly once, but the last hop is
at-least-once. If the process dies after the mail server accepted an email and before the row is
marked <code class="language-plaintext highlighter-rouge">sent</code>, a retry can send that email again. The design keeps that window as small as it can;
it can’t close it, because no system can make an external send and a database write atomic.</p>

<h2 id="3-accepted-is-not-delivered">3. “Accepted” is not “delivered”</h2>

<p>Web Push has two legs: my server hands the message to the browser’s push service, and the push
service delivers it to the phone whenever the phone wakes up. The <code class="language-plaintext highlighter-rouge">201</code> I get back only covers the
first leg.</p>

<p>So every push carries a single-use receipt URL. The server stores only a SHA-256 digest of the
token, behind its own unique index. The service worker posts the receipt after it has shown the
notification:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">event</span><span class="p">.</span><span class="nx">waitUntil</span><span class="p">((</span><span class="k">async</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="k">await</span> <span class="nb">self</span><span class="p">.</span><span class="nx">registration</span><span class="p">.</span><span class="nx">showNotification</span><span class="p">(</span><span class="nx">title</span><span class="p">,</span> <span class="nx">options</span><span class="p">)</span>
  <span class="k">if</span> <span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">receipt_url</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">try</span> <span class="p">{</span>
      <span class="k">await</span> <span class="nx">fetch</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">receipt_url</span><span class="p">,</span> <span class="p">{</span> <span class="na">method</span><span class="p">:</span> <span class="dl">"</span><span class="s2">POST</span><span class="dl">"</span><span class="p">,</span> <span class="na">keepalive</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span> <span class="na">credentials</span><span class="p">:</span> <span class="dl">"</span><span class="s2">omit</span><span class="dl">"</span> <span class="p">})</span>
    <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">_</span><span class="p">)</span> <span class="p">{</span>
      <span class="c1">// Receipt is best effort; an unconfirmed delivery is reported after 24 h.</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">})())</span>
</code></pre></div></div>

<p>The receipt endpoint is deliberately unauthenticated and CSRF-exempt, because the phone’s session
may have expired. The single-use token is the only credential, and the endpoint is rate limited.
A digest moves <code class="language-plaintext highlighter-rouge">pending → awaiting_receipt → sent</code> only when a device confirms it. An hourly job
marks anything still unconfirmed after 24 hours as failed, and I see it in the next daily summary.
For “bill paid” and supply alerts, an unconfirmed push falls back to email.</p>

<p>I measured this before relying on it. On a Pixel 9 with the app closed, the push service accepted
every message within a second. With the screen off, one receipt arrived <strong>25.6 minutes</strong> later.
Overnight with battery saver on, one arrived after <strong>112 minutes</strong>. If I had treated <code class="language-plaintext highlighter-rouge">201</code> as
“delivered”, those reminders would have shown as delivered while they were still waiting.</p>

<h2 id="4-pin-it-down-with-tests">4. Pin it down with tests</h2>

<p>The behavior is covered at the level a user would describe it:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">test</span> <span class="s2">"nothing before the member's reminder hour; at 08:00 one digest per channel; later runs add nothing"</span> <span class="k">do</span>
  <span class="n">bill</span>
  <span class="n">run_at</span><span class="p">(</span><span class="n">taipei</span><span class="p">(</span><span class="mi">2026</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">30</span><span class="p">))</span>
  <span class="n">assert_empty</span> <span class="n">deliveries</span>
  <span class="n">assert_enqueued_jobs</span> <span class="mi">2</span><span class="p">,</span> <span class="ss">only: </span><span class="no">DeliverReminderJob</span> <span class="k">do</span>
    <span class="n">run_at</span><span class="p">(</span><span class="n">taipei</span><span class="p">(</span><span class="mi">2026</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
  <span class="k">end</span>
  <span class="n">assert_equal</span> <span class="sx">%w[in_app email web_push]</span><span class="p">,</span> <span class="n">deliveries</span><span class="p">.</span><span class="nf">pluck</span><span class="p">(</span><span class="ss">:channel</span><span class="p">)</span>
  <span class="c1"># … (status and wording checks trimmed)</span>
  <span class="n">run_at</span><span class="p">(</span><span class="n">taipei</span><span class="p">(</span><span class="mi">2026</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
  <span class="n">assert_equal</span> <span class="mi">3</span><span class="p">,</span> <span class="n">deliveries</span><span class="p">.</span><span class="nf">count</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Alongside it, another test checks that a digest stuck in <code class="language-plaintext highlighter-rouge">pending</code> for two hours is dispatched
again.</p>

<h2 id="what-id-take-to-any-project">What I’d take to any project</h2>

<ul>
  <li><strong>Put the invariant where every writer has to go through it.</strong> A unique index can’t be skipped by
a forgotten code path or a second worker.</li>
  <li><strong>Name the unit of idempotency.</strong> Here it’s <em>member × household × channel × local day</em>. Once that’s
written down, the index almost writes itself.</li>
  <li><strong>Keep “decided”, “sent” and “received” as separate states.</strong> Each one fails differently, and
merging them hides the failures.</li>
  <li><strong>Measure the edge you don’t control</strong> before you design around it.</li>
</ul>

<p>The code is in the <a href="https://github.com/yuhruh/HouseHold_Notification">Household Tracker repository</a>.</p>]]></content><author><name>Rita Huang</name></author><category term="Rails" /><category term="PostgreSQL" /><category term="Web Push" /><category term="Reliability" /><summary type="html"><![CDATA[How Household Tracker uses unique indexes as locks so each family member gets exactly one reminder digest per day, and why it only counts a push as delivered when the phone says so.]]></summary></entry></feed>