Contents Lesson 11 of 18

9 min read · professional

Reviewing for cost

By the end of this lesson you will have a predicted and a measured price for one view of your screen page that agree, and a test that fails the day a change makes that view cost more.

Lens two. In a market tool, cost is not an abstraction about performance — it is your daily allowance, and running out means the tool stops.

The N+1 that costs money

A screen returns forty rows. The designer wants a sector label and a short description per row. An assistant, asked for that, writes:

const rows = await screen(filters);
const enriched = await Promise.all(
  rows.map(async (r) => ({
    ...r,
    profile: await fetchFundamentals(r.code),   // one request, 10 calls, per row
  })),
);

Correct output. Four hundred and five API calls where you expected five — a /screener request costs 5 and each /fundamentals request costs 10, both measured 2026-08-26 — and Promise.all fires them simultaneously, so you may also collect a rate-limit rejection on top.

The classic N+1, except each N is metered and billed. Notice it is invisible in the rendered page — the screen looks right, and the meter is the only thing that says otherwise. Which is why the meter has been on screen since Build Your First Tool lesson 4.

And the sector was already there. The screener response includes sector and industry:

{"code":"NVDA","sector":"Technology","industry":"Semiconductors", "...": "..."}

Forty extra requests, four hundred calls, to fetch a field that arrived in the first response. This is the most common cost bug in market tooling and it is always the same shape: not knowing what the payload already contains.

The refresh that never sleeps

Second pattern, from Build Your First Tool and worth re-checking here because a screen costs five times what a quote request does (5 calls against 1):

useEffect(() => {
  const t = setInterval(runScreen, 30_000);
  return () => clearInterval(t);
}, [filters]);

Two screens a minute, ten calls, from any open tab, whether or not anyone is looking. And the dependency on filters means every keystroke in a filter box tears down and restarts the timer — and if filters is rebuilt on each render rather than memoised, the effect re-runs every render, which is a screen per render.

There is no version of a screener that needs to auto-refresh every thirty seconds. It runs on the last completed session; the data does not change during your morning.

Three questions for the cost lens

  1. How many calls does this make? Count them, do not estimate.
  2. What does that number scale with? Rows, keystrokes, renders and open tabs are all multipliers, and only one of them is under your control.
  3. Is the data already in a response I have? Ask before adding a fetch, every time.

Measure rather than reason

You have an instrument. Read used from curl -s localhost:3000/api/usage (the starter's meter; the /user endpoint behind it is not reachable through the proxy), do the thing, wait a few seconds for the counter to catch up, read it again.

Do this after any change that touches fetching, because the arithmetic in your head is reliably optimistic and the meter is not. A change that quietly triples your cost per view is invisible in every other way.

Try it now

Read your screener's fetching code and write down the predicted number of calls for one page view. Then measure it with the meter. If prediction and measurement disagree, the gap is a bug you have not found yet — go and find it before reading the next lesson.

The prompt

Mock mode on, plan mode on, and paste:

Price one view of the screen page in API calls: list every request it
makes, with estimateCalls() for each, and say whether anything refetches
on a timer, per keystroke or once per row. Then add screenPageCalls() to
src/lib/screens.ts (if a function that prices the screen page already
exists, rename it screenPageCalls and extend it instead of adding a
second one), worked out from the
same request the screen page sends, the way pageLoadCalls() is for the
watchlist, and tests/screen-cost.test.ts asserting one view costs 5. No live request; I will measure. Done means
npm test, typecheck, lint and check:leak green; show me the diff.

A good answer names one screener request at five calls and an account read, if the page shows one, at none; adds screenPageCalls() and its test; and changes nothing else unless it found a timer or a per-row fetch, which it reports first.

Check it yourself

  1. The price came before your measurement and named each request.
  2. Mock mode off: curl -s localhost:3000/api/usage, one load of the screen page, a few seconds, the same curl again. used rose by five. This needs your own key on a plan that includes the screener, and no other tab or program using it: the shared demo key answers 403 on EODHD's screener endpoint and its counter moves with other people's requests, so on mock, demo or a free key rely on the test and the arithmetic instead.
  3. grep -rn setInterval src prints nothing.
  4. Change the test's expected 5 to 4 and run npm test: red, naming both numbers. Put it back.
Compare with ours
// src/lib/screens.ts: priced from the request it sends, so the number cannot drift
export const screenPageCalls = (req: ScreenRequest) =>
  (estimateCalls(req.path, req.params) ?? 0) + (estimateCalls("user") ?? 0);

// tests/screen-cost.test.ts
it("one view of the screen costs one screener request", () => {
  expect(screenPageCalls(screenRequest(new URLSearchParams("f=avgvol_1d:gt:1000000")))).toBe(5);
});

The full state at the end of this unit is on the starter's branch ref/build-a-screener/u3.

Checkpoint

npm test && npm run typecheck
git status   # only the files this step touched, no .env*
git add -A
git commit -m "Price the screen page from its own request: five calls, pinned by a test"

Then answer this lesson's questions.