<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: James M. Vu</title>
    <description>The latest articles on DEV Community by James M. Vu (@jamesvu).</description>
    <link>https://dev.to/jamesvu</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3940235%2F59d061e5-cbf4-40bf-a87e-10406a6d93b0.jpg</url>
      <title>DEV Community: James M. Vu</title>
      <link>https://dev.to/jamesvu</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jamesvu"/>
    <language>en</language>
    <item>
      <title>From a polling Bash script to an event-driven Swift daemon on macOS</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Thu, 26 Nov 2026 22:32:17 +0000</pubDate>
      <link>https://dev.to/jamesvu/from-a-polling-bash-script-to-an-event-driven-swift-daemon-on-macos-2739</link>
      <guid>https://dev.to/jamesvu/from-a-polling-bash-script-to-an-event-driven-swift-daemon-on-macos-2739</guid>
      <description>&lt;p&gt;The first version of &lt;a href="https://github.com/vuminhhoa/macsentry" rel="noopener noreferrer"&gt;MacSentry&lt;/a&gt;'s root daemon was a 1,110-line Bash script that polled the system in a loop. It worked, but on my Apple M4 development Mac it was measured at about 10% of one core at one point, and even after two rounds of optimization it still used about 4.5%, all day. The Swift rewrite runs at about 0.4%. This post covers what actually made the difference: forks, polling, cheap change detection, letting macOS deprioritize the daemon, and an undocumented &lt;code&gt;netstat&lt;/code&gt; behavior that silently hides connections.&lt;/p&gt;

&lt;p&gt;The numbers come from the commit history and were measured on that one machine. Treat them as orders of magnitude, not benchmarks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Measure per check before rewriting anything
&lt;/h2&gt;

&lt;p&gt;Before the rewrite, the Bash version got two rounds of optimization, and both were guided by timing each check rather than guessing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Skipping work when nothing changed (details below) cut the time spent on checks per cycle from about 16.6 s to 8.1 s.&lt;/li&gt;
&lt;li&gt;A fork-free fast path when a list had not changed, no more &lt;code&gt;date&lt;/code&gt; and &lt;code&gt;cksum&lt;/code&gt; forks, &lt;code&gt;lsof&lt;/code&gt; only for suspicious programs, slower polling for checks that rarely change, and no &lt;code&gt;wazuh-control&lt;/code&gt; call every 30 seconds brought the daemon from 12.0 s of CPU per 120 s to 4.6 s, roughly from 10% of one core to 4%.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Those rounds showed where the cost was, and that the remaining cost was structural: a shell script cannot read process tables or wait for events without forking something.&lt;/p&gt;

&lt;h2&gt;
  
  
  Forks were the cost, so read data through APIs
&lt;/h2&gt;

&lt;p&gt;Each &lt;code&gt;ps&lt;/code&gt;, &lt;code&gt;lsof&lt;/code&gt; or &lt;code&gt;codesign&lt;/code&gt; call starts a process, loads it, and produces text that the script then parses with more processes. The Swift daemon reads the same data directly:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Shell&lt;/th&gt;
&lt;th&gt;Swift daemon&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;ps&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;proc_listallpids&lt;/code&gt;, &lt;code&gt;proc_pidinfo&lt;/code&gt;, &lt;code&gt;sysctl(KERN_PROCARGS2)&lt;/code&gt; for arguments&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;lsof -i&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;proc_pidinfo(PROC_PIDLISTFDS)&lt;/code&gt; and &lt;code&gt;proc_pidfdinfo(PROC_PIDFDSOCKETINFO)&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;who&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;getutxent&lt;/code&gt; (utmpx)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;codesign -dv&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;SecStaticCodeCreateWithPath&lt;/code&gt;, &lt;code&gt;SecCodeCopySigningInformation&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;ioreg&lt;/code&gt;, &lt;code&gt;pmset&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;IOKit&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;defaults read&lt;/code&gt;, &lt;code&gt;launchctl&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Reading the plist files with &lt;code&gt;PropertyListSerialization&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Commands are still used where there is no API, such as &lt;code&gt;netstat&lt;/code&gt;, &lt;code&gt;profiles&lt;/code&gt;, &lt;code&gt;kmutil&lt;/code&gt; and &lt;code&gt;sfltool&lt;/code&gt;. They run rarely, and the slow ones run on a separate low-priority queue so they never block the main loop. &lt;code&gt;sfltool dumpbtm&lt;/code&gt; alone takes 3–5 seconds.&lt;/p&gt;

&lt;h2&gt;
  
  
  Subscribe to events instead of polling
&lt;/h2&gt;

&lt;p&gt;Polling means paying every few seconds to learn that nothing changed. The daemon now subscribes to what macOS already announces, and every callback only enqueues work:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://developer.apple.com/documentation/coreservices/file_system_events" rel="noopener noreferrer"&gt;FSEvents&lt;/a&gt;&lt;/strong&gt; for LaunchAgents and LaunchDaemons, &lt;code&gt;/etc&lt;/code&gt;, &lt;code&gt;~/.ssh&lt;/code&gt; and other persistence folders.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;IOKit&lt;/strong&gt; for USB devices (&lt;code&gt;IOServiceAddMatchingNotification&lt;/code&gt;), power source changes, and sleep and wake (&lt;code&gt;IORegisterForSystemPower&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;DiskArbitration&lt;/strong&gt; for external volumes, and &lt;strong&gt;SCDynamicStore&lt;/strong&gt; for network, proxy and DNS changes.&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;dispatch source on the spool directory&lt;/strong&gt; for messages from the Endpoint Security helper.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Two IOKit details are easy to get wrong. A matching notification fires once and then only re-arms after you drain its iterator with &lt;code&gt;IOIteratorNext&lt;/code&gt;, including right after registering. And a power callback that receives "can the system sleep?" or "the system will sleep" must answer with &lt;code&gt;IOAllowPowerChange&lt;/code&gt;, or macOS waits for it before sleeping.&lt;/p&gt;

&lt;p&gt;Events also come in bursts: plugging in one USB hub produces several notifications. A small debounce merges them into one check a second later.&lt;/p&gt;

&lt;p&gt;What remains is a 2-second timer for things with no event, such as new TCP connections, and a fallback scan for everything else at slower intervals: 10 seconds, 30 seconds, a minute, five minutes. When the Endpoint Security helper is running, it already reports SSH logins and reverse shell commands as they happen, so the timer polls those less often.&lt;/p&gt;

&lt;h2&gt;
  
  
  netstat hides sockets when called from a non-Apple binary
&lt;/h2&gt;

&lt;p&gt;This one is not documented anywhere I could find, so take it as observed behavior on recent macOS versions. When &lt;code&gt;netstat -an -p tcp&lt;/code&gt; is started by a binary that is not Apple's, even as a child process, sockets owned by other processes are left out of its output. Nothing reports an error; the list is just shorter.&lt;/p&gt;

&lt;p&gt;Two changes work around it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Combine two sources.&lt;/strong&gt; The daemon reads sockets per process through &lt;code&gt;libproc&lt;/code&gt;, which sees everything when run as root, and also parses &lt;code&gt;netstat&lt;/code&gt;, which sees sockets that belong to no process, such as connections launchd holds for &lt;code&gt;sshd&lt;/code&gt; before it starts. A connection counts if either source reports it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Let launchd run &lt;code&gt;netstat&lt;/code&gt; for the app.&lt;/strong&gt; When the menu bar app has to scan by itself (without the daemon), it submits a tiny launchd job that runs &lt;code&gt;netstat&lt;/code&gt; every two seconds and writes the output to a file. Jobs started by launchd were not affected, and the app only reads the file. When the daemon is running, it publishes its scan in a world-readable file under &lt;code&gt;/var/run&lt;/code&gt;, so the app does not scan at all.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The general lesson: when a tool's output looks plausible but incomplete, compare it against a second source before trusting it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Detect change cheaply, then do the expensive work
&lt;/h2&gt;

&lt;p&gt;Most checks ask "did this set of files change?". Hashing every file each time is wasteful, so the daemon first compares a cheap signature: &lt;code&gt;ctime&lt;/code&gt;, size and path of each file. Only when that differs does it hash, diff and alert.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ctime&lt;/code&gt; instead of &lt;code&gt;mtime&lt;/code&gt; is deliberate. &lt;a href="https://keith.github.io/xcode-man-pages/utimes.2.html" rel="noopener noreferrer"&gt;&lt;code&gt;utimes(2)&lt;/code&gt;&lt;/a&gt; lets the owner set the access and modification times to any value, but the inode change time is always set to the current time, so a modified file cannot pretend to be untouched by restoring its old timestamp.&lt;/p&gt;

&lt;p&gt;Two more rules prevent alert floods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The first run only records a baseline.&lt;/strong&gt; Installing MacSentry should not report every LaunchAgent that was already there. The same applies when the daemon's state format changes: a version marker triggers a new baseline instead of a burst of false "new" items.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;An empty read is an error, not "everything was removed".&lt;/strong&gt; Lists that can never be empty (users, applications) skip the pass when they come back empty, and a browser profile that cannot be read is skipped instead of being recorded as an empty baseline.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Let macOS deprioritize the daemon
&lt;/h2&gt;

&lt;p&gt;A security monitor should not compete with the user. Both root jobs are declared as background work in their LaunchDaemon plist:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight xml"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;key&amp;gt;&lt;/span&gt;ProcessType&lt;span class="nt"&gt;&amp;lt;/key&amp;gt;&amp;lt;string&amp;gt;&lt;/span&gt;Background&lt;span class="nt"&gt;&amp;lt;/string&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;key&amp;gt;&lt;/span&gt;LowPriorityIO&lt;span class="nt"&gt;&amp;lt;/key&amp;gt;&amp;lt;true/&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://keith.github.io/xcode-man-pages/launchd.plist.5.html" rel="noopener noreferrer"&gt;&lt;code&gt;launchd.plist(5)&lt;/code&gt;&lt;/a&gt; describes &lt;code&gt;Background&lt;/code&gt; jobs as "processes that do work that was not directly requested by the user", with resource limits applied, and &lt;code&gt;LowPriorityIO&lt;/code&gt; marks the daemon's filesystem I/O as low priority. The trade-off is explicit: when the machine is busy, an alert may arrive a few seconds late.&lt;/p&gt;

&lt;h2&gt;
  
  
  One serial queue removes a class of bugs
&lt;/h2&gt;

&lt;p&gt;Every check and every piece of state runs on one serial dispatch queue. Event callbacks, the timer and the spool watcher only enqueue work. That removes the need for locks entirely, which matters in a program whose whole job is comparing "before" and "after".&lt;/p&gt;

&lt;p&gt;It also removed the most frustrating bugs of the Bash version. Shell functions share variables unless every local is declared, and two of them didn't: a helper that read new log lines overwrote a loop variable, so remote-control alerts showed the wrong log path, and the throttling helper overwrote a variable in the connection check. Neither produced an error.&lt;/p&gt;

&lt;h2&gt;
  
  
  Results
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Bash daemon&lt;/th&gt;
&lt;th&gt;Bash, optimized&lt;/th&gt;
&lt;th&gt;Swift daemon&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;CPU per 120 s&lt;/td&gt;
&lt;td&gt;12.0 s&lt;/td&gt;
&lt;td&gt;4.6 s&lt;/td&gt;
&lt;td&gt;—&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Share of one core&lt;/td&gt;
&lt;td&gt;~10%&lt;/td&gt;
&lt;td&gt;~4–4.5%&lt;/td&gt;
&lt;td&gt;~0.4%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Change detection&lt;/td&gt;
&lt;td&gt;Polling&lt;/td&gt;
&lt;td&gt;Polling with ctime prefilter&lt;/td&gt;
&lt;td&gt;Events, polling as fallback&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Process and socket data&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;ps&lt;/code&gt;, &lt;code&gt;lsof&lt;/code&gt;, &lt;code&gt;who&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Same, fewer calls&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;libproc&lt;/code&gt;, &lt;code&gt;sysctl&lt;/code&gt;, utmpx&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fub9n3t5amln2gziaez5l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fub9n3t5amln2gziaez5l.png" alt="Bar chart of the daemon's share of one CPU core: about 10% for the Bash daemon, about 4.5% after optimizing it, and about 0.4% for the Swift daemon." width="800" height="233"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Measured on one Mac. The rewrite cut the share of a core by about ten times, mostly by not forking and not polling.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;On the same machine, the whole of MacSentry now uses about 0.4–0.8% of one core for the daemon, about 2% for the Endpoint Security helper with &lt;code&gt;exec&lt;/code&gt; monitoring on, and about 0.2% for the menu bar app. The &lt;a href="https://vuminhhoa.com/en/blog/endpoint-security-eslogger-swift" rel="noopener noreferrer"&gt;Endpoint Security post&lt;/a&gt; covers how the helper keeps its share down.&lt;/p&gt;

&lt;p&gt;The rewrite was worth it, but most of the gain came from two ideas that work in any language: don't start a process to read data the kernel can give you directly, and don't ask "did anything change?" when the system can tell you.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Time each check before rewriting; two rounds of optimizing the Bash daemon showed the remaining cost was structural, not a slow function.&lt;/li&gt;
&lt;li&gt;Forks were the main cost, so read process, socket, login and signing data through &lt;code&gt;libproc&lt;/code&gt;, &lt;code&gt;sysctl&lt;/code&gt;, utmpx, Security and IOKit instead of parsing command output.&lt;/li&gt;
&lt;li&gt;Subscribe to FSEvents, IOKit, DiskArbitration and SCDynamicStore instead of polling, debounce bursts, and keep slower polling only as a fallback.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;netstat&lt;/code&gt; started by a non-Apple binary silently leaves out other processes' sockets on recent macOS versions, as far as I observed, so combine it with a second source before trusting its output.&lt;/li&gt;
&lt;li&gt;Compare a cheap &lt;code&gt;ctime&lt;/code&gt;, size and path signature before hashing, record a baseline on the first run, and treat an empty read as an error.&lt;/li&gt;
&lt;li&gt;Declare the daemon as &lt;code&gt;Background&lt;/code&gt; with &lt;code&gt;LowPriorityIO&lt;/code&gt;, and run all checks and state on one serial queue so no locks are needed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you've moved a polling daemon to events on macOS, or found other tools that quietly return partial output, I'd love to compare notes. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>macos</category>
      <category>swift</category>
      <category>bash</category>
      <category>fsevents</category>
    </item>
    <item>
      <title>Making a Mac security monitor hard to silence</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Wed, 25 Nov 2026 22:41:39 +0000</pubDate>
      <link>https://dev.to/jamesvu/making-a-mac-security-monitor-hard-to-silence-4hn</link>
      <guid>https://dev.to/jamesvu/making-a-mac-security-monitor-hard-to-silence-4hn</guid>
      <description>&lt;p&gt;A security monitor that can be switched off quietly is worse than none, because it still looks reassuring. This post covers how &lt;a href="https://github.com/vuminhhoa/macsentry" rel="noopener noreferrer"&gt;MacSentry&lt;/a&gt;, my open-source Mac monitor, tries to make silencing it noisy: telling a reboot apart from &lt;code&gt;kill -9&lt;/code&gt;, two processes that watch each other, an append-only log, a dead man's switch, and a Telegram detail that lets malware delete your alerts if you are not careful.&lt;/p&gt;

&lt;p&gt;The goal is not to be unstoppable. Someone with root can, given time, stop any local monitor. The goal is that the attempt itself gets reported, from outside the machine, before it succeeds.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get the evidence off the machine first
&lt;/h2&gt;

&lt;p&gt;Anything stored only on the Mac can be cleaned up by whoever gets in. So every finding is sent to Telegram the moment it happens, and the local log is a second copy, not the primary record.&lt;/p&gt;

&lt;p&gt;Delivery has to survive the conditions in which alerts matter most:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Retry only transient failures.&lt;/strong&gt; No connection, HTTP 429 and 5xx are retried every 10 seconds for up to about five minutes, because right after boot or wake the network is often not up yet. Other errors (a revoked token, a wrong chat ID) are logged once instead of retried forever.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Respect the message limit.&lt;/strong&gt; The &lt;a href="https://core.telegram.org/bots/api#sendmessage" rel="noopener noreferrer"&gt;Bot API&lt;/a&gt; accepts 1–4096 characters per message. Long alerts, such as a diff of a changed file, are cut at a safe length with a note pointing to the full entry in the local log.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;On shutdown, send synchronously.&lt;/strong&gt; When launchd sends &lt;code&gt;SIGTERM&lt;/code&gt;, the daemon makes one send attempt and waits up to five seconds for it before exiting, so the "Mac is shutting down" message actually leaves.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  A Telegram bot can delete its own alerts for 48 hours
&lt;/h2&gt;

&lt;p&gt;This is the detail I missed at first. The Bot API's &lt;a href="https://core.telegram.org/bots/api#deletemessage" rel="noopener noreferrer"&gt;&lt;code&gt;deleteMessage&lt;/code&gt;&lt;/a&gt; lets a bot delete its own outgoing messages in private chats and groups, as long as they were sent less than 48 hours ago. The token is all you need to call it.&lt;/p&gt;

&lt;p&gt;MacSentry has a menu bar app running as the user, and that app needs a token to send its own alerts. Its token therefore lives in the user's home folder, readable by anything running as that user. If the root daemon used the same bot, malware running as the user could read the token and delete the daemon's alerts too, including the one about itself.&lt;/p&gt;

&lt;p&gt;The fix is a second bot. The installer asks for a separate token for the daemon and stores it in &lt;code&gt;/etc/macsentry.conf&lt;/code&gt;, owned by root with mode 0600. The daemon also checks whether its token matches the app's and, if so, sends a reminder once a week. A user-level attacker can still delete the app's messages, but not the daemon's, and the daemon is the one that reports persistence and tampering.&lt;/p&gt;

&lt;h2&gt;
  
  
  Telling a reboot from kill -9
&lt;/h2&gt;

&lt;p&gt;A process cannot catch &lt;code&gt;SIGKILL&lt;/code&gt;, so it cannot report its own forced death. It can, however, notice on the next start that its previous run did not end normally. The daemon combines two facts (shortened from &lt;code&gt;daemon/Sources/main.swift&lt;/code&gt;, alert text translated):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="n"&gt;boot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;bootTime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;// sysctl KERN_BOOTTIME&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;readText&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;sp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"lastboot"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;boot&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;alert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"🟢 The Mac just started"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;exists&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;sp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"clean_stop"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;info&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"▶️ macsentryd restarted"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;alert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"⚠️ macsentryd was stopped abruptly (kill -9 or a crash) and launchd restarted it"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;SIGTERM&lt;/code&gt; handler writes the &lt;code&gt;clean_stop&lt;/code&gt; marker before exiting. If the boot time is unchanged and the marker is missing, the previous instance died without running its handler, which means &lt;code&gt;SIGKILL&lt;/code&gt; or a crash. Because the job has &lt;code&gt;KeepAlive&lt;/code&gt;, launchd restarts it within seconds and the alert goes out.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp85sg9x9nqzzcrt7qssv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp85sg9x9nqzzcrt7qssv.png" alt="Decision tree run when the MacSentry daemon starts: if the boot time changed, it reports that the Mac just started; otherwise, if the clean_stop marker exists, it logs a restart; otherwise it alerts that it was stopped abruptly by kill -9 or a crash." width="800" height="620"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Two facts saved before exit, the boot time and a marker written on SIGTERM, are enough to tell the three cases apart.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Planned stops must not look like attacks
&lt;/h2&gt;

&lt;p&gt;A monitor that cries wolf on every update teaches you to ignore it. The installer therefore leaves markers before it touches anything: &lt;code&gt;updating&lt;/code&gt; (the stop is an update, not a shutdown), &lt;code&gt;clean_stop&lt;/code&gt; (the next start is not a &lt;code&gt;kill -9&lt;/code&gt;) and &lt;code&gt;just_updated&lt;/code&gt; (the changes to MacSentry's own files that follow are expected). The installer also waits for the old daemon to exit fully before starting the new one, because the old one may still be sending its last message. The update flow itself is in &lt;a href="https://vuminhhoa.com/en/blog/macos-app-self-update-from-source" rel="noopener noreferrer"&gt;one-click updates for a macOS app built from source&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The same idea covers rebuilds. The daemon records the code signature of its own binaries. A rebuild signed with the same certificate is reported silently; a binary whose signer changed, or that lost its signature, is reported as a possible swap. The same check runs for the executable of every LaunchDaemon and LaunchAgent in &lt;code&gt;/Library&lt;/code&gt;: an update usually keeps its publisher, a swapped binary usually does not.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two processes that watch each other
&lt;/h2&gt;

&lt;p&gt;MacSentry has two long-running parts with different weaknesses:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;strong&gt;daemon&lt;/strong&gt; runs as root from boot, before anyone logs in. A normal user cannot stop it.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;menu bar app&lt;/strong&gt; runs as the user. It is a LaunchAgent with &lt;code&gt;KeepAlive&lt;/code&gt; set to &lt;code&gt;{SuccessfulExit: false}&lt;/code&gt;, and it has no Quit item.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;They check each other. The daemon alerts if no MacSentry app is running for the logged-in user; the app alerts if the daemon or the Endpoint Security helper has been missing for about a minute, and again when it comes back.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;SuccessfulExit&lt;/code&gt; detail matters. &lt;a href="https://keith.github.io/xcode-man-pages/launchd.plist.5.html" rel="noopener noreferrer"&gt;&lt;code&gt;launchd.plist(5)&lt;/code&gt;&lt;/a&gt; defines &lt;code&gt;SuccessfulExit: false&lt;/code&gt; as "restart the job unless it exits with status zero". When a second copy of the app starts (for example, opened from Finder while the launchd copy is running), it must exit with a &lt;em&gt;non-zero&lt;/em&gt; status. Exiting with 0 would tell launchd the job finished normally, and if that happened to the only copy, nothing would be left running.&lt;/p&gt;

&lt;h2&gt;
  
  
  Watch the commands that silence monitors
&lt;/h2&gt;

&lt;p&gt;Endpoint Security events (covered in &lt;a href="https://vuminhhoa.com/en/blog/endpoint-security-eslogger-swift" rel="noopener noreferrer"&gt;reading eslogger from Swift&lt;/a&gt;) let MacSentry see commands, not just their effects. Rules flag:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;launchctl bootout&lt;/code&gt;, &lt;code&gt;unload&lt;/code&gt; or &lt;code&gt;disable&lt;/code&gt; aimed at MacSentry, Wazuh or common EDR agents, and &lt;code&gt;pkill&lt;/code&gt; or &lt;code&gt;killall&lt;/code&gt; of their processes;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;chflags&lt;/code&gt; removing the append-only or immutable flags, and &lt;code&gt;log erase&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;turning off SIP, Gatekeeper, the firewall or &lt;code&gt;pf&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each alert includes the user and the full parent chain, so you can see whether the command came from your terminal or from something you do not recognize.&lt;/p&gt;

&lt;h2&gt;
  
  
  An append-only log, and what it does not protect
&lt;/h2&gt;

&lt;p&gt;The local log is created with the system append-only flag:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;chflags sappnd /var/log/macsentry.log
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;According to &lt;a href="https://keith.github.io/xcode-man-pages/chflags.1.html" rel="noopener noreferrer"&gt;&lt;code&gt;chflags(1)&lt;/code&gt;&lt;/a&gt;, only the super-user can set &lt;code&gt;sappnd&lt;/code&gt;, and &lt;a href="https://keith.github.io/xcode-man-pages/chflags.2.html" rel="noopener noreferrer"&gt;&lt;code&gt;chflags(2)&lt;/code&gt;&lt;/a&gt; defines the flag as "the file may only be appended to". While it is set, existing lines cannot be rewritten or truncated, and the file cannot be removed, even by root. Root can still clear the flag first, so this stops non-root processes and accidental edits, not a determined administrator. Clearing the flag is itself one of the commands above, so it is reported before the log can be touched.&lt;/p&gt;

&lt;p&gt;A cryptographic chain is stronger when you control the storage: I described one, with hash chains and an HMAC key kept outside the database, in &lt;a href="https://vuminhhoa.com/en/blog/tamper-evident-audit-log-postgresql" rel="noopener noreferrer"&gt;building a tamper-evident audit log in PostgreSQL&lt;/a&gt;. For a local file on a machine you may no longer trust, sending each entry off the machine as it happens matters more than how the local copy is protected.&lt;/p&gt;

&lt;h2&gt;
  
  
  A dead man's switch covers what the Mac cannot report
&lt;/h2&gt;

&lt;p&gt;Some events end with nothing left to report them: the Mac is wiped, the power is cut, the daemon is removed by someone with root. For those, the daemon pings an outside URL every minute, for example a check on &lt;a href="https://healthchecks.io" rel="noopener noreferrer"&gt;healthchecks.io&lt;/a&gt;. The service alerts you when the pings stop. It is the same principle as monitoring the monitor in &lt;a href="https://vuminhhoa.com/en/blog/self-hosted-vps-side-projects" rel="noopener noreferrer"&gt;self-hosting side projects&lt;/a&gt;: the signal that something died has to come from somewhere that did not die with it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Keep the secrets out of reach of what you watch
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The daemon's token sits in a root-only file and is only ever in memory; it never appears on a command line. The early shell version passed it to &lt;code&gt;curl&lt;/code&gt; on standard input (&lt;code&gt;curl -K -&lt;/code&gt;) for the same reason: arguments show up in &lt;code&gt;ps&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The Endpoint Security helper never holds a token. It writes findings into a spool directory that only root can read, and the daemon sends them.&lt;/li&gt;
&lt;li&gt;File diffs and everything the helper sends are masked before they leave the machine: Telegram bot tokens, and values that follow names like &lt;code&gt;TOKEN=&lt;/code&gt; or &lt;code&gt;PASSWORD:&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Threat&lt;/th&gt;
&lt;th&gt;What MacSentry does&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Local evidence cleaned up&lt;/td&gt;
&lt;td&gt;Send each finding to Telegram immediately; retry transient failures for ~5 minutes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Malware deletes the bot's alerts&lt;/td&gt;
&lt;td&gt;Separate root-only bot for the daemon; warn when tokens are shared&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;kill -9&lt;/code&gt; on the daemon&lt;/td&gt;
&lt;td&gt;Boot time plus a clean-stop marker; launchd restarts and the restart is reported&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;False alarms from updates&lt;/td&gt;
&lt;td&gt;Installer markers; same-signer rebuilds reported silently&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;App or daemon stopped&lt;/td&gt;
&lt;td&gt;Each watches the other; app relaunched by launchd unless it exits non-zero&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Commands that disable monitoring&lt;/td&gt;
&lt;td&gt;Endpoint Security rules with the full parent chain&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Machine wiped or powered off&lt;/td&gt;
&lt;td&gt;Heartbeat to an outside dead man's switch&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;None of this makes a Mac safe on its own. MacSentry is a tripwire next to FileVault, updates and an EDR if you have one. What these details buy is that turning the tripwire off is itself something you hear about.&lt;/p&gt;

&lt;p&gt;If you've worked on making a local monitor hard to switch off quietly, I'd love to compare notes. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>macos</category>
      <category>launchd</category>
      <category>telegrambotapi</category>
      <category>tamperdetection</category>
    </item>
    <item>
      <title>Endpoint Security on macOS without the entitlement: eslogger and Swift</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Tue, 24 Nov 2026 23:13:35 +0000</pubDate>
      <link>https://dev.to/jamesvu/endpoint-security-on-macos-without-the-entitlement-eslogger-and-swift-40e2</link>
      <guid>https://dev.to/jamesvu/endpoint-security-on-macos-without-the-entitlement-eslogger-and-swift-40e2</guid>
      <description>&lt;p&gt;Endpoint Security is the macOS API that EDR products use to see every process launch, login and permission change. Using it directly requires an entitlement that Apple grants case by case. This post shows how &lt;a href="https://github.com/vuminhhoa/macsentry" rel="noopener noreferrer"&gt;MacSentry&lt;/a&gt;, my open-source Mac monitor, gets the same events through &lt;code&gt;/usr/bin/eslogger&lt;/code&gt; instead, and what it took to make that fast and quiet: reading JSON Lines without parsing most of them, matching rules against the right program, and not alerting on itself.&lt;/p&gt;

&lt;h2&gt;
  
  
  eslogger gives you Endpoint Security events without the entitlement
&lt;/h2&gt;

&lt;p&gt;A native Endpoint Security client needs the &lt;a href="https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.developer.endpoint-security.client" rel="noopener noreferrer"&gt;&lt;code&gt;com.apple.developer.endpoint-security.client&lt;/code&gt;&lt;/a&gt; entitlement, and Apple's documentation says plainly that you must request it. For a personal tool built from source, that is not realistic.&lt;/p&gt;

&lt;p&gt;macOS ships &lt;code&gt;eslogger&lt;/code&gt;, a command-line Endpoint Security client that prints events as JSON Lines. MacSentry's helper, &lt;code&gt;macsentry-es&lt;/code&gt;, is a root LaunchDaemon that starts &lt;code&gt;eslogger&lt;/code&gt; with a list of event names and reads its standard output. The &lt;a href="https://keith.github.io/xcode-man-pages/eslogger.1.html" rel="noopener noreferrer"&gt;&lt;code&gt;eslogger(1)&lt;/code&gt;&lt;/a&gt; man page sets the terms, and each one shaped the design:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;It must run as root, and the &lt;em&gt;responsible process&lt;/em&gt; needs Full Disk Access.&lt;/strong&gt; Because the helper launches &lt;code&gt;eslogger&lt;/code&gt; as a child, macOS checks the helper's binary, so Full Disk Access goes to &lt;code&gt;/usr/local/libexec/macsentry-es&lt;/code&gt;, not to &lt;code&gt;eslogger&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;It supports notify events only, never auth events.&lt;/strong&gt; You can see that something happened, but you cannot block it. That matches what MacSentry is: a tripwire that reports, not a shield.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;"eslogger is NOT API in any sense."&lt;/strong&gt; The output format may change between macOS releases without warning. The helper therefore saves the first raw sample of every event type to disk, and a small script prints their structure, so when a field moves I can see where it went instead of guessing. Field access is tolerant too: the failure reason of a &lt;code&gt;sudo&lt;/code&gt; event, for example, is looked up in more than one place.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;It suppresses events from its own process group&lt;/strong&gt;, to avoid feedback loops. That covers the helper itself, but not the separate root daemon, which comes back below.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The helper subscribes to around twenty events: &lt;code&gt;authentication&lt;/code&gt;, &lt;code&gt;tcc_modify&lt;/code&gt;, &lt;code&gt;exec&lt;/code&gt;, &lt;code&gt;sudo&lt;/code&gt;, &lt;code&gt;su&lt;/code&gt;, &lt;code&gt;openssh_login&lt;/code&gt;, &lt;code&gt;screensharing_attach&lt;/code&gt;, XProtect and Gatekeeper events, Background Task Management (&lt;code&gt;btm_launch_item_add&lt;/code&gt;), configuration profiles and Open Directory changes (new users, admin group edits). &lt;code&gt;eslogger --list-events&lt;/code&gt; prints what your macOS version supports.&lt;/p&gt;

&lt;p&gt;A side benefit: &lt;code&gt;sudo&lt;/code&gt;, &lt;code&gt;su&lt;/code&gt; and &lt;code&gt;openssh_login&lt;/code&gt; replaced a &lt;code&gt;log stream&lt;/code&gt; reader that cost about 5% of one core. The daemon now starts &lt;code&gt;log stream&lt;/code&gt; only as a fallback when the helper is down; how the rest of the daemon moved from polling to events is in &lt;a href="https://vuminhhoa.com/en/blog/macos-daemon-bash-to-swift-event-driven" rel="noopener noreferrer"&gt;rewriting MacSentry's daemon from Bash to Swift&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnwzgha3s4gxnrmg60yzp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnwzgha3s4gxnrmg60yzp.png" alt="Pipeline of the Endpoint Security helper: eslogger prints JSON Lines, getline reads them into one reused buffer, an Aho–Corasick prefilter on the raw bytes drops most exec lines, JSONSerialization parses the rest, rules are matched against the executable, the helper skips its own commands and allowlisted ones, writes findings to a spool with an atomic rename, and the daemon sends the alert." width="800" height="1227"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Each step is cheaper than the next, so most events are dropped before anything is parsed or allocated.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Read JSON Lines with getline and skip the parser for most lines
&lt;/h2&gt;

&lt;p&gt;Almost all the volume is &lt;code&gt;exec&lt;/code&gt;. Every program launch becomes a line that carries the full argument list and environment, often around 4 KB, and a development machine launches a lot of programs. Only a tiny fraction of them can match a rule, so the goal is to reject the rest before allocating anything.&lt;/p&gt;

&lt;p&gt;Two changes did most of the work:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Read lines with &lt;a href="https://man.freebsd.org/cgi/man.cgi?query=getline&amp;amp;sektion=3" rel="noopener noreferrer"&gt;&lt;code&gt;getline(3)&lt;/code&gt;&lt;/a&gt;.&lt;/strong&gt; It buffers in user space and reuses one buffer for every line. The obvious Swift approaches allocate or copy per line: &lt;code&gt;FileHandle.availableData&lt;/code&gt; plus removing the consumed prefix from a &lt;code&gt;Data&lt;/code&gt; buffer copies the remainder each time, and &lt;code&gt;readLine()&lt;/code&gt; creates a &lt;code&gt;String&lt;/code&gt; for every line.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Prefilter &lt;code&gt;exec&lt;/code&gt; lines on the raw bytes.&lt;/strong&gt; Each rule declares &lt;em&gt;needles&lt;/em&gt;, strings the raw line must contain for the rule to possibly match. All needles go into one &lt;a href="https://doi.org/10.1145/360825.360855" rel="noopener noreferrer"&gt;Aho–Corasick&lt;/a&gt; automaton, built as a case-insensitive DFA, so a single pass over the line checks all of them at once instead of calling &lt;code&gt;memmem&lt;/code&gt; once per needle. Lines with no needle are dropped without ever reaching &lt;code&gt;JSONSerialization&lt;/code&gt;.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="k"&gt;func&lt;/span&gt; &lt;span class="nf"&gt;execIrrelevant&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="n"&gt;hay&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UnsafeRawBufferPointer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Bool&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="n"&gt;isExec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;execMarker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;withUnsafeBytes&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nf"&gt;memmem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hay&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;baseAddress&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hay&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$0&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;baseAddress&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$0&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="kc"&gt;nil&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;isExec&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;needleMatcher&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;matches&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hay&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One detail is easy to miss: JSON may escape &lt;code&gt;/&lt;/code&gt; as &lt;code&gt;\/&lt;/code&gt;, so a needle like &lt;code&gt;/dev/tcp/&lt;/code&gt; is added in both forms.&lt;/p&gt;

&lt;p&gt;With both changes, replaying 100,000 recorded events through the helper took 0.77 s instead of 8.7 s. The replay mode (&lt;code&gt;macsentry-es --replay &amp;lt; events.jsonl&lt;/code&gt;) needs no root and sends nothing, which made that measurement easy to repeat.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3elkkxseg4fuxvtnslmk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3elkkxseg4fuxvtnslmk.png" alt="Bar chart of the time to replay 100,000 recorded events: 8.7 seconds before, 0.77 seconds with getline and the prefilter." width="800" height="180"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Replaying 100,000 recorded events: about eleven times faster.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Even so, &lt;code&gt;exec&lt;/code&gt; monitoring is the most expensive part of MacSentry, because &lt;code&gt;eslogger&lt;/code&gt; itself has to serialize every launch. On a busy development Mac the helper and &lt;code&gt;eslogger&lt;/code&gt; together use about 2% of one core, so the installer asks whether to enable it and &lt;code&gt;ES_EXEC=0&lt;/code&gt; turns it off.&lt;/p&gt;

&lt;h2&gt;
  
  
  Match rules against the program that runs, not the text
&lt;/h2&gt;

&lt;p&gt;A regular expression over the whole command line cannot tell a command from data that merely mentions it. MacSentry's own early shell version shows the problem: it sent Telegram messages with &lt;code&gt;curl&lt;/code&gt;, so an alert &lt;em&gt;describing&lt;/em&gt; a keychain read put the text &lt;code&gt;security find-generic-password&lt;/code&gt; into &lt;code&gt;curl&lt;/code&gt;'s arguments, where a command-line rule would see it and fire again.&lt;/p&gt;

&lt;p&gt;The fix is to give each rule the set of programs it applies to (from &lt;code&gt;es/Rules.swift&lt;/code&gt;, with the alert title translated):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight swift"&gt;&lt;code&gt;&lt;span class="nf"&gt;rule&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"🔑 Keychain password read"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;alert&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"security"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
     &lt;span class="cp"&gt;#"(^|/)security\s+(dump-keychain|(find-generic-password|find-internet-password)\b.*\s-[wg]\b|export\b)"#)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The keychain rule is only evaluated when the executable is &lt;code&gt;security&lt;/code&gt;. Reverse shell patterns only apply to shells and interpreters (&lt;code&gt;bash&lt;/code&gt;, &lt;code&gt;nc&lt;/code&gt;, &lt;code&gt;socat&lt;/code&gt;, &lt;code&gt;python&lt;/code&gt;, &lt;code&gt;osascript&lt;/code&gt;...). A separate list of &lt;em&gt;data carriers&lt;/em&gt; (&lt;code&gt;curl&lt;/code&gt;, &lt;code&gt;wget&lt;/code&gt;, &lt;code&gt;echo&lt;/code&gt;, &lt;code&gt;grep&lt;/code&gt;, &lt;code&gt;git&lt;/code&gt;...) is never evaluated at all, because their arguments are data, not commands. The same set of programs also provides the default needles for the prefilter above, so both layers agree on what a rule is about.&lt;/p&gt;

&lt;p&gt;Legitimate tools still trip rules. Claude Code, for example, reads its own login token from the keychain with &lt;code&gt;security find-generic-password&lt;/code&gt;. Rather than weakening the rule, &lt;code&gt;/etc/macsentry.allow&lt;/code&gt; holds regular expressions matched against &lt;code&gt;"&amp;lt;command&amp;gt; || &amp;lt;parent chain&amp;gt;"&lt;/code&gt;, so an exception can name both the command and the program that ran it. Allowed matches are logged at most once an hour, since they tend to repeat constantly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Don't alert on your own commands
&lt;/h2&gt;

&lt;p&gt;The MacSentry daemon runs a few commands that the rules would flag, and because it is a separate LaunchDaemon, &lt;code&gt;eslogger&lt;/code&gt;'s process-group suppression does not hide them. Two techniques handle this:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Look at the parents' full command lines.&lt;/strong&gt; For each suspicious &lt;code&gt;exec&lt;/code&gt;, the helper walks the parent chain through &lt;code&gt;libproc&lt;/code&gt; and &lt;code&gt;sysctl(KERN_PROCARGS2)&lt;/code&gt; and skips the event if any ancestor is a MacSentry binary. Process names are not enough here; you need the command line to see &lt;code&gt;/usr/local/libexec/macsentryd&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mark expected events when the parent is already gone.&lt;/strong&gt; To read the screen lock setting the daemon runs &lt;code&gt;sudo -u &amp;lt;user&amp;gt; sysadminctl&lt;/code&gt;, and by the time the &lt;code&gt;sudo&lt;/code&gt; event arrives, the intermediate processes have exited. So the daemon touches a marker file just before the call, and the helper ignores a root-initiated &lt;code&gt;sudo&lt;/code&gt; within 15 seconds of it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Walking from the recorded parent PID, not the process itself, also matters: short-lived processes have often exited before the event is handled.&lt;/p&gt;

&lt;h2&gt;
  
  
  Small operational details that prevent silent failures
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Send &lt;code&gt;eslogger&lt;/code&gt;'s stderr to a file, not a pipe.&lt;/strong&gt; If nobody reads a pipe while the child runs, it eventually fills and &lt;code&gt;eslogger&lt;/code&gt; blocks forever, with no error anywhere. A file also keeps the last error for diagnostics, such as "not permitted" when Full Disk Access is missing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Report liveness even when the machine is idle.&lt;/strong&gt; The helper touches a heartbeat file on events and on a 60-second timer while &lt;code&gt;eslogger&lt;/code&gt; is running, and the daemon alerts if that file goes stale. Without the timer, a quiet machine would look like a dead helper.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hand results to the daemon through a spool with an atomic rename.&lt;/strong&gt; The helper writes &lt;code&gt;name.tmp&lt;/code&gt;, then renames it to &lt;code&gt;name.msg&lt;/code&gt;, so the daemon never reads a half-written message. The helper never holds the Telegram token, and it masks bot tokens and &lt;code&gt;KEY=value&lt;/code&gt; style secrets before writing anything.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Problem&lt;/th&gt;
&lt;th&gt;What MacSentry does&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Endpoint Security needs an Apple-approved entitlement&lt;/td&gt;
&lt;td&gt;Run &lt;code&gt;/usr/bin/eslogger&lt;/code&gt; as a child of a root helper with Full Disk Access&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Output format is not a stable API&lt;/td&gt;
&lt;td&gt;Save a raw sample per event type, read fields tolerantly&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;exec&lt;/code&gt; lines are large and frequent&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;getline&lt;/code&gt; plus a one-pass Aho–Corasick prefilter on raw bytes (8.7 s → 0.77 s per 100k events)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Rules matching text inside data&lt;/td&gt;
&lt;td&gt;Rules scoped to the executable; data carriers never evaluated&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Alerts on its own commands&lt;/td&gt;
&lt;td&gt;Check parents' command lines; marker file for expected &lt;code&gt;sudo&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Silent hangs and silent death&lt;/td&gt;
&lt;td&gt;stderr to a file, liveness file on a timer, atomic spool&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;code&gt;eslogger&lt;/code&gt; is not a replacement for a signed system extension: it cannot block anything and its format can change under you. For a personal tool that only needs to &lt;em&gt;see&lt;/em&gt; what happens on one Mac, it gets surprisingly close.&lt;/p&gt;

&lt;p&gt;If you've built a monitor on &lt;code&gt;eslogger&lt;/code&gt; or a native Endpoint Security client, I'd love to compare notes. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>macos</category>
      <category>endpointsecurity</category>
      <category>swift</category>
      <category>ahocorasick</category>
    </item>
    <item>
      <title>Building an end-to-end encrypted chat app with libsodium</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Tue, 24 Nov 2026 14:00:15 +0000</pubDate>
      <link>https://dev.to/jamesvu/building-an-end-to-end-encrypted-chat-app-with-libsodium-3fnh</link>
      <guid>https://dev.to/jamesvu/building-an-end-to-end-encrypted-chat-app-with-libsodium-3fnh</guid>
      <description>&lt;p&gt;End-to-end encryption (E2EE) sounds simple: encrypt on the sender's device, decrypt on the recipient's, and the server in the middle only sees ciphertext. When building &lt;a href="https://chat.vuminhhoa.com/" rel="noopener noreferrer"&gt;E2EE Chat&lt;/a&gt;, the harder part wasn't the algorithms but one question: &lt;strong&gt;what if the server itself cheats?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This post walks through the app's key design, which &lt;a href="https://doc.libsodium.org/" rel="noopener noreferrer"&gt;libsodium&lt;/a&gt; primitive does which job, and the general limits every design of this kind has to accept. If you're learning about E2EE, I hope it helps you see how the pieces fit together.&lt;/p&gt;

&lt;h2&gt;
  
  
  System overview
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Part&lt;/th&gt;
&lt;th&gt;Stack&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Web app (PWA)&lt;/td&gt;
&lt;td&gt;React 19, TanStack Router and Query, Tailwind CSS 4, libsodium&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;API&lt;/td&gt;
&lt;td&gt;Fastify 5, Drizzle ORM on PostgreSQL, Centrifugo, Web Push&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Files&lt;/td&gt;
&lt;td&gt;S3-compatible object storage&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Accounts&lt;/td&gt;
&lt;td&gt;Keycloak, OpenID Connect with PKCE&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Reads and writes go through REST, and every change (new messages, typing, read markers…) is pushed in real time over &lt;a href="https://centrifugal.dev/" rel="noopener noreferrer"&gt;Centrifugo&lt;/a&gt; (Socket.IO until November 2026). The server creates a user on their first API call, after &lt;a href="https://vuminhhoa.com/en/blog/self-hosted-keycloak-multiple-apps" rel="noopener noreferrer"&gt;verifying the Keycloak access token&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The core property: the server only ever sees &lt;strong&gt;ciphertext&lt;/strong&gt;. Messages, reactions, attachment contents, and even attachment &lt;em&gt;metadata&lt;/em&gt; (name, type, size, duration) are encrypted in the browser.&lt;/p&gt;

&lt;h2&gt;
  
  
  The keys
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Key&lt;/th&gt;
&lt;th&gt;Algorithm&lt;/th&gt;
&lt;th&gt;Stored&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Identity key pair&lt;/td&gt;
&lt;td&gt;X25519 (&lt;code&gt;crypto_box_keypair&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;Public key on the server; secret key only in IndexedDB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Signing key pair&lt;/td&gt;
&lt;td&gt;Ed25519, derived from the X25519 secret key&lt;/td&gt;
&lt;td&gt;Published with the identity key; never stored on its own&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Keyring backup&lt;/td&gt;
&lt;td&gt;Argon2id (&lt;code&gt;crypto_pwhash&lt;/code&gt;) + secretbox, passphrase of 12+ characters&lt;/td&gt;
&lt;td&gt;On the server, readable only by its owner&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Chat key&lt;/td&gt;
&lt;td&gt;32 random bytes, sealed to each member (&lt;code&gt;crypto_box_seal&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;On the server, one copy per member&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Messages and files&lt;/td&gt;
&lt;td&gt;secretbox (XSalsa20-Poly1305) with a &lt;code&gt;crypto_kdf&lt;/code&gt; subkey&lt;/td&gt;
&lt;td&gt;On the message&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  A key per conversation
&lt;/h3&gt;

&lt;p&gt;Each conversation has a 32-byte &lt;strong&gt;symmetric key&lt;/strong&gt;. Whoever creates it &lt;em&gt;seals&lt;/em&gt; it to every member's X25519 public key (&lt;code&gt;crypto_box_seal&lt;/code&gt;, a "sealed box": encrypted to the recipient's public key, openable only with the matching secret key) and uploads the sealed copies. The server holds them but can't open any.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fghnthdw42k57ymuuw6fk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fghnthdw42k57ymuuw6fk.png" alt="Diagram: the creator’s browser makes chat key version N, seals it with crypto_box_seal to the X25519 public key of Alice, Bob and Carol; the server stores the three sealed copies but cannot open any; each member opens their copy with their own secret key; messages and files are encrypted with secretbox using a subkey derived from the chat key." width="800" height="817"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The server holds every copy of the chat key and can read none of them.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Keys are &lt;strong&gt;versioned&lt;/strong&gt;. When group membership changes, the key rotates: the server only accepts a membership change &lt;em&gt;together with&lt;/em&gt; a new key version. Members who leave don't get the next key, and the next person to send a message creates it. Chat keys are append-only, so old versions stay and old history stays readable.&lt;/p&gt;

&lt;h3&gt;
  
  
  Losing a device
&lt;/h3&gt;

&lt;p&gt;The secret key lives only in the browser's IndexedDB. To use the app on another device, the user sets a &lt;strong&gt;passphrase&lt;/strong&gt;. The keyring is encrypted with a key derived from it through Argon2id before it's stored on the server. The passphrase must be at least 12 characters and not on a list of guessable ones, because Argon2id only slows guessing down; it can't save a weak password.&lt;/p&gt;

&lt;h2&gt;
  
  
  The hard part: not trusting the server
&lt;/h2&gt;

&lt;p&gt;Encryption stops the server from &lt;em&gt;reading&lt;/em&gt;. But it still stores and relays everything, so it could:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;make up a chat key itself (and therefore know it),&lt;/li&gt;
&lt;li&gt;quietly add a member to a group,&lt;/li&gt;
&lt;li&gt;swap someone's public key for its own,&lt;/li&gt;
&lt;li&gt;hold back messages, reorder them, or replay old ones.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;No design can prevent all of this, because the server still stores and relays everything. The realistic goal is to make it &lt;strong&gt;detectable&lt;/strong&gt; on the user's side.&lt;/p&gt;

&lt;h3&gt;
  
  
  Everything is signed
&lt;/h3&gt;

&lt;p&gt;Each user has an Ed25519 signing key, derived from their X25519 secret key (keyed BLAKE2b, then &lt;code&gt;crypto_sign_seed_keypair&lt;/code&gt;) and published alongside the identity key. Because it's derived, the signing key never needs storing or backing up on its own: recovering the X25519 secret key recovers it too. Everything a member produces is signed:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Chat key versions&lt;/strong&gt;, over the chat, version, creator and recipients. A key the server made up isn't used to send. A member the server added on its own gets no key.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Messages and edits&lt;/strong&gt;, over the sender, key version, content, reply target and attachment. A message that doesn't check out is marked "Unverified".&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Unsends&lt;/strong&gt;, &lt;strong&gt;reactions&lt;/strong&gt;, &lt;strong&gt;chat previews&lt;/strong&gt; and &lt;strong&gt;notifications&lt;/strong&gt; are all checked. A notification never shows content that doesn't verify.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Message chains
&lt;/h3&gt;

&lt;p&gt;A signature proves &lt;em&gt;who&lt;/em&gt; wrote something, not that the server delivered &lt;em&gt;everything&lt;/em&gt;. So each member's messages in a chat form a &lt;strong&gt;signed chain&lt;/strong&gt; (the same idea as a &lt;a href="https://vuminhhoa.com/en/blog/tamper-evident-audit-log-postgresql" rel="noopener noreferrer"&gt;tamper-evident audit log&lt;/a&gt;): numbered 1, 2, 3…, each naming the newest message its sender had seen. From that, the app can detect:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;messages held back (a gap in the numbers, or a message that refers to one this device never got),&lt;/li&gt;
&lt;li&gt;messages shown out of order,&lt;/li&gt;
&lt;li&gt;an old message replayed under a new id, or a version older than one already seen.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each device keeps a &lt;strong&gt;ledger&lt;/strong&gt; in IndexedDB of what it has seen and what the user trusts (contacts' keys, their own earlier keys). The ledger is backed up for the user's other devices, encrypted with a key only their keyring can derive.&lt;/p&gt;

&lt;h3&gt;
  
  
  When someone's key changes
&lt;/h3&gt;

&lt;p&gt;The app trusts the first key it sees for a contact, an approach usually called TOFU (trust on first use), as in SSH. After that, if someone's key changes, the app &lt;strong&gt;stops encrypting for them&lt;/strong&gt; until the user accepts the new key. For stronger assurance, two people compare &lt;strong&gt;safety numbers&lt;/strong&gt; outside the chat: by scanning each other's QR code in person, reading them out, or sending one through another app. A mismatch is never marked as verified.&lt;/p&gt;

&lt;h2&gt;
  
  
  General limits of this approach
&lt;/h2&gt;

&lt;p&gt;Knowing a technique's limits matters as much as knowing how it works. Any design that detects tampering with signatures and message chains, like the one above, shares these:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Detection depends on what comes later.&lt;/strong&gt; A withheld message only shows up when another message refers to it. That's why protocols such as MLS add agreement on the group's state.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Each device only remembers what it has seen.&lt;/strong&gt; A new device has to trust what it's given until more evidence arrives.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;E2EE protects content, not metadata.&lt;/strong&gt; The server still knows who talks to whom, and when. Reducing metadata takes quite different techniques, such as Signal's sealed sender.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Small details that matter
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Web Push&lt;/strong&gt; carries no message content, because the server has none to send.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Privacy settings&lt;/strong&gt; (hide online status, no read receipts, no typing indicators) are enforced by the server and apply both ways, like WhatsApp: turn read receipts off and you don't see other people's either.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Upload limits&lt;/strong&gt;: files not attached to a message count against a 200 MB per-user quota and are deleted after 24 hours.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deleting an account&lt;/strong&gt; requires a sign-in within the last 5 minutes. Public keys are kept, so what that person signed still verifies.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Testing&lt;/strong&gt;: the server logic is tested against an in-memory PostgreSQL (PGlite), and end-to-end flows with Playwright.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  If you're building your own
&lt;/h2&gt;

&lt;p&gt;Designing it yourself is a good way to understand each problem in E2EE. But for a product with real users, start from an audited protocol: the &lt;a href="https://signal.org/docs/" rel="noopener noreferrer"&gt;Signal Protocol&lt;/a&gt; for one-to-one chat, or &lt;a href="https://www.rfc-editor.org/rfc/rfc9420" rel="noopener noreferrer"&gt;MLS (RFC 9420)&lt;/a&gt; for groups. In cryptography, the problems worth worrying about are usually the ones you haven't thought of, and those protocols have had many people thinking about them.&lt;/p&gt;

&lt;p&gt;You can try the app at &lt;a href="https://chat.vuminhhoa.com/" rel="noopener noreferrer"&gt;chat.vuminhhoa.com&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The server should only ever see ciphertext: messages, reactions, attachment contents and attachment metadata are all encrypted in the browser.&lt;/li&gt;
&lt;li&gt;Each conversation has a versioned 32-byte key, sealed to every member with &lt;code&gt;crypto_box_seal&lt;/code&gt;, and the key rotates whenever membership changes.&lt;/li&gt;
&lt;li&gt;A keyring backup encrypted with an Argon2id-derived key lets users move to a new device, but Argon2id only slows guessing, so the passphrase must be long and not on a guessable list.&lt;/li&gt;
&lt;li&gt;Encryption stops the server from reading, not from cheating. The realistic goal is to make cheating detectable on the user's side.&lt;/li&gt;
&lt;li&gt;Sign everything with an Ed25519 key derived from the X25519 secret key, and chain each member's messages so withheld, reordered or replayed messages show up.&lt;/li&gt;
&lt;li&gt;Trust a contact's first key, stop encrypting for them when it changes, and compare safety numbers outside the chat for stronger assurance.&lt;/li&gt;
&lt;li&gt;Detection depends on later messages, a new device has to trust what it's given, and metadata stays visible. For a product with real users, start from the Signal Protocol or MLS.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you've designed end-to-end encryption for an app of your own, I'd love to compare notes. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>cryptography</category>
      <category>libsodium</category>
      <category>react</category>
      <category>fastify</category>
    </item>
    <item>
      <title>Vietnamese lunar calendar in JavaScript: why 5 test dates weren’t enough</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Thu, 19 Nov 2026 21:44:21 +0000</pubDate>
      <link>https://dev.to/jamesvu/vietnamese-lunar-calendar-in-javascript-why-5-test-dates-werent-enough-40kj</link>
      <guid>https://dev.to/jamesvu/vietnamese-lunar-calendar-in-javascript-why-5-test-dates-werent-enough-40kj</guid>
      <description>&lt;p&gt;Showing the lunar date in an app sounds simple: find a library, call a function, display "9th day of the 7th month". When adding the Vietnamese lunar calendar to &lt;a href="https://plan.vuminhhoa.com/" rel="noopener noreferrer"&gt;Day planner&lt;/a&gt;, a personal time-management app, the most interesting part turned out to be choosing the library, because of something easy to miss: &lt;strong&gt;a library can be right on every date you test and still be wrong for Vietnam.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Vietnamese lunar calendar isn't the Chinese one
&lt;/h2&gt;

&lt;p&gt;The lunisolar calendar is astronomical: the first day of a month is the day of the new moon, and leap months are inserted based on the solar terms. Both depend on &lt;strong&gt;when&lt;/strong&gt; an astronomical event happens, and therefore on the &lt;strong&gt;time zone&lt;/strong&gt; used to compute it.&lt;/p&gt;

&lt;p&gt;Vietnam computes its lunar calendar in Hanoi time (UTC+7), China in Beijing time (UTC+8). When a new moon falls between 23:00 and midnight in Hanoi, it's already the next day in Beijing, and the two countries start the month on different days. The best-known example: for the Lunar New Year of 2007, Vietnam celebrated Tết on February 17, China on February 18.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7dku1r12436au9zzyrqj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7dku1r12436au9zzyrqj.png" alt="Timeline of one new moon that happens between 23:00 and midnight Hanoi time: on the Hanoi clock (UTC+7) it falls on day N, while on the Beijing clock (UTC+8) it is already after midnight, on day N+1, so the two calendars start the month on different days." width="800" height="472"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The same instant falls on different dates in Hanoi and Beijing, and the month starts on the date of the new moon.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Most of the time the two calendars agree. That's exactly what makes the differences hard to spot.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing 5 dates: all correct
&lt;/h2&gt;

&lt;p&gt;I looked at the popular JavaScript libraries:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Library&lt;/th&gt;
&lt;th&gt;Time zone&lt;/th&gt;
&lt;th&gt;Has&lt;/th&gt;
&lt;th&gt;Lacks&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;vietnamese-date&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;UTC+7&lt;/td&gt;
&lt;td&gt;Lunar date, stems and branches, auspicious hours, TypeScript&lt;/td&gt;
&lt;td&gt;Auspicious days, solar terms, holidays&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;@nghiavuive/lunar_date_vi&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;—&lt;/td&gt;
&lt;td&gt;Stems and branches, solar terms, auspicious hours&lt;/td&gt;
&lt;td&gt;Auspicious days, holidays&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;lunar-javascript&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;UTC+8&lt;/td&gt;
&lt;td&gt;Nearly everything: auspicious days and hours, the 12 day officers, do's and don'ts, solar terms, festivals&lt;/td&gt;
&lt;td&gt;Output in Chinese, no types, ~109 KB gzipped&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;code&gt;lunar-javascript&lt;/code&gt; has every feature, so I tested it on 5 dates: Tết 2025, Tết 2026, the first full moon of 2026, the Mid-Autumn Festival, and the leap second month of 2023. All 5 matched the Vietnamese calendar. The plan was to use it, with a table translating its Chinese output into Sino-Vietnamese.&lt;/p&gt;

&lt;h2&gt;
  
  
  Scanning 40,542 days: 3.48% wrong
&lt;/h2&gt;

&lt;p&gt;Five lucky matches don't prove much, so I wrote a script comparing the two libraries on &lt;strong&gt;every day from 1990 to 2100&lt;/strong&gt;, 40,542 days in all:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Comparison&lt;/th&gt;
&lt;th&gt;Result&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Lunar day/month: &lt;code&gt;lunar-javascript&lt;/code&gt; (UTC+8) vs &lt;code&gt;vietnamese-date&lt;/code&gt; (UTC+7)&lt;/td&gt;
&lt;td&gt;
&lt;strong&gt;3.48% differ&lt;/strong&gt;, about 12 days a year on average; some years even disagree on the leap month (1995, for example)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Day stem-branch&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;No differences&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Auspicious/inauspicious days&lt;/td&gt;
&lt;td&gt;
&lt;strong&gt;16% differ&lt;/strong&gt;, even on days where the lunar month agrees&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Three results, each with its own cause:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lunar dates differ&lt;/strong&gt; because of the time zone, as explained above.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The day's stem-branch never differs&lt;/strong&gt;, because it's simply a 60-day cycle counted continuously from the Julian day number, independent of astronomy and time zones.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Auspicious days differ by 16%&lt;/strong&gt; for an entirely different reason: &lt;code&gt;lunar-javascript&lt;/code&gt; assigns the 12 day officers by &lt;strong&gt;solar term&lt;/strong&gt; (the Chinese method), while common Vietnamese calendars assign them by &lt;strong&gt;lunar month&lt;/strong&gt;, following the method in Phan Kế Bính's book on Vietnamese customs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first 5 dates caught none of this, because festival dates rarely land on the boundary days.&lt;/p&gt;

&lt;h2&gt;
  
  
  The fix: a library for the astronomy, data tables for the culture
&lt;/h2&gt;

&lt;p&gt;The final design splits the work in two:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Astronomy comes from a library; don't write it yourself.&lt;/strong&gt; &lt;code&gt;vietnamese-date&lt;/code&gt; (based on Hồ Ngọc Đức's algorithm, computed in UTC+7, about 4 KB gzipped) handles the lunar day, month and year, leap months, stems and branches, and auspicious hours. Astronomical algorithms are easy to get subtly wrong, and there's no reason to rewrite one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Culture comes from small, verified data tables.&lt;/strong&gt; No Vietnamese JavaScript library has auspicious days or lunar holidays, so I added them as fixed data, not algorithms:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The 12 day officers&lt;/strong&gt;: Thanh Long, Minh Đường, Thiên Hình, Chu Tước, Kim Quỹ, Thiên Đức, Bạch Hổ, Ngọc Đường, Thiên Lao, Huyền Vũ, Tư Mệnh, Câu Trần. Six are auspicious: Thanh Long, Minh Đường, Kim Quỹ, Thiên Đức, Ngọc Đường, Tư Mệnh.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Where Thanh Long starts, by lunar month&lt;/strong&gt;: months 1 and 7 start on a Tý day, 2 and 8 on Dần, 3 and 9 on Thìn, 4 and 10 on Ngọ, 5 and 11 on Thân, 6 and 12 on Tuất.&lt;/li&gt;
&lt;li&gt;From there: &lt;code&gt;officer = (day's branch − month's starting branch) mod 12&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Simplified from &lt;code&gt;lunar.ts&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;godIndex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dayBranch&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;startBranch&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lunarMonth&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;12&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;isAuspicious&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;AUSPICIOUS&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;godIndex&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The extra &lt;code&gt;+ 12&lt;/code&gt; and second &lt;code&gt;% 12&lt;/code&gt; are there because in JavaScript &lt;code&gt;-3 % 12&lt;/code&gt; is &lt;code&gt;-3&lt;/code&gt;, not &lt;code&gt;9&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lunar holidays&lt;/strong&gt; are a lookup by &lt;code&gt;month × 100 + day&lt;/code&gt;: Tết (1/1), the first full moon (15/1), the Cold Food Festival (3/3), the Hùng Kings' Commemoration (10/3), Buddha's Birthday (15/4), the Double Fifth (5/5), Vu Lan (15/7), Mid-Autumn (15/8) and the Kitchen Gods' day (23/12).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Solar terms&lt;/strong&gt; are the only place with a formula: compute the sun's longitude at midnight Vietnam time for that day; every 15° is one term.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Do's and don'ts (activities considered favorable or unfavorable on a given day) I &lt;strong&gt;left out&lt;/strong&gt;. Schools of thought differ, there's no reliable data source for the Vietnamese tradition, and I didn't want to make up a list that merely looks right.&lt;/p&gt;

&lt;h2&gt;
  
  
  A few details when wiring it into the app
&lt;/h2&gt;

&lt;p&gt;Day planner keeps its data in the browser, and the lunar calendar is computed on the device too, which is why bundle size mattered when choosing the library. (How the app stores and searches its activity library in IndexedDB is in &lt;a href="https://vuminhhoa.com/en/blog/large-tree-indexeddb-rxdb" rel="noopener noreferrer"&gt;a large tree in IndexedDB with RxDB&lt;/a&gt;.) Three details came up when wiring it in:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Avoid off-by-one days from the device's time zone.&lt;/strong&gt; The app stores days as local &lt;code&gt;YYYY-MM-DD&lt;/code&gt; strings. To convert, I build a &lt;code&gt;Date&lt;/code&gt; at &lt;strong&gt;noon&lt;/strong&gt; of that day rather than midnight. Midnight is the danger zone: any time zone shift pushes it into the previous day.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Memoize by day.&lt;/strong&gt; The week view asks for 7 days, again on every re-render. A &lt;code&gt;Map&lt;/code&gt; keyed by the day string is enough.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Regression tests&lt;/strong&gt; for the verified dates, for the 12 officers' defining rule (a Tý day in the first month must be Thanh Long), and for results not depending on the time of day. If a library upgrade ever shifts the calendar, the tests go red.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What this setup doesn't cover
&lt;/h2&gt;

&lt;p&gt;The calendar now shows the right lunar dates for Vietnam, but a few things are outside what it does:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Do's and don'ts aren't there at all&lt;/strong&gt;, for the reasons above. Anyone who needs them has to pick a school of thought and a source first.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Auspicious days follow one convention&lt;/strong&gt;, the lunar-month method. Someone who follows the solar-term method will disagree on about 16% of days, and each side is consistent with its own rules.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The holidays are a fixed list&lt;/strong&gt; of nine lunar dates. Anything else has to be added to the table by hand.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The scan compares two libraries&lt;/strong&gt;, so it shows where they disagree and why, not which one is right on each day. My trust in &lt;code&gt;vietnamese-date&lt;/code&gt; rests on Hồ Ngọc Đức's algorithm computed in UTC+7 and on the dates I checked against the Vietnamese calendar, and the scan only covers 1990 to 2100.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;The lesson isn't really about lunar calendars. It's that &lt;strong&gt;"right on the cases I tried" is far from "right"&lt;/strong&gt;, especially when the errors only show up in rare edge cases.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Vietnam computes its lunar calendar in UTC+7 and China in UTC+8, so a library built on the Chinese calendar gives a different lunar date on 3.48% of days from 1990 to 2100, about 12 days a year.&lt;/li&gt;
&lt;li&gt;Five festival dates all matched, because they rarely land on boundary days. A script comparing all 40,542 days found the differences in seconds.&lt;/li&gt;
&lt;li&gt;Auspicious days can differ even when the lunar month agrees: Vietnamese calendars assign the 12 day officers by lunar month, the Chinese method by solar term.&lt;/li&gt;
&lt;li&gt;Take the astronomy from a library (&lt;code&gt;vietnamese-date&lt;/code&gt;) and the culture from small, verified data tables (day officers, holidays).&lt;/li&gt;
&lt;li&gt;Build a &lt;code&gt;Date&lt;/code&gt; at noon rather than midnight so a time zone shift can't push it into the previous day, and pin the verified dates in regression tests.&lt;/li&gt;
&lt;li&gt;Leave out what has no reliable source, such as do's and don'ts, rather than inventing data that only looks right.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you're working with the Vietnamese lunar calendar too, &lt;a href="https://web.archive.org/web/20210224052208/https://www.informatik.uni-leipzig.de/~duc/amlich/calrules_en.html" rel="noopener noreferrer"&gt;Hồ Ngọc Đức's article&lt;/a&gt; (an Internet Archive copy, since the original page is no longer online) on the algorithm is the foundation of most Vietnamese lunar libraries today. And if you'd like to talk it through, my email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>typescript</category>
      <category>mlch</category>
      <category>testing</category>
    </item>
    <item>
      <title>Parsing money the way Vietnamese people type it: 2,5tr, 500k and 1tr+500k</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Wed, 18 Nov 2026 21:32:38 +0000</pubDate>
      <link>https://dev.to/jamesvu/parsing-money-the-way-vietnamese-people-type-it-25tr-500k-and-1tr500k-1d46</link>
      <guid>https://dev.to/jamesvu/parsing-money-the-way-vietnamese-people-type-it-25tr-500k-and-1tr500k-1d46</guid>
      <description>&lt;p&gt;In Vietnam nobody types "2500000" for an electricity bill. People write "2,5tr", "2.5 triệu", "500k", "0,1 tỷ" or "2.500.000", and in a spreadsheet they happily type "=250k*3". &lt;a href="https://finance.vuminhhoa.com/" rel="noopener noreferrer"&gt;Financial Plan&lt;/a&gt;, my budgeting app, is almost entirely amount fields, so it had to read all of these. This post covers the small parser behind them, the dot that means two different things, sums typed like in Excel, keeping the caret in place while formatting, and the missing + key on phone keyboards.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why a number input can't hold Vietnamese amounts
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;input type="number"&amp;gt;&lt;/code&gt; rejects letters, so "2,5tr" is out, and it reads separators by the browser's rules, not the user's. Vietnamese also uses the opposite marks to English: &lt;code&gt;vi-VN&lt;/code&gt; groups thousands with a dot and uses a comma for decimals, so "2.500.000" is two million five hundred thousand. Yet the same people will write "2.5tr" with a dot as the decimal point, because that is how phone keyboards and English-language apps taught them.&lt;/p&gt;

&lt;p&gt;So every amount in the app is a text field with &lt;code&gt;inputmode="decimal"&lt;/code&gt;, which asks phones for a numeric keypad, and a parser that turns the text into a number when the field is saved.&lt;/p&gt;

&lt;h2&gt;
  
  
  One figure: a number plus an optional unit
&lt;/h2&gt;

&lt;p&gt;A single figure is digits and separators, optionally followed by a unit. The units are the ones people actually type: &lt;code&gt;k&lt;/code&gt;, &lt;code&gt;n&lt;/code&gt;, &lt;code&gt;nghìn&lt;/code&gt;, &lt;code&gt;ngàn&lt;/code&gt; for thousands; &lt;code&gt;tr&lt;/code&gt;, &lt;code&gt;triệu&lt;/code&gt;, &lt;code&gt;trieu&lt;/code&gt;, &lt;code&gt;m&lt;/code&gt; for millions; &lt;code&gt;tỷ&lt;/code&gt;, &lt;code&gt;tỉ&lt;/code&gt;, &lt;code&gt;ty&lt;/code&gt;, &lt;code&gt;b&lt;/code&gt; for billions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;match&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;/^&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;\&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;ngh&lt;/span&gt;ì&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;ng&lt;/span&gt;à&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;tr&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;tri&lt;/span&gt;ệ&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;trieu&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;ỷ&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;ỉ&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;ty&lt;/span&gt;&lt;span class="o"&gt;|&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;$&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before matching, the input is lowercased, spaces are removed, and so are the currency's code, symbol and common spellings (&lt;code&gt;VND&lt;/code&gt;, &lt;code&gt;₫&lt;/code&gt;, &lt;code&gt;vnđ&lt;/code&gt;, &lt;code&gt;đ&lt;/code&gt;), plus a leading &lt;code&gt;=&lt;/code&gt;. "100.000đ", "100.000 VND" and "100000" all reach the parser as the same string.&lt;/p&gt;

&lt;p&gt;The unit decides what the separators mean:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;With a unit, the separator is a decimal point.&lt;/strong&gt; "2,5tr" and "2.5tr" are both 2,500,000; the comma is replaced by a dot and the figure is multiplied by the unit.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Without a unit, in a currency with no decimals, every dot and comma is grouping.&lt;/strong&gt; "2.500.000", "2,500,000" and "2500000" are the same number. The Vietnamese đồng has no subunit in use, so a bare figure is always whole.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;In a currency with decimals,&lt;/strong&gt; the currency's own locale decides: its grouping mark is dropped and its decimal mark becomes the point. "$2,500.50" and "2.500,50 €" each read correctly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The result is rounded to the currency's decimal places, so a sum like "100k/3" saves as 33,333 đ, not 33,333.333.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwamdcsrzoejfusscy1qw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwamdcsrzoejfusscy1qw.png" alt="Decision flow for one typed figure: clean up the input, then if there is a unit (k, tr, triệu, tỷ, m, b) the comma or dot is a decimal point and the figure is multiplied by the unit; otherwise, if the currency has decimals, its own locale decides both marks; otherwise every dot and comma is grouping." width="800" height="683"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The unit decides what a separator means: with a unit it is a decimal point, without one, in đồng, it only groups digits.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The dot that means two things
&lt;/h2&gt;

&lt;p&gt;Formatting while typing is where the ambiguity bites. Showing "2.500.000" as the user types "2500000" is helpful; turning "2.5" into "25" because the dot looked like a grouping mark is not.&lt;/p&gt;

&lt;p&gt;The rule the app settled on: only reformat text that is unambiguously a plain whole figure, meaning digits only, or digits in groups of three separated by dots.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;PLAIN&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;/^-?&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;\&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="o"&gt;+|&lt;/span&gt;\&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;\&lt;span class="p"&gt;.&lt;/span&gt;\&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;$&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;"2500000" and "2.500.000" match and get grouped. "2.5tr", "0,1 tỷ" and "14.31" don't, so they are left exactly as typed and only converted to the full figure when the field loses focus. One exception keeps editing pleasant: if the previous value was a figure the formatter produced, deleting a digit from "2.500.000" leaves "2.50.000", which no longer matches the pattern but should still be regrouped.&lt;/p&gt;

&lt;p&gt;What this does not solve is a bare decimal in đồng. With no unit every dot is grouping, so "2.5" saves as 25 đ and "14.31" as 1,431 đ. The parser can't tell a slip from a real figure, so whoever means two and a half million has to type the unit.&lt;/p&gt;

&lt;h2&gt;
  
  
  Keeping the caret where it was
&lt;/h2&gt;

&lt;p&gt;Reformatting a field moves its text around, and a naïve update sends the caret to the end, which makes fixing a digit in the middle impossible. The fix is to count digits rather than characters: before formatting, count how many digits sit before the caret; after formatting, walk the new string and place the caret after the same number of digits. Inserted dots don't count, so the caret stays after the digit the user just typed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sums, as in a spreadsheet
&lt;/h2&gt;

&lt;p&gt;People budget with arithmetic: "1tr+500k" for two payments, "=250k*3" for three of something, "(3tr+2tr)/2" for an average. Any amount field accepts this.&lt;/p&gt;

&lt;p&gt;The input is split on operators, including the ones phones and Excel users type: &lt;code&gt;×&lt;/code&gt; and &lt;code&gt;x&lt;/code&gt; for multiplication, &lt;code&gt;÷&lt;/code&gt; for division, and &lt;code&gt;−&lt;/code&gt; (the real minus sign) as well as &lt;code&gt;-&lt;/code&gt;. Then a small recursive-descent parser evaluates it with the usual precedence:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;sum&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;product&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="s2"&gt;"+"&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="s2"&gt;"-"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="s2"&gt;"+"&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nf"&gt;product&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nf"&gt;product&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;product&lt;/code&gt; handles &lt;code&gt;*&lt;/code&gt; and &lt;code&gt;/&lt;/code&gt; the same way, and &lt;code&gt;factor&lt;/code&gt; handles unary minus, brackets and single figures, each parsed with the rules above, so "1,5tr*2" mixes units and arithmetic. Anything that doesn't fully parse returns &lt;code&gt;NaN&lt;/code&gt;: tokens left over, an unclosed bracket, or a result that isn't finite, such as a division by zero. The field then keeps its previous value and a message shows what it couldn't read, with examples of what it can, instead of saving a wrong number.&lt;/p&gt;

&lt;p&gt;Two details make it usable:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;A leading minus is a figure, not a sum.&lt;/strong&gt; "-500k" is a negative amount; "1tr-500k" is a sum. The check strips one leading minus before looking for operators.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The result shows under the field while typing&lt;/strong&gt;, and what gets saved is the figure, not the expression. Reopening the field shows "1.500.000", which is what the rest of the app works with.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Phones have no + key on the number pad
&lt;/h2&gt;

&lt;p&gt;On iOS, &lt;code&gt;inputmode="decimal"&lt;/code&gt; brings up a keypad of digits and a decimal separator, with no plus or minus at all. So on touch devices, detected with &lt;code&gt;matchMedia("(pointer: coarse)")&lt;/code&gt;, a focused amount field shows its own row of &lt;code&gt;+ − × ÷&lt;/code&gt; keys.&lt;/p&gt;

&lt;p&gt;Those keys have to type into a React-controlled input as if the user had pressed them. Setting &lt;code&gt;input.value&lt;/code&gt; directly doesn't trigger React's &lt;code&gt;onChange&lt;/code&gt;, so the code goes through the native setter and dispatches an &lt;code&gt;input&lt;/code&gt; event:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="nb"&gt;Object&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getOwnPropertyDescriptor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HTMLInputElement&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prototype&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"value"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;set&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;el&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;el&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dispatchEvent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Event&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"input"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;bubbles&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nf"&gt;requestAnimationFrame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;el&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setSelectionRange&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;caret&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;caret&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The caret is restored on the next frame, after React has re-rendered the field.&lt;/p&gt;

&lt;p&gt;These fields hit one more iOS quirk: the page zooms into any field with text under 16 px. That fix sits with the other iPhone details in &lt;a href="https://vuminhhoa.com/en/blog/installed-pwa-iphone-updates-deploys" rel="noopener noreferrer"&gt;keeping an installed PWA usable on iPhone across updates and deploys&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Displaying amounts: let Intl decide
&lt;/h2&gt;

&lt;p&gt;Output uses &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat" rel="noopener noreferrer"&gt;&lt;code&gt;Intl.NumberFormat&lt;/code&gt;&lt;/a&gt; rather than hand-written rules. The app asks &lt;code&gt;formatToParts&lt;/code&gt; how the currency's home locale writes 1234.5, and reads off the symbol, which side it goes on, whether there's a space, the grouping and decimal marks and the number of decimals. That gives "2.500.000 ₫", "$2,500.50" and "2.500,50 €" from the same code; supporting another currency is one line naming its locale. Short forms follow the interface language: "2,5 tr" in Vietnamese and "2.5M" in English.&lt;/p&gt;

&lt;p&gt;Negative amounts use the real minus sign "−" rather than a hyphen, which lines up with "+" and reads correctly in screen readers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tests pin down what people type
&lt;/h2&gt;

&lt;p&gt;The parser is easy to break with a well-meant change, so its tests are a table of real inputs:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Typed&lt;/th&gt;
&lt;th&gt;Read as&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;5.500.000&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;5,500,000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;5.5tr&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;5,500,000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;5,5 triệu&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;5,500,000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;500k&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;500,000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;0,1 tỷ&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;100,000,000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-2tr&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;−2,000,000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;=250k*3&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;750,000&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;abc&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;not a number&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;empty&lt;/td&gt;
&lt;td&gt;no value&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Problem&lt;/th&gt;
&lt;th&gt;What the app does&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Units and Vietnamese separators&lt;/td&gt;
&lt;td&gt;Text field with &lt;code&gt;inputmode="decimal"&lt;/code&gt;; a unit makes the separator a decimal point, no unit makes it grouping&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Formatting while typing&lt;/td&gt;
&lt;td&gt;Only plain whole figures are regrouped; anything else waits for blur&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Caret jumping to the end&lt;/td&gt;
&lt;td&gt;Place it after the same number of digits&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Sums like "1tr+500k"&lt;/td&gt;
&lt;td&gt;Tokenizer plus a recursive-descent parser; result shown live, figure saved&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;No + key on phone keypads&lt;/td&gt;
&lt;td&gt;A row of &lt;code&gt;+ − × ÷&lt;/code&gt; keys on touch devices, typed through the native value setter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Several currencies&lt;/td&gt;
&lt;td&gt;Symbol, side, marks and decimals read from &lt;code&gt;Intl.NumberFormat&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;None of this is large, a few hundred lines with the tests, but it is the part of a budgeting app that users touch most. An amount field that understands "1tr+500k" is one fewer reason to keep a calculator open next to it.&lt;/p&gt;

&lt;p&gt;If you've built an amount field that reads "2,5tr" or "500k" in your own way, I'd love to compare notes. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>parsing</category>
      <category>intlnumberformat</category>
      <category>forms</category>
    </item>
    <item>
      <title>An installed PWA on iPhone: safe updates, deploys and iOS details</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Tue, 17 Nov 2026 21:53:12 +0000</pubDate>
      <link>https://dev.to/jamesvu/an-installed-pwa-on-iphone-safe-updates-deploys-and-ios-details-7a2</link>
      <guid>https://dev.to/jamesvu/an-installed-pwa-on-iphone-safe-updates-deploys-and-ios-details-7a2</guid>
      <description>&lt;p&gt;A PWA added to an iPhone's home screen looks like a native app, and people treat it like one: they open it from the icon, leave it in the background for days, and expect it to keep working when a new version ships. &lt;a href="https://finance.vuminhhoa.com/" rel="noopener noreferrer"&gt;Financial Plan&lt;/a&gt;, my budgeting app, is used mostly this way. This post collects what it took to make updates safe, survive deploys that replace files under an open tab, and get the iOS details right: a logo that jumped on launch, fields that zoomed the page, and push notifications.&lt;/p&gt;

&lt;p&gt;How the app syncs its data offline is a separate topic, covered in &lt;a href="https://vuminhhoa.com/en/blog/local-first-pwa-offline-sync" rel="noopener noreferrer"&gt;local-first PWA sync&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Ship updates when the user is ready, not mid-sentence
&lt;/h2&gt;

&lt;p&gt;The service worker precaches the whole app, so it opens offline and while the servers are down. The other side of that is that a new version doesn't appear by itself: the browser downloads it in the background, and it waits until the open pages are done with the old one.&lt;/p&gt;

&lt;p&gt;The app decides when to switch:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;A visible tab gets a toast&lt;/strong&gt;, "a new version is ready", with a Reload button that stays until used. Reloading on its own could throw away a half-typed form.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A hidden tab switches at once.&lt;/strong&gt; Nobody is looking, so there is nothing to interrupt.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Open tabs check for updates every 30 minutes and whenever they become visible again&lt;/strong&gt;, because an installed app may stay open for days without a navigation that would trigger the browser's own check.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There is also a manual path in Settings › Version &amp;amp; updates. Every build writes a &lt;code&gt;/version.json&lt;/code&gt; that is never cached, so the page can compare its own build ID with the latest one. That page distinguishes three states that are easy to merge by mistake: &lt;em&gt;up to date&lt;/em&gt;, &lt;em&gt;ready&lt;/em&gt; (a newer build is downloaded and applying it is one reload), and &lt;em&gt;failed&lt;/em&gt; (a newer build exists, but it couldn't be downloaded, for example offline). Showing "up to date" when the download failed would be a lie.&lt;/p&gt;

&lt;p&gt;Finally, the app calls &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/persist" rel="noopener noreferrer"&gt;&lt;code&gt;navigator.storage.persist()&lt;/code&gt;&lt;/a&gt; so the browser doesn't evict its IndexedDB data under storage pressure. For a local-first app, that data may be the only copy of changes not yet synced.&lt;/p&gt;

&lt;h2&gt;
  
  
  A deploy can break the tabs that are already open
&lt;/h2&gt;

&lt;p&gt;The bug: a tab running yesterday's version navigates to a page whose code is loaded lazily. That chunk's file name contains a content hash from yesterday's build, and today's deploy no longer has it. The host's single-page-app rewrite answered &lt;em&gt;every&lt;/em&gt; unknown path with &lt;code&gt;index.html&lt;/code&gt;, so the browser received HTML where it expected JavaScript, failed to parse it, and the page broke.&lt;/p&gt;

&lt;p&gt;Three changes fixed it:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Missing assets are a real 404.&lt;/strong&gt; The rewrite now skips &lt;code&gt;/assets/&lt;/code&gt;, so a request for a chunk that no longer exists fails cleanly instead of returning HTML.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Caching follows what can change.&lt;/strong&gt; Hashed files under &lt;code&gt;/assets/&lt;/code&gt; are cached for a year as &lt;code&gt;immutable&lt;/code&gt;; &lt;code&gt;index.html&lt;/code&gt;, the service worker scripts and &lt;code&gt;version.json&lt;/code&gt; are &lt;code&gt;no-cache&lt;/code&gt;, so the next load always asks for the current ones.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A failed chunk moves the tab to the latest version.&lt;/strong&gt; Vite fires a &lt;a href="https://vite.dev/guide/build#load-error-handling" rel="noopener noreferrer"&gt;&lt;code&gt;vite:preloadError&lt;/code&gt;&lt;/a&gt; event when a dynamic import fails. The app handles it by activating the waiting service worker if there is one, or reloading otherwise. Since 31 October 2026 this logic lives in the shared &lt;code&gt;@vuminhhoa/ui&lt;/code&gt; package rather than in the app.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The recovery has a guard, because a real outage also makes chunks fail to load, and reloading forever would make it worse (as the app shipped it in October; the current version adds error handling):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Number&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sessionStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;RELOAD_KEY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;sessionStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;RELOAD_KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;30_000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="n"&gt;toast&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;t&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"pwa.loadFailed"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"stale-version"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At most one automatic reload every 30 seconds; after that, the user sees an error and decides.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Figymmda0l0g3uizpades.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Figymmda0l0g3uizpades.png" alt="Sequence diagram between an open tab running yesterday's build and the host serving today's deploy. Before: the tab requests a chunk with an old hash, the SPA rewrite answers 200 with index.html, and the page breaks because it got HTML instead of JavaScript. After: the same request gets a 404 because the rewrite skips /assets/, and the vite:preloadError handler activates the waiting service worker or reloads, at most once every 30 seconds." width="800" height="809"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;A clean 404 turns a broken page into an error the app can recover from.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The launch logo that moved, and measuring instead of guessing
&lt;/h2&gt;

&lt;p&gt;The app shows its logo from the very first paint, in plain HTML outside React, and fades it out once the first page is ready. On an installed iPhone app, the logo visibly jumped upward a moment after launch.&lt;/p&gt;

&lt;p&gt;The first fix assumed the cause: the status bar appears a moment after the first paint and changes the page's top edge, so the logo was positioned from the bottom edge instead. It still moved. So a temporary build logged the real sizes on the device, and the numbers said something else entirely: the page is &lt;strong&gt;844 px tall at the first paint and 797 px tall 74 ms later&lt;/strong&gt;. Its &lt;em&gt;bottom&lt;/em&gt; edge moves up past the home indicator; its top edge and &lt;code&gt;100vh&lt;/code&gt; stay where they are.&lt;/p&gt;

&lt;p&gt;With that known, the fix was simple. In standalone mode, the splash is a fixed box &lt;code&gt;100vh&lt;/code&gt; tall from the top, and the logo sits in the middle of that box, which doesn't change:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight css"&gt;&lt;code&gt;&lt;span class="k"&gt;@media&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nt"&gt;display-mode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nt"&gt;standalone&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nc"&gt;.splash&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;bottom&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;auto&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;height&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;100vh&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The logo still shifted on the screen as the page resized, so two days later one more step went in: in the installed app, a small classic script (&lt;code&gt;public/splash.js&lt;/code&gt;) keeps the logo hidden until the page has its final size, on that resize or after 300 ms without one, and then fades it in over 150 ms.&lt;/p&gt;

&lt;p&gt;The measuring code came out again in the commit right after the one that added it. The lesson is the useful part: two reasonable explanations of a layout shift were both wrong, and logging &lt;code&gt;innerHeight&lt;/code&gt; frame by frame for the first 4 seconds on the real device took minutes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fields that zoomed the page
&lt;/h2&gt;

&lt;p&gt;iOS zooms the page into any text field whose font size is under 16 px when it gets focus, in Safari and in the installed app alike. The app's fields were 14 px, so every tap on an amount zoomed in and left the layout shifted. How those fields read amounts typed as "2,5tr" or "500k" is in &lt;a href="https://vuminhhoa.com/en/blog/parsing-vietnamese-money-input" rel="noopener noreferrer"&gt;parsing money the way Vietnamese people type it&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Fields are 16 px on small screens and 14 px from the &lt;code&gt;sm&lt;/code&gt; breakpoint up, except on touch iPhones and iPads, which always get 16 px through an &lt;code&gt;ios-touch&lt;/code&gt; variant in &lt;code&gt;@vuminhhoa/ui&lt;/code&gt;. An earlier version also set &lt;code&gt;maximum-scale=1&lt;/code&gt; in the viewport. On iOS that stops the automatic zoom and still allows pinch zoom, but Chrome on Android disables pinch zoom with it unless the user forces zoom in its accessibility options, and the app dropped it in November 2026.&lt;/p&gt;

&lt;h2&gt;
  
  
  A tab bar that minimizes like iOS's
&lt;/h2&gt;

&lt;p&gt;On phones the app has a bottom tab bar that shrinks while scrolling down, as Safari's own toolbar does. The first version also grew back at the end of short pages, and iOS's rubber-band bounce past the end counted as scrolling up. The rules that made it feel native:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Only scrolling &lt;em&gt;up&lt;/em&gt; brings the full bar back, never reaching the end.&lt;/li&gt;
&lt;li&gt;The bounce past the top or the bottom is ignored.&lt;/li&gt;
&lt;li&gt;It takes 24 px of movement in one direction to change state.&lt;/li&gt;
&lt;li&gt;Pages that scroll less than 240 px always keep the full bar.&lt;/li&gt;
&lt;li&gt;Every page starts with the full bar; restoring its scroll position isn't scrolling down.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Push notifications from a local-first app
&lt;/h2&gt;

&lt;p&gt;Web Push works on iPhone only for web apps added to the home screen, since &lt;a href="https://webkit.org/blog/13878/web-push-for-web-apps-on-ios-and-ipados/" rel="noopener noreferrer"&gt;iOS 16.4&lt;/a&gt;. The app's reminders are things like a credit card bill due in three days, last month not closed yet, or a term deposit maturing.&lt;/p&gt;

&lt;p&gt;The data lives on the device, but a phone can't run code on a schedule from a web app. So the server works the reminders out from the synced records, with the &lt;strong&gt;same calculation engine&lt;/strong&gt; the app uses (it lives in a package shared by both). That avoids a second, slightly different implementation of "when is this bill due". A few details:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;One notification a day&lt;/strong&gt;, around 8:00 Vietnam time, with everything due. Each reminder is claimed in a table &lt;em&gt;before&lt;/em&gt; it is sent, so a retry or a second server instance can't send it twice.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Amounts are hidden by default&lt;/strong&gt;, because notifications show on the lock screen.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://webkit.org/blog/16535/meet-declarative-web-push/" rel="noopener noreferrer"&gt;Declarative Web Push&lt;/a&gt;&lt;/strong&gt;, available since iOS 18.4, lets the system show a notification from the payload alone, without waking a service worker. Other browsers get the same payload through a small push service worker that shows it and opens the right page on tap.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Subscriptions are cleaned up.&lt;/strong&gt; Endpoints are accepted only on the browsers' push services, dropped on HTTP 404 or 410, and dropped if the app hasn't renewed them in 30 days. Signing out removes the device's subscription.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Opening the app clears the icon's badge through the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Badging_API" rel="noopener noreferrer"&gt;Badging API&lt;/a&gt;, so the number on the icon is only the reminders not yet seen.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Problem&lt;/th&gt;
&lt;th&gt;What the app does&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Updates interrupting work&lt;/td&gt;
&lt;td&gt;Toast with Reload in visible tabs, silent switch in hidden ones, checks every 30 min and on focus&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;"Up to date" when it isn't&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;/version.json&lt;/code&gt; never cached; up to date, ready and failed shown apart&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Deploys breaking open tabs&lt;/td&gt;
&lt;td&gt;404 for missing assets, immutable hashed files, &lt;code&gt;vite:preloadError&lt;/code&gt; recovery with a 30 s guard&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Logo jumping on launch&lt;/td&gt;
&lt;td&gt;Measured on the device: the bottom edge moves; logo centred in a &lt;code&gt;100vh&lt;/code&gt; box, shown once the page has resized&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Page zooming into fields&lt;/td&gt;
&lt;td&gt;16 px fields on phones and on iOS touch screens (&lt;code&gt;ios-touch&lt;/code&gt;)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Reminders for an offline app&lt;/td&gt;
&lt;td&gt;Computed on the server with the shared engine; claimed before sending; amounts hidden&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Most of these were found by using the app every day on an iPhone, not by testing it in a desktop browser with a phone-sized window. An installed PWA is a different environment, and it has to be tested as one.&lt;/p&gt;

&lt;p&gt;If you've shipped updates to a PWA that people keep installed on their iPhones, I'd love to compare notes. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>pwa</category>
      <category>serviceworker</category>
      <category>ios</category>
      <category>webpush</category>
    </item>
    <item>
      <title>A large tree in IndexedDB with RxDB: indexes, trigram search and lazy loading</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Tue, 17 Nov 2026 14:00:16 +0000</pubDate>
      <link>https://dev.to/jamesvu/a-large-tree-in-indexeddb-with-rxdb-indexes-trigram-search-and-lazy-loading-1lpd</link>
      <guid>https://dev.to/jamesvu/a-large-tree-in-indexeddb-with-rxdb-indexes-trigram-search-and-lazy-loading-1lpd</guid>
      <description>&lt;p&gt;&lt;a href="https://plan.vuminhhoa.com/" rel="noopener noreferrer"&gt;Day planner&lt;/a&gt;, my time-management app, keeps a library of &lt;em&gt;blocks&lt;/em&gt;: reusable activities that nest inside each other ("Weekend study" contains "Focus session 1", "Break", "Reading", and "Reading" has its own chapters). Everything lives in the browser, in IndexedDB through &lt;a href="https://rxdb.info/" rel="noopener noreferrer"&gt;RxDB&lt;/a&gt;, and the library can grow without limit. This post covers what made a tree in IndexedDB slow, and the changes that made reading, searching and drawing it depend on what's on screen rather than on the size of the whole table: an index that RxDB couldn't build, a trigram search that ignores Vietnamese diacritics, lazy loading, virtualization, and tests that count queries instead of milliseconds.&lt;/p&gt;

&lt;h2&gt;
  
  
  A query that took 19.6 seconds for 61 nodes
&lt;/h2&gt;

&lt;p&gt;Each block stores its parent in &lt;code&gt;parent_id&lt;/code&gt;, which is &lt;code&gt;null&lt;/code&gt; for top-level blocks. Loading a subtree meant asking for the children of one level at a time:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;snapshot_nodes&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;selector&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;parent_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;$in&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;parentIds&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That looks like an index lookup. It wasn't. A day's plan with two levels and 61 nodes, in a table of 2,061 nodes, took &lt;strong&gt;19.6 seconds&lt;/strong&gt; to load, because every level was a full scan of the table.&lt;/p&gt;

&lt;p&gt;The reason is in &lt;a href="https://rxdb.info/rx-schema.html" rel="noopener noreferrer"&gt;RxDB's schema rules&lt;/a&gt;: indexes are only allowed on fields of type &lt;code&gt;string&lt;/code&gt;, &lt;code&gt;integer&lt;/code&gt; or &lt;code&gt;number&lt;/code&gt;. A nullable field is declared as &lt;code&gt;["string", "null"]&lt;/code&gt;, which is neither, so &lt;code&gt;parent_id&lt;/code&gt; could never be indexed. Without an index, &lt;code&gt;$in&lt;/code&gt; falls back to reading every document.&lt;/p&gt;

&lt;h2&gt;
  
  
  A non-null shadow column, filled by a hook
&lt;/h2&gt;

&lt;p&gt;The obvious fix, storing a sentinel like &lt;code&gt;""&lt;/code&gt; in &lt;code&gt;parent_id&lt;/code&gt; instead of &lt;code&gt;null&lt;/code&gt;, would have broken dozens of places that check &lt;code&gt;if (!block.parent_id)&lt;/code&gt; to mean "this is a root". So the fix adds a second column instead:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;parent_key&lt;/code&gt;&lt;/strong&gt; is a non-null copy of &lt;code&gt;parent_id&lt;/code&gt;, equal to it, or &lt;code&gt;""&lt;/code&gt; for a root. It exists only to be indexed; &lt;code&gt;parent_id&lt;/code&gt; keeps its meaning everywhere else.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A &lt;code&gt;preInsert&lt;/code&gt; and &lt;code&gt;preSave&lt;/code&gt; hook fills it on every write&lt;/strong&gt; (repository calls, bulk inserts, upserts, migrations), so no code path can forget it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A schema migration backfills it&lt;/strong&gt; for blocks that already exist on users' devices.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With that, loading a subtree is one indexed lookup per level, and the number of round trips is the depth of the tree (two or three in practice), not the number of nodes.&lt;/p&gt;

&lt;p&gt;The same trick was later needed for &lt;code&gt;category_id&lt;/code&gt;, for the same reason. A shadow column also has consequences for sync, which are a story of their own in &lt;a href="https://vuminhhoa.com/en/blog/rxdb-sync-silent-failures" rel="noopener noreferrer"&gt;four bugs that silently broke RxDB sync&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Read one branch at a time, not the whole table
&lt;/h2&gt;

&lt;p&gt;Even with the index, the library page originally &lt;em&gt;observed the whole table&lt;/em&gt; and derived the tree in JavaScript: build a map, group by parent, count children. Everything on the page cost time proportional to the total number of blocks.&lt;/p&gt;

&lt;p&gt;Now the tree loads lazily:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Roots and the children of each expanded branch&lt;/strong&gt; are separate reactive queries on &lt;code&gt;parent_key&lt;/code&gt;. Collapsing a branch drops its subscription.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Breadcrumbs and detail panels&lt;/strong&gt; walk up by &lt;code&gt;findById&lt;/code&gt; instead of searching an in-memory copy of the table.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deleting or duplicating a subtree&lt;/strong&gt; walks it breadth-first through the index.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A test checks the property that matters. It reads the 20 children of one branch in a table of 120 blocks, then again in a table of 2,020 blocks (16.8 times larger), and compares the times. When the page watched the whole table, the ratio would be close to 16.8; with the index it came out at about &lt;strong&gt;0.95×&lt;/strong&gt;, i.e. constant. The test fails if the ratio goes above 6, a generous margin because it runs on &lt;code&gt;fake-indexeddb&lt;/code&gt; in CI.&lt;/p&gt;

&lt;h2&gt;
  
  
  Substring search without a full-text index
&lt;/h2&gt;

&lt;p&gt;Search is harder. Users expect "contains" matching: typing "họp" should find "Cuộc họp nhóm". An index on &lt;code&gt;title&lt;/code&gt; can only help with prefixes, and RxDB has no full-text search, so the first version loaded every block and filtered in JavaScript.&lt;/p&gt;

&lt;p&gt;The fix is a small inverted index in the style of a search engine, kept in its own &lt;strong&gt;local-only&lt;/strong&gt; collection that is never synced:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Normalize the text&lt;/strong&gt;: strip Vietnamese diacritics, lowercase, collapse spaces. NFD decomposition removes most marks, but &lt;code&gt;đ&lt;/code&gt; is its own letter in Unicode, not &lt;code&gt;d&lt;/code&gt; plus a mark, so it needs an explicit rule.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Split into trigrams&lt;/strong&gt;, overlapping three-character pieces: "cuoc hop" gives &lt;code&gt;cuo&lt;/code&gt;, &lt;code&gt;uoc&lt;/code&gt;, &lt;code&gt;oc&lt;/code&gt;, &lt;code&gt;c h&lt;/code&gt;, &lt;code&gt;ho&lt;/code&gt;, &lt;code&gt;hop&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Store one row per (block, trigram)&lt;/strong&gt; with an index on the trigram.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;To search&lt;/strong&gt;, split the query the same way, fetch the rows matching any of its trigrams with one indexed &lt;code&gt;$in&lt;/code&gt;, then &lt;strong&gt;verify&lt;/strong&gt; each candidate by checking that its normalized title really contains the normalized query. Results are ranked by how many trigrams matched.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvjvol3ogusxel1vhs2df.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvjvol3ogusxel1vhs2df.png" alt="Flow of the trigram search: the title Cuộc họp nhóm is normalized to cuoc hop nhom, split into overlapping three-character trigrams, and stored as one indexed row per block and trigram in a local-only collection. A query such as hop is split the same way and fetched with one indexed $in, then each candidate is kept only if its normalized title really contains the query, ranked by how many trigrams matched." width="800" height="870"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The index only narrows the candidates; the final check on the normalized title decides.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;normalizeForSearch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;normalize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'NFD'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;replace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;̀&lt;span class="o"&gt;-&lt;/span&gt;ͯ&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;replace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;đ&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'d'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;replace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;Đ&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'d'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toLowerCase&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;replace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;\&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="o"&gt;+/&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;' '&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;trim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because both sides are normalized, typing without diacritics ("hop") finds "họp", which is how many Vietnamese users type on a laptop.&lt;/p&gt;

&lt;p&gt;A few practical details:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The index is updated explicitly by the commands&lt;/strong&gt; that create, rename, duplicate, delete or undo blocks, not by a generic observer. A rename deletes the block's old trigrams before inserting new ones, since a shorter title loses some.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Primary keys can't contain leading or trailing spaces in RxDB&lt;/strong&gt;, and trigrams often do (&lt;code&gt;"oc "&lt;/code&gt;), so the row ID encodes the trigram while the indexed field keeps its real value.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Existing libraries are backfilled in the background&lt;/strong&gt; on startup, page by page with an ID cursor, so the whole table is never loaded into memory at once.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Trigrams need at least three characters.&lt;/strong&gt; Queries shorter than that can't use the index, which is a general limit of the technique worth planning for.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Draw only the rows on screen
&lt;/h2&gt;

&lt;p&gt;The tree used to render recursively: every expanded node was in the DOM. A library with thousands of open blocks meant thousands of rows.&lt;/p&gt;

&lt;p&gt;The tree is now flattened into a list in pre-order, descending only into expanded nodes, so every visible row is one array element with its depth. That list goes to &lt;a href="https://tanstack.com/virtual/latest" rel="noopener noreferrer"&gt;TanStack Virtual&lt;/a&gt;, which mounts only the rows in the viewport plus a small overscan.&lt;/p&gt;

&lt;p&gt;One view deliberately isn't virtualized: the day editor. Its drag and drop between nesting levels needs every sortable item in the DOM, and a day has a few dozen nodes, so the benefit is small and the risk real.&lt;/p&gt;

&lt;h2&gt;
  
  
  A depth limit, for usability rather than speed
&lt;/h2&gt;

&lt;p&gt;Blocks can nest at most &lt;strong&gt;8 levels deep&lt;/strong&gt;. The real costs come from fan-out and total size, which the changes above handle; depth is limited because a pathological tree is unusable and recursive code paths deserve a bound. Moving a whole subtree checks the parent's depth plus one plus the height of the moved subtree, since a node being dragged can be fine while its grandchildren would cross the limit.&lt;/p&gt;

&lt;p&gt;There is deliberately no limit on how many children a block can have: a day with many blocks is a valid use, and the expensive paths for wide trees (rendering and deletion) are handled directly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Count queries in tests, not milliseconds
&lt;/h2&gt;

&lt;p&gt;Timing tests on CI machines are noisy. Most of the performance tests in this codebase count instead:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;How many queries an operation makes.&lt;/strong&gt; Copying a week forward used to call &lt;code&gt;count()&lt;/code&gt; once per day for every week ahead, about 364 queries for a year; it now makes one range query. Importing a file did one &lt;code&gt;findOne&lt;/code&gt; per row and now does one &lt;code&gt;find&lt;/code&gt; plus one &lt;code&gt;bulkUpsert&lt;/code&gt;. The tests assert the query counts, so an N+1 pattern coming back fails the build.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Which plan the database uses.&lt;/strong&gt; On the server, tests run &lt;code&gt;EXPLAIN&lt;/code&gt; on a real PostgreSQL with 50,000 rows and assert that the sync pull uses an index scan, not a sequential scan. If someone drops or changes the index, the test turns red, independently of how fast the CI machine is.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Problem&lt;/th&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;$in&lt;/code&gt; on a nullable &lt;code&gt;parent_id&lt;/code&gt; scanned the table&lt;/td&gt;
&lt;td&gt;Non-null &lt;code&gt;parent_key&lt;/code&gt; shadow column, filled by write hooks, indexed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Page derived the tree from the whole table&lt;/td&gt;
&lt;td&gt;Lazy queries per expanded branch; constant cost per branch&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Substring search loaded every block&lt;/td&gt;
&lt;td&gt;Local-only trigram index, diacritics stripped, candidates verified&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Thousands of rows in the DOM&lt;/td&gt;
&lt;td&gt;Flattened tree plus virtualization; drag-and-drop view left alone&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pathological nesting&lt;/td&gt;
&lt;td&gt;Depth limit of 8, checked against subtree height on moves&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Performance regressions&lt;/td&gt;
&lt;td&gt;Tests that count queries and check query plans&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;These changes were made and tested at the scale of thousands of blocks, with the goal that nothing on screen depends on the total size. The common thread is simple: in IndexedDB as in a server database, check that the query you think is indexed actually is.&lt;/p&gt;

&lt;p&gt;If you've kept a large tree fast in IndexedDB or RxDB, I'd love to compare notes. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>rxdb</category>
      <category>indexeddb</category>
      <category>performance</category>
      <category>search</category>
    </item>
    <item>
      <title>Four bugs that silently broke RxDB sync, and how they were fixed</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Thu, 12 Nov 2026 21:02:17 +0000</pubDate>
      <link>https://dev.to/jamesvu/four-bugs-that-silently-broke-rxdb-sync-and-how-they-were-fixed-29pc</link>
      <guid>https://dev.to/jamesvu/four-bugs-that-silently-broke-rxdb-sync-and-how-they-were-fixed-29pc</guid>
      <description>&lt;p&gt;&lt;a href="https://note.vuminhhoa.com/" rel="noopener noreferrer"&gt;Personal OS&lt;/a&gt; keeps its data in the browser with &lt;a href="https://rxdb.info/" rel="noopener noreferrer"&gt;RxDB&lt;/a&gt; and syncs it to a Spring Boot and PostgreSQL backend through RxDB's &lt;a href="https://rxdb.info/replication.html" rel="noopener noreferrer"&gt;custom replication&lt;/a&gt;. The bugs that cost the most time there had one thing in common: nothing reported an error. Edits disappeared, a collection stopped syncing, or every write failed after a reload, and the logs looked normal. This post walks through four of them, what caused each, and the fix.&lt;/p&gt;

&lt;p&gt;How changes reach other devices in real time, with Server-Sent Events, is covered in &lt;a href="https://vuminhhoa.com/en/blog/spring-boot-sse-redis-pubsub" rel="noopener noreferrer"&gt;SSE with Spring Boot and Redis Pub/Sub&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The protocol in one paragraph
&lt;/h2&gt;

&lt;p&gt;Every successful write on the server gets a &lt;code&gt;version&lt;/code&gt; from a per-user sequence that only goes up. That number is both the replication checkpoint (a device pulls "everything after version N") and the way to detect conflicts: a push says which version it assumed, and the server rejects it if the row has moved on. When two devices really did edit the same row, the conflict handler keeps the copy with the higher server version, which in practice is the one already on the server; the client's &lt;code&gt;updated_at&lt;/code&gt; only breaks ties between copies at the same version. An edit made offline still goes through on reconnect, as long as no other device changed that row in the meantime. The cost is that when one did, the offline edit is dropped whole, not merged. For one person's data on a few devices that's rare, and it's the trade-off this design accepts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bug 1: rows created on this device lost every later edit
&lt;/h2&gt;

&lt;p&gt;The symptom: create a block, then rename it. The rename looked saved, then reverted after the next sync. Deleting it did nothing either.&lt;/p&gt;

&lt;p&gt;What happened, step by step:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A new row is created locally with &lt;code&gt;version = 0&lt;/code&gt; and pushed. The push succeeds, but the server's response lists only conflicts; it doesn't send back the version it assigned.&lt;/li&gt;
&lt;li&gt;The next pull brings the row with its real version, say 1. RxDB first asks the conflict handler's &lt;code&gt;isEqual(pulled, local)&lt;/code&gt; whether anything changed.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;isEqual&lt;/code&gt; had a shortcut: if either side had &lt;code&gt;version === 0&lt;/code&gt;, return &lt;code&gt;false&lt;/code&gt;. RxDB treated the documents as different, but in that step it didn't write the pulled one locally either.&lt;/li&gt;
&lt;li&gt;The local row stayed at &lt;code&gt;version = 0&lt;/code&gt; forever. Every later edit was pushed with "assumed version 0", the server was at 1, so every edit was a conflict, and the conflict handler discarded the user's change.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp920404i1ujw74qw1j8m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp920404i1ujw74qw1j8m.png" alt="Sequence diagram between this device and the server: the device pushes a new row at version 0 and gets OK without the assigned version; the next pull brings the row at version 1, isEqual returns different because one side has version 0, and the pulled row is not written. A rename is then pushed assuming version 0, the server answers conflict because the row is at version 1, and the conflict handler drops the rename." width="800" height="727"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The row never learns its real version, so every later edit loses a conflict it should not have.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The fix was to delete the shortcut and compare the three fields that matter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;isEqual&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;version&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;version&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_deleted&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_deleted&lt;/span&gt;
    &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;updated_at&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;updated_at&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A pulled row at version 1 now differs from the local row at version 0, so RxDB writes the real version down. A local edit not yet pushed has the same version as the server but a newer &lt;code&gt;updated_at&lt;/code&gt;, so it still isn't overwritten by a pull.&lt;/p&gt;

&lt;p&gt;RxDB calls &lt;code&gt;isEqual&lt;/code&gt; very often and requires it to be synchronous, so comparing three scalar fields is also the cheap option; a deep comparison of whole documents isn't.&lt;/p&gt;

&lt;p&gt;The bug was found and pinned with an &lt;strong&gt;integration test that runs a full sync loop with real RxDB against a mock server that follows the backend's contract&lt;/strong&gt;, plus backend tests for the server side of the same scenario. Unit tests of the conflict handler alone had passed throughout.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bug 2: a column that only exists on the client
&lt;/h2&gt;

&lt;p&gt;The &lt;a href="https://vuminhhoa.com/en/blog/large-tree-indexeddb-rxdb" rel="noopener noreferrer"&gt;large tree post&lt;/a&gt; describes &lt;code&gt;parent_key&lt;/code&gt;: a non-null copy of &lt;code&gt;parent_id&lt;/code&gt; that exists only so the browser can index it. The server has no such column. That broke sync in two directions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Push.&lt;/strong&gt; The client sent &lt;code&gt;parent_key&lt;/code&gt; along with every block. The server validates column names and rejects unknown ones with HTTP 400 rather than ignoring them. Every push of that collection failed, the change stayed in RxDB's queue, and was retried forever. The fix strips local-only fields at the last moment before a document leaves the device:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;stripLocalOnly&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;doc&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="cm"&gt;/* removes parent_key, category_key */&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Pull.&lt;/strong&gt; Locally, &lt;code&gt;parent_key&lt;/code&gt; is filled by &lt;code&gt;preInsert&lt;/code&gt; and &lt;code&gt;preSave&lt;/code&gt; hooks. But replication writes pulled documents through RxDB's storage layer directly, &lt;strong&gt;not through the collection&lt;/strong&gt;, so those hooks never run on the pull path. Pulled blocks arrived without &lt;code&gt;parent_key&lt;/code&gt;; in development that failed schema validation, and in production the blocks were saved but invisible to every query on &lt;code&gt;parent_key&lt;/code&gt;, so freshly synced blocks were missing from the library tree. The fix adds the derived fields in the pull handler's modifier.&lt;/p&gt;

&lt;p&gt;That fix had its own trap. RxDB &lt;a href="https://rxdb.info/rx-schema.html" rel="noopener noreferrer"&gt;always sets &lt;code&gt;additionalProperties: false&lt;/code&gt;&lt;/a&gt; at the top level of a schema, so adding a field the collection doesn't declare makes &lt;em&gt;every&lt;/em&gt; pull of that collection fail. &lt;code&gt;snapshot_nodes&lt;/code&gt; has &lt;code&gt;category_id&lt;/code&gt; but no &lt;code&gt;category_key&lt;/code&gt;, so a hard-coded "add both keys" would have broken it. The derivation now reads which derived columns each collection's schema declares, instead of naming collections in code.&lt;/p&gt;

&lt;p&gt;The general rule: &lt;strong&gt;a local-only derived column needs handling at three places&lt;/strong&gt;, the write hooks, the push modifier and the pull modifier, and only the first one is obvious.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0zh82eh5v7z67yqiyiao.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0zh82eh5v7z67yqiyiao.png" alt="Diagram of a local-only derived column: on the device, preInsert and preSave hooks add parent_key when the app writes a block; the push modifier strips local-only fields before data goes to the server, which has no parent_key column; the pull modifier adds the derived fields the schema declares, because replication writes straight to storage and the hooks never run." width="800" height="700"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Hooks only cover writes made through the collection; sync needs its own two places.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Bug 3: a migration that finished but never said so
&lt;/h2&gt;

&lt;p&gt;After a schema change, a real device ended up with every write to one collection failing with RxDB error &lt;code&gt;COL25&lt;/code&gt;, thrown because the collection was flagged as still migrating. The data showed up fine; reordering, editing or deleting anything in that collection failed. Reloading didn't help.&lt;/p&gt;

&lt;p&gt;The state on disk, captured from a real device, explained it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rx-migration-status|library_blocks-v-4  → DONE, 1704/1704, 100%
collection|library_blocks-3             → still alive (_deleted = false)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After moving the data, RxDB's migration has two more steps: delete the metadata document of the old collection version, &lt;em&gt;then&lt;/em&gt; clear its "migration in progress" flag. If the process dies between those two steps (a closed tab, a power cut, iOS killing a background tab), the old metadata survives. On the next start, RxDB sees it, decides a migration is needed and sets the flag again, but the migration has nothing left to do, so the flag is never cleared. Awaiting &lt;code&gt;migratePromise()&lt;/code&gt; doesn't help either: it waits for work that is already done and never reports it.&lt;/p&gt;

&lt;p&gt;The fix performs the step RxDB missed, marking the old metadata document as deleted, but only when &lt;strong&gt;both&lt;/strong&gt; conditions hold: a status record says the migration is &lt;code&gt;DONE&lt;/code&gt;, and the old metadata is still alive. A migration that is genuinely &lt;code&gt;RUNNING&lt;/code&gt; is left alone, because deleting its metadata would lose the data not yet moved. The repair touches only RxDB's bookkeeping documents, never user data, and runs before &lt;code&gt;migratePromise()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bug 4: a safety net that tore itself
&lt;/h2&gt;

&lt;p&gt;A device that comes back after a long time can't trust its checkpoint: the server purges deletion records (tombstones) after a while, so an old checkpoint might miss deletes. The safety net: if the last successful sync was more than &lt;strong&gt;60 days&lt;/strong&gt; ago, drop the checkpoint and pull the whole account again.&lt;/p&gt;

&lt;p&gt;Three details made it worse than no safety net:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;"Never synced" was treated as "too old".&lt;/strong&gt; A full resync clears the last-sync timestamp, so the next start found no timestamp, resynced again, and so on: every app start downloaded the whole account. A missing timestamp now means "not stale"; the checkpoint is 0 anyway, so the first pull runs normally.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The timestamp was only written on some code paths.&lt;/strong&gt; It is now written after every successful pull.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A clock moved backwards&lt;/strong&gt; produces a timestamp in the future; the age can't be known, so it is reset to now instead of forcing a resync.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There is also an invariant between client and server: the client's 60 days must stay &lt;strong&gt;shorter than the server's tombstone retention&lt;/strong&gt;, 90 days. If it were longer, a device returning after 75 days would skip the full resync while the server had already purged the deletes it missed, and deleted rows would come back to life on that device. The client reads the server's retention from a config endpoint at startup and logs a loud error if the invariant is broken. It only warns: a deployment mistake shouldn't stop sync entirely.&lt;/p&gt;

&lt;h2&gt;
  
  
  Not a sync bug, but just as quiet: a white screen from chunk splitting
&lt;/h2&gt;

&lt;p&gt;To improve caching, RxDB and RxJS were moved into their own vendor chunk with a manual chunks rule. Moving RxJS pulled in modules that React's chunk also needed, which created a &lt;strong&gt;circular dependency between two chunks&lt;/strong&gt;. Module initialization order broke, the RxDB chunk called an export of the React chunk before it existed (&lt;code&gt;Cm is not a function&lt;/code&gt; in the minified build), and production showed a white screen. The development server, which doesn't bundle, was fine.&lt;/p&gt;

&lt;p&gt;The split was reverted and the production build checked in preview. The caching gain wasn't worth an app that might not open, and the lesson is to test chunking changes on a production build, never only on the dev server.&lt;/p&gt;

&lt;h2&gt;
  
  
  Less load while nobody is looking
&lt;/h2&gt;

&lt;p&gt;One more change that didn't fix a bug but cut server load: only the leader tab opens the Server-Sent Events stream, a tab hidden for more than five minutes closes it and reopens on return, and each reconnection is followed by one check against the server's latest version. While the stream is healthy, the periodic safety pull runs every 30 minutes instead of more often.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Symptom&lt;/th&gt;
&lt;th&gt;Cause&lt;/th&gt;
&lt;th&gt;Fix&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Edits to new rows reverted&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;isEqual&lt;/code&gt; shortcut kept local &lt;code&gt;version = 0&lt;/code&gt; forever&lt;/td&gt;
&lt;td&gt;Compare version, deleted flag and timestamp directly&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Collection stopped pushing&lt;/td&gt;
&lt;td&gt;Local-only column rejected by the server (400)&lt;/td&gt;
&lt;td&gt;Strip local-only fields before push&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Synced blocks missing from the tree&lt;/td&gt;
&lt;td&gt;Write hooks don't run on the pull path&lt;/td&gt;
&lt;td&gt;Derive the columns in the pull modifier, from the schema&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Every write fails with &lt;code&gt;COL25&lt;/code&gt; after reload&lt;/td&gt;
&lt;td&gt;Migration killed between its last two steps&lt;/td&gt;
&lt;td&gt;Repair only when status is &lt;code&gt;DONE&lt;/code&gt; and old metadata is alive&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Full download on every start&lt;/td&gt;
&lt;td&gt;"Never synced" treated as stale&lt;/td&gt;
&lt;td&gt;Missing timestamp means not stale; invariant with tombstone retention&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;White screen in production&lt;/td&gt;
&lt;td&gt;Circular dependency between manual chunks&lt;/td&gt;
&lt;td&gt;Revert the split; preview production builds&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The common lesson: when sync goes wrong, it rarely throws. Each of these was found by looking at the state on a real device or by a test that ran the whole loop, not by reading error logs.&lt;/p&gt;

&lt;p&gt;If you've tracked down sync bugs in RxDB or another local-first stack that never threw an error, I'd love to compare notes. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>rxdb</category>
      <category>offlinesync</category>
      <category>springboot</category>
      <category>debugging</category>
    </item>
    <item>
      <title>Local-first PWA sync: last-writer-wins done carefully</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Thu, 12 Nov 2026 14:00:14 +0000</pubDate>
      <link>https://dev.to/jamesvu/local-first-pwa-sync-last-writer-wins-done-carefully-5e5e</link>
      <guid>https://dev.to/jamesvu/local-first-pwa-sync-last-writer-wins-done-carefully-5e5e</guid>
      <description>&lt;p&gt;Most web apps treat the server as the source of truth: every action sends a request, waits for the reply, then updates the UI. Lose the network and the app freezes. For &lt;a href="https://finance.vuminhhoa.com/" rel="noopener noreferrer"&gt;Financial Plan&lt;/a&gt; (a monthly budgeting PWA), I went the other way: &lt;strong&gt;local-first&lt;/strong&gt;. Data lives on the device, and the app works offline and even when the server is down. The server is only there to sync between devices and keep a backup.&lt;/p&gt;

&lt;p&gt;Making an app work offline isn't the hard part. The hard part is &lt;strong&gt;syncing&lt;/strong&gt; when the same person edits on a laptop and a phone, sometimes online and sometimes not. This post covers the main decisions and the edge cases I ran into.&lt;/p&gt;

&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdqnzqtoyh2p79saaqzfi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdqnzqtoyh2p79saaqzfi.png" alt="Architecture of the app: in the browser, the React UI reads and writes IndexedDB, which is the source of truth and marks records with updatedAt and dirty, while a service worker caches the whole app. Only when online, IndexedDB syncs with the server through one POST /v1/sync request that pushes dirty records and pulls changes after the cursor; the server gives each change a seq in PostgreSQL." width="800" height="675"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The UI never talks to the network; only the sync step does.&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The UI only reads and writes IndexedDB&lt;/strong&gt; (through &lt;a href="https://dexie.org/" rel="noopener noreferrer"&gt;Dexie&lt;/a&gt;) and never waits on the network. Every record has an &lt;code&gt;updatedAt&lt;/code&gt; and a &lt;code&gt;dirty&lt;/code&gt; flag meaning "not on the server yet".&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A service worker caches the whole app&lt;/strong&gt; (every route, the fonts), so it opens offline. A new version only takes over when the user taps "Reload", so the UI never changes on its own.&lt;/li&gt;
&lt;li&gt;The app calls &lt;code&gt;navigator.storage.persist()&lt;/code&gt; so the browser doesn't evict its data when the device runs low on space. Without it, IndexedDB is only "best-effort" storage.&lt;/li&gt;
&lt;li&gt;The data schema is written in zod in a shared package. Client and server validate with &lt;strong&gt;the same schema&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The sync protocol: one request, both directions
&lt;/h2&gt;

&lt;p&gt;Each sync is a single request: push the &lt;code&gt;dirty&lt;/code&gt; records and, in the same round trip, pull everything changed since the last &lt;code&gt;cursor&lt;/code&gt;. The server gives every change an increasing &lt;code&gt;seq&lt;/code&gt; number, and the next pull only fetches what has a &lt;code&gt;seq&lt;/code&gt; greater than the &lt;code&gt;cursor&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Sync runs in the background:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;1.5 seconds after each change (so a burst of typing becomes one request),&lt;/li&gt;
&lt;li&gt;when the network comes back, and when the user returns to the tab,&lt;/li&gt;
&lt;li&gt;and once a minute.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On failure (server down, timeout, 5xx, 429), the app retries with &lt;strong&gt;exponential backoff&lt;/strong&gt; from 5 seconds up to 5 minutes. The changes stay safely queued on the device.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Multiple tabs&lt;/strong&gt; are an easy case to forget: two tabs syncing at once push duplicates and fight over the &lt;code&gt;cursor&lt;/code&gt;. The &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API" rel="noopener noreferrer"&gt;Web Locks API&lt;/a&gt; solves it neatly: whichever tab gets the lock syncs, the others skip. In simplified form:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;navigator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;locks&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;request&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"finance-sync"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;ifAvailable&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="c1"&gt;// another tab is syncing&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;syncOnce&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conflicts: last writer wins, per record
&lt;/h2&gt;

&lt;p&gt;Conflict resolution ranges from simple (last-writer-wins) to complex (CRDTs). For personal finance data, where two devices rarely edit &lt;em&gt;the same field&lt;/em&gt; at the same moment, &lt;strong&gt;last-writer-wins per record&lt;/strong&gt; is enough, as long as a few details are right:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The server only overwrites when &lt;code&gt;updatedAt&lt;/code&gt; is newer.&lt;/strong&gt; That makes re-sending a change harmless (idempotent). It matters because a request can succeed but lose its response, and the client will send it again.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Pushing a version older than the server's&lt;/strong&gt; gets the current version sent back so the client can catch up.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deletes are tombstones&lt;/strong&gt; (&lt;code&gt;data: null&lt;/code&gt;), not real deletes. With a real delete, other devices have no way to learn the record is gone, and would push it right back.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;seq&lt;/code&gt; order must match commit order
&lt;/h3&gt;

&lt;p&gt;This one is subtle. Say two syncs for the same user run concurrently: request A takes &lt;code&gt;seq = 10&lt;/code&gt; but commits slowly, request B takes &lt;code&gt;seq = 11&lt;/code&gt; and commits first. A pull in between sees &lt;code&gt;seq = 11&lt;/code&gt;, moves its &lt;code&gt;cursor&lt;/code&gt; to 11, and &lt;strong&gt;misses change 10 forever&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftyag0il8fanhadz30muc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftyag0il8fanhadz30muc.png" alt="Sequence diagram: sync A takes seq 10, sync B takes seq 11 and commits first, a pull sees seq 11 and sets its cursor to 11, then A commits seq 10 late. The next pull asks for seq greater than 11, so change 10 never arrives." width="800" height="670"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;A seq handed out before commit can become visible after a higher one.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The fix: only one sync per user at a time, using a PostgreSQL advisory lock inside the transaction:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="nf"&gt;pg_try_advisory_xact_lock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;hashtextextended&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$userId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note the &lt;code&gt;try&lt;/code&gt;. If a sync is already running, the new request gets an immediate &lt;strong&gt;429&lt;/strong&gt; and the client retries, instead of waiting. Waiting requests hold the pool's connections, and every other user queues up behind them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Clocks: don't trust each device's time
&lt;/h2&gt;

&lt;p&gt;Last-writer-wins relies on &lt;code&gt;updatedAt&lt;/code&gt;, and &lt;code&gt;updatedAt&lt;/code&gt; comes from the device's clock. A phone running 10 minutes fast "wins" every edit made elsewhere during those 10 minutes.&lt;/p&gt;

&lt;p&gt;Two layers of protection:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Correct to the server's clock, NTP-style.&lt;/strong&gt; Every sync response includes &lt;code&gt;serverTime&lt;/code&gt;. The client computes its offset against the &lt;em&gt;middle&lt;/em&gt; of the round trip and stamps changes with the corrected time:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;   &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;clockOffset&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;serverTime&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;number&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sentAt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;number&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receivedAt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;number&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
     &lt;span class="nb"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;serverTime&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sentAt&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;receivedAt&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The server never stores a time more than 1 minute ahead of its own.&lt;/strong&gt; Anything stamped further ahead is pulled back to that limit, so a device with a wrong clock can't keep winning.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;One more small but important detail: &lt;strong&gt;saving a record unchanged doesn't count as a change.&lt;/strong&gt; Many forms save every field they display. If each "Save" stamped a new time, a form on the laptop would silently overwrite an edit just made on the phone.&lt;/p&gt;

&lt;h2&gt;
  
  
  Design the data to avoid conflicts
&lt;/h2&gt;

&lt;p&gt;The best conflict resolution is not having the conflict. Originally a month was one record, holding both the plan and the actual figures. Editing the plan on a laptop while entering actuals on a phone meant one side lost.&lt;/p&gt;

&lt;p&gt;The fix was to &lt;strong&gt;split a month into three records&lt;/strong&gt;: the plan, the actuals when the month is closed, and the actuals being entered. These are usually edited at different times on different devices, so once split, conflicts all but disappear. Old single-record months are still readable and get split once the device has synced.&lt;/p&gt;

&lt;p&gt;The general rule: &lt;strong&gt;the unit of sync should match the unit a user edits at one time.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Other edge cases
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;An old app meets new data.&lt;/strong&gt; A user may open an old (cached) version of the app while another device has synced a new kind of record. Records of an unknown kind are kept untouched on the device, don't break the sync, and get used once the app updates.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Signing in is optional.&lt;/strong&gt; If the auth server is down, the app keeps working. A token that can't be refreshed because the network is gone only pauses syncing; it doesn't sign the user out.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data created before signing in.&lt;/strong&gt; If the account is empty, the data goes up automatically. If the account already has data, the app asks: use the account's data, or merge this device's in. Never decide that for the user.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A newly signed-in device&lt;/strong&gt; waits for its first sync before showing any figures. Otherwise it could create an empty plan and push it over the real data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Signing out clears local data&lt;/strong&gt; (the device may be shared), but only after pushing pending changes. If some can't be sent, the app warns first.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Knowing who changed what.&lt;/strong&gt; Every record a device pushes is written to an audit log whose own history can't be quietly rewritten. How that works is in &lt;a href="https://vuminhhoa.com/en/blog/tamper-evident-audit-log-postgresql" rel="noopener noreferrer"&gt;a tamper-evident audit log in PostgreSQL&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  When local-first is worth it
&lt;/h2&gt;

&lt;p&gt;Local-first pays off when users need the app to be fast and work offline, and the data mostly belongs to &lt;em&gt;one person&lt;/em&gt; using a few devices. It fits less well when many people edit the same data in real time (look at CRDTs or a server as arbiter then), or when the data is too large to keep on the device.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The UI only reads and writes IndexedDB and never waits on the network; the server syncs between devices and keeps a backup.&lt;/li&gt;
&lt;li&gt;One request pushes dirty records and pulls everything after the cursor, with backoff on failure and a Web Lock so only one tab syncs.&lt;/li&gt;
&lt;li&gt;Last-writer-wins per record is enough for one person's data, if overwrites are idempotent and deletes are tombstones.&lt;/li&gt;
&lt;li&gt;A &lt;code&gt;seq&lt;/code&gt; handed out before commit can become visible after a higher one, so allow one sync per user at a time with a non-blocking advisory lock.&lt;/li&gt;
&lt;li&gt;Don't trust device clocks: correct them to the server's time, cap timestamps on the server, and don't count an unchanged save as a change.&lt;/li&gt;
&lt;li&gt;Shape the data so the unit of sync matches the unit a user edits at one time; splitting a month into three records removed most conflicts.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To go deeper, Ink &amp;amp; Switch's essay &lt;a href="https://www.inkandswitch.com/local-first/" rel="noopener noreferrer"&gt;Local-first software&lt;/a&gt; is a great place to start. And if you're building an offline app too and want to compare notes, my email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>localfirst</category>
      <category>pwa</category>
      <category>indexeddb</category>
      <category>postgres</category>
    </item>
    <item>
      <title>Self-hosting side projects: principles and silent failures</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Tue, 10 Nov 2026 20:34:35 +0000</pubDate>
      <link>https://dev.to/jamesvu/self-hosting-side-projects-principles-and-silent-failures-2di9</link>
      <guid>https://dev.to/jamesvu/self-hosting-side-projects-principles-and-silent-failures-2di9</guid>
      <description>&lt;p&gt;My side projects used to each be deployed their own way: some were cloned onto the server and built there, some ran from a &lt;code&gt;docker-compose&lt;/code&gt; file that only existed on that machine, and environment variables lived wherever they happened to land. It all ran, but every change meant first remembering how I'd done it last time.&lt;/p&gt;

&lt;p&gt;This post covers how I brought it all under one roof, and the real mistakes I made along the way. If you run a server for your own projects, I hope a few of these save you an evening or two of debugging.&lt;/p&gt;

&lt;h2&gt;
  
  
  Put everything in git
&lt;/h2&gt;

&lt;p&gt;The foundation: &lt;strong&gt;no hand edits on the server&lt;/strong&gt;. Compose files, config, alert rules and dashboards all live in one repo. To change something, change it in the repo, push, and let CI apply it. Images are built in each app's CI, not on the server.&lt;/p&gt;

&lt;p&gt;That gives you three things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;History&lt;/strong&gt;: every change has a commit, a reason, and can be reverted.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Rebuildability&lt;/strong&gt;: if the server is lost, you rebuild from the repo and a backup, not from memory.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Drift detection&lt;/strong&gt;: the rebuild script, run in &lt;code&gt;--dry-run&lt;/code&gt; mode against the live server, should report "nothing to change". If it doesn't, git and reality have drifted apart.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One small mistake shows why versions must live somewhere readable: for a while, the database versions sat inside an encrypted secrets file. Diffs were unreadable, the dependency update tool couldn't see them, and some containers ended up running tags like &lt;code&gt;latest&lt;/code&gt; that differed from what the file said, without anyone noticing. Now every image is pinned to an exact version right in the compose file.&lt;/p&gt;

&lt;h2&gt;
  
  
  Expose as little as possible to the internet
&lt;/h2&gt;

&lt;p&gt;Little effort, large payoff: every service exposed to the internet is something to patch, monitor and worry about. A few ways to cut that down:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use a tunnel instead of opening ports.&lt;/strong&gt; Services such as Cloudflare Tunnel let the server connect outward, so you don't need to open web ports on the machine. DDoS filtering and rate limiting happen before traffic reaches you.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Separate the admin path from the user path.&lt;/strong&gt; Admin access should go over a private network (a VPN), not the public internet.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Don't route what's only used internally.&lt;/strong&gt; Databases, caches and &lt;code&gt;/metrics&lt;/code&gt; endpoints only need to talk to each other on Docker's internal network.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Give each app its own database user&lt;/strong&gt;, with rights on its own database only, instead of a shared admin account.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;None of this makes a system "secure" in any absolute sense. It just reduces the number of places to worry about, so you can worry about the rest more carefully.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deploys you can back out of
&lt;/h2&gt;

&lt;p&gt;The current flow:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The app's repo runs its tests and builds an image.&lt;/li&gt;
&lt;li&gt;The running version of each app is recorded in a file in the infrastructure repo, so the deploy history is simply that file's &lt;code&gt;git log&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The new version first runs as a &lt;strong&gt;canary&lt;/strong&gt;: a separate container that takes no traffic and has to pass its health check. Only then does it replace the running version; otherwise it rolls back on its own.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The biggest win isn't automation, it's that &lt;strong&gt;rolling back becomes boring&lt;/strong&gt;: revert a commit and you're done.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fcakassbnjrdyz4n9pghh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fcakassbnjrdyz4n9pghh.png" alt="Flow diagram: the app repository’s CI runs tests and builds an image; the new version is recorded in a file in the infrastructure repository, whose git log is the deploy history; the deploy starts a canary container that takes no traffic and must pass its health check; if healthy it replaces the running version, otherwise it rolls back on its own and the old version keeps running." width="800" height="720"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;A failed canary never touches the running version, and undoing a release is reverting one commit.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Two real bugs I hit while building this, neither of which raised an error:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;cmd | grep -q&lt;/code&gt; in a script with &lt;code&gt;set -o pipefail&lt;/code&gt;.&lt;/strong&gt; &lt;code&gt;grep -q&lt;/code&gt; exits as soon as it finds a match, the command before it gets SIGPIPE, and the whole pipeline counts as failed. The deploy script therefore reported "already up to date" instead of deploying. The fix: capture the output in a variable first, then &lt;code&gt;grep&lt;/code&gt; the variable.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sharing a &lt;code&gt;concurrency&lt;/code&gt; group between GitHub Actions workflows.&lt;/strong&gt; As the &lt;a href="https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/control-the-concurrency-of-workflows-and-jobs" rel="noopener noreferrer"&gt;GitHub Actions concurrency docs&lt;/a&gt; describe, GitHub keeps only &lt;em&gt;one&lt;/em&gt; pending run per group by default, and a newer run cancels the pending one before it. Some deploys simply vanished. Each workflow now has its own group.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Secrets: no plain text in git
&lt;/h2&gt;

&lt;p&gt;There are a few options, depending on scale:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Encrypt secrets before committing them, with a tool such as &lt;a href="https://github.com/getsops/sops" rel="noopener noreferrer"&gt;sops&lt;/a&gt;, and decrypt only where they're used.&lt;/li&gt;
&lt;li&gt;Or use the secret store of the CI or hosting platform you're on.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Whichever you choose, three habits are worth keeping: give each component exactly the access it needs; write down how to rotate each secret &lt;em&gt;before&lt;/em&gt; you need to; and rotate a secret as soon as it shows up somewhere it shouldn't, even if it's "probably fine".&lt;/p&gt;

&lt;h2&gt;
  
  
  Alerts: few, but right
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Alert on symptoms&lt;/strong&gt; users feel (errors, slowness, unreachable), not causes. High CPU that hurts nobody isn't worth bothering anyone about.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Check from the user's point of view.&lt;/strong&gt; A probe that calls the public URLs along the same path users take (including TLS certificate expiry) catches failures that metrics inside the server can't see.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Treat alert rules as code&lt;/strong&gt;, with unit tests (Prometheus has &lt;a href="https://prometheus.io/docs/prometheus/latest/configuration/unit_testing_rules/" rel="noopener noreferrer"&gt;&lt;code&gt;promtool test rules&lt;/code&gt;&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Check metric names against the real exporter before writing a rule.&lt;/strong&gt; This is the mistake I find most dangerous: a rule that uses a metric that &lt;em&gt;doesn't exist&lt;/em&gt; never fires and never reports an error. I had an "Elasticsearch is down" alert like that. It sat there looking reassuring, and could never have gone off.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Monitor the monitoring.&lt;/strong&gt; If monitoring runs on the server it watches, it goes quiet when the server dies. A regular "I'm alive" signal sent to an outside service solves that.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Backups only count if they restore
&lt;/h2&gt;

&lt;p&gt;The rule I follow: &lt;strong&gt;a backup only counts once it has been restored successfully.&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Test-restore automatically and regularly into a temporary environment, using &lt;strong&gt;the same database versions&lt;/strong&gt; as production, and check the data.&lt;/li&gt;
&lt;li&gt;Alert when a backup fails, when the latest one is too old, and when a test restore fails.&lt;/li&gt;
&lt;li&gt;Keep at least one copy off the server, and encrypt it.&lt;/li&gt;
&lt;li&gt;For upgrades that change a schema one way (such as Keycloak upgrades), try them first on a copy loaded from a backup, and take a fresh backup right before upgrading.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Other silent failures worth knowing
&lt;/h2&gt;

&lt;p&gt;The mistakes that cost me the most time all had one thing in common: no error message.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Bind-mount a file that doesn't exist yet&lt;/strong&gt; and Docker creates a &lt;em&gt;directory&lt;/em&gt; with that name, and the container runs as if nothing happened (&lt;a href="https://docs.docker.com/engine/storage/bind-mounts/" rel="noopener noreferrer"&gt;Docker's bind mount docs&lt;/a&gt; say that with &lt;code&gt;-v&lt;/code&gt; a missing source is always created as a directory, while &lt;code&gt;--mount&lt;/code&gt; refuses to start). A custom MySQL config of mine was "applied" that way for 8 months, which is to say never.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;rsync --filter=':- .gitignore'&lt;/code&gt;&lt;/strong&gt; only applies the rules on the receiving side if a &lt;code&gt;.gitignore&lt;/code&gt; &lt;em&gt;already exists&lt;/em&gt; there. A sync nearly deleted data and &lt;code&gt;.env&lt;/code&gt; files because of it. Every sync with deletes now goes through a script that does a dry run first and refuses when it's about to delete anything that looks like data or a secret.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Before moving an app to a new setup, compare the old and new configuration.&lt;/strong&gt; One missing environment variable can switch off a feature without any error showing up.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Keep compose files, config, alert rules and dashboards in one git repo and never edit the server by hand; a &lt;code&gt;--dry-run&lt;/code&gt; rebuild that reports "nothing to change" shows git and the server still agree.&lt;/li&gt;
&lt;li&gt;Pin every image to an exact version in a file people and tools can read, not inside an encrypted secrets file.&lt;/li&gt;
&lt;li&gt;Expose as little as possible: a tunnel instead of open ports, admin access over a VPN, internal services only on Docker's internal network, and one database user per app.&lt;/li&gt;
&lt;li&gt;Deploy through a canary that must pass its health check, and record versions in git so rolling back is reverting one commit.&lt;/li&gt;
&lt;li&gt;Alert on symptoms users feel, test alert rules, check metric names against the real exporter, and monitor the monitoring from outside the server.&lt;/li&gt;
&lt;li&gt;A backup only counts once a test restore has succeeded.&lt;/li&gt;
&lt;li&gt;None of this takes much money: Cloudflare Tunnel and the Prometheus and Grafana stack have free tiers that are plenty for side projects. The hard part is discipline: no hand edits "just this once", and always asking "if this broke, would I know?".&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you've run into silent failures like these on your own server, I'd love to compare notes. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>docker</category>
      <category>cloudflaretunnel</category>
      <category>gitops</category>
      <category>prometheus</category>
    </item>
    <item>
      <title>Modeling hospital procurement bidding: lessons from my graduation project</title>
      <dc:creator>James M. Vu</dc:creator>
      <pubDate>Tue, 10 Nov 2026 14:00:14 +0000</pubDate>
      <link>https://dev.to/jamesvu/modeling-hospital-procurement-bidding-lessons-from-my-graduation-project-4i9l</link>
      <guid>https://dev.to/jamesvu/modeling-hospital-procurement-bidding-lessons-from-my-graduation-project-4i9l</guid>
      <description>&lt;p&gt;My graduation project at Hanoi University of Science and Technology (2024) was a system for a hospital's &lt;strong&gt;medical supplies department&lt;/strong&gt;: clinical departments propose purchases, the supplies department takes each proposal through public procurement bidding, and the equipment that wins the tender goes into the managed inventory. The running version is at &lt;a href="https://bid.vuminhhoa.com/" rel="noopener noreferrer"&gt;bid.vuminhhoa.com&lt;/a&gt; (the interface is in Vietnamese).&lt;/p&gt;

&lt;p&gt;The hardest part wasn't the code but &lt;strong&gt;understanding and modeling the process&lt;/strong&gt;. Public procurement has many steps, each step produces paperwork, and the people doing the work think in steps, not in tables. This post covers the main modeling decisions, which ones held up, and what I would do differently.&lt;/p&gt;

&lt;h2&gt;
  
  
  The process to digitize
&lt;/h2&gt;

&lt;p&gt;Simplified, a purchase goes through three stages:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fldmn4c35jtusyj0tq4z1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fldmn4c35jtusyj0tq4z1.png" alt="Flow of a purchase: a clinical department proposes, the supplies department approves, procurement runs through six phases from price quotation to contract with about 30 steps that each have a date and a document, then acceptance imports the equipment into the managed inventory." width="799" height="712"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Three stages, and the middle one holds about 30 steps of the same shape: a date and a document.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The six procurement phases follow the Vietnamese contractor selection sequence, where each "publish" step means posting to the &lt;a href="https://muasamcong.mof.gov.vn/" rel="noopener noreferrer"&gt;national e-procurement system&lt;/a&gt;:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Phase&lt;/th&gt;
&lt;th&gt;Example steps&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Price quotation&lt;/td&gt;
&lt;td&gt;Post the request for quotation, quotation deadline&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Expert team&lt;/td&gt;
&lt;td&gt;Procurement council meeting, budget approval, forming the expert and appraisal teams&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Contractor selection plan&lt;/td&gt;
&lt;td&gt;Draft, appraise, approve and publish the plan&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Bidding documents&lt;/td&gt;
&lt;td&gt;Draft, preparation report, approval rounds, publish the invitation to bid&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Selection result&lt;/td&gt;
&lt;td&gt;Evaluation report, negotiation, appraisal, approval of the result&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Contract&lt;/td&gt;
&lt;td&gt;Notify bidders, performance guarantee, sign, hand over, warranty guarantee&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;About 30 steps in total, and nearly every one has the same shape: &lt;strong&gt;a date and a document&lt;/strong&gt;. Spotting that early makes everything downstream simpler (the last section covers what happened when I spotted it late).&lt;/p&gt;

&lt;h2&gt;
  
  
  Proposal and procurement are one record
&lt;/h2&gt;

&lt;p&gt;A department's proposal and the procurement activity share one table, told apart by an &lt;code&gt;isProposal&lt;/code&gt; flag:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A department creates a proposal: a new row, &lt;code&gt;isProposal = true&lt;/code&gt;, proposal status "Pending".&lt;/li&gt;
&lt;li&gt;The supplies department approves it: &lt;strong&gt;the same row&lt;/strong&gt; flips to &lt;code&gt;isProposal = false&lt;/code&gt; and starts the activity status at "Waiting to start".&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The main benefit is that a procurement activity keeps its whole history, from who proposed and who approved on which date down to every bidding step, without joining two tables or copying data between stages. The cost is one table with columns that only mean something in one stage (proposal approver, activity approver...). For a process where each stage always inherits from the previous one, I think that trade-off is worth it.&lt;/p&gt;

&lt;p&gt;Status is split into two fields, because the two stages have separate life cycles:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F416zaamxb5ijv2fmxatk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F416zaamxb5ijv2fmxatk.png" alt="State diagram of one database row: as a proposal (isProposal = true) it goes from Pending to Approved or Rejected; on approval the same row sets isProposal to false and its activity status goes from Waiting to start, to In progress, to Awaiting approval, then to Completed or Cancelled." width="800" height="891"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;One row, two status fields: approving a proposal flips the same row into a procurement activity.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;One lesson: &lt;strong&gt;write the allowed transitions down as a table and enforce it on the server&lt;/strong&gt;, with each transition as its own action ("submit", "approve", "cancel") rather than a field anyone can write. The business rules then live in one place, and the UI only asks "what can be done from this state?".&lt;/p&gt;

&lt;h2&gt;
  
  
  Each phase is a JSON column
&lt;/h2&gt;

&lt;p&gt;Thirty steps, each with a date and a document, would be some sixty columns. Instead each phase is &lt;strong&gt;one JSON column&lt;/strong&gt;, and its default shape lives in code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;defaultContractorPlan&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="n"&gt;plan&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;     &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;review&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;   &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;approval&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;publish&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On read, the server merges the stored value over the default:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="n"&gt;contractorPlan&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;defaultContractorPlan&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bidding&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;contractorPlan&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Adding a step then means editing a constant and a form, with no migration. Older activities get the new step, empty.&lt;/p&gt;

&lt;p&gt;The trade-off to know up front: data in JSON is &lt;strong&gt;harder to query and to constrain&lt;/strong&gt;. The database can't check types or index it as easily as a regular column. This works when the steps are mostly &lt;em&gt;recorded and displayed&lt;/em&gt;; if you need reports like "how many tenders are stuck at bidding document appraisal", pull at least the progress state out into its own column.&lt;/p&gt;

&lt;h2&gt;
  
  
  Documents must follow the record's life cycle
&lt;/h2&gt;

&lt;p&gt;Each step has an attached file in a file storage service. Orphaned files come easily: a user replaces a file and the old one stays; an activity is deleted and its files remain.&lt;/p&gt;

&lt;p&gt;The fix is to have the form track changes by &lt;strong&gt;field path&lt;/strong&gt; and send three lists on save:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;createdFields&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'technical_bid.draft.document'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;updatedFields&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'contract_signing.contract.document'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;deletedFields&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'expert_team.purchase_meeting.document'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The server walks each list: &lt;code&gt;created&lt;/code&gt; uploads; &lt;code&gt;updated&lt;/code&gt; deletes the old file and uploads the new one; &lt;code&gt;deleted&lt;/code&gt; removes the file and sets the field to &lt;code&gt;null&lt;/code&gt;. Deleting a whole activity walks all six JSON columns to clean up its documents.&lt;/p&gt;

&lt;p&gt;The general lesson: &lt;strong&gt;don't make the server guess what changed by diffing the whole object&lt;/strong&gt;; with nested data that's both costly and error-prone. The client knows exactly what the user just did, and sending "what changed" lets the server do the right thing. Also, calls to file storage aren't part of the database transaction, so order the steps so that a failure halfway leaves a stray file (which can be cleaned up), never a record pointing to a file that's gone.&lt;/p&gt;

&lt;h2&gt;
  
  
  Acceptance is one transaction
&lt;/h2&gt;

&lt;p&gt;The last step, approving the activity, is also when the winning equipment enters the inventory. The equipment list is prepared beforehand as an Excel file, the format the supplies department already works in, and kept on the activity as a "preview list". The equipment only really exists once the activity is approved.&lt;/p&gt;

&lt;p&gt;Duplicate &lt;strong&gt;model numbers&lt;/strong&gt; are checked at two levels:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Within the file&lt;/strong&gt;, in the browser as soon as the Excel is read: duplicate rows are highlighted to fix before sending.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Against existing data&lt;/strong&gt;, on the server, inside the approval transaction.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Shortened from &lt;code&gt;biddingService.ts&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;sequelize&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;transaction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;Bidding&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;approval&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;where&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;duplicates&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;Equipment&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;where&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;modelNumber&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Op&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;in&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;modelNumbers&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;duplicates&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ConflictError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'duplicateEquipment'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;duplicates&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;Equipment&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;bulkCreate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;equipmentList&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;Activity&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;actor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;action&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sb"&gt;`imported ${equipmentList.length} items...`&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;// After commit: update the search index.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three things matter here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The status change, the new equipment and the log entry succeed or fail together.&lt;/strong&gt; An activity can't be "Completed" while the inventory is missing its equipment.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A duplicate error returns the duplicate rows themselves&lt;/strong&gt;, so the UI can show them for the user to fix, instead of "Something went wrong".&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The search index is updated after commit.&lt;/strong&gt; The database is the source of truth; the index is a copy that a reindex script can rebuild at any time. Updating the index inside the transaction would leave it holding equipment that doesn't exist if the transaction rolls back. (The Vietnamese search setup for this inventory has &lt;a href="https://vuminhhoa.com/en/blog/vietnamese-search-elasticsearch" rel="noopener noreferrer"&gt;its own post&lt;/a&gt;.)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It's also worth knowing the general limit of "check, then write": two concurrent transactions can both see "no duplicate". The reliable guard for this is a &lt;strong&gt;unique constraint in the database&lt;/strong&gt;; the check in code is still worth keeping to return a readable message.&lt;/p&gt;

&lt;h2&gt;
  
  
  Permissions in the department's own words
&lt;/h2&gt;

&lt;p&gt;Permissions are named the way the supplies department talks: "Create purchase proposal", "Approve procurement activity", "View all equipment"... An administrator creates roles and ticks permissions, so a change in who does what needs no code change.&lt;/p&gt;

&lt;p&gt;Two axes are worth keeping apart:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Permission&lt;/strong&gt; answers "which &lt;em&gt;actions&lt;/em&gt; can you take": create, edit, approve.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Scope&lt;/strong&gt; answers "whose &lt;em&gt;data&lt;/em&gt; can you see": staff of one department only see their department's proposals and equipment, unless they hold "view all".&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Merging the two (say, a role called "Internal Medicine staff") multiplies roles by the number of departments. Kept apart, one role serves every department and the scope comes from the user's department.&lt;/p&gt;

&lt;p&gt;To test permissions, the project has a script that simulates the whole supplies department: five roles, five staff members tied to departments, all six bidding phases through to acceptance. The part I find most worth copying: &lt;strong&gt;every user tries both what they're allowed to do and what they aren't&lt;/strong&gt;. A permission test that only exercises the allowed path proves half of it.&lt;/p&gt;

&lt;h2&gt;
  
  
  An activity log for people to read
&lt;/h2&gt;

&lt;p&gt;Every significant action writes one line with &lt;em&gt;who&lt;/em&gt;, &lt;em&gt;did what&lt;/em&gt;, &lt;em&gt;to which object&lt;/em&gt;, like "… imported 12 items from procurement activity …". The dashboard shows this timeline so the whole department can see where things stand.&lt;/p&gt;

&lt;p&gt;This log is for following the work, not for evidence that can't be denied. If you need history that even a database administrator can't quietly rewrite, see &lt;a href="https://vuminhhoa.com/en/blog/tamper-evident-audit-log-postgresql" rel="noopener noreferrer"&gt;a tamper-evident audit log in PostgreSQL&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two years later
&lt;/h2&gt;

&lt;p&gt;The project ran from March to July 2024. I've come back to it a few times since: moving to TypeScript, adding equipment search with Elasticsearch, caching, Google sign-in and single sign-on.&lt;/p&gt;

&lt;p&gt;The data model's skeleton is the same as in 2024: one table with an &lt;code&gt;isProposal&lt;/code&gt; flag, six JSON columns for six phases, a preview equipment list. What had to be redone was the &lt;strong&gt;shape inside&lt;/strong&gt; the JSON columns. The 2024 version used flat field names in unaccented Vietnamese, two separate fields per step:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// 2024&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;ngayHopHoiDongMuaSam&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;taiLieuHopHoiDongMuaSam&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;ngayPheDuyetDuToan&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;   &lt;span class="n"&gt;taiLieuPheDuyetDuToan&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// later&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;purchaseMeeting&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;budgetApproval&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With each step as a &lt;code&gt;{ date, document }&lt;/code&gt; object, the form needs one component for every step, and the file cleanup only looks for &lt;code&gt;document&lt;/code&gt; keys instead of remembering sixty field names. That's the price of noticing "every step is a date plus a document" late.&lt;/p&gt;

&lt;p&gt;If you're building software for a multi-step administrative process, my advice is to sit with the people who do the work and &lt;strong&gt;draw the process before drawing the tables&lt;/strong&gt;: list the steps, the paperwork each one produces, who approves it, then look for the shape the steps share. The database usually falls out of that.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Most of the roughly 30 procurement steps share one shape, a date and a document. Spotting that early simplifies the forms, the storage and the file cleanup; I spotted it late and had to reshape the JSON.&lt;/li&gt;
&lt;li&gt;A proposal and its procurement activity are one row with an &lt;code&gt;isProposal&lt;/code&gt; flag, so the whole history stays in one record, at the cost of columns that only mean something in one stage.&lt;/li&gt;
&lt;li&gt;Write the allowed status transitions down as a table, enforce them on the server, and expose each transition as its own action.&lt;/li&gt;
&lt;li&gt;One JSON column per phase, merged over a default shape in code, lets you add steps without a migration, but it is harder to query and constrain than regular columns.&lt;/li&gt;
&lt;li&gt;Have the client send which fields were created, updated and deleted, so the server can manage attached files without diffing nested objects.&lt;/li&gt;
&lt;li&gt;Approval, new equipment and the log entry go in one transaction; the search index is updated after commit, and a unique constraint is the reliable guard against duplicates.&lt;/li&gt;
&lt;li&gt;Keep permissions (which actions) separate from scope (whose data), and test both the allowed and the forbidden paths for every user.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you've modeled a similar process differently, I'd love to hear about it. My email is on the &lt;a href="https://vuminhhoa.com/en#contact" rel="noopener noreferrer"&gt;home page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>domainmodeling</category>
      <category>node</category>
      <category>sequelize</category>
      <category>mysql</category>
    </item>
  </channel>
</rss>
