Blog

Running on one Cloudflare plan: from guarding free limits to $5 a month

Plainfeed is a website that shows new videos from the YouTube channels you pick, in upload order, with no algorithmic recommendations or Shorts. At the end of the first post I said the next technical post would be about running on a single Cloudflare plan and keeping strangers from using up D1's daily limits. In the meantime I moved from the free plan to the $5-a-month plan, so this post covers both: what I did on the free plan, and the numbers after switching.

The whole backend lives in one Cloudflare account.

Service What it does
Pages Static files and server functions (/api/*: feed, channel lookup, comments, sign-in and sync)
Two D1 (SQLite) databases User DB (each account's channels, feeds, watched videos) and cache DB (fetched videos per channel, daily budgets)
One Worker Scheduled jobs: new-video notification subscriptions every 10 minutes (with hourly stats inside), daily cleanup, and publishing scheduled posts each morning

A few terms first.

The free plan's limits

In short: the free plan has daily limits across the whole account, and when you hit one, the server stops for the rest of the day.

These are the free limits as I noted them in October. They reset at midnight UTC (9 a.m. in Korea).

What Daily limit When exceeded
Server function requests (Pages Functions and Workers combined) 100,000 Server functions stop for the day. Static files are still served
D1 rows written 100,000 Every DB query fails, so sign-in and sync stop too
D1 rows read 5 million Same
Outbound calls per invocation 50 That request fails

For one person, that's plenty. The problem was that the feed, channel lookup and comments APIs can be called by anyone, without signing in. I built it that way so people can try it from the home page without an account.

Ways a stranger could use up the limits

In short: when I ran the numbers on October 28, one determined person could use up a daily limit in anywhere from a few minutes to a few hours.

I had a Cloudflare rate-limiting rule per IP (20 requests per 10 seconds). It stops bursts, but someone calling steadily about once a second stays under it and can still make over 80,000 calls a day from a single IP. With the structure I had then, the math looked like this:

Path Cost per request Time to hit the daily limit
Feed for 30 already-cached channels about 540 rows read 2–3 hours for 5 million reads
Feed with real channel IDs swapped each time about 1,100 rows written a few minutes for 100,000 writes
Channel lookup and comments with URLs, videos or page tokens swapped 1–2 YouTube API units a few hours for the 10,000-unit YouTube quota

Hitting a D1 limit doesn't just stop the feed. Queries to the user DB in the same account fail too, so sign-in and sync stop for the day. So I changed two things.

Fix 1: one row per channel

In short: I moved to one row per channel, so a feed for 30 cached channels now reads 30 rows.

Before, I stored a row per video and also had a time index. That meant a feed also read the video and channel info tables, about 540 rows in all. I changed it to one row per channel, with the RSS result and each video's duration and live state packed into that row as JSON. I also dropped the time index from the cache tables (D1 counts a row in each index when you write an indexed column).

One feed request Before After
Read 30 cached channels about 540 rows 30 rows
Write for 30 new channels about 1,100 rows about 150 rows

Now even if all 100,000 daily function requests were used, reads would come to 3 million rows, short of 5 million.

Fix 2: daily budgets

In short: expensive work (fetching new channels, refreshing, channel lookups, comments, fallbacks) gets a daily cap, counted both overall and per requester.

Fetching a channel for the first time still costs writes and YouTube quota. So I keep a daily budget in the cache DB and do only that much each day. Past the cap, that work is skipped and the request is answered from what's cached.

// Compare what a request wants to today's remaining budget: all or nothing per kind. Trimmed
for (const k of kinds) {
  grant[k] = used("all", k) + want[k] <= L.all[k]
          && used(who, k) + want[k] <= L.client[k];
  if (!grant[k]) continue;
  mine[k] = want[k];                                   // per requester: exact
  if (rand() < Math.min(1, want[k] / step[k]))         // overall: approximate, now and then
    all[k] = Math.max(want[k], step[k]);
}

If the budget table is missing or can't be read, requests go through anyway. A budget that takes the site down would cause the very thing it's meant to prevent.

What code couldn't cap: request counts

In short: server function requests are counted the moment they reach a function, so code can't reduce them.

The two fixes above put a ceiling on D1 and YouTube quota. But if requests alone passed 100,000 in a day, server functions would still stop for the day. The conclusion I wrote in the design doc at the time was "move to Workers Paid ($5 a month) when usage grows." On the paid plan, going over doesn't stop anything; you pay for what you use (about $0.30 per extra million requests).

November 7: $5 a month

In short: on the day Google approved the OAuth verification, I switched to the paid plan because I wanted to experience running a real service.

I didn't switch because I'd hit a limit. It was the day importing subscriptions with a Google account went live, and I wanted to pay for and run a service myself.

To keep the switch small, I'd already gathered every number that differs by plan into lib/plan.js. After changing the plan in the dashboard, I only set PLAN to "paid" in three places across two config files and deployed.

// Numbers that differ by plan (trimmed). Paid numbers when env.PLAN is "paid"
export const PLANS = {
  free: { maxCalls: 48,  maxFallback: 6,  websubPerRun: 40,
          budget: { all: { new_channel: 1000, refresh: 20000 /* … */ } } },
  paid: { maxCalls: 100, maxFallback: 15, websubPerRun: 100,
          budget: { all: { new_channel: 5000, refresh: 100000 /* … */ } } },
};
export const planOf = (env) => PLANS[env?.PLAN === "paid" ? "paid" : "free"];
Number Free Paid
Outbound calls per feed request 48 100
Channels fetched via fallback per request when RSS fails 6 15
New-video notification subscriptions per scheduled run 40 100
Daily refresh budget (overall) 20,000 100,000
Daily new-channel budget (overall) 1,000 5,000

Order mattered. Setting "paid" before changing the plan would have made feed requests exceed the free plan's 50 outbound calls and fail. Reviewing it again that day, I found one more thing: Cloudflare counts D1 calls as outbound calls too (about 8 per feed request). So I left a note in the code that if I ever go back to the free plan, the limit has to drop to 40 or lower, not 48.

Some things stayed the same. The YouTube quota (10,000 units a day) has nothing to do with the Cloudflare plan, so the lookup and comment budgets stayed the same and fallbacks only went up 1.5×. The new-channel budget went up 5×, but at about 0.32 units per channel, even using all of it comes to around 1,600 units. The number of channels per request (30) stayed too. An invocation opens at most 6 outbound connections at once on either plan, so sending several requests of 30 in parallel is faster.

What I actually used

In short: from November 7 to the morning of the 25th (about 18 days) there were about 18,300 requests, 0.2% of the 10 million included each month, and the bill is still the base $5.

I checked these on the morning of November 25 in the dashboard and with wrangler d1 info.

Item Used Included in the paid plan
Requests (Nov 7 – morning of Nov 25, whole account) about 18,300 10 million / month
CPU time (same period) about 168,000 ms 30 million ms / month
Paid on top $0
Site function requests (last 24 hours) 1,174, 0 errors
Scheduled Worker (runs per day on its schedule) 146
Cache DB writes · reads (last 24 hours) 3,696 · 44,045 rows
User DB writes · reads (last 24 hours) 41 · 11,553 rows
DB size cache 3.99 MB · user 176 KB
Bars comparing the last 24 hours with the free plan's daily limits. Function requests: about 1,300 of 100,000 (1.3%). D1 writes: about 3,700 of 100,000 rows (3.7%). D1 reads: about 56,000 of 5 million rows (1.1%).
Current use is far below even the free plan's daily limits.

Going by current use alone, the free plan would be enough. Most cache DB writes come from the scheduled job every 10 minutes (new-video notification subscriptions) and from rewriting a channel's row when a new video comes in. I switched anyway so that the site keeps running that day even if someone hammers it or traffic suddenly grows. Going over just means paying for what's used.

Wrapping up

On the free plan my biggest worry was "it stops when it hits a limit," so I moved to one row per channel and put daily budgets in place. Request counts were the one thing code couldn't cap, so I moved to the $5-a-month plan. It's money going out every month for a personal project, but as the price of running something like a real service, I think $5 is on the cheap side.

How I saved YouTube API quota is covered separately in Living on 10,000 YouTube API units a day.

Keep reading

All posts