<?xml version="1.0" encoding="UTF-8" ?>
    <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
      <channel>
        <title>Kotree | Deo Subarno - Software &amp; Game Developer — Web platform notes</title>
        <link>https://kotree.netlify.app/notes/series/web-platform-notes</link>
        <description>Kotree notes in the series &quot;Web platform notes&quot;</description>
        <language>en</language>
        <lastBuildDate>Sat, 12 Sep 2026 00:00:00 GMT</lastBuildDate>
        <atom:link href="https://kotree.netlify.app/notes/series/web-platform-notes/feed.xml" rel="self" type="application/rss+xml" />
        
      <item>
        <title>Offline first without a framework</title>
        <link>https://kotree.netlify.app/notes/2025-11-15-offline-first-without-a-framework</link>
        <guid>https://kotree.netlify.app/notes/2025-11-15-offline-first-without-a-framework</guid>
        <pubDate>Sat, 15 Nov 2025 00:00:00 GMT</pubDate>
        <category>offline</category>
        <category>service-worker</category>
        <category>web-platform</category>
        <description><![CDATA[<p>Offline-first has a reputation as a framework problem. It is mostly three decisions: what to keep, where writes wait, and what to tell the user when neither works. The web platform has an answer for each, and the answers fit in a few hundred lines.</p><h2>What gets cached</h2><p>Two caches, not one. Static assets are hashed by the build, so they can be cache-first and kept for as long as that build exists. Pages are network-first with a cache fallback, because a stale page is usually better than no page, but a fresh one is better still. A small offline page is precached and served for any navigation that misses both.</p><p>Caching HTML is not enough. A cached document still references hashed `/_next/static/...` files. If those are missing, the page arrives unstyled or blank. Install fetches each precached page with `cache: &apos;reload&apos;` and stores the assets its HTML references.</p><p>The cache name carries the build identifier, for example `kotree-offline-cache-v7`. On activate, every cache not in a keep-list is deleted. The queue&apos;s data cache is on that list: deleting the cache that holds unsent messages during an upgrade would be a memorable way to lose a guestbook entry.</p><h2>Writes wait in IndexedDB</h2><p>Nothing that changes state goes through the service worker&apos;s fetch handler. A POST cannot be cached, and pretending otherwise produces confusing replays. Instead the page writes a record to IndexedDB and updates the UI optimistically.</p><p>A record needs more than the payload:</p><pre><code>{ id: crypto.randomUUID(), kind: &apos;guestbook&apos;, payload, createdAt, attempts: 0 }</code></pre><p>The `id` doubles as an idempotency key. It is sent with the request and stored by the server under a unique index, so a replay after a dropped response returns the original entry instead of creating a second one. Without that, every flaky connection becomes a duplicate.</p><p>Replaying needs the CSRF token that was valid when the user pressed send. A worker cannot read the page&apos;s memory or `localStorage`, so the token sits in IndexedDB next to the queue and is refreshed whenever the page is open.</p><p>Draining is deliberately boring: take the oldest record, send it, delete it on success, increment `attempts` and stop on a 4xx that will not improve. A `navigator.locks` lock, where available, stops two tabs draining the same queue at once. Where it is not, the server&apos;s idempotency key is the backstop.</p><h2>Background sync is a bonus</h2><p>`registration.sync.register(&apos;kotree-sync-queues&apos;)` lets Chromium wake the worker after the connection returns, even if the tab is closed. It is the nicest version of this feature and it is not available everywhere. Safari does not implement the Background Sync API, and a service worker on iOS can be evicted when the browser decides it has had enough.</p><p>So the queue also drains on the `online` event, on `visibilitychange`, and on the next page load. The UI should say &quot;waiting to send&quot;, not &quot;will send when you are back&quot;, because only one of those is a promise the platform can keep. The distinction matters when someone closes the tab and assumes the message is already delivered.</p><h2>The failure modes worth designing for</h2><ul><li>**A cached page from an old deploy** references chunks that no longer exist. Keep the previous build&apos;s assets for a while, and do not cache HTML forever.</li><li>**Storage is unavailable.** Private browsing, a full disk or a blocked origin can make `indexedDB.open` fail. Keep the message in the form and show the error; do not pretend it was queued.</li><li>**The token expired.** A 401 or 403 should keep the record and ask the user to refresh, not discard their text.</li><li>**The server is down.** Retry with a cap and a visible state. Infinite retries drain the battery and hide the problem.</li><li>**The browser evicted the cache.** Safari clears unused site data after about seven days. A queue that lives only on the device can vanish.</li><li>**`navigator.onLine` is wrong.** It reports an interface, not a working route. Treat a failed fetch as the signal.</li></ul><h2>Testing it</h2><p>Playwright can take the context offline, reload, submit, reload again, go online and assert that exactly one entry reached the database. The double reload proves the queue survived; the single entry proves the idempotency key worked. A second test activates a new worker and checks that the old cache is gone while the queue remains.</p><p>None of this requires Workbox. It requires being honest about the difference between &quot;saved&quot; and &quot;sent&quot;, which is the whole feature.</p>]]></description>
        <content:encoded><![CDATA[<p>Offline-first has a reputation as a framework problem. It is mostly three decisions: what to keep, where writes wait, and what to tell the user when neither works. The web platform has an answer for each, and the answers fit in a few hundred lines.</p><h2>What gets cached</h2><p>Two caches, not one. Static assets are hashed by the build, so they can be cache-first and kept for as long as that build exists. Pages are network-first with a cache fallback, because a stale page is usually better than no page, but a fresh one is better still. A small offline page is precached and served for any navigation that misses both.</p><p>Caching HTML is not enough. A cached document still references hashed `/_next/static/...` files. If those are missing, the page arrives unstyled or blank. Install fetches each precached page with `cache: &apos;reload&apos;` and stores the assets its HTML references.</p><p>The cache name carries the build identifier, for example `kotree-offline-cache-v7`. On activate, every cache not in a keep-list is deleted. The queue&apos;s data cache is on that list: deleting the cache that holds unsent messages during an upgrade would be a memorable way to lose a guestbook entry.</p><h2>Writes wait in IndexedDB</h2><p>Nothing that changes state goes through the service worker&apos;s fetch handler. A POST cannot be cached, and pretending otherwise produces confusing replays. Instead the page writes a record to IndexedDB and updates the UI optimistically.</p><p>A record needs more than the payload:</p><pre><code>{ id: crypto.randomUUID(), kind: &apos;guestbook&apos;, payload, createdAt, attempts: 0 }</code></pre><p>The `id` doubles as an idempotency key. It is sent with the request and stored by the server under a unique index, so a replay after a dropped response returns the original entry instead of creating a second one. Without that, every flaky connection becomes a duplicate.</p><p>Replaying needs the CSRF token that was valid when the user pressed send. A worker cannot read the page&apos;s memory or `localStorage`, so the token sits in IndexedDB next to the queue and is refreshed whenever the page is open.</p><p>Draining is deliberately boring: take the oldest record, send it, delete it on success, increment `attempts` and stop on a 4xx that will not improve. A `navigator.locks` lock, where available, stops two tabs draining the same queue at once. Where it is not, the server&apos;s idempotency key is the backstop.</p><h2>Background sync is a bonus</h2><p>`registration.sync.register(&apos;kotree-sync-queues&apos;)` lets Chromium wake the worker after the connection returns, even if the tab is closed. It is the nicest version of this feature and it is not available everywhere. Safari does not implement the Background Sync API, and a service worker on iOS can be evicted when the browser decides it has had enough.</p><p>So the queue also drains on the `online` event, on `visibilitychange`, and on the next page load. The UI should say &quot;waiting to send&quot;, not &quot;will send when you are back&quot;, because only one of those is a promise the platform can keep. The distinction matters when someone closes the tab and assumes the message is already delivered.</p><h2>The failure modes worth designing for</h2><ul><li>**A cached page from an old deploy** references chunks that no longer exist. Keep the previous build&apos;s assets for a while, and do not cache HTML forever.</li><li>**Storage is unavailable.** Private browsing, a full disk or a blocked origin can make `indexedDB.open` fail. Keep the message in the form and show the error; do not pretend it was queued.</li><li>**The token expired.** A 401 or 403 should keep the record and ask the user to refresh, not discard their text.</li><li>**The server is down.** Retry with a cap and a visible state. Infinite retries drain the battery and hide the problem.</li><li>**The browser evicted the cache.** Safari clears unused site data after about seven days. A queue that lives only on the device can vanish.</li><li>**`navigator.onLine` is wrong.** It reports an interface, not a working route. Treat a failed fetch as the signal.</li></ul><h2>Testing it</h2><p>Playwright can take the context offline, reload, submit, reload again, go online and assert that exactly one entry reached the database. The double reload proves the queue survived; the single entry proves the idempotency key worked. A second test activates a new worker and checks that the old cache is gone while the queue remains.</p><p>None of this requires Workbox. It requires being honest about the difference between &quot;saved&quot; and &quot;sent&quot;, which is the whole feature.</p>]]></content:encoded>
      </item>
      <item>
        <title>View transitions in practice</title>
        <link>https://kotree.netlify.app/notes/2025-12-13-view-transitions-in-practice</link>
        <guid>https://kotree.netlify.app/notes/2025-12-13-view-transitions-in-practice</guid>
        <pubDate>Sat, 13 Dec 2025 00:00:00 GMT</pubDate>
        <category>css</category>
        <category>view-transitions</category>
        <category>performance</category>
        <description><![CDATA[<p>The view transition API is deceptively small. You wrap a DOM change in `document.startViewTransition`, the browser takes an old snapshot, applies the change, takes a new one, and animates between them. The difficulty is choosing what deserves a name, and accepting that the effect is decoration.</p><h2>Two modes, one idea</h2><p>Same-document transitions cover client-side route changes and state changes. The callback mutates the DOM; the browser handles the rest.</p><p>Cross-document transitions cover ordinary navigations. Both pages opt in with `@view-transition { navigation: auto; }`, and the browser animates between the documents. It only works for same-origin navigations.</p><p>Support is wide enough to use as an enhancement. Chromium has had both for years. Safari shipped same-document transitions in 18.0 and cross-document in 18.2. Firefox arrived late in 2025 with same-document support, so cross-document navigation is still the less even ground. Without support, the navigation simply happens, which is the correct fallback.</p><h2>Naming is the design work</h2><p>The root element gets a transition automatically. Everything else needs `view-transition-name`, unique among rendered elements. A duplicate name aborts the whole transition with a console warning, a harsh way to learn that two list items share a name.</p><p>Name a handful of things: the site mark, the page title, maybe a hero image that genuinely persists between routes. Do not name every card in a grid. Each named element becomes a snapshot layer, and a long list is a memory and raster cost for an animation nobody asked for.</p><p>If items are reordered, names can be generated from a stable id, for example `card-${id}`. Keep the set small and remove names when elements are off screen. A name on a hidden or duplicated element is worse than no transition.</p><h2>Keep the callback synchronous</h2><p>The callback runs between the snapshots. If it returns a promise, the browser waits and the old frame sits on screen while data loads, which looks like a frozen page. Prefetch first, then start the transition and commit synchronously.</p><p>In React, that means `flushSync` around the state update inside the callback. React batches updates, and a commit after the snapshot is captured produces a transition from the old state to itself. The API is not React-aware; the flush is the bridge.</p><p>Nested transitions throw, so guard against a second call while one is running. A boolean, or a check on the transition&apos;s `finished` promise, is enough to stop a double click producing an unhandled rejection.</p><h2>Motion is a preference, not a default</h2><p>The media query is not optional:</p><pre><code>@media (prefers-reduced-motion: reduce) {
  ::view-transition-group(*),
  ::view-transition-old(*),
  ::view-transition-new(*) {
    animation: none !important;
  }
}</code></pre><p>Shortening the duration to a millisecond is not removing the animation; the snapshots still happen and some people still notice the flash. Set `animation: none`, and skip the call when the preference is set. The in-app motion switch duplicates the rule under `[data-motion=&apos;off&apos;]`.</p><p>A transition should communicate a change the user caused. A fade on first paint is not a transition; it is a delay with styling.</p><h2>Where WebKit still differs</h2><p>Snapshots are flattened images, so anything that depends on live compositing can look wrong. Fixed and sticky headers may appear twice or jump between positions. `backdrop-filter`, `filter` and `mix-blend-mode` can render differently in the old and new layers. Elements inside `overflow: hidden` can be clipped at the wrong boundary when a transform has created a containing block.</p><p>Some of this improves with each release; some is inherent to snapshotting. Test the transition in Safari, not just the endpoint. The common failures are a duplicated header, a missing shadow and a focus ring a frame late.</p><p>Back and forward navigation is inconsistent. A page restored from the back-forward cache may not run the transition at all. Focus and selection are frozen during the animation, so move focus after `transition.finished`.</p><h2>The performance bill</h2><p>A transition captures pixels. A small named header is cheap; a full-page snapshot of a long document is not, particularly under CPU throttling. The animation runs on the compositor, but the capture and layout work happen on the main thread, which is what can hurt Interaction to Next Paint.</p><p>Do not start a transition on scroll or every keystroke, keep named areas small, and measure with a cold cache and a throttled CPU. A 200 ms crossfade can feel instant while adding a frame of delay to a navigation that used to be immediate.</p><h2>When not to</h2><p>If the new page has a different shape, a transition can be more disorienting than a clean cut. A data table gains nothing from a crossfade. If the user asked for less motion, the answer is no motion. The API suits a few moments, not every route.</p><p>The site&apos;s route change is still a plain CSS fade: predictable, cheap and works everywhere. The native API is reserved for places where continuity means something.</p>]]></description>
        <content:encoded><![CDATA[<p>The view transition API is deceptively small. You wrap a DOM change in `document.startViewTransition`, the browser takes an old snapshot, applies the change, takes a new one, and animates between them. The difficulty is choosing what deserves a name, and accepting that the effect is decoration.</p><h2>Two modes, one idea</h2><p>Same-document transitions cover client-side route changes and state changes. The callback mutates the DOM; the browser handles the rest.</p><p>Cross-document transitions cover ordinary navigations. Both pages opt in with `@view-transition { navigation: auto; }`, and the browser animates between the documents. It only works for same-origin navigations.</p><p>Support is wide enough to use as an enhancement. Chromium has had both for years. Safari shipped same-document transitions in 18.0 and cross-document in 18.2. Firefox arrived late in 2025 with same-document support, so cross-document navigation is still the less even ground. Without support, the navigation simply happens, which is the correct fallback.</p><h2>Naming is the design work</h2><p>The root element gets a transition automatically. Everything else needs `view-transition-name`, unique among rendered elements. A duplicate name aborts the whole transition with a console warning, a harsh way to learn that two list items share a name.</p><p>Name a handful of things: the site mark, the page title, maybe a hero image that genuinely persists between routes. Do not name every card in a grid. Each named element becomes a snapshot layer, and a long list is a memory and raster cost for an animation nobody asked for.</p><p>If items are reordered, names can be generated from a stable id, for example `card-${id}`. Keep the set small and remove names when elements are off screen. A name on a hidden or duplicated element is worse than no transition.</p><h2>Keep the callback synchronous</h2><p>The callback runs between the snapshots. If it returns a promise, the browser waits and the old frame sits on screen while data loads, which looks like a frozen page. Prefetch first, then start the transition and commit synchronously.</p><p>In React, that means `flushSync` around the state update inside the callback. React batches updates, and a commit after the snapshot is captured produces a transition from the old state to itself. The API is not React-aware; the flush is the bridge.</p><p>Nested transitions throw, so guard against a second call while one is running. A boolean, or a check on the transition&apos;s `finished` promise, is enough to stop a double click producing an unhandled rejection.</p><h2>Motion is a preference, not a default</h2><p>The media query is not optional:</p><pre><code>@media (prefers-reduced-motion: reduce) {
  ::view-transition-group(*),
  ::view-transition-old(*),
  ::view-transition-new(*) {
    animation: none !important;
  }
}</code></pre><p>Shortening the duration to a millisecond is not removing the animation; the snapshots still happen and some people still notice the flash. Set `animation: none`, and skip the call when the preference is set. The in-app motion switch duplicates the rule under `[data-motion=&apos;off&apos;]`.</p><p>A transition should communicate a change the user caused. A fade on first paint is not a transition; it is a delay with styling.</p><h2>Where WebKit still differs</h2><p>Snapshots are flattened images, so anything that depends on live compositing can look wrong. Fixed and sticky headers may appear twice or jump between positions. `backdrop-filter`, `filter` and `mix-blend-mode` can render differently in the old and new layers. Elements inside `overflow: hidden` can be clipped at the wrong boundary when a transform has created a containing block.</p><p>Some of this improves with each release; some is inherent to snapshotting. Test the transition in Safari, not just the endpoint. The common failures are a duplicated header, a missing shadow and a focus ring a frame late.</p><p>Back and forward navigation is inconsistent. A page restored from the back-forward cache may not run the transition at all. Focus and selection are frozen during the animation, so move focus after `transition.finished`.</p><h2>The performance bill</h2><p>A transition captures pixels. A small named header is cheap; a full-page snapshot of a long document is not, particularly under CPU throttling. The animation runs on the compositor, but the capture and layout work happen on the main thread, which is what can hurt Interaction to Next Paint.</p><p>Do not start a transition on scroll or every keystroke, keep named areas small, and measure with a cold cache and a throttled CPU. A 200 ms crossfade can feel instant while adding a frame of delay to a navigation that used to be immediate.</p><h2>When not to</h2><p>If the new page has a different shape, a transition can be more disorienting than a clean cut. A data table gains nothing from a crossfade. If the user asked for less motion, the answer is no motion. The API suits a few moments, not every route.</p><p>The site&apos;s route change is still a plain CSS fade: predictable, cheap and works everywhere. The native API is reserved for places where continuity means something.</p>]]></content:encoded>
      </item>
      <item>
        <title>React 19 and the external store</title>
        <link>https://kotree.netlify.app/notes/2026-01-10-react-19-external-store</link>
        <guid>https://kotree.netlify.app/notes/2026-01-10-react-19-external-store</guid>
        <pubDate>Sat, 10 Jan 2026 00:00:00 GMT</pubDate>
        <category>react</category>
        <category>state</category>
        <category>typescript</category>
        <description><![CDATA[<p>Some state does not belong to a component. A toast can be raised from a fetch handler or a plain module with no React tree in sight. A theme preference has to be read before the first paint. Putting either in context means a provider at the root and a re-render of every consumer when one toast appears. A small module store is a better fit, and React has shipped the hook that reads one safely since React 18.</p><h2>The contract</h2><p>`useSyncExternalStore` takes three functions: subscribe, getSnapshot and getServerSnapshot. Subscribe registers a callback and returns an unsubscribe. The snapshot is the current value. React calls the snapshot during render and re-renders when the store notifies.</p><pre><code>const listeners = new Set&lt;() =&gt; void&gt;();
let snapshot = { theme: &apos;system&apos;, motion: &apos;system&apos; };
const subscribe = (fn: () =&gt; void) =&gt; {
  listeners.add(fn);
  return () =&gt; listeners.delete(fn);
};
const getSnapshot = () =&gt; snapshot;
const getServerSnapshot = () =&gt; snapshot;</code></pre><p>Two rules make or break it. Define the functions outside the component; a new `subscribe` on every render forces a resubscribe. And `getSnapshot` must return a cached reference. Building an object or filtering an array inside it returns a new value each call, which React reports as &quot;the result of getSnapshot should be cached&quot; and can loop forever.</p><h2>Tearing, briefly</h2><p>Concurrent rendering can pause in the middle of a tree. If the store changes while React is rendering, one component may read the old value and another the new one. That is tearing: a single committed UI showing two versions of state.</p><p>`useSyncExternalStore` detects a change between render and commit and restarts the render synchronously, so the committed tree is consistent. The cost is that an update can throw away work, so stores should change at human speed, not per pointer move. Copying the snapshot into `useState` in an effect brings back a stale copy; read the store in render.</p><h2>Preferences</h2><p>The theme, motion, contrast and effects settings are one object in `localStorage`, with defaults for anything missing. The store reads it lazily on the client and keeps the parsed object in memory. Writes go through one function: merge, persist, notify. A failed write, in private mode or when the quota is full, still updates memory so the current tab behaves correctly, but the choice will not survive a reload.</p><p>Hydration is the trap. The server renders defaults because it cannot know the visitor&apos;s stored theme. If the client&apos;s first snapshot already contains the stored value, the markup differs and React reports a mismatch. The fix is to start on the defaults, render, then read storage in an effect and notify. That is one extra render, not a mismatch. The visual flash is handled separately by an inline script that sets `data-theme` and `data-motion` on the `&lt;html&gt;` element before the stylesheet paints.</p><p>The effect also listens to `storage` so one tab updates the others, and to `matchMedia` for system preferences. Both listeners are removed on teardown. A `system` value stays separate from the explicit choice, so &quot;follow the system&quot; keeps working when the operating system changes at dusk.</p><h2>Toasts</h2><p>A toast queue is an array plus a counter. Adding a toast creates a new array, which changes the snapshot identity and wakes subscribers. Removing one filters it out. The queue caps at three.</p><p>The timer belongs in the store, not the component. If the component owns it, unmounting leaves the timer alive and remounting restarts it. The store can pause a timer while the pointer is over the stack, which helps anyone who needs longer to read.</p><p>The server snapshot is a shared empty array constant. A fresh `[]` is a new reference every call and the hook will complain; the constant is safe because changes replace the array.</p><p>Toasts are announced through an `aria-live=&quot;polite&quot;` region with `role=&quot;status&quot;`. It has to exist before the first toast so screen readers pick up the change.</p><h2>Where the pattern stops</h2><p>External stores suit low-frequency, shared state: preferences, toasts, a feature flag, the command palette mode. They are a poor place for pointer coordinates or scroll position. Those belong in a ref and, if visible, a `requestAnimationFrame` write.</p><p>React has no selector version of the hook. Subscribing to a small store and reading the whole object is fine; the component re-renders when any field changes, which is cheap at this size. If a store grows, split it by concern rather than adding a selector and an equality function that will eventually be wrong.</p><p>The appeal is that non-React code becomes a first-class producer. A fetch wrapper can raise a toast without a hook, and a preference can be read before React exists. The hook is the bridge, not the owner.</p>]]></description>
        <content:encoded><![CDATA[<p>Some state does not belong to a component. A toast can be raised from a fetch handler or a plain module with no React tree in sight. A theme preference has to be read before the first paint. Putting either in context means a provider at the root and a re-render of every consumer when one toast appears. A small module store is a better fit, and React has shipped the hook that reads one safely since React 18.</p><h2>The contract</h2><p>`useSyncExternalStore` takes three functions: subscribe, getSnapshot and getServerSnapshot. Subscribe registers a callback and returns an unsubscribe. The snapshot is the current value. React calls the snapshot during render and re-renders when the store notifies.</p><pre><code>const listeners = new Set&lt;() =&gt; void&gt;();
let snapshot = { theme: &apos;system&apos;, motion: &apos;system&apos; };
const subscribe = (fn: () =&gt; void) =&gt; {
  listeners.add(fn);
  return () =&gt; listeners.delete(fn);
};
const getSnapshot = () =&gt; snapshot;
const getServerSnapshot = () =&gt; snapshot;</code></pre><p>Two rules make or break it. Define the functions outside the component; a new `subscribe` on every render forces a resubscribe. And `getSnapshot` must return a cached reference. Building an object or filtering an array inside it returns a new value each call, which React reports as &quot;the result of getSnapshot should be cached&quot; and can loop forever.</p><h2>Tearing, briefly</h2><p>Concurrent rendering can pause in the middle of a tree. If the store changes while React is rendering, one component may read the old value and another the new one. That is tearing: a single committed UI showing two versions of state.</p><p>`useSyncExternalStore` detects a change between render and commit and restarts the render synchronously, so the committed tree is consistent. The cost is that an update can throw away work, so stores should change at human speed, not per pointer move. Copying the snapshot into `useState` in an effect brings back a stale copy; read the store in render.</p><h2>Preferences</h2><p>The theme, motion, contrast and effects settings are one object in `localStorage`, with defaults for anything missing. The store reads it lazily on the client and keeps the parsed object in memory. Writes go through one function: merge, persist, notify. A failed write, in private mode or when the quota is full, still updates memory so the current tab behaves correctly, but the choice will not survive a reload.</p><p>Hydration is the trap. The server renders defaults because it cannot know the visitor&apos;s stored theme. If the client&apos;s first snapshot already contains the stored value, the markup differs and React reports a mismatch. The fix is to start on the defaults, render, then read storage in an effect and notify. That is one extra render, not a mismatch. The visual flash is handled separately by an inline script that sets `data-theme` and `data-motion` on the `&lt;html&gt;` element before the stylesheet paints.</p><p>The effect also listens to `storage` so one tab updates the others, and to `matchMedia` for system preferences. Both listeners are removed on teardown. A `system` value stays separate from the explicit choice, so &quot;follow the system&quot; keeps working when the operating system changes at dusk.</p><h2>Toasts</h2><p>A toast queue is an array plus a counter. Adding a toast creates a new array, which changes the snapshot identity and wakes subscribers. Removing one filters it out. The queue caps at three.</p><p>The timer belongs in the store, not the component. If the component owns it, unmounting leaves the timer alive and remounting restarts it. The store can pause a timer while the pointer is over the stack, which helps anyone who needs longer to read.</p><p>The server snapshot is a shared empty array constant. A fresh `[]` is a new reference every call and the hook will complain; the constant is safe because changes replace the array.</p><p>Toasts are announced through an `aria-live=&quot;polite&quot;` region with `role=&quot;status&quot;`. It has to exist before the first toast so screen readers pick up the change.</p><h2>Where the pattern stops</h2><p>External stores suit low-frequency, shared state: preferences, toasts, a feature flag, the command palette mode. They are a poor place for pointer coordinates or scroll position. Those belong in a ref and, if visible, a `requestAnimationFrame` write.</p><p>React has no selector version of the hook. Subscribing to a small store and reading the whole object is fine; the component re-renders when any field changes, which is cheap at this size. If a store grows, split it by concern rather than adding a selector and an equality function that will eventually be wrong.</p><p>The appeal is that non-React code becomes a first-class producer. A fetch wrapper can raise a toast without a hook, and a preference can be read before React exists. The hook is the bridge, not the owner.</p>]]></content:encoded>
      </item>
      <item>
        <title>MongoDB indexes that earn their keep</title>
        <link>https://kotree.netlify.app/notes/2026-02-07-mongodb-indexes-that-earn-their-keep</link>
        <guid>https://kotree.netlify.app/notes/2026-02-07-mongodb-indexes-that-earn-their-keep</guid>
        <pubDate>Sat, 07 Feb 2026 00:00:00 GMT</pubDate>
        <category>mongodb</category>
        <category>performance</category>
        <category>testing</category>
        <description><![CDATA[<p>An index is a promise about how a collection will be read. Every promise costs something on every write, so the goal is not many indexes. It is a collection where each hot query has one and nobody has to guess which.</p><h2>Start with the query</h2><p>Write down the filter, the sort and the projection before opening the shell. The index follows from those three, not from the fields that look important. A single-field index on `createdAt` suits a plain reverse-chronological list. It does not suit a list that floats pinned entries to the top, because the filter on `pinned` and the sort on `createdAt` are two different jobs.</p><p>The guestbook&apos;s page one runs `{ pinned: true }`, sorted by `createdAt` descending, with a limit. The index is `{ pinned: 1, createdAt: -1 }`. The old `{ createdAt: -1 }` index could sort, but it examined every recent document and discarded the unpinned ones. After a year of posts, that is the page load.</p><h2>Equality, sort, range</h2><p>The useful rule is ESR: equality fields first, then the sort, then the range. MongoDB can use an index prefix for equality, keep the matching rows in index order for the sort, and apply a range bound to what remains. Put the range before the sort and the index can no longer return sorted rows directly.</p><p>An index also has a direction. MongoDB can scan backwards, reversing every key at once. `{ pinned: 1, createdAt: -1 }` serves a descending sort for a fixed `pinned`; it does not serve a mixed sort unless the index matches that pattern or is exactly reversed.</p><p>Only one range field gets efficient bounds. If a query ranges over both `createdAt` and `score`, the index can bound one and filter the other after the fetch. That is often fine, but it should be a decision rather than a surprise in the explain output.</p><h2>Reading the explain plan</h2><p>`explain(&apos;executionStats&apos;)` runs the query and reports the work. Look at four things:</p><ul><li>The winning stage. `IXSCAN` is the goal; `COLLSCAN` on a collection that is not tiny is a failure.</li><li>`totalKeysExamined` against `nReturned`. A ratio near one means the index is selective. Hundreds means it scans a lot to return a little.</li><li>`totalDocsExamined` against `nReturned`. Fetching documents costs more than reading keys; a covered projection can make this zero.</li><li>A `SORT` stage. If it appears, the index did not satisfy the sort and MongoDB is sorting in memory, with a limit before it spills to disk.</li></ul><p>`queryPlanner` mode is cheaper and shows rejected plans, which helps when the optimizer picks something unexpected. `hint()` is useful for an A/B comparison, but not as a permanent fix; the optimizer usually knows more about the data than the person writing the hint.</p><p>Small collections lie: a collection scan is fast and may be chosen. Test with a year of dates and a realistic mix.</p><h2>An audit that runs in CI</h2><p>The index list drifts: a query is added in one branch, the index lands in another file, and six months later production has an index nobody remembers.</p><p>The audit rebuilds declared indexes in a scratch database, seeds documents, and runs each hot query through `explain()`. It fails on a collection scan for a collection not kept small by a TTL, on a sort stage the index should have handled, or on a ratio of keys examined to rows returned above a threshold. It also compares the declared list with the collection, so an index that exists only in an old migration is reported rather than trusted.</p><p>`$indexStats` shows which indexes have been used since the last restart. It needs real traffic and resets with the server, so it is operational rather than a test.</p><h2>TTL is an index with a job</h2><p>A TTL index is a single-field index on a `Date` (or an array of dates) with `expireAfterSeconds`. A background thread wakes roughly every minute and deletes expired documents. It is not a scheduler and not precise: a document can live a minute or two past its deadline, and a busy primary can lag further.</p><p>That suits rate-limit buckets, sessions, vitals samples and bans. It does not suit anything a user expects to keep. TTL deletes are real deletes, with no undo. The field must be a real `Date`, not an ISO string; a string index never expires anything.</p><p>Compound TTL indexes do not exist. If expiry depends on two fields, store a computed `expiresAt` date and index that. Changing the expiry later is a `collMod`, not a deployment. Every TTL index still costs writes and memory, so one per collection is usually enough.</p><p>The point is not a perfect index, but a collection where the hot paths are known, expensive scans are caught before a user feels them, and the indexes that remain are doing work.</p>]]></description>
        <content:encoded><![CDATA[<p>An index is a promise about how a collection will be read. Every promise costs something on every write, so the goal is not many indexes. It is a collection where each hot query has one and nobody has to guess which.</p><h2>Start with the query</h2><p>Write down the filter, the sort and the projection before opening the shell. The index follows from those three, not from the fields that look important. A single-field index on `createdAt` suits a plain reverse-chronological list. It does not suit a list that floats pinned entries to the top, because the filter on `pinned` and the sort on `createdAt` are two different jobs.</p><p>The guestbook&apos;s page one runs `{ pinned: true }`, sorted by `createdAt` descending, with a limit. The index is `{ pinned: 1, createdAt: -1 }`. The old `{ createdAt: -1 }` index could sort, but it examined every recent document and discarded the unpinned ones. After a year of posts, that is the page load.</p><h2>Equality, sort, range</h2><p>The useful rule is ESR: equality fields first, then the sort, then the range. MongoDB can use an index prefix for equality, keep the matching rows in index order for the sort, and apply a range bound to what remains. Put the range before the sort and the index can no longer return sorted rows directly.</p><p>An index also has a direction. MongoDB can scan backwards, reversing every key at once. `{ pinned: 1, createdAt: -1 }` serves a descending sort for a fixed `pinned`; it does not serve a mixed sort unless the index matches that pattern or is exactly reversed.</p><p>Only one range field gets efficient bounds. If a query ranges over both `createdAt` and `score`, the index can bound one and filter the other after the fetch. That is often fine, but it should be a decision rather than a surprise in the explain output.</p><h2>Reading the explain plan</h2><p>`explain(&apos;executionStats&apos;)` runs the query and reports the work. Look at four things:</p><ul><li>The winning stage. `IXSCAN` is the goal; `COLLSCAN` on a collection that is not tiny is a failure.</li><li>`totalKeysExamined` against `nReturned`. A ratio near one means the index is selective. Hundreds means it scans a lot to return a little.</li><li>`totalDocsExamined` against `nReturned`. Fetching documents costs more than reading keys; a covered projection can make this zero.</li><li>A `SORT` stage. If it appears, the index did not satisfy the sort and MongoDB is sorting in memory, with a limit before it spills to disk.</li></ul><p>`queryPlanner` mode is cheaper and shows rejected plans, which helps when the optimizer picks something unexpected. `hint()` is useful for an A/B comparison, but not as a permanent fix; the optimizer usually knows more about the data than the person writing the hint.</p><p>Small collections lie: a collection scan is fast and may be chosen. Test with a year of dates and a realistic mix.</p><h2>An audit that runs in CI</h2><p>The index list drifts: a query is added in one branch, the index lands in another file, and six months later production has an index nobody remembers.</p><p>The audit rebuilds declared indexes in a scratch database, seeds documents, and runs each hot query through `explain()`. It fails on a collection scan for a collection not kept small by a TTL, on a sort stage the index should have handled, or on a ratio of keys examined to rows returned above a threshold. It also compares the declared list with the collection, so an index that exists only in an old migration is reported rather than trusted.</p><p>`$indexStats` shows which indexes have been used since the last restart. It needs real traffic and resets with the server, so it is operational rather than a test.</p><h2>TTL is an index with a job</h2><p>A TTL index is a single-field index on a `Date` (or an array of dates) with `expireAfterSeconds`. A background thread wakes roughly every minute and deletes expired documents. It is not a scheduler and not precise: a document can live a minute or two past its deadline, and a busy primary can lag further.</p><p>That suits rate-limit buckets, sessions, vitals samples and bans. It does not suit anything a user expects to keep. TTL deletes are real deletes, with no undo. The field must be a real `Date`, not an ISO string; a string index never expires anything.</p><p>Compound TTL indexes do not exist. If expiry depends on two fields, store a computed `expiresAt` date and index that. Changing the expiry later is a `collMod`, not a deployment. Every TTL index still costs writes and memory, so one per collection is usually enough.</p><p>The point is not a perfect index, but a collection where the hot paths are known, expensive scans are caught before a user feels them, and the indexes that remain are doing work.</p>]]></content:encoded>
      </item>
      <item>
        <title>A CI that stays green</title>
        <link>https://kotree.netlify.app/notes/2026-03-07-ci-that-stays-green</link>
        <guid>https://kotree.netlify.app/notes/2026-03-07-ci-that-stays-green</guid>
        <pubDate>Sat, 07 Mar 2026 00:00:00 GMT</pubDate>
        <category>ci</category>
        <category>testing</category>
        <category>github-actions</category>
        <description><![CDATA[<p>A CI that is always red teaches everyone to ignore it. A CI that is always green because it retries everything teaches the same lesson more slowly. The useful middle is a pipeline where a failure means something, a retry is recorded, and the whole thing finishes before someone switches to another branch.</p><h2>The matrix is a budget</h2><p>The temptation is a full grid: three operating systems, three browsers, two Node versions. That is eighteen jobs, each installing dependencies and building the app, and the queue alone can outlast the tests. Most of the grid tests combinations nobody uses.</p><p>The shape that works here is one canonical gate and a few compatibility checks. Ubuntu with the current LTS Node and Chromium runs lint, typecheck, unit tests and the full end-to-end suite. A single Windows job runs the visual baselines, because those are generated on Windows and comparing them elsewhere is a different test. WebKit and Firefox get a smoke journey on one operating system, not the full suite.</p><p>Sharding is tempting once the end-to-end run passes ten minutes. It also breaks stateful tests: shared rate limits, a single database and a test that logs in as the admin will interfere across shards. Either give each shard its own database and its own rate-limit prefix, or shard only the read-only specs. A half-sharded suite that fails at random is worse than a slow one.</p><h2>Ports and stale processes</h2><p>Most &quot;works locally, fails in CI&quot; stories are a server on the wrong port. Playwright&apos;s `webServer` option helps, but only if it is configured honestly: `reuseExistingServer: !process.env.CI`, a port from the environment, and a `baseURL` derived from the same value. Hard-coding `localhost:3000` in one place and letting the server choose another is a reliable way to test yesterday&apos;s build.</p><p>On Windows, a killed parent process does not always take its children with it. A Next server can survive a cancelled job and hold the port, so the next run connects to the old process. GitHub&apos;s runners are fresh machines, which hides this; a self-hosted runner does not. If the process tree matters, kill it as a tree rather than adding a dependency for port cleanup.</p><p>Give every job `timeout-minutes`, and give the workflow a `concurrency` group with `cancel-in-progress: true`. A push that supersedes another should stop the old run rather than queue behind it.</p><h2>A flake policy, not a retry count</h2><p>Retries are a painkiller. One retry in CI, zero locally, is a defensible default. The important part is what happens next: the run is marked as flaky, an annotation is written, and someone owns the fix. A test that needs a retry every week is not slow; it is broken.</p><p>The usual causes are worth naming because they are usually fixable. `waitForTimeout` is a guess; use a web-first assertion. `networkidle` is a promise the app cannot keep once it polls. A test that depends on the current date breaks at midnight; freeze the clock. A test that depends on random window positions breaks when the seed changes; seed the random.</p><p>Quarantine is the last resort, and it needs an issue and a date. A skipped test with no owner is a deleted test with extra steps.</p><h2>Keep the evidence</h2><p>When a browser test fails in CI, the trace is worth more than the log. Record a trace on the first retry, keep a video only on failure, and upload the HTML report and any diffs as artifacts with a short retention. The next person should be able to open one file and see what the browser saw.</p><p>Build once and reuse the artifact. Installing dependencies and running `next build` in every shard is wasted minutes and, worse, means each shard can test a slightly different build. Cache the pnpm store keyed by the lockfile, install with `--frozen-lockfile`, and pass the build output forward.</p><h2>Audit exceptions that expire</h2><p>`pnpm audit` is useful until an advisory has no fix and the build is red for a month. The answer is not `--ignore` in the script. It is a small JSON file with one entry per exception: the advisory, why it does not apply or cannot be fixed yet, an owner, and an expiry date. CI fails when the date passes. The exception is visible in review, and it cannot quietly become permanent.</p><p>The same principle applies to lint suppressions and skipped tests. A suppression without a reason is a bug with a comment syntax.</p><h2>What green means</h2><p>A green run should mean the thing you just pushed works in the browser, on the database, with the service worker registered. It should finish quickly enough that nobody merges around it. And when it goes red, the first question should be &quot;what broke?&quot;, not &quot;which test is flaky this time?&quot;.</p><p>The pipeline has to stay small enough to trust.</p>]]></description>
        <content:encoded><![CDATA[<p>A CI that is always red teaches everyone to ignore it. A CI that is always green because it retries everything teaches the same lesson more slowly. The useful middle is a pipeline where a failure means something, a retry is recorded, and the whole thing finishes before someone switches to another branch.</p><h2>The matrix is a budget</h2><p>The temptation is a full grid: three operating systems, three browsers, two Node versions. That is eighteen jobs, each installing dependencies and building the app, and the queue alone can outlast the tests. Most of the grid tests combinations nobody uses.</p><p>The shape that works here is one canonical gate and a few compatibility checks. Ubuntu with the current LTS Node and Chromium runs lint, typecheck, unit tests and the full end-to-end suite. A single Windows job runs the visual baselines, because those are generated on Windows and comparing them elsewhere is a different test. WebKit and Firefox get a smoke journey on one operating system, not the full suite.</p><p>Sharding is tempting once the end-to-end run passes ten minutes. It also breaks stateful tests: shared rate limits, a single database and a test that logs in as the admin will interfere across shards. Either give each shard its own database and its own rate-limit prefix, or shard only the read-only specs. A half-sharded suite that fails at random is worse than a slow one.</p><h2>Ports and stale processes</h2><p>Most &quot;works locally, fails in CI&quot; stories are a server on the wrong port. Playwright&apos;s `webServer` option helps, but only if it is configured honestly: `reuseExistingServer: !process.env.CI`, a port from the environment, and a `baseURL` derived from the same value. Hard-coding `localhost:3000` in one place and letting the server choose another is a reliable way to test yesterday&apos;s build.</p><p>On Windows, a killed parent process does not always take its children with it. A Next server can survive a cancelled job and hold the port, so the next run connects to the old process. GitHub&apos;s runners are fresh machines, which hides this; a self-hosted runner does not. If the process tree matters, kill it as a tree rather than adding a dependency for port cleanup.</p><p>Give every job `timeout-minutes`, and give the workflow a `concurrency` group with `cancel-in-progress: true`. A push that supersedes another should stop the old run rather than queue behind it.</p><h2>A flake policy, not a retry count</h2><p>Retries are a painkiller. One retry in CI, zero locally, is a defensible default. The important part is what happens next: the run is marked as flaky, an annotation is written, and someone owns the fix. A test that needs a retry every week is not slow; it is broken.</p><p>The usual causes are worth naming because they are usually fixable. `waitForTimeout` is a guess; use a web-first assertion. `networkidle` is a promise the app cannot keep once it polls. A test that depends on the current date breaks at midnight; freeze the clock. A test that depends on random window positions breaks when the seed changes; seed the random.</p><p>Quarantine is the last resort, and it needs an issue and a date. A skipped test with no owner is a deleted test with extra steps.</p><h2>Keep the evidence</h2><p>When a browser test fails in CI, the trace is worth more than the log. Record a trace on the first retry, keep a video only on failure, and upload the HTML report and any diffs as artifacts with a short retention. The next person should be able to open one file and see what the browser saw.</p><p>Build once and reuse the artifact. Installing dependencies and running `next build` in every shard is wasted minutes and, worse, means each shard can test a slightly different build. Cache the pnpm store keyed by the lockfile, install with `--frozen-lockfile`, and pass the build output forward.</p><h2>Audit exceptions that expire</h2><p>`pnpm audit` is useful until an advisory has no fix and the build is red for a month. The answer is not `--ignore` in the script. It is a small JSON file with one entry per exception: the advisory, why it does not apply or cannot be fixed yet, an owner, and an expiry date. CI fails when the date passes. The exception is visible in review, and it cannot quietly become permanent.</p><p>The same principle applies to lint suppressions and skipped tests. A suppression without a reason is a bug with a comment syntax.</p><h2>What green means</h2><p>A green run should mean the thing you just pushed works in the browser, on the database, with the service worker registered. It should finish quickly enough that nobody merges around it. And when it goes red, the first question should be &quot;what broke?&quot;, not &quot;which test is flaky this time?&quot;.</p><p>The pipeline has to stay small enough to trust.</p>]]></content:encoded>
      </item>
      <item>
        <title>Target size is a design constraint</title>
        <link>https://kotree.netlify.app/notes/2026-04-04-target-size-is-a-design-constraint</link>
        <guid>https://kotree.netlify.app/notes/2026-04-04-target-size-is-a-design-constraint</guid>
        <pubDate>Sat, 04 Apr 2026 00:00:00 GMT</pubDate>
        <category>accessibility</category>
        <category>wcag</category>
        <category>design</category>
        <description><![CDATA[<p>Small controls are usually an aesthetic decision. A 16-pixel close icon looks tidy next to a 16-pixel title. The cost is paid by anyone with a tremor, a fat finger or a phone held one-handed. WCAG 2.2 made that cost measurable.</p><h2>The rule</h2><p>Success Criterion 2.5.8, Target Size (Minimum), is Level AA. Pointer targets must be at least 24 by 24 CSS pixels, with five exceptions. The important ones are:</p><ul><li>**Spacing.** A 24-pixel diameter circle centred on the target must not intersect another target&apos;s circle. This is how a 16-pixel icon can still pass, as long as its neighbours are far enough away.</li><li>**Equivalent.** A smaller control is allowed if the same action is available through a larger one on the same page.</li><li>**Inline.** Links inside a sentence are exempt, because making every word in a paragraph 24 pixels tall would break the text.</li><li>**User agent.** A control drawn by the browser, such as a native select arrow, is not yours to size.</li><li>**Essential.** A target whose size is essential to the information, such as a map pin, can be smaller.</li></ul><p>Level AAA asks for 44 by 44 under 2.5.5, and that is the better target for anything used often. Apple&apos;s guidance is 44 points, Material&apos;s is 48 density-independent pixels. The 24-pixel rule is a floor, not a goal.</p><h2>The spacing exception is not a loophole</h2><p>The exception is often read as &quot;small buttons are fine if there is a gap&quot;. The actual test is geometric: draw a 24-pixel circle around the centre of the target and check that it does not overlap the circle around any other target. A row of 16-pixel icon buttons with 4-pixel gaps fails, because the circles overlap even though the visible icons do not.</p><p>In practice, a 16-pixel icon needs about 8 pixels of clear space before its circle stops overlapping a neighbour&apos;s. That is close to the padding a comfortable button already has. The exception exists for inline links and for genuinely dense interfaces, not for a toolbar that could simply be taller.</p><p>The measurement is the target, not the icon. Padding and a transparent border count if they receive the pointer, so the visual can stay small while the hit area grows. The trap is two expanded areas overlapping invisibly.</p><h2>What it changes in a design</h2><p>The controls that fail first are predictable: modal close buttons, pagination, tag chips, icon-only actions in table rows, social links in a footer, and the arrows on a carousel. On a phone, a 24-pixel control is already marginal; a 44-pixel row is easier to hit and easier to read.</p><p>Density is the real trade-off. An admin table with 32-pixel rows can pass if each action has enough space, but the row itself is still a small target. A 44-pixel row costs vertical space and buys fewer misclicks. For a public wall or a settings panel, that is usually the right trade.</p><p>The 320-pixel viewport is the stress test. At 320 CSS pixels, roughly a 400% zoom on a 1280-pixel screen, every horizontal arrangement is one bad decision away from a scrollbar. A row of five 24-pixel buttons plus gaps may fit; five 44-pixel buttons with text labels will not. The answer is wrapping or a menu, not shrinking below the floor.</p><h2>Testing it</h2><p>Automated tools are inconsistent here. axe has a target-size rule, but it is experimental and cannot evaluate the spacing exception reliably. The dependable check is a small Playwright script: collect every visible interactive element, measure its bounding box, and assert the minimum. Then do the harder check: for each target under 24, compute the 24-pixel circle and look for intersections with another target&apos;s circle.</p><p>That script catches the invisible overlap that a screenshot review misses. It also needs a viewport sweep, because a control that is comfortable at 1440 pixels can be squeezed at 320. Run it at 320, 390, 768 and 1280, with the text-spacing override switched on, and with the pointer coarse where the browser supports it.</p><p>Keyboard focus is a separate test. A target can be large and still unreachable; tab order, visible focus and a name are not covered by 2.5.8.</p><h2>The Win95 problem</h2><p>The Windows 95 desktop is the hardest case, because the entire visual language is built on 16-pixel controls. The title bar buttons are tiny by design. The fix is not to redraw them at 44 pixels; it is to keep the pixels and give each button a larger transparent hit area, then check that the areas do not overlap. The close button can look like 1995 and behave like 2026.</p><p>That is the useful way to think about the criterion. It is not asking for bigger icons. It is asking for a pointer target that a person can hit, which is a different measurement and often a cheaper fix.</p>]]></description>
        <content:encoded><![CDATA[<p>Small controls are usually an aesthetic decision. A 16-pixel close icon looks tidy next to a 16-pixel title. The cost is paid by anyone with a tremor, a fat finger or a phone held one-handed. WCAG 2.2 made that cost measurable.</p><h2>The rule</h2><p>Success Criterion 2.5.8, Target Size (Minimum), is Level AA. Pointer targets must be at least 24 by 24 CSS pixels, with five exceptions. The important ones are:</p><ul><li>**Spacing.** A 24-pixel diameter circle centred on the target must not intersect another target&apos;s circle. This is how a 16-pixel icon can still pass, as long as its neighbours are far enough away.</li><li>**Equivalent.** A smaller control is allowed if the same action is available through a larger one on the same page.</li><li>**Inline.** Links inside a sentence are exempt, because making every word in a paragraph 24 pixels tall would break the text.</li><li>**User agent.** A control drawn by the browser, such as a native select arrow, is not yours to size.</li><li>**Essential.** A target whose size is essential to the information, such as a map pin, can be smaller.</li></ul><p>Level AAA asks for 44 by 44 under 2.5.5, and that is the better target for anything used often. Apple&apos;s guidance is 44 points, Material&apos;s is 48 density-independent pixels. The 24-pixel rule is a floor, not a goal.</p><h2>The spacing exception is not a loophole</h2><p>The exception is often read as &quot;small buttons are fine if there is a gap&quot;. The actual test is geometric: draw a 24-pixel circle around the centre of the target and check that it does not overlap the circle around any other target. A row of 16-pixel icon buttons with 4-pixel gaps fails, because the circles overlap even though the visible icons do not.</p><p>In practice, a 16-pixel icon needs about 8 pixels of clear space before its circle stops overlapping a neighbour&apos;s. That is close to the padding a comfortable button already has. The exception exists for inline links and for genuinely dense interfaces, not for a toolbar that could simply be taller.</p><p>The measurement is the target, not the icon. Padding and a transparent border count if they receive the pointer, so the visual can stay small while the hit area grows. The trap is two expanded areas overlapping invisibly.</p><h2>What it changes in a design</h2><p>The controls that fail first are predictable: modal close buttons, pagination, tag chips, icon-only actions in table rows, social links in a footer, and the arrows on a carousel. On a phone, a 24-pixel control is already marginal; a 44-pixel row is easier to hit and easier to read.</p><p>Density is the real trade-off. An admin table with 32-pixel rows can pass if each action has enough space, but the row itself is still a small target. A 44-pixel row costs vertical space and buys fewer misclicks. For a public wall or a settings panel, that is usually the right trade.</p><p>The 320-pixel viewport is the stress test. At 320 CSS pixels, roughly a 400% zoom on a 1280-pixel screen, every horizontal arrangement is one bad decision away from a scrollbar. A row of five 24-pixel buttons plus gaps may fit; five 44-pixel buttons with text labels will not. The answer is wrapping or a menu, not shrinking below the floor.</p><h2>Testing it</h2><p>Automated tools are inconsistent here. axe has a target-size rule, but it is experimental and cannot evaluate the spacing exception reliably. The dependable check is a small Playwright script: collect every visible interactive element, measure its bounding box, and assert the minimum. Then do the harder check: for each target under 24, compute the 24-pixel circle and look for intersections with another target&apos;s circle.</p><p>That script catches the invisible overlap that a screenshot review misses. It also needs a viewport sweep, because a control that is comfortable at 1440 pixels can be squeezed at 320. Run it at 320, 390, 768 and 1280, with the text-spacing override switched on, and with the pointer coarse where the browser supports it.</p><p>Keyboard focus is a separate test. A target can be large and still unreachable; tab order, visible focus and a name are not covered by 2.5.8.</p><h2>The Win95 problem</h2><p>The Windows 95 desktop is the hardest case, because the entire visual language is built on 16-pixel controls. The title bar buttons are tiny by design. The fix is not to redraw them at 44 pixels; it is to keep the pixels and give each button a larger transparent hit area, then check that the areas do not overlap. The close button can look like 1995 and behave like 2026.</p><p>That is the useful way to think about the criterion. It is not asking for bigger icons. It is asking for a pointer target that a person can hit, which is a different measurement and often a cheaper fix.</p>]]></content:encoded>
      </item>
      <item>
        <title>Fonts and the largest paint</title>
        <link>https://kotree.netlify.app/notes/2026-05-02-fonts-and-the-largest-paint</link>
        <guid>https://kotree.netlify.app/notes/2026-05-02-fonts-and-the-largest-paint</guid>
        <pubDate>Sat, 02 May 2026 00:00:00 GMT</pubDate>
        <category>performance</category>
        <category>fonts</category>
        <category>core-web-vitals</category>
        <description><![CDATA[<p>Fonts are a strange performance topic because the expensive part is usually invisible in the network panel. A 200-kilobyte family downloads once, caches, and costs nothing on the next page. The bill arrives on the first visit, as text that appears late or moves after it appears.</p><h2>What LCP is measuring</h2><p>Largest Contentful Paint is the time the largest text block or image within the viewport is painted. If the largest element is a heading, the font matters. If it is a hero image, the font is irrelevant to LCP, though it can still cause layout shift elsewhere.</p><p>Check before optimising. A PerformanceObserver with `buffered: true` reports the LCP entry and its `element`. On the home page it was the heading, so the font work was part of the LCP work.</p><p>`font-display` decides what happens while the file loads. `block` hides the text for up to three seconds, which can push the largest paint out by the same amount. `swap` paints the fallback immediately and swaps when the font arrives, which protects LCP but can move the layout. `optional` avoids the swap entirely if the font is not ready quickly, at the cost of showing the fallback for that visit. None of these is universally right; the choice depends on whether the text is the design or the content.</p><h2>One file, preloaded</h2><p>The first rule is to preload only the font that the first screen actually uses. A preload hint is a high-priority request that competes with the stylesheet and the LCP image. Preloading four weights because the design might use them is a way to make the first paint slower.</p><p>A variable font collapses several weights into one file. A Latin subset removes glyphs most English pages never render. Together they can take a 200-kilobyte family under 30 kilobytes. Check the licence; most open fonts allow subsetting, and the licence should travel with the file.</p><pre><code>&lt;link rel=&quot;preload&quot; href=&quot;/fonts/site-latin.woff2&quot; as=&quot;font&quot; type=&quot;font/woff2&quot; crossorigin&gt;</code></pre><p>The `crossorigin` attribute is required even when the font is served from the same origin, because fonts are fetched in CORS mode. Without it the browser downloads the file twice and the console warns about an unused preload.</p><p>Self-hosting removes the third-party connection and the privacy question. It also means the font is covered by the same cache headers as the rest of the build. Next.js can do the preload and the fallback metrics through `next/font/local`, which is one less hand-written hint.</p><h2>Match the fallback</h2><p>The layout shift comes from the difference between the fallback and the real font: different x-height, different ascent, different line height. CSS can adjust the fallback&apos;s metrics so the swap moves almost nothing.</p><p>`size-adjust` scales the glyphs. `ascent-override`, `descent-override` and `line-gap-override` change the vertical metrics. The numbers come from the font files, and a fallback face can be generated per family. The aim is a line box that does not jump, not a perfect match.</p><p>This matters more on a slow connection than a fast one, because the fallback is visible for longer. It also matters for the heading that is the LCP element: a swap that changes the line count can move the largest text and produce a new LCP time.</p><h2>Measuring under throttling</h2><p>A font test on a fast desktop with a warm cache measures nothing. Use a cold context, disable the service worker, and throttle the CPU. In Playwright, the Chrome DevTools Protocol exposes `Emulation.setCPUThrottlingRate`; a rate of 4 is a reasonable stand-in for a mid-range phone. Network throttling is separate and should be set to something honest, such as Fast 3G, rather than left unthrottled.</p><p>Then measure the same way every time: navigate, wait for the load event plus a short settle, read the buffered LCP entries, and take the median of five runs. Record the element, not just the number, because a change to the layout can change which element wins.</p><p>Lab numbers are not field data. They compare two builds on the same machine and mislead when quoted as a user experience. The sampled field data on the status page is the other half of the picture.</p><h2>What changed here</h2><p>The site had a single display face loaded at three weights, no preload, and a fallback with different vertical metrics. The subset and the variable file replaced three requests with one. The preload pointed at the file the heading used. The fallback was adjusted until the heading&apos;s line box barely moved.</p><p>In a local cold-cache run at 4× CPU, the heading&apos;s paint moved from about 1.1 seconds to about 0.7 seconds, and the layout shift around the swap dropped below 0.01. Those are lab numbers on one machine, not a promise about a phone on a train.</p><p>The advice is unglamorous: fewer files, smaller files, one preload, a fallback that fits, and a measurement that does not flatter the machine.</p>]]></description>
        <content:encoded><![CDATA[<p>Fonts are a strange performance topic because the expensive part is usually invisible in the network panel. A 200-kilobyte family downloads once, caches, and costs nothing on the next page. The bill arrives on the first visit, as text that appears late or moves after it appears.</p><h2>What LCP is measuring</h2><p>Largest Contentful Paint is the time the largest text block or image within the viewport is painted. If the largest element is a heading, the font matters. If it is a hero image, the font is irrelevant to LCP, though it can still cause layout shift elsewhere.</p><p>Check before optimising. A PerformanceObserver with `buffered: true` reports the LCP entry and its `element`. On the home page it was the heading, so the font work was part of the LCP work.</p><p>`font-display` decides what happens while the file loads. `block` hides the text for up to three seconds, which can push the largest paint out by the same amount. `swap` paints the fallback immediately and swaps when the font arrives, which protects LCP but can move the layout. `optional` avoids the swap entirely if the font is not ready quickly, at the cost of showing the fallback for that visit. None of these is universally right; the choice depends on whether the text is the design or the content.</p><h2>One file, preloaded</h2><p>The first rule is to preload only the font that the first screen actually uses. A preload hint is a high-priority request that competes with the stylesheet and the LCP image. Preloading four weights because the design might use them is a way to make the first paint slower.</p><p>A variable font collapses several weights into one file. A Latin subset removes glyphs most English pages never render. Together they can take a 200-kilobyte family under 30 kilobytes. Check the licence; most open fonts allow subsetting, and the licence should travel with the file.</p><pre><code>&lt;link rel=&quot;preload&quot; href=&quot;/fonts/site-latin.woff2&quot; as=&quot;font&quot; type=&quot;font/woff2&quot; crossorigin&gt;</code></pre><p>The `crossorigin` attribute is required even when the font is served from the same origin, because fonts are fetched in CORS mode. Without it the browser downloads the file twice and the console warns about an unused preload.</p><p>Self-hosting removes the third-party connection and the privacy question. It also means the font is covered by the same cache headers as the rest of the build. Next.js can do the preload and the fallback metrics through `next/font/local`, which is one less hand-written hint.</p><h2>Match the fallback</h2><p>The layout shift comes from the difference between the fallback and the real font: different x-height, different ascent, different line height. CSS can adjust the fallback&apos;s metrics so the swap moves almost nothing.</p><p>`size-adjust` scales the glyphs. `ascent-override`, `descent-override` and `line-gap-override` change the vertical metrics. The numbers come from the font files, and a fallback face can be generated per family. The aim is a line box that does not jump, not a perfect match.</p><p>This matters more on a slow connection than a fast one, because the fallback is visible for longer. It also matters for the heading that is the LCP element: a swap that changes the line count can move the largest text and produce a new LCP time.</p><h2>Measuring under throttling</h2><p>A font test on a fast desktop with a warm cache measures nothing. Use a cold context, disable the service worker, and throttle the CPU. In Playwright, the Chrome DevTools Protocol exposes `Emulation.setCPUThrottlingRate`; a rate of 4 is a reasonable stand-in for a mid-range phone. Network throttling is separate and should be set to something honest, such as Fast 3G, rather than left unthrottled.</p><p>Then measure the same way every time: navigate, wait for the load event plus a short settle, read the buffered LCP entries, and take the median of five runs. Record the element, not just the number, because a change to the layout can change which element wins.</p><p>Lab numbers are not field data. They compare two builds on the same machine and mislead when quoted as a user experience. The sampled field data on the status page is the other half of the picture.</p><h2>What changed here</h2><p>The site had a single display face loaded at three weights, no preload, and a fallback with different vertical metrics. The subset and the variable file replaced three requests with one. The preload pointed at the file the heading used. The fallback was adjusted until the heading&apos;s line box barely moved.</p><p>In a local cold-cache run at 4× CPU, the heading&apos;s paint moved from about 1.1 seconds to about 0.7 seconds, and the layout shift around the swap dropped below 0.01. Those are lab numbers on one machine, not a promise about a phone on a train.</p><p>The advice is unglamorous: fewer files, smaller files, one preload, a fallback that fits, and a measurement that does not flatter the machine.</p>]]></content:encoded>
      </item>
      <item>
        <title>Webmentions for one person</title>
        <link>https://kotree.netlify.app/notes/2026-08-22-webmentions-for-one-person</link>
        <guid>https://kotree.netlify.app/notes/2026-08-22-webmentions-for-one-person</guid>
        <pubDate>Sat, 22 Aug 2026 00:00:00 GMT</pubDate>
        <category>indieweb</category>
        <category>webmentions</category>
        <category>privacy</category>
        <description><![CDATA[<p>A webmention is a simple idea: when a page links to yours, it sends a POST to an endpoint you advertise, and you can show that someone responded. The protocol is small. The operational part, verifying that the sender owns the page, deciding what to display and keeping the spam out, is where the time goes.</p><h2>Receiving</h2><p>The endpoint accepts a form-encoded `source` and `target`. It returns 202 quickly and does the work later; a sender should not wait for a fetch and a parse. The target must be a URL on this site, and the source must be a URL that is not this site. A self-mention is not interesting and is an easy way to create a loop.</p><p>The discovery link goes in the document head: `&lt;link rel=&quot;webmention&quot; href=&quot;/api/webmention&quot;&gt;`. A sender that supports the protocol finds it. A sender that does not can still be handled by hand, which is the realistic fallback for a site with a small audience.</p><h2>Verifying</h2><p>The endpoint fetches the source and checks that it actually links to the target. That check is the whole security model. Without it, anyone can claim any mention. With it, the cost of spam rises to owning a page and publishing a link.</p><p>The fetch needs limits: HTTPS only, a timeout, a maximum body size, a redirect cap, and a block on private addresses. A webmention endpoint that fetches arbitrary URLs is an SSRF primitive, and a serverless function with access to a metadata service is a bad place to discover that. Resolve the host, reject loopback and link-local ranges, and do not follow redirects to them.</p><p>Parsing is microformats2 where available. An `h-entry` gives the author, the published date and the content. A plain page gives a title and a paragraph. Both are acceptable; the display should degrade to &quot;mentioned this&quot; rather than inventing metadata. The source&apos;s `&lt;title&gt;` is not automatically safe text, and the excerpt needs the same escaping as any other user content.</p><h2>Storage and display</h2><p>One document per `(source, target)` pair, with a unique compound index. Re-sending the same mention updates the existing row rather than adding a duplicate; the protocol expects idempotence. Store the source, target, type, author name, author URL, excerpt, published date, received date and a status: pending, approved or rejected.</p><p>The default is pending. A mention appears on the site only after a human approves it. That is slower, and it is the right default for a site that does not want to publish someone else&apos;s words without looking. The public display can show a count and a short excerpt with a link to the source, which is enough.</p><p>The source is the canonical copy. If it disappears, the mention should disappear too; a periodic check for 404 or 410 is cheaper than storing a full copy and pretending it is permanent. Avatars should be proxied or omitted, because a remote image is a tracking pixel with good manners.</p><h2>Moderation and spam</h2><p>The verification fetch removes the cheapest spam, but not all of it. A link farm can publish a page that links to everything and send a thousand mentions. Rate limits per source host and per IP, a cap on new mentions per day, and a blocklist of known bad hosts cover most of it.</p><p>The moderation queue shows the source URL, the excerpt and the time. Approve, reject or ban the host. Bans expire, like the guestbook&apos;s, because a permanent ban for a bad afternoon is more administration than it is worth. The audit log records the decision with a hashed IP, not the address.</p><p>Privacy is mostly about not collecting more than needed. The mention is public by definition, but the sender&apos;s IP is not. Hash it, truncate it, and let it expire. Do not store the full HTML of the source; store the fields you display.</p><h2>Why RSS may be enough</h2><p>The uncomfortable question is whether any of this is necessary. For a personal site, the number of people who write about it and know what a webmention is may be zero. RSS already lets a reader follow the site; a manual &quot;mentioned elsewhere&quot; list costs five minutes and no endpoint.</p><p>A receiver makes sense when replies actually arrive, or when the site wants to join a conversation with other IndieWeb sites. Building it before that is a hobby, which is fine, as long as it is named as one. The endpoint is not the hard part; the moderation queue is. A feature that produces an empty queue for a year is a feature that could have been a paragraph.</p><p>If the goal is simply to know when someone links, a search engine alert or a weekly look at the referrer log is enough. Webmentions are worth building when the alternative, checking by hand, has actually become annoying.</p>]]></description>
        <content:encoded><![CDATA[<p>A webmention is a simple idea: when a page links to yours, it sends a POST to an endpoint you advertise, and you can show that someone responded. The protocol is small. The operational part, verifying that the sender owns the page, deciding what to display and keeping the spam out, is where the time goes.</p><h2>Receiving</h2><p>The endpoint accepts a form-encoded `source` and `target`. It returns 202 quickly and does the work later; a sender should not wait for a fetch and a parse. The target must be a URL on this site, and the source must be a URL that is not this site. A self-mention is not interesting and is an easy way to create a loop.</p><p>The discovery link goes in the document head: `&lt;link rel=&quot;webmention&quot; href=&quot;/api/webmention&quot;&gt;`. A sender that supports the protocol finds it. A sender that does not can still be handled by hand, which is the realistic fallback for a site with a small audience.</p><h2>Verifying</h2><p>The endpoint fetches the source and checks that it actually links to the target. That check is the whole security model. Without it, anyone can claim any mention. With it, the cost of spam rises to owning a page and publishing a link.</p><p>The fetch needs limits: HTTPS only, a timeout, a maximum body size, a redirect cap, and a block on private addresses. A webmention endpoint that fetches arbitrary URLs is an SSRF primitive, and a serverless function with access to a metadata service is a bad place to discover that. Resolve the host, reject loopback and link-local ranges, and do not follow redirects to them.</p><p>Parsing is microformats2 where available. An `h-entry` gives the author, the published date and the content. A plain page gives a title and a paragraph. Both are acceptable; the display should degrade to &quot;mentioned this&quot; rather than inventing metadata. The source&apos;s `&lt;title&gt;` is not automatically safe text, and the excerpt needs the same escaping as any other user content.</p><h2>Storage and display</h2><p>One document per `(source, target)` pair, with a unique compound index. Re-sending the same mention updates the existing row rather than adding a duplicate; the protocol expects idempotence. Store the source, target, type, author name, author URL, excerpt, published date, received date and a status: pending, approved or rejected.</p><p>The default is pending. A mention appears on the site only after a human approves it. That is slower, and it is the right default for a site that does not want to publish someone else&apos;s words without looking. The public display can show a count and a short excerpt with a link to the source, which is enough.</p><p>The source is the canonical copy. If it disappears, the mention should disappear too; a periodic check for 404 or 410 is cheaper than storing a full copy and pretending it is permanent. Avatars should be proxied or omitted, because a remote image is a tracking pixel with good manners.</p><h2>Moderation and spam</h2><p>The verification fetch removes the cheapest spam, but not all of it. A link farm can publish a page that links to everything and send a thousand mentions. Rate limits per source host and per IP, a cap on new mentions per day, and a blocklist of known bad hosts cover most of it.</p><p>The moderation queue shows the source URL, the excerpt and the time. Approve, reject or ban the host. Bans expire, like the guestbook&apos;s, because a permanent ban for a bad afternoon is more administration than it is worth. The audit log records the decision with a hashed IP, not the address.</p><p>Privacy is mostly about not collecting more than needed. The mention is public by definition, but the sender&apos;s IP is not. Hash it, truncate it, and let it expire. Do not store the full HTML of the source; store the fields you display.</p><h2>Why RSS may be enough</h2><p>The uncomfortable question is whether any of this is necessary. For a personal site, the number of people who write about it and know what a webmention is may be zero. RSS already lets a reader follow the site; a manual &quot;mentioned elsewhere&quot; list costs five minutes and no endpoint.</p><p>A receiver makes sense when replies actually arrive, or when the site wants to join a conversation with other IndieWeb sites. Building it before that is a hobby, which is fine, as long as it is named as one. The endpoint is not the hard part; the moderation queue is. A feature that produces an empty queue for a year is a feature that could have been a paragraph.</p><p>If the goal is simply to know when someone links, a search engine alert or a weekly look at the referrer log is enough. Webmentions are worth building when the alternative, checking by hand, has actually become annoying.</p>]]></content:encoded>
      </item>
      <item>
        <title>The real cost of a personal site</title>
        <link>https://kotree.netlify.app/notes/2026-09-12-the-real-cost-of-a-personal-site</link>
        <guid>https://kotree.netlify.app/notes/2026-09-12-the-real-cost-of-a-personal-site</guid>
        <pubDate>Sat, 12 Sep 2026 00:00:00 GMT</pubDate>
        <category>operations</category>
        <category>privacy</category>
        <category>writing</category>
        <description><![CDATA[<p>A personal site looks cheap because the visible costs are small. A domain is about twelve pounds a year. Hosting on a free tier is zero. A small MongoDB cluster is zero. The number that matters is not on the invoice; it is the hours spent keeping the thing alive, and the attention spent worrying about it.</p><h2>Money, roughly</h2><p>The domain is the only unavoidable recurring cost. TLS is free. A static site can be hosted for nothing on several platforms, and a serverless function or two usually fits inside the free allowance. A database with a few thousand documents fits in a free tier with room to spare.</p><p>The costs that surprise people are attached to features: a search service, an email provider, an AI key, a queue. Each has a dashboard, a bill and a failure mode. The cheapest architecture has the fewest vendors.</p><p>The domain is also an identity. Changing it breaks links, feeds and passwords. Pick one and keep it; redirects are never as complete as they look.</p><h2>Time, honestly</h2><p>A dependency update is fifteen minutes until it is not. A major framework upgrade is a day, then a week of small regressions. A browser update can change a layout or a test baseline. A certificate renewal is automatic until the automation breaks.</p><p>The maintenance that actually matters is smaller and more regular: checking the error log, reading the uptime alert, restoring a backup once a quarter, and writing something. The last one is the point of the site and the first thing to disappear when the plumbing takes over.</p><p>A useful rule is that every feature should have an owner, and on a personal site the owner is always you. If a feature cannot survive two weeks of neglect, it needs a kill switch or it should not ship.</p><h2>Backups and restores</h2><p>The database is the only irreplaceable part. The content is in git, the code is in git, and the configuration is mostly reproducible. The guestbook, the click counts and the audit log are not.</p><p>Take a logical backup on a schedule, encrypt it, and store it somewhere that is not the same provider. Test the restore before trusting it. A backup that has never been restored is a file with a hopeful name.</p><p>The free tier of a hosted database may not include continuous backups. That is fine for a personal site, as long as the export is deliberate and the restore path is written down. The same applies to environment variables: keep an encrypted copy, not a screenshot in a notes app.</p><h2>Analytics without tracking</h2><p>The useful numbers are small: which pages are read, which links are clicked, whether the site is fast. None of that requires a third-party script, a cookie banner or a user identifier.</p><p>Server-side page views can be counted per day and per path, with no IP stored. Click counts can be incremented on the redirect. Core Web Vitals can be sampled and aggregated. The stats page can show totals and trends without pretending to know who anyone is.</p><p>The limitation is real: no unique visitors across days, no funnels, no attribution. A personal site does not need them. If the question is &quot;is anyone reading the notes?&quot;, a daily count answers it. If the question is &quot;which campaign converted?&quot;, the site has become a business and should be measured like one, with the consent and plumbing that implies.</p><h2>Deciding what not to build</h2><p>The most expensive features are the ones with a social surface. Comments need moderation. Accounts need password resets and support. A public API needs keys and abuse handling. A webmention endpoint needs verification and a queue. Each is a reasonable thing to build, and each adds a place where something can go wrong at 2 a.m.</p><p>The alternative is not to build nothing. It is to build the smallest version that answers the actual need: a guestbook instead of comments, a static search index instead of a search service, a manual list of mentions instead of a receiver, a tip jar instead of a checkout.</p><p>Every one of those choices has a cost too, usually a limitation the user can see. The trade is worth making explicit in the privacy note or the colophon, so the next person, including future you, knows why the site is small.</p><h2>The number to watch</h2><p>The site is cheap in money and expensive in attention. The useful metric is not the monthly bill; it is how many days go by without thinking about it. A site that runs for a month unnoticed, then welcomes you back with a working build and a readable error log, is doing its job.</p><p>That is the real cost: not the hosting, but the decision to keep the surface small enough to maintain.</p>]]></description>
        <content:encoded><![CDATA[<p>A personal site looks cheap because the visible costs are small. A domain is about twelve pounds a year. Hosting on a free tier is zero. A small MongoDB cluster is zero. The number that matters is not on the invoice; it is the hours spent keeping the thing alive, and the attention spent worrying about it.</p><h2>Money, roughly</h2><p>The domain is the only unavoidable recurring cost. TLS is free. A static site can be hosted for nothing on several platforms, and a serverless function or two usually fits inside the free allowance. A database with a few thousand documents fits in a free tier with room to spare.</p><p>The costs that surprise people are attached to features: a search service, an email provider, an AI key, a queue. Each has a dashboard, a bill and a failure mode. The cheapest architecture has the fewest vendors.</p><p>The domain is also an identity. Changing it breaks links, feeds and passwords. Pick one and keep it; redirects are never as complete as they look.</p><h2>Time, honestly</h2><p>A dependency update is fifteen minutes until it is not. A major framework upgrade is a day, then a week of small regressions. A browser update can change a layout or a test baseline. A certificate renewal is automatic until the automation breaks.</p><p>The maintenance that actually matters is smaller and more regular: checking the error log, reading the uptime alert, restoring a backup once a quarter, and writing something. The last one is the point of the site and the first thing to disappear when the plumbing takes over.</p><p>A useful rule is that every feature should have an owner, and on a personal site the owner is always you. If a feature cannot survive two weeks of neglect, it needs a kill switch or it should not ship.</p><h2>Backups and restores</h2><p>The database is the only irreplaceable part. The content is in git, the code is in git, and the configuration is mostly reproducible. The guestbook, the click counts and the audit log are not.</p><p>Take a logical backup on a schedule, encrypt it, and store it somewhere that is not the same provider. Test the restore before trusting it. A backup that has never been restored is a file with a hopeful name.</p><p>The free tier of a hosted database may not include continuous backups. That is fine for a personal site, as long as the export is deliberate and the restore path is written down. The same applies to environment variables: keep an encrypted copy, not a screenshot in a notes app.</p><h2>Analytics without tracking</h2><p>The useful numbers are small: which pages are read, which links are clicked, whether the site is fast. None of that requires a third-party script, a cookie banner or a user identifier.</p><p>Server-side page views can be counted per day and per path, with no IP stored. Click counts can be incremented on the redirect. Core Web Vitals can be sampled and aggregated. The stats page can show totals and trends without pretending to know who anyone is.</p><p>The limitation is real: no unique visitors across days, no funnels, no attribution. A personal site does not need them. If the question is &quot;is anyone reading the notes?&quot;, a daily count answers it. If the question is &quot;which campaign converted?&quot;, the site has become a business and should be measured like one, with the consent and plumbing that implies.</p><h2>Deciding what not to build</h2><p>The most expensive features are the ones with a social surface. Comments need moderation. Accounts need password resets and support. A public API needs keys and abuse handling. A webmention endpoint needs verification and a queue. Each is a reasonable thing to build, and each adds a place where something can go wrong at 2 a.m.</p><p>The alternative is not to build nothing. It is to build the smallest version that answers the actual need: a guestbook instead of comments, a static search index instead of a search service, a manual list of mentions instead of a receiver, a tip jar instead of a checkout.</p><p>Every one of those choices has a cost too, usually a limitation the user can see. The trade is worth making explicit in the privacy note or the colophon, so the next person, including future you, knows why the site is small.</p><h2>The number to watch</h2><p>The site is cheap in money and expensive in attention. The useful metric is not the monthly bill; it is how many days go by without thinking about it. A site that runs for a month unnoticed, then welcomes you back with a working build and a readable error log, is doing its job.</p><p>That is the real cost: not the hosting, but the decision to keep the surface small enough to maintain.</p>]]></content:encoded>
      </item>
      </channel>
    </rss>