One data layer for three panels
By the end of this lesson you will have a src/lib/market-store.ts that turns overlapping requests for quotes into one, records when each answer was fetched and shares a request already in flight, tested with a fake fetcher, and a home page whose "as of" shows the oldest quote rather than the newest.
Two panels want AAPL. Fetched independently that is two requests for one fact, and this lesson is the piece of architecture that makes it one.
The price list, and why it decides the design
From Build Your First Tool, measured 2026-08-26:
| Endpoint | Calls per request |
|---|---|
/user |
0 |
/eod and friends |
1, whatever the row count |
/real-time |
1 per symbol |
/news |
5 per ticker |
/screener, /technical |
5 |
/fundamentals |
10 |
A cockpit multiplies whatever you get wrong here. Three panels each fetching their own quotes for an overlapping set of ten symbols is thirty calls where fourteen distinct symbols would have cost fourteen.
A request cache with one owner
One module owns fetching. Panels ask it for symbols; they never call the proxy themselves.
const quotes = await marketStore.quotes(["AAPL.US", "MSFT.US"]);
Three responsibilities, and each removes a class of bug:
Deduplicate within a tick. Collect every symbol asked for in the same frame, issue one request, hand the same rows to every caller. Two panels asking for AAPL simultaneously produce one fetch.
Cache with an explicit age. Store {rows, fetchedAt} and let panels ask how old it is. Never cache without recording when — a cache with no age is how a dashboard shows Tuesday's prices on Wednesday and looks fine doing it.
Share the in-flight promise. If a fetch for AAPL is already running, a second asker gets the same promise rather than a second request. Six lines, and it is what stops a re-render storm becoming a quota event.
One snapshot, one timestamp
Here is a fixture from a live multi-symbol response:
[{"code":"AAPL.US","timestamp":1787689680,"close":309.90},
{"code":"MSFT.US","timestamp":1787689680,"close":491.71},
{"code":"TSLA.US","timestamp":1787689740,"close":350.25}]
Two rows at 20:28:00 UTC and one at 20:29:00 — sixty seconds apart in the same response. The API is not being inconsistent; those are the last trades it had for each symbol, and thinly traded instruments are much further behind than a minute.
So a dashboard header reading "as of now" is false. Show the oldest timestamp in the set, because a cockpit is only as current as its stalest panel, and that is the number a person needs before acting.
Panels do not fetch
The rule that makes all of this hold: a panel receives data, it does not go and get it. A panel that fetches is a panel that cannot be reused, cannot be tested without a network, and will eventually duplicate a request some other panel already made.
This is the same boundary discipline as the transport layer in Build a Screener, one level up.
Try it now
Count the distinct symbols your three panels want on a typical view, then count the requests they currently make. The gap is what the data layer buys you, and it is usually two to three times.
The prompt
Mock mode on, plan mode on, and paste:
Plan a market store in a new src/lib/market-store.ts, made by a function
that takes the quote fetcher, the clock and a maxAge as parameters. Its
quotes(symbols) gathers every symbol asked for in the same tick into one
request for the union, keeps each row with its fetchedAt and serves it
again while it is younger than maxAge, and gives a second caller the
request already in flight. Add oldestTimestamp(rows). Write
tests/market-store.test.ts first with a fake fetcher that counts its
calls: two callers in one tick with overlapping symbols make one call for
the union, and asking again inside maxAge makes none. Then make the home
page's "as of" the oldest timestamp rather than the newest, and the age
printed beside it follow that same time. First, with
estimateCalls in src/lib/cost.ts, tell me what one home page load costs
now and after this change; it must not go up. Mock mode only. Run npm
test, typecheck, lint and check:leak, and show me the diff.
A good answer adds the store and its test and changes two things in src/app/page.tsx: the time is the oldest quote's, and the age beside it follows that time, or the page prints a newest-row age under an oldest-row time. The store does not import eodhdFetch: the fetcher comes in as a parameter, which is why the test needs no network and no mock. The dashboard starts using it in unit 2, from the browser, through the proxy.
Check it yourself
- The new tests went red on a stub and are green now; in the overlap test the fake fetcher counted a single call.
grep -n eodhdFetch src/lib/market-store.tsprints nothing.- In mock mode, open
fixtures/real-time.jsonand move the timestamp of the oldest row, VOD (LSE) (three and a half hours behind the others), an hour earlier. Reload the watchlist: the time above it moves back by an hour. Move a row that is not the oldest, such as AAPL, and the time stays put, because the header shows the stalest row and AAPL is not it. Put the fixture back. - The agent's price for one home page load is the same before and after the change.
Compare with ours
// src/lib/market-store.ts: one owner for fetching, and every row knows its age
export function createMarketStore(fetchQuotes: (symbols: string[]) => Promise<Row[]>,
now: () => number, maxAgeMs: number) {
const cache = new Map<string, { row: Row; fetchedAt: number }>();
const pending = new Map<string, Promise<void>>(); // queued this tick, or in flight
let tick: { symbols: string[]; done: Promise<void> } | null = null;
function enqueue(symbol: string): Promise<void> {
if (tick === null) {
const batch: string[] = [];
const done = Promise.resolve().then(async () => { // after this tick's callers
tick = null;
try {
for (const row of await fetchQuotes(batch)) cache.set(row.code, { row, fetchedAt: now() });
} finally {
for (const s of batch) pending.delete(s);
}
});
tick = { symbols: batch, done };
}
tick.symbols.push(symbol);
return tick.done;
}
const fresh = (s: string) => now() - (cache.get(s)?.fetchedAt ?? -Infinity) < maxAgeMs;
return {
async quotes(symbols: string[]) {
for (const s of symbols) if (!fresh(s) && !pending.has(s)) pending.set(s, enqueue(s));
await Promise.all(symbols.map((s) => pending.get(s))); // shared, never repeated
return symbols.flatMap((s) => cache.get(s) ?? []); // each with its fetchedAt
},
};
}
The full state at the end of this unit is on the starter's branch ref/build-a-dashboard/u1.
Checkpoint
npm test && npm run typecheck
git status # the files you expect, and no .env file
git add -A
git commit -m "One market store: a request per tick, an age on every row, in-flight shared"
Then answer this lesson's questions.