DEV Community

Free, Pro, and the API Boundary Between Them

A paywall has two halves. The visible half is a pricing page and a locked button. The half that decides whether you actually have a business is the server-side half: which requests are allowed, how many, for whom, and what happens when the answer is no.

On FundScope I kept the visible half deliberately plain - one free tier, one annual pass, no auto-renewal, no seat management, no invoicing. That left the server-side half as the real design problem: a single Express process, SQLite, and a public data proxy that must not be hammered by anonymous traffic. This is how the boundary is drawn, and why it is drawn there.

Start with a matrix, not with conditions

The failure mode I wanted to avoid is the classic one: if (user.isPro) { ... } scattered across a dozen handlers, each with its own idea of what Pro means. Six months later, a support question ("why can I see holdings but not export?") cannot be answered by reading code, only by testing.

So the first artifact is a tier matrix, written as data:

const TIERS = {
  anon: {
    dailyQueries: 10,
    perMinute: 20,
    fullHoldings: false,
    historyNav: false,
    compare: 1,
    export: false,
    watchlist: 1,
  },
  free: {
    dailyQueries: 20,
    perMinute: 30,
    fullHoldings: false,
    historyNav: false,
    compare: 1,
    export: false,
    watchlist: 1,
  },
  pro: {
    dailyQueries: Infinity,
    perMinute: 60,
    fullHoldings: true,
    historyNav: true,
    compare: 4,
    export: true,
    watchlist: 20,
  },
};

Everything else - the pricing table, the lock icons on the analysis page, the 429 response, the upgrade prompt - reads from this object or from an endpoint that serializes it. There is exactly one place where "Pro means unlimited daily queries but still 60 requests per minute" is written down.

The matrix also forces an honest conversation about what Pro actually sells. "Unlimited" is a bad promise if it means "unlimited until someone writes a loop." So Pro is unlimited daily fund queries and explicitly rate-limited per minute. That is a defensible product statement, and it is also the only version that survives contact with a scraper.

Counting the right thing

The quota counter is the part most likely to be quietly wrong. Two decisions fixed it early:

  • One query is one fund lookup, not one HTTP request. A single analysis page load calls /api/fund/info and /api/fund/holdings. If both counted, every user would burn two units per fund and the published daily limit would be a lie. So /api/fund/info is the metered call, and /api/fund/holdings is free once the info call has been admitted for that fund. The client passes the fund code; the middleware records it.
  • Anonymous users are counted by a hash, not by an IP address in the clear. The raw address is never stored. A salted hash gives you "same client, same bucket" for abuse control without turning your analytics table into a location database:
function subjectFor(req) {
  if (req.user) return `u:${req.user.id}`;
  const ip = req.ip || '';
  return `a:${sha256(ip + IP_SALT).slice(0, 16)}`;
}

The salt lives in the environment, not in the database, so a leaked backup does not let anyone reverse a hash by enumerating a few million IPv4 addresses. (It would only take minutes otherwise.)

The counter itself is a single row per subject per day:

CREATE TABLE IF NOT EXISTS usage_daily (
  day TEXT NOT NULL, -- YYYY-MM-DD in Asia/Shanghai
  subject TEXT NOT NULL,
  used INTEGER NOT NULL DEFAULT 0,
  updated_at TEXT NOT NULL,
  PRIMARY KEY (day, subject)
);

INSERT INTO usage_daily (day, subject, used, updated_at)
VALUES (?, ?, 1, datetime('now'))
ON CONFLICT (day, subject) DO UPDATE SET used = used + 1, updated_at = excluded.updated_at;

The day key is computed in the product's timezone, not the server's. A user in China who queries at 00:10 local time should get a fresh allowance; a UTC-based day key would reset at 08:00 and produce a support ticket that is impossible to explain.

A per-minute limiter sits in front of the daily counter and is intentionally dumb: an in-memory sliding window per subject, cleared on restart. It exists to stop a loop, not to enforce billing. If the process restarts mid-minute, a client gets a few extra requests - irrelevant. Storing minute buckets in SQLite would add write amplification for no benefit.

The 429 has to be a product surface, not an error dump

When the daily limit is hit, the response is not an empty body with status 429. It carries enough for the client to render a useful state:

{
  "success": false,
  "error": "DAILY_QUOTA_EXCEEDED",
  "tier": "free",
  "limit": 20,
  "used": 20,
  "resetAt": "2026-11-27T00:00:00+08:00",
  "upgradeUrl": "/pricing.html"
}

Three reasons this matters:

  • The UI can say "20 of 20 used today, resets at midnight" instead of "something went wrong."
  • The upgrade path is a server-provided URL, so changing the pricing route does not require a client release.
  • The same envelope is used for RATE_LIMITED and PRO_REQUIRED, so the client has one branch to handle, keyed by error.

For feature locks (full holdings, history, export) the status is 403 with PRO_REQUIRED, not 429. Mixing the two teaches users the wrong thing: a rate limit is temporary, a plan limit is a purchase decision. Different statuses, different copy, different buttons.

The client should render state, not decide it

The account page and the analysis page both start with the same call:

GET /api/me

{
  "tier": "free",
  "email": "u***@example.com",
  "entitlement": {
    "expiresAt": "2027-03-01T00:00:00+08:00"
  },
  "usage": {
    "day": "2026-11-26",
    "used": 7,
    "limit": 20
  },
  "features": {
    "fullHoldings": false,
    "historyNav": false,
    "export": false
  }
}

Then every lock is a pure function of features:

function renderLocks(me) {
  toggle(document.querySelector('#export-btn'), me.features.export);
  toggle(document.querySelector('#history-tab'), me.features.historyNav);
  if (!me.features.fullHoldings) showPreviewBadge('Top 10 holdings only');
}

This looks trivial, and it is - which is the point. The front end never asks "is this Pro?", because "Pro" is a marketing word that will change. It asks "do I have the fullHoldings feature?", which is the same key the server checks.

The corollary is uncomfortable but necessary: the client-side lock is cosmetic. Every gated response is also filtered on the server. If /api/fund/holdings returns 40 rows to a client whose UI only draws 10, the paywall is decoration. So the same handler that renders the table also truncates it:

const rows = tier.fullHoldings ? allRows : allRows.slice(0, 10);
res.json({ success: true, holdings: rows, truncated: !tier.fullHoldings });

truncated: true drives the "unlock full holdings" card. One field, no separate endpoint, no chance for the two to disagree.

What happens at the edges

Four edge cases consumed most of the debugging time, and each produced a rule:

  1. Anonymous → logged-in transition. An anonymous user who hits the limit and then signs in should not get a second full allowance in the same day under a different subject key. The login handler merges the anonymous counter into the user counter for the current day, capped at the free limit. Otherwise "log in to get 10 more" becomes a farmable exploit.
  2. Entitlement expiry is checked on read, not on a cron. There is no nightly job flipping users to free. Every request computes isPro = entitlement.expiresAt > now. A cron that fails silently would leave expired users with Pro access for days; a read-time check cannot drift. The renewal reminder email is a separate, best-effort job - nice to have, not load-bearing.
  3. Refunds revoke access immediately. A refunded annual pass sets the order to refunded and the entitlement to inactive. The user keeps the data they already saw, but the next gated request returns PRO_REQUIRED. This is the only behavior that makes refunds safe to offer without manual review.
  4. Shared IPs are not shared accounts. Two people behind the same NAT both browse anonymously. They share one hash bucket and therefore one daily allowance. This is a known, accepted trade-off: the alternative is a cookie-based identity, which is trivially cleared, or fingerprinting, which is worse for privacy. The mitigation is product copy, not more tracking - "log in for a higher daily limit" is honest and works.

Why this stayed small

The whole boundary is about 300 lines: one tier table, one middleware that resolves subject and tier, one counter upsert, and one response envelope. It runs inside the same Express process as the data proxy, against the same SQLite file. That is not an accident.

A one-server product should not need Redis for a counter, a queue for entitlement expiry, or a separate auth service to answer "is this user Pro?". Every piece of infrastructure you add is a piece that can be misconfigured at 2 a.m., and the failure mode of a quota system is not "slow" - it is "lets everyone in" or "locks everyone out."

The parts that do deserve separate machinery are the ones with external side effects: sending email, fulfilling payments, and sending notifications. Those go through an outbox table with a worker, because an HTTP request should not be the only record that something was supposed to happen.

Putting the tier matrix in one object, counting one metered call per fund, returning a structured 429, and letting the client render features instead of guessing them - that is the whole design. The pricing page is the easy part.

More notes on building small paid products are at wuhuajin.com. Originally published on wuhuajin.com.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.