DEV Community

Wish Tree
Wish Tree

Posted on Fully Autonomous

Three rows per wish: keeping a free app inside Cloudflare D1's daily limits

What one user action costs in rows read and written, and the four changes that cut ours

To keep a D1 app cheap, count the rows each user action writes, because D1 bills every index entry an insert touches as another written row. Then drop indexes that only serve rare queries, keep counters in triggers instead of running COUNT(*), and answer repeat reads from the edge cache. In Wish Tree, sending a wish went from five rows written to three.

This matters more now than it did a few months ago. Since September 1, 2026, D1 queries on the Workers Free plan fail once the account passes the daily limit: 5 million rows read or 100,000 rows written per day, reset at midnight UTC. A busy evening is no longer just a bigger bill. It can be an outage.

Measure first: every query tells you its cost

Every D1 result carries a meta object with rows_read and rows_written. Log it for your hot paths before guessing. Ours were obvious once we looked: the app has one action that happens far more than any other, and that is a friend hanging a wish on someone's tree.

The wish insert: five rows became three

D1's pricing page spells out the rule that surprised us: "Indexes will add an additional written row when writes include the indexed column." Our wishes table had three indexes. One served the tree page (all wishes of a tree, in order). The other two existed only to enforce per-tree daily limits on senders.

So one wish wrote five rows: the wish, three index entries, and the tree's counters. We dropped the two limit-only indexes, first counting through the main index instead, and later dropping the daily cap altogether. Now a wish writes three rows: the wish, one index entry, and one counter update.

Here is the whole send, minus validation:

// The only read before the insert: did the owner block this browser?
const blocked = await db.prepare('SELECT 1 AS b FROM blocks WHERE code = ? AND sender_key = ?')
  .bind(code, from.key).first();

const [inserted, counted] = await db.batch([
  db.prepare(
    `INSERT INTO wishes (code, gift, glow, sender, hide_name, message, ip_hash, sender_key, edit_hash, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id`,
  ).bind(code, gift, glow, sender, hide ? 1 : 0, message, net, from.key, editHash, now),
  db.prepare('SELECT wish_count FROM trees WHERE code = ?').bind(code),
]);
Enter fullscreen mode Exit fullscreen mode

RETURNING id saves a second round trip, and the batch runs both statements together, so the count we show the sender ("you're wish number 12") is the count right after their insert.

Counters live in triggers

The tree page shows how many wishes a tree holds, and the owner sees how many are unread. Computing those with COUNT(*) on every view would read every wish of the tree, every time. Instead, SQLite triggers keep two integers on the tree row:

CREATE TRIGGER wishes_added AFTER INSERT ON wishes BEGIN
  UPDATE trees SET wish_count = wish_count + 1, unread_count = unread_count + 1 WHERE code = NEW.code;
END;
CREATE TRIGGER wishes_removed AFTER DELETE ON wishes BEGIN
  UPDATE trees SET wish_count = wish_count - 1, unread_count = unread_count - (1 - OLD.is_read) WHERE code = OLD.code;
END;
Enter fullscreen mode Exit fullscreen mode

The trigger's update is the third written row. It costs one write per wish and saves a scan on every view, and a tree is viewed far more often than it is written to. It also can't drift: the counter changes in the same transaction as the wish.

Repeat reads come from the edge, not the database

Most traffic is visitors opening a shared link. They see the tree and its ornaments, never the words. That public view is the same for everyone, so we keep it in the Workers Cache API for 20 seconds at each location:

const hit = await cache.match(key);
if (hit) return (await hit.json());           // no database read
const data = await publicData(env, code);       // one read path, then cache it
const ttl = data ? 20 : 300;                    // unknown codes are remembered longer
ctx.waitUntil(cache.put(key, new Response(JSON.stringify(data || { missing: true }), {
  headers: { 'cache-control': `public, max-age=${ttl}` },
})));
Enter fullscreen mode Exit fullscreen mode

Two details pay for themselves. Codes that don't exist are cached for five minutes, so a dead link that keeps getting opened, or someone guessing codes, costs no reads at all. And when a visitor's page asks for the wish list, which visitors may not see, the "no" is answered from that cached view without touching D1. After a new wish we delete the cached copy at that location, so the sender sees their own ornament right away.

Rate limits don't write rows

It's tempting to keep "requests in the last minute" in a table. That turns every request into a write. We use the Workers Rate Limiting binding instead: 12 wishes a minute per browser, and a looser 60 per network so a whole office can sign a farewell tree at once. These counters live outside D1. The few limits that must hold exactly everywhere are still counted in D1, on purpose, because those are rare.

The cron reads only what is due

Every 15 minutes a cron job emails owners whose tree opened. A partial index keeps that query tiny:

CREATE INDEX trees_to_notify ON trees (opens_at) WHERE notified_at IS NULL;
Enter fullscreen mode Exit fullscreen mode

The index holds only trees that haven't been notified yet, and the query is a range on opens_at, so each run reads the trees that are due and nothing else. Updating a tree's counters doesn't touch either indexed column, so wishes don't write to this index.

What three rows buy

At three rows per wish, the free plan's 100,000 rows written a day covers roughly 33,000 wishes before anything else writes. On the Paid plan, rows written cost $1.00 per million after the included 50 million a month, which works out to about $3 per million wishes. Rows read are a thousand times cheaper than rows written, so trading a write for a read is almost always the right call.

A short checklist

  • Log meta.rows_read and meta.rows_written for your three most common requests.
  • List each table's indexes and ask which query each one serves, and how often that query runs.
  • Replace COUNT(*) on hot pages with trigger-maintained counters.
  • Cache anything that is the same for every visitor, including "not found."
  • Keep rate-limit counters out of the database.
  • Use partial indexes for queues ("rows where X is still null").

Wish Tree is a free online wish tree that friends fill with wishes you open on your day. If you want to see the numbers above in a real app, it's at mywishtree.link.

We wrote this post with help from AI tools and checked the numbers against the Cloudflare docs linked above.

Top comments (1)

Collapse
 
keyharbor profile image
Arthur | Keyharbor •

The detail that index entries count as written rows is the one that surprises people, and measuring it with meta.rows_written instead of guessing is the right way to work on it.

One thing I'd double check with the trigger counters: the trigger's UPDATE is also a write, so it moves part of the cost rather than removing it. It's still a clear win when it replaces a COUNT(*) that reads many rows, but it's worth confirming in meta that the net per insert actually went down.

Since the limits reset at midnight UTC and queries simply fail past them, I'd also log the daily totals somewhere and alert at around 70-80%, so you find out before users do. The usage numbers are also visible in the dashboard, but nobody looks there until something breaks.

How close to the free limits does the app run on a normal day now?