<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Matteo Mazzocchi]]></title><description><![CDATA[Matteo Mazzocchi]]></description><link>https://mazzocchimatteo.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 26 Nov 2026 14:14:23 GMT</lastBuildDate><atom:link href="https://mazzocchimatteo.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Stop, don't guess: the rules I give my AI for reading lab reports]]></title><description><![CDATA[For a medical client, I built the part of a system that reads lab reports. A PDF comes in from a laboratory, the system pulls out the values (blood tests…]]></description><link>https://mazzocchimatteo.hashnode.dev/stop-don-t-guess-the-rules-i-give-my-ai-for-reading-lab-reports</link><guid isPermaLink="true">https://mazzocchimatteo.hashnode.dev/stop-don-t-guess-the-rules-i-give-my-ai-for-reading-lab-reports</guid><category><![CDATA[AI]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[healthcare]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Matteo Mazzocchi]]></dc:creator><pubDate>Wed, 25 Nov 2026 21:10:16 GMT</pubDate><content:encoded><![CDATA[<p>For a medical client, I built the part of a system that reads lab reports. A PDF comes in from a laboratory, the system pulls out the values (blood tests, mostly), converts them, and puts them in front of a doctor.</p>
<p>Over 99% of the values that are in the reports are read automatically. This post is about the other part, the small one, because that's where the real design lives. And it's where my AI assistant, left alone, writes code that is plausible, tidy, and wrong in a way that matters: when it doesn't know a number, it makes one up.</p>
<h2>The code that looks right</h2>
<p>Ask an AI to "extract the values from the report, and handle missing data gracefully", and you get something like this:</p>
<pre><code class="language-ts">function readValue(text: string, test: string): number {
  const match = text.match(new RegExp(`${test}\\s+([\\d.,]+)`));
  if (!match) return lastKnownValue(test) ?? 0;   // "graceful"
  return parseFloat(match[1].replace(',', '.'));
}
</code></pre>
<p>Nothing crashes. Every test gets a number. The dashboard is full. A reviewer sees a sensible fallback.</p>
<p>Now read it as the doctor. A missing value became the patient's last known value, or zero. The unit was ignored. And the code can't tell you which numbers were read and which were invented, because they all have the same type: <code>number</code>.</p>
<p>Jim Shore described this pattern in 2004, in a short IEEE Software column called "Fail Fast". His example is a configuration reader that returns a default when a property is missing: the program keeps working, and fails in strange ways later. In a config file that's a debugging problem. In a lab report it's a wrong number in front of a doctor, looking exactly like a right one.</p>
<h2>Four states, not one</h2>
<p>The fix starts with the type. A value pulled from a report is not a number. It's one of four things:</p>
<pre><code class="language-ts">type Reading =
  | { kind: 'read'; test: TestCode; value: number; unit: CanonicalUnit }
  | { kind: 'absent'; test: TestCode }                       // the document doesn't contain it
  | { kind: 'unreadable'; test: TestCode; reason: string }   // it's there, we couldn't read it
  | { kind: 'estimated'; test: TestCode; value: number; unit: CanonicalUnit; basis: string };
</code></pre>
<p>The difference between <code>absent</code> and <code>unreadable</code> is the whole point. "The lab didn't run this test" and "my parser failed on this line" look identical in a database column (an empty cell), and they mean opposite things. One is a fact about the patient's report. The other is a bug in my system.</p>
<p>I learned how much this matters by looking at the empty cells. Many of them were tests that had simply never been performed: correct, nothing to fix. But some came from a wrong upload: a test <em>request</em> form, uploaded where the report should have gone. A request form lists test names with no results next to them. A naive parser reads it as "a report where everything is missing", and that's a lie told with a straight face.</p>
<p>So one rule is cheap and catches it: <strong>a document with no values at all is not an empty report. It's a stop.</strong> Someone has to look at it.</p>
<p>Password-protected PDFs belong here too. They exist, and they arrive. A locked file must never become "zero values found": it gets its own outcome, <code>locked</code>, and goes to a person, who can get the password from the lab or ask for a new copy.</p>
<h2>Some values are never estimated</h2>
<p>Is an estimate ever acceptable? Sometimes, and the doctor needs to know when. The rules I work with are:</p>
<ul>
<li>A <strong>critical</strong> value (an inflammation marker, for example) is <strong>never</strong> estimated. If it's missing, the report stops.</li>
<li><strong>At most one</strong> estimated value per report, and it is always declared, with a visible mark next to it. Never a silent one.</li>
<li>Everything else that the machine can't read goes to support.</li>
</ul>
<p>Which tests are critical and how many estimates are allowed are not decisions for the code. They are medical decisions, so they live in configuration, and the code only applies them:</p>
<pre><code class="language-ts">type ReportOutcome =
  | { kind: 'ready'; readings: Reading[] }
  | { kind: 'stopped'; reasons: StopReason[] };

function decideReport(readings: Reading[], policy: ReadingPolicy): ReportOutcome {
  const reasons: StopReason[] = [];
  if (readings.every((r) =&gt; r.kind === 'absent')) reasons.push({ kind: 'no-values-at-all' });

  for (const r of readings) {
    const critical = policy.criticalTests.has(r.test);
    if (critical &amp;&amp; r.kind !== 'read') reasons.push({ kind: 'critical-not-read', test: r.test });
    if (r.kind === 'unreadable') reasons.push({ kind: 'needs-a-person', test: r.test, why: r.reason });
  }

  const estimates = readings.filter((r) =&gt; r.kind === 'estimated').length;
  if (estimates &gt; policy.maxEstimatesPerReport) reasons.push({ kind: 'too-many-estimates', estimates });

  return reasons.length &gt; 0 ? { kind: 'stopped', reasons } : { kind: 'ready', readings };
}
</code></pre>
<p>The shape matters more than the details. The function never returns a number pretending to be a reading. It returns <code>ready</code> or <code>stopped</code>, and <code>stopped</code> always carries its reasons, so the person who picks it up knows what to look at.</p>
<h2>Units are where plausible numbers come from</h2>
<p>The system recognises and converts 123 units of measure automatically. That number sounds like overkill until you see the same value written two ways by two labs, a factor of 10,000 apart.</p>
<p>Think about what that means for a parser. Same patient, same test, same result: one lab prints a small number, another prints a number ten thousand times bigger, and both are correct in their own unit. Skip the conversion, or guess the factor, and you get a value that is perfectly readable, perfectly plausible as a number, and off by four orders of magnitude. The AI will happily guess the factor from the unit's name, because the name looks familiar.</p>
<p>NASA lost the Mars Climate Orbiter in 1999 to a cousin of this bug. The investigation board's report gives the root cause as a "failure to use metric units" in one ground software file: one side produced data in English units, the other expected metric, and nothing between them checked. Every individual number looked fine.</p>
<p>So the rules for units are strict:</p>
<pre><code class="language-ts">type Conversion =
  | { kind: 'converted'; value: number; unit: CanonicalUnit }
  | { kind: 'unknown-unit'; written: string };

function toCanonical(value: number, written: string, units: UnitTable): Conversion {
  const known = units.lookup(normalise(written));   // the table lives in configuration
  if (!known) return { kind: 'unknown-unit', written };
  return { kind: 'converted', value: value * known.factor, unit: known.canonical };
}
</code></pre>
<p>An unknown unit is not converted "by similarity". It becomes <code>unreadable</code>, and a person sees it. When they confirm what it means, add it to the table once, with a test, and from then on the machine handles it. A table can grow to a hundred entries and more that way without a single guess in it.</p>
<h2>The person is part of the system</h2>
<p>It's tempting to think of support as the exception handler. It isn't. When the data isn't enough, the system stops, and someone on the support side corrects it from a console: a value, but also a patient's name, date of birth, or email. That's not a failure of automation. It's half of the design.</p>
<p>Lisanne Bainbridge wrote about this in 1983, in "Ironies of Automation": the more you automate, the more the human is left with exactly the cases the machine couldn't handle, the hardest ones, often without the practice or the context to handle them well. So the console has to make the hard case easy: show the piece of the page next to the empty field, say why the machine stopped, and accept only the correction it asked for.</p>
<p>And every correction is recorded in a log that can't be rewritten. Pat Helland's paper "Immutability Changes Everything" has a section title that says it all: "Accountants Don't Use Erasers". A wrong correction is fixed by a new entry, never by editing the old one:</p>
<pre><code class="language-ts">type Correction = {
  reportId: string;
  field: string;
  previous: string | null;
  corrected: string;
  correctedBy: string;
  correctedAt: Date;
  reason: string;
};

// append is the only write: give the app's database role INSERT on this
// table, and no UPDATE or DELETE.
await corrections.append(correction);
</code></pre>
<p>Put the rule in the permissions, not just in the code. If the app can't run an UPDATE on that table, neither can the next feature your AI writes.</p>
<h2>And then you lock it in</h2>
<p>A rule in a comment is a rule the AI will forget. Next month I'll ask for support for a new lab format, the assistant will add a parser, and somewhere in it there will be a friendly <code>?? 0</code>.</p>
<p>So the guardrail is a test, and the test needs real data. Build a bench of real reports, anonymised, with an answer key for each one: which values are there, which are absent, which tests are critical. Include the ugly ones: the locked PDF, the request form uploaded by mistake, the lab with the odd unit. Then the test reads them all and counts:</p>
<pre><code class="language-ts">it('never estimates where an estimate is not allowed', async () =&gt; {
  const results = await readBench(anonymisedReports);
  const tally = countReadings(results, answerKey);

  expect(tally.estimatedCritical).toBe(0);
  expect(tally.reportsOverEstimateLimit).toBe(0);
  expect(tally.absentButActuallyPresent).toBe(0);   // "not there" must mean not there
  expect(tally.read).toBeGreaterThanOrEqual(baseline.read);
});
</code></pre>
<p>Each line guards a different lie. An estimate on a critical value: red. Two estimates on one report: red. A value the answer key says is on the page, reported as absent: red. A parser change that silently reads less than before: red. When a future change brings back the graceful fallback, this test fails, and the AI has to explain itself.</p>
<h2>The rule, in one line</h2>
<p><strong>When a system reads data for a doctor, stopping is a feature and guessing is a bug: every value must say whether it was read, absent, unreadable, or estimated and declared.</strong></p>
<p>It works well beyond medicine: invoices, bank statements, delivery notes, any document where a plausible wrong number costs more than a pause. Your AI assistant is very good at making code that never stops. Your job is to tell it where it must.</p>
<h2>Further reading</h2>
<p>The ideas here come from people who thought about them long before me:</p>
<ul>
<li>Lisanne Bainbridge, "Ironies of Automation", <em>Automatica</em>, vol. 19, no. 6, pp. 775-779 (1983).</li>
<li>James Shore, "Fail Fast", <em>IEEE Software</em>, vol. 21, no. 5 (2004), in the Design column edited by Martin Fowler.</li>
<li>NASA, <em>Mars Climate Orbiter Mishap Investigation Board Phase I Report</em> (November 10, 1999).</li>
<li>Pat Helland, "Immutability Changes Everything", CIDR 2015, section 2: "Accountants Don't Use Erasers".</li>
</ul>
<p>What I added is small: four states instead of one number, and a bench of real reports that turns red the moment a guess sneaks back in.</p>
<hr />
<p><em>I'm Matteo Mazzocchi, an Italian developer. I build CRMs and back-office systems for small businesses, with an AI pair and a lot of tests that say no. More about my work: <a href="https://mazzocchimatteo.com">mazzocchimatteo.com</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Make the database do the minimum: six rules I give my AI]]></title><description><![CDATA[I build CRMs and back-office systems for small Italian companies, and I write most of the code with an AI assistant. That works well for a lot of things…]]></description><link>https://mazzocchimatteo.hashnode.dev/make-the-database-do-the-minimum-six-rules-i-give-my-ai</link><guid isPermaLink="true">https://mazzocchimatteo.hashnode.dev/make-the-database-do-the-minimum-six-rules-i-give-my-ai</guid><category><![CDATA[database]]></category><category><![CDATA[postgres]]></category><category><![CDATA[AI]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Matteo Mazzocchi]]></dc:creator><pubDate>Wed, 25 Nov 2026 21:08:42 GMT</pubDate><content:encoded><![CDATA[<p>I build CRMs and back-office systems for small Italian companies, and I write most of the code with an AI assistant. That works well for a lot of things. It works badly for one thing in particular: the database.</p>
<p>My AI writes queries that are correct. They return the right rows, the tests pass, the page loads. With a hundred rows in the table. After a year of real use, the same page can take seconds, and the database plan you're paying for is suddenly too small.</p>
<p>The reason is simple. In my setups the database is the small, expensive resource, and the application server is the big, cheap one. Every query, every megabyte of database memory, has to justify itself. The AI doesn't know that. It writes the shortest code that works, and the shortest code usually asks the database to do more than it should.</p>
<p>One system I worked on had a sync loop that re-read calendars every minute "to see if anything changed". Nobody noticed it in development. In production, that one loop made most of all the requests the database received.</p>
<p>So I wrote the rules down. Here are six of them, the ones that make sense without any context.</p>
<h2>1. No reads inside a loop</h2>
<p>What the AI writes, if you let it:</p>
<pre><code class="language-ts">const orders = await db.query('select id, customer_id from orders where day = $1', [day]);
for (const order of orders) {
  order.customer = await db.query('select name from customers where id = $1', [order.customer_id]);
}
</code></pre>
<p>One query for the list, then one more for each row. This is the classic <strong>N+1 problem</strong>, and Markus Winand explains it well on use-the-index-luke.com, in the section on nested loops: it's usually an ORM doing it silently, but an AI does it just as happily by hand. With 10 orders it's invisible. With 2,000 it's 2,001 round trips.</p>
<p><strong>The rule:</strong> read each piece of data once per request, as a set. Independent reads start together, not one after the other.</p>
<pre><code class="language-ts">const orders = await db.query('select id, customer_id from orders where day = $1', [day]);
const customerIds = [...new Set(orders.map((o) =&gt; o.customer_id))];
const customers = await db.query('select id, name from customers where id = any($1)', [customerIds]);
</code></pre>
<p>Two queries, whatever the number of orders.</p>
<h2>2. Short, targeted reads</h2>
<p>What the AI writes:</p>
<pre><code class="language-ts">const all = await db.query('select * from contacts');
const open = all.filter((c) =&gt; c.status === 'open').slice(0, 50);
</code></pre>
<p>It reads every column of every row, ships them to Node, and throws most of them away. And on every page open it adds a <code>select count(*)</code> of the whole table, because the UI shows "1,234 contacts".</p>
<p><strong>The rule:</strong> only the columns you need (never <code>select *</code> on a wide table), filtered by columns that have an index, with a limit. Never "read everything and filter later". No exact counts of a big table on every page load.</p>
<pre><code class="language-ts">const open = await db.query(
  `select id, name, updated_at from contacts
   where status = $1 order by updated_at desc limit $2`,
  [ContactStatus.Open, config.contactsPageSize],
);
</code></pre>
<p>Plus an index on <code>(status, updated_at)</code>. Winand's <em>SQL Performance Explained</em> is the book that taught me why the index has to match both the filter and the order, and why a limit only helps when the database can stop early.</p>
<h2>3. Dashboards read a saved summary</h2>
<p>Ask an AI for "a dashboard with the number of open deals per stage" and you'll get one of two things. Either a big <code>group by</code> over the live tables on every page view, or, if you said "make it fast", a trigger that updates a counter on every insert and delete.</p>
<p>The first one gets slower every month. The second one is worse: every write now pays for the dashboard, the counter drifts the first time a bulk import skips the trigger, and nobody can explain why the number is wrong.</p>
<p><strong>The rule:</strong> a dashboard reads a small summary table with the numbers already computed. A background job rebuilds it on a slow schedule (the interval lives in configuration), and there's an "Update now" button next to "Last updated". The rebuild:</p>
<ul>
<li>runs <strong>one at a time</strong>: it takes a database lock without waiting, and if the lock is taken it answers "already running";</li>
<li><strong>replaces, never adds</strong>: it recomputes from the real rows, so a missed run can't leave a wrong total behind;</li>
<li>is checked every night against a real count, with an alert if they differ.</li>
</ul>
<p>And no triggers for counters or summaries.</p>
<pre><code class="language-ts">type RefreshOutcome = 'refreshed' | 'already-running';

async function refreshDealSummary(db: Db): Promise&lt;RefreshOutcome&gt; {
  return db.transaction(async (tx) =&gt; {
    const [{ locked }] = await tx.query(
      'select pg_try_advisory_xact_lock($1) as locked', [LockKey.DealSummary]);
    if (!locked) return 'already-running';

    await tx.query('delete from deal_summary');
    await tx.query(`insert into deal_summary (stage, open_deals, computed_at)
                    select stage, count(*), now() from deals where closed_at is null group by stage`);
    return 'refreshed';
  });
}
</code></pre>
<p><code>pg_try_advisory_xact_lock</code> returns immediately instead of waiting, and the lock goes away with the transaction. Two people pressing "Update now" at the same moment get one rebuild and one "already running".</p>
<h2>4. External calls after the response</h2>
<p>What the AI writes for "save the contact form and email me":</p>
<pre><code class="language-ts">await db.transaction(async (tx) =&gt; {
  await tx.query('insert into messages (...) values (...)', [...]);
  await emailProvider.send(notificationFor(message)); // waits on the network
});
</code></pre>
<p>It looks tidy: everything in one transaction. But the transaction stays open, holding a connection and its locks, for as long as the email provider takes to answer. On a slow day that's seconds, and connections are exactly what a small database has the fewest of.</p>
<p><strong>The rule:</strong> never keep a transaction open while you wait for an external service. Commit first, answer the user, then do the outside work (after the response, or through a queue).</p>
<pre><code class="language-ts">const message = await saveMessage(db, form);   // short transaction, committed
scheduleAfterResponse(() =&gt; notifyOwner(message));
return { status: 'received' };
</code></pre>
<p>This is how my own site handles its contact form: the message is saved, the visitor gets the answer, and the notification goes out after the response. If the notification fails, that has its own path (I wrote about uncertain deliveries in the first article of this series), but it never holds the database hostage.</p>
<h2>5. No state in the process</h2>
<p>This one is not about queries, but it ends in the same place: a system that breaks when it grows.</p>
<p>My site runs headless Chrome to read web pages, fill in forms and print PDFs. Each Chrome is heavy, and the server is shared with other systems. So there's a brake: a small semaphore that lets at most 2 Chrome instances run at the same time, puts the next requests in a first-come-first-served queue, and fails cleanly if a request waits too long. The limit and the wait come from configuration.</p>
<p>It works. But here's the honest part: the semaphore lives <strong>in the memory of one process</strong>. With one copy of the server, the limit is 2. Start a second copy behind a load balancer and each copy has its own semaphore. The limit is now 4, and nobody changed a line.</p>
<p>This is the stateless processes rule from Adam Wiggins' <em>The Twelve-Factor App</em>, factor VI: the memory of a process is fine for a brief cache, not for anything the next request depends on. Counters, limits towards providers, queues, tokens: they belong in the database or another shared place.</p>
<p>I've seen the expensive version of this mistake. Another system I worked on kept its rate limit towards a phone service in memory. When it went to several copies, the limit multiplied with them, and the provider started saying "too many requests".</p>
<p>So my site's project file says, in plain words, that it runs as <strong>one copy only</strong>, and that the Chrome brake and a few other in-memory counters must be rewritten before a second copy exists. I'd rather have a known, written limitation than an invisible one. If you can't fix it today, write down where it breaks.</p>
<h2>6. Measure first</h2>
<p>Every rule above can be overdone. An AI that has read them will happily add indexes nobody uses and summary tables for pages nobody opens.</p>
<p>Donald Knuth's famous line, "premature optimization is the root of all evil", comes from his 1974 paper <em>Structured Programming with go to Statements</em>. People quote only that half. In the paper, the next sentence says we should not pass up our opportunities in the critical 3%, and then he says that programmers' intuitive guesses about which code is critical fail, and that measurement tools are what tell you. The point is not "don't optimize". It's "measure, then optimize what the measurement shows".</p>
<p>On Postgres, <code>pg_stat_statements</code> counts time and rows for every query shape, and a slow-query log catches the rest. My site's database has both turned on. The rule I give my AI: every performance fix comes with the number before and after, and the command that produced it. Martin Kleppmann, in the first chapter of <em>Designing Data-Intensive Applications</em>, makes the same point from the other side: you can't talk about scaling until you've described your load and measured your performance.</p>
<h2>The check that blocks</h2>
<p>As always with an AI, a rule in a document is a rule it will forget the next time it writes a new page. So the rule has to become a test that goes red.</p>
<p>The test I want on every important action counts the database queries it makes, and fails if the number grows with the data:</p>
<pre><code class="language-ts">it('lists the day orders with a constant number of queries', async () =&gt; {
  const db = countingDb(testDb);              // wraps the client, counts every query

  await seedOrders(testDb, { count: 1 });
  await listDayOrders(db, today);
  const withOne = db.queriesMade();

  db.resetCount();
  await seedOrders(testDb, { count: 50 });
  await listDayOrders(db, today);

  expect(db.queriesMade()).toBe(withOne);     // 50 orders must not mean 50 more queries
});
</code></pre>
<p>There's no magic budget in it: the test only says that more rows must not mean more queries. When the AI brings back a read inside a loop, this goes red, and it has to explain itself.</p>
<p>I'll be honest: my rules file asks for this test on every action, but not every project of mine has it yet. It's the next check I'm adding, because it's the one that catches the mistake an AI makes most often.</p>
<h2>The rules, in one line</h2>
<p><strong>The database stores and finds; the application server computes, waits and remembers nothing.</strong></p>
<h2>Further reading</h2>
<p>The ideas here aren't mine. These explain them better:</p>
<ul>
<li>Markus Winand, <em>SQL Performance Explained</em> (self-published, 2012), and its free web edition, use-the-index-luke.com: the chapters on indexes, partial results and the N+1 problem (section "Nested Loops").</li>
<li>Adam Wiggins, <em>The Twelve-Factor App</em> (12factor.net), factor VI, "Processes".</li>
<li>Donald E. Knuth, "Structured Programming with go to Statements", <em>Computing Surveys</em>, vol. 6, no. 4 (ACM, December 1974).</li>
<li>Martin Kleppmann, <em>Designing Data-Intensive Applications</em> (O'Reilly, 2017): chapter 1, on describing load and performance.</li>
<li>The PostgreSQL documentation: "pg_stat_statements" and "Advisory Locks".</li>
</ul>
<p>What I added is small: turning each of them into a sentence my AI reads before it writes code, and, when it matters, into a test that says no.</p>
<hr />
<p><em>I'm Matteo Mazzocchi, an Italian developer. I build CRMs and back-office systems for small businesses, with an AI pair and a lot of tests that say no. More about my work: <a href="https://mazzocchimatteo.com">mazzocchimatteo.com</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[The unsubscribe link that only worked on paper]]></title><description><![CDATA[When I rebuilt an old email system, I found this. Every marketing email had an "Unsubscribe" link in the footer, pointing to a real endpoint. And clicking…]]></description><link>https://mazzocchimatteo.hashnode.dev/the-unsubscribe-link-that-only-worked-on-paper</link><guid isPermaLink="true">https://mazzocchimatteo.hashnode.dev/the-unsubscribe-link-that-only-worked-on-paper</guid><category><![CDATA[webdev]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Testing]]></category><category><![CDATA[privacy]]></category><dc:creator><![CDATA[Matteo Mazzocchi]]></dc:creator><pubDate>Wed, 25 Nov 2026 21:07:38 GMT</pubDate><content:encoded><![CDATA[<p>When I rebuilt an old email system, I found this. Every marketing email had an "Unsubscribe" link in the footer, pointing to a real endpoint.</p>
<p>And clicking it didn't unsubscribe anyone.</p>
<p>The footer link was a normal link, so clicking it sent a <code>GET</code>. The endpoint only accepted <code>POST</code>. The link existed on paper, in the code and in every email, and it did nothing for the one person who needed it.</p>
<p>Unsubscribing isn't a nice-to-have. Under the GDPR, Article 7(3) says withdrawing consent must be "as easy to withdraw as to give consent", and Article 21 says that when someone objects to direct marketing, their data can't be used for it anymore. I'm a developer, not a lawyer, so check with yours about what applies to you. But on the technical side, the lesson was clear, and it wasn't really about <code>GET</code>.</p>
<h2>What the AI writes if you let it</h2>
<p>Ask an AI assistant for "an unsubscribe endpoint" and you get something reasonable:</p>
<pre><code class="language-ts">export async function POST(req: Request) {
  const { email } = await req.json();
  await db.query(`update subscribers set active = false where email = $1`, [email]);
  return new Response('ok');
}
</code></pre>
<p>Then you ask for a webhook from your email provider, and it writes another <code>update</code>, slightly different. Then a recovery job, and a third one.</p>
<p>Now the rule "this person said no" lives in three places. One closes all sequences, one only the current one; one writes to the consent log, two don't. Each looks fine in its own pull request.</p>
<p>Andrew Hunt and David Thomas put this in one sentence in <em>The Pragmatic Programmer</em>: every piece of knowledge must have a single, unambiguous, authoritative representation within a system. They mean knowledge, not just code. "What happens when someone unsubscribes" is knowledge, and it's legal knowledge, which makes copies of it more expensive.</p>
<h2>One function, every door</h2>
<p>In my rebuild, the rule lives in one function that runs inside a transaction someone else opened. Everything that unsubscribes a person ends up there:</p>
<pre><code class="language-ts">type UnsubscribeOutcome =
  | { kind: 'unsubscribed'; closedSequences: number }
  | { kind: 'rejected'; reason: 'malformed' | 'bad-signature' | 'expired' | 'unknown-subscription' };

export async function unsubscribeWithin(
  tx: Transaction,
  deps: { secret: string; now: () =&gt; Date },
  rules: { tokenValidDays: number },     // from configuration, not from code
  request: { token: string; requestedAt: Date },
): Promise&lt;UnsubscribeOutcome&gt; {
  const token = readUnsubscribeToken(deps.secret, request.token, request.requestedAt, rules.tokenValidDays);
  if (token.kind === 'rejected') return token;

  const subscription = await findSubscription(tx, token.subscriptionId);
  if (!subscription) return { kind: 'rejected', reason: 'unknown-subscription' };

  const closedSequences = await closeAllSequencesFor(tx, subscription.email, 'unsubscribed', deps.now());
  await recordConsent(tx, {
    email: subscription.email,
    purpose: 'marketing',
    granted: false,
    source: 'unsubscribe-link',
    evidence: { sequence: subscription.sequence, subscription: subscription.id },
  });
  return { kind: 'unsubscribed', closedSequences };
}
</code></pre>
<p>A few decisions are hidden in there, so let me spell them out:</p>
<ul>
<li><strong>It closes every sequence for that address</strong>, not just the one the email came from. Someone who says "stop" doesn't mean "stop this newsletter, keep the other two".</li>
<li><strong>The "no" goes into a consent log</strong>, with where it came from. If someone asks "why did you stop writing to me?" or "why did you write to me after I said no?", there's an answer with evidence.</li>
<li><strong>The token is signed and has an expiry</strong>, and the expiry is checked at the time the person <em>clicked</em>, not the time the server got around to processing it. That matters for the next section.</li>
<li><strong>The token carries a subscription id, not the email address.</strong> Links end up in access logs. An email address in a URL is personal data in a log file.</li>
<li><strong>The outcome is explicit</strong>, not <code>true</code> or <code>false</code>: every caller knows why a request was refused.</li>
</ul>
<p>Then the doors. The route serves both methods with the same handler:</p>
<pre><code class="language-ts">export const GET = handleUnsubscribe;   // the footer link people click
export const POST = handleUnsubscribe;  // the one-click button in Gmail, Yahoo and others
</code></pre>
<p>The <code>POST</code> is not optional anymore. RFC 8058 (John Levine and Tobias Herkula) defines one-click unsubscribe: a <code>List-Unsubscribe</code> header with an HTTPS link, plus <code>List-Unsubscribe-Post: List-Unsubscribe=One-Click</code>. The mailbox shows an "Unsubscribe" button and sends a <code>POST</code> for the user. Since 2024, Gmail and Yahoo expect it from bulk senders, and Gmail also wants a visible link in the body.</p>
<p>There's a trade-off with the <code>GET</code>, and the RFC itself names it: anti-spam software often fetches links in emails automatically, without the user doing anything. A <code>GET</code> that unsubscribes can unsubscribe someone who never clicked. The alternative is a <code>GET</code> that shows a page with a confirm button. I chose the direct <code>GET</code>: a "no" too many costs me a reader, a lost "no" costs someone their right. Make that choice on purpose, whichever way you go.</p>
<p>The other two doors:</p>
<ul>
<li><strong>The email provider's webhook.</strong> A hard bounce closes all sequences for the address. An unsubscribe made in the provider's panel closes them and writes the "no" too. This one has no token, so it can't call <code>unsubscribeWithin</code>; it calls the same two pieces underneath, <code>closeAllSequencesFor</code> and <code>recordConsent</code>. If the webhook is lost, a periodic job asks the provider for blocked addresses and does the same.</li>
<li><strong>The recovery job.</strong> This one needs a story.</li>
</ul>
<h2>The "ok" that can't be taken back</h2>
<p>When the one-click button sends its <code>POST</code> and gets a <code>200</code>, the mailbox is done. It won't retry. The person has seen "you're unsubscribed". So if my database write fails after I said "ok", that "no" is gone.</p>
<p>So the route does two things, in two steps. First it stores the request (token and time of the click) in a table. Then it processes it, and <strong>the same transaction that runs <code>unsubscribeWithin</code> marks the request as processed</strong>:</p>
<pre><code class="language-ts">async function processStoredRequest(db: Database, id: string) {
  return db.transaction(async (tx) =&gt; {
    const claimed = await claimUnprocessedRequest(tx, id);  // update ... where processed_at is null returning ...
    if (!claimed) return { kind: 'already-processed' } as const;
    return unsubscribeWithin(tx, deps, rules, claimed);
  });
}
</code></pre>
<p>If anything inside fails, the transaction rolls back and the request stays unprocessed. A background job picks up requests older than a few minutes and calls the same <code>processStoredRequest</code>. Either the sequences are closed <em>and</em> the "no" is recorded <em>and</em> the request is marked, or none of them. And because the expiry is checked against the original click time, a token clicked on its last valid day still works when the job processes it later.</p>
<h2>The bug the tests couldn't see</h2>
<p>Here's the second lesson, and it's subtler than the <code>GET</code>.</p>
<p>A request must be processed once. That rule ended up in two places: the job's query that <em>lists</em> unprocessed requests (<code>where processed_at is null</code>), and the <em>claim</em> that marks one as processed (<code>update ... where processed_at is null</code>). Belt and braces. It looks like extra safety.</p>
<p>While building this, I removed the condition from one of the two places to see what would break. The tests stayed green: the other place covered for it. They only went red with both removed. So next month my AI assistant could "simplify" one guard away and nothing would say no, and the day someone touches the other one, a real person gets two entries in the consent log.</p>
<p>That question, "if I break this line, does any test notice?", has a name. It's <strong>mutation testing</strong>, and it goes back to R. A. DeMillo, R. J. Lipton and F. G. Sayward, "Hints on Test Data Selection" (1978): make small deliberate changes to the program, and check that your tests can tell the changed program from the real one. A change that no test notices is a test you're missing.</p>
<p>You don't need a tool to start. When the AI writes a guard, I ask it, line by line: <em>which test goes red if I delete this?</em> If the answer is "none", there are two honest fixes:</p>
<ol>
<li><strong>Decide which place is the rule.</strong> For me, the claim is the rule: it's atomic, inside the transaction, and it also protects against the route and the job racing each other. The list filter is just an optimisation.</li>
<li><strong>Test the rule directly.</strong> Process the same request twice, or let the job process it while the route is still in the middle, and assert one "no" in the consent log. That test fails if the claim loses its condition, no matter what the list query does.</li>
</ol>
<p>And write the trap down where the next session will read it. Mine is one line in the project's instructions file: the "once" rule lives in two places, removing it from one keeps tests green, change the rules only in <code>unsubscribeWithin</code>.</p>
<h2>And then you lock it in</h2>
<p>Every door gets its own test, because every door is a separate way to get it wrong:</p>
<pre><code class="language-ts">it('the footer link unsubscribes with GET and with POST', async () =&gt; {
  const link = unsubscribeLinkFrom(await sentEmail());

  expect((await request(link, { method: 'GET' })).status).toBe(200);
  expect(await openSequences('mario@example.com')).toEqual([]);
  expect(await lastConsent('mario@example.com')).toMatchObject({ granted: false, source: 'unsubscribe-link' });

  expect((await request(link, { method: 'POST' })).status).toBe(200);
  await runSequenceJob(later);
  expect(emailsSent()).toHaveLength(1);  // nothing after the "no"
});
</code></pre>
<p>Then the same shape for the rest: the job after a failed consent write (one "no", not zero, not two), the database down at the click, the route and the job racing, a bad token, a hard bounce, a lost webhook. If a door has no test, sooner or later it's the door that doesn't work. That's how the footer link went unnoticed.</p>
<h2>The rule, in one line</h2>
<p><strong>A legal rule lives in one function, every way in has its own test, and every guard has a test that fails without it.</strong></p>
<h2>Further reading</h2>
<ul>
<li>Regulation (EU) 2016/679 (GDPR), Article 7(3) "Conditions for consent" and Article 21 "Right to object", text at gdpr-info.eu.</li>
<li>J. Levine, T. Herkula, RFC 8058, "Signaling One-Click Functionality for List Email Headers" (IETF, 2017).</li>
<li>Google, "Email sender guidelines" (Gmail Help), and Yahoo, "Sender Best Practices" (Yahoo Sender Hub): the one-click unsubscribe requirements for bulk senders, in force since 2024.</li>
<li>Andrew Hunt, David Thomas, <em>The Pragmatic Programmer, 20th Anniversary Edition</em> (Addison-Wesley, 2019): "DRY: The Evils of Duplication".</li>
<li>R. A. DeMillo, R. J. Lipton, F. G. Sayward, "Hints on Test Data Selection: Help for the Practicing Programmer", <em>Computer</em> (IEEE), April 1978: where mutation testing starts.</li>
</ul>
<p>None of this is legal advice: it's the engineering side of a legal duty.</p>
<hr />
<p><em>I'm Matteo Mazzocchi, an Italian developer. I build CRMs and back-office systems for small businesses, with an AI pair and a lot of tests that say no. More about my work: <a href="https://mazzocchimatteo.com">mazzocchimatteo.com</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Timeout is not failure: the email bug every AI writes]]></title><description><![CDATA[I build back-office systems for small Italian companies: CRMs, booking flows, the boring machinery that sends the right email to the right person. I write…]]></description><link>https://mazzocchimatteo.hashnode.dev/timeout-is-not-failure-the-email-bug-every-ai-writes</link><guid isPermaLink="true">https://mazzocchimatteo.hashnode.dev/timeout-is-not-failure-the-email-bug-every-ai-writes</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[backend]]></category><category><![CDATA[webdev]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Matteo Mazzocchi]]></dc:creator><pubDate>Wed, 25 Nov 2026 21:06:15 GMT</pubDate><content:encoded><![CDATA[<p>I build back-office systems for small Italian companies: CRMs, booking flows, the boring machinery that sends the right email to the right person. I write most of that code with an AI assistant. I'm not hiding it, it's how I work.</p>
<p>And there is one bug my assistant writes almost every time, in every project, unless I stop it. It looks like good engineering. It passes the tests. And in production it sends your customer the same email twice.</p>
<h2>The code that looks right</h2>
<p>Ask an AI to "send the confirmation email, and make it robust", and you'll get something like this:</p>
<pre><code class="language-ts">async function sendConfirmation(booking: Booking) {
  for (let attempt = 1; attempt &lt;= 3; attempt++) {
    try {
      await emailProvider.send(confirmationFor(booking));
      return;
    } catch (err) {
      if (attempt === 3) throw err;
      await sleep(1000 * attempt);
    }
  }
}
</code></pre>
<p>Retries, backoff, a final throw. A reviewer would approve it. So would I, on a tired day.</p>
<p>The problem is hidden in that <code>catch</code>. It treats every error the same way: <em>the email didn't go out, try again</em>. That's true for some errors. For the most common one in production, it's not.</p>
<h2>What a timeout actually tells you</h2>
<p>Say the request to your email provider times out after 10 seconds. What do you know?</p>
<p>Not much. Maybe the request never left your server. Maybe it reached the provider, the provider queued the email, and the response got lost on the way back. Maybe the provider is just slow today and your email is already in the customer's inbox.</p>
<p>A timeout doesn't mean "failed". It means <strong>"I don't know"</strong>. This isn't news: it's one of the first things Martin Kleppmann explains about unreliable networks in <em>Designing Data-Intensive Applications</em>. When you get no answer, you can't tell a lost request from a lost response. But it's easy to forget when the code that handles it is three lines long and written by someone else, or by something else.</p>
<p>And when you retry on "I don't know", you sometimes send it twice. For a newsletter, that's embarrassing. For a booking confirmation, a password reset, an invoice or a medical report, it's a support ticket, or worse, a customer who stops trusting your system.</p>
<p>The tests don't catch it because the fake email provider in your tests either succeeds or fails cleanly. Real networks have a third state, and nobody wrote a test for it.</p>
<h2>First, the real fix (if you can have it)</h2>
<p>If your provider supports an <strong>idempotency key</strong>, use it. You send a unique key with each email, the provider remembers it, and a retry with the same key is ignored instead of sent again. That's how payment APIs make retries safe (Brandur Leach's write-up of Stripe-style idempotency keys is the classic explanation), and it's the answer Malcolm Featonby gives in the Amazon Builders' Library: make the write idempotent, then retry freely.</p>
<p>Many transactional email APIs don't offer that. The one I use doesn't document one. So the rest of this post is what you do when the other side can't deduplicate for you.</p>
<h2>Three outcomes, not two</h2>
<p>Sending an email then has three possible results:</p>
<ol>
<li><strong>Sent.</strong> The provider answered "OK".</li>
<li><strong>Refused.</strong> You know for sure it didn't go out: the provider rejected the request, or the request never reached it. Safe to retry.</li>
<li><strong>Uncertain.</strong> You asked and you got no clear answer. <strong>Never retry automatically.</strong></li>
</ol>
<p>In code, I make the third one a type of its own, so nobody (human or AI) can treat it like the others by accident:</p>
<pre><code class="language-ts">/** The provider rejected it, or the request never reached it: the email did not go out. Safe to retry. */
export class DeliveryRefused extends Error {
  override readonly name = 'DeliveryRefused';
}

/** We don't know if the email went out: no answer in time, or the connection broke after the request was sent. */
export class DeliveryUncertain extends Error {
  override readonly name = 'DeliveryUncertain';
}
</code></pre>
<p>The interesting part is deciding which is which. My rule: <strong>an error is "refused" only if it proves the email didn't go out</strong>. On the network side, that means the request never arrived: the DNS name didn't resolve, nobody was listening on the port, the network had no route, the connection was never opened. On the HTTP side, it means the provider looked at the request and said no (a 4xx). Everything else is uncertain, the timeout first of all, and a 5xx too: a gateway that answers 502 or 504 may have passed your request on before giving up.</p>
<pre><code class="language-ts">// network errors that prove the request never reached the provider
const NEVER_ARRIVED = new Set([
  'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED',
  'EHOSTUNREACH', 'ENETUNREACH', 'UND_ERR_CONNECT_TIMEOUT',
]);

// the email adapter: the only place that knows how the provider talks
async function sendEmail(msg: Message, config: EmailConfig): Promise&lt;void&gt; {
  let res: Response;
  try {
    res = await fetch(config.providerUrl, {
      method: 'POST',
      body: JSON.stringify(msg),
      signal: AbortSignal.timeout(config.timeoutMs),
    });
  } catch (err) {
    const code = networkErrorCode(err); // reads err.code or err.cause.code
    if (code &amp;&amp; NEVER_ARRIVED.has(code)) throw new DeliveryRefused(`never arrived (${code})`);
    throw new DeliveryUncertain('no answer, the email may have gone out');
  }
  if (res.status &gt;= 500) throw new DeliveryUncertain(`provider answered ${res.status}, it may have gone out`);
  if (!res.ok) throw new DeliveryRefused(`provider rejected it (${res.status})`);
}
</code></pre>
<p>Notice the default. When in doubt, the code says "uncertain". An AI tends to write the opposite: it lists the scary errors and treats everything else as "retry". The safe default has to be written down, because it's not the one that comes naturally.</p>
<p>(Reads are different. If a request that only reads times out, nothing changed on the other side, so you can retry it, with backoff, a little random jitter and a limit, as the Google SRE book and Marc Brooker's piece on backoff and jitter both recommend, so your retries don't pile onto a provider that is already struggling. The rule here is only about calls that <em>write</em>: send an email, charge a card, post a message.)</p>
<h2>Claim it before you send it</h2>
<p>Three outcomes are not enough on their own. If your server restarts in the middle of a send, the retry logic is gone, and a background job might pick up the "unsent" email and send it again.</p>
<p>So before sending, the code <strong>claims</strong> the email in the database. A claim is a row that says "this email is being sent, hands off". It's written and committed on its own, and the send happens after, with no database transaction left open while we wait for the provider. The send happens only if the claim succeeds, and what happens next depends on the outcome:</p>
<pre><code class="language-ts">type SendOutcome = 'sent' | 'already-claimed' | 'uncertain';

async function sendEmailOnce(id: string, send: () =&gt; Promise&lt;void&gt;): Promise&lt;SendOutcome&gt; {
  if (!(await claimEmail(id))) return 'already-claimed'; // someone else has it, or it's already done

  try {
    await send();
  } catch (err) {
    if (err instanceof DeliveryUncertain) {
      alertHuman(`email ${id}: outcome unknown, stays claimed, will NOT be resent`);
      return 'uncertain';                                  // the claim stays: nobody resends it
    }
    await releaseClaim(id);                                // only a sure "no" frees the claim
    throw err;
  }

  await markEmailSent(id).catch(() =&gt;
    alertHuman(`email ${id} went out but the mark failed: stays claimed, will not be resent`),
  );
  return 'sent';
}
</code></pre>
<p>Read the branches again, because each one is a decision:</p>
<ul>
<li><strong>Refused</strong> frees the claim, so the next run of the job retries it. Correct: we know it didn't go out.</li>
<li><strong>Uncertain</strong> keeps the claim and tells a person. The email is stuck on purpose. One stuck email a month is cheap; one duplicate medical report is not.</li>
<li><strong>Sent but not marked</strong> (the database write failed right after a successful send) also keeps the claim. Again: never resend.</li>
<li><strong>The process dies</strong> between the claim and the answer. Nobody is left to alert anyone, so the recovery job does it: a claim with no outcome, older than a few minutes, is treated as uncertain. It gets flagged, never resent.</li>
</ul>
<p>In the vocabulary of distributed systems, this is choosing <strong>at-most-once</strong> delivery: an email may occasionally need a human, but it never goes out twice. The opposite choice, at-least-once (the transactional outbox pattern that Chris Richardson describes in <em>Microservices Patterns</em>, for example), never loses a message but needs the receiver to deduplicate. Without an idempotency key, the receiver here is your customer's inbox, and inboxes don't deduplicate.</p>
<p>Two details that make the human part cheaper:</p>
<ul>
<li><strong>Ask the provider later.</strong> If your provider has an API for message events or logs, the recovery job can look up the uncertain email after a while and settle it on its own: found means sent, so mark it. Only what's still unknown reaches a person.</li>
<li><strong>No apology on uncertainty.</strong> When the outcome is uncertain, my flows also skip the "sorry, something went wrong" email. If the customer may already have the real one, an apology for a failure that maybe didn't happen is just a second confusing email.</li>
</ul>
<h2>And then you lock it in</h2>
<p>Here's the part that matters most when an AI writes your code: <strong>a rule in a comment is a rule the AI will forget</strong>. Next month I'll ask for a new email flow, the assistant will write the friendly retry loop again, and it will look fine.</p>
<p>So the rule becomes a test that fails. The fake email provider in my tests can do the nasty thing real networks do: accept the email, then time out.</p>
<pre><code class="language-ts">it('never resends an email whose outcome is uncertain', async () =&gt; {
  const provider = fakeProviderThatAcceptsThenTimesOut();

  await sendConfirmation(booking, { provider });
  await runRecoveryJob({ provider });            // the job that picks up "unsent" emails
  await sendConfirmation(booking, { provider }); // and a user clicking twice

  expect(provider.accepted).toHaveLength(1);     // one email reached the customer, not three
});
</code></pre>
<p>This test is the real guardrail. When a future change brings back the naive retry, the test goes red, and the AI has to explain itself. That's a pattern I use everywhere now: when I find a trap that matters, it doesn't go into a note. It goes into a check that blocks.</p>
<h2>The rule, in one line</h2>
<p><strong>A read can be retried. A write can be retried only if it's idempotent, or if you're sure it never arrived.</strong></p>
<p>It applies far beyond email: payments, SMS, WhatsApp messages, webhooks you call, anything that changes the world outside your database. Your AI assistant knows how to write a retry loop. What it doesn't know is which of your errors mean "I don't know". You have to tell it, and then you have to make the test suite remember.</p>
<h2>Further reading</h2>
<p>The ideas in this post aren't mine. I learned them from these, and they explain them better:</p>
<ul>
<li>Martin Kleppmann, <em>Designing Data-Intensive Applications</em> (O'Reilly, 2017): chapter 8 on unreliable networks and timeouts, chapters 11 and 12 on idempotence and exactly-once processing.</li>
<li>Malcolm Featonby, "Making retries safe with idempotent APIs", Amazon Builders' Library.</li>
<li>Marc Brooker, "Timeouts, retries, and backoff with jitter", Amazon Builders' Library (2019).</li>
<li>Brandur Leach, "Implementing Stripe-like Idempotency Keys in Postgres" (brandur.org, 2017).</li>
<li>Betsy Beyer, Chris Jones, Jennifer Petoff, Niall Richard Murphy (eds.), <em>Site Reliability Engineering</em> (O'Reilly, 2016): chapter 22, "Addressing Cascading Failures", by Mike Ulrich.</li>
<li>Chris Richardson, <em>Microservices Patterns</em> (Manning, 2018): the transactional outbox.</li>
</ul>
<p>What I added is small: the habit of turning each of these rules into a test, so the AI that writes my code can't forget them.</p>
<hr />
<p><em>I'm Matteo Mazzocchi, an Italian developer. I build CRMs and back-office systems for small businesses, with an AI pair and a lot of tests that say no. More about my work: <a href="https://mazzocchimatteo.com">mazzocchimatteo.com</a>.</em></p>
]]></content:encoded></item></channel></rss>