Our Trading App Felt Slow. The Cause Wasn't One Big Bug — It Was a Pile of Small Waits.
Six optimizations across the WebSocket layer, background tabs, live charts and the post-login loader of a real-time React trading app, and the reasoning behind each.
We build a real-time trading web app in React. Over a few weeks we went through everything between the WebSocket and the loading screen. No single fix made the app fast. The slowness came from many small waits stacked on top of each other, so the work was finding and removing them one by one.
- Layer 1: the socket, with one connection and clear subscription ownership.
- Layer 2: background tabs, which need different rules from visible ones.
- Layer 3: connection health, because "open" doesn't mean data is flowing.
- Layer 4: the live chart, where gaps appear after a tab comes back.
- Layer 5: the post-login loader, where idle time can be put to use.
- Layer 6: caching, with one source of truth for every request.
1. One shared socket, with subscriptions owned by whoever needs them
The most common real-time mistake is every component opening its own connection. Charts, watchlists and order windows each hold a socket, and the server and the browser both pay for it. We moved to a single market-data socket that nobody else opens.
- Each screen subscribes to the instruments it shows and tags the subscription with a location key, for example pocketchart-<id>.
- When that screen unmounts, it unsubscribes only its own tag. One screen closing never cuts another screen's feed.
- Two screens can watch the same instrument. The feed stays alive until the last tag leaves.
- The subscriber list lives outside React state. A subscription change isn't a render, so it shouldn't trigger one.
- After a reconnect, we replay every active subscription from that list automatically. No screen needs to know the socket dropped.
// Simplified sketch: subscriptions keyed by instrument, then by owner tag.
const subs = new Map<string, Set<string>>(); // instrument -> location tags
function subscribe(instrument: string, location: string) {
const owners = subs.get(instrument) ?? new Set();
if (owners.size === 0) socket.send(subscribeFrame(instrument)); // first owner
owners.add(location);
subs.set(instrument, owners);
}
function unsubscribe(instrument: string, location: string) {
const owners = subs.get(instrument);
if (!owners) return;
owners.delete(location);
if (owners.size === 0) {
socket.send(unsubscribeFrame(instrument)); // last owner left
subs.delete(instrument);
}
}
// On reconnect, replay everything that is still wanted.
socket.onopen = () => {
for (const instrument of subs.keys()) socket.send(subscribeFrame(instrument));
};Ownership is what prevents leaks. If subscriptions have no owner, nobody knows who is allowed to remove them, so they pile up until someone clears everything and breaks another screen.
2. Treat background tabs differently
A hidden tab doesn't need 60 updates a second. Nobody is looking at it, and the browser is already throttling it. Doing full-rate work there wastes CPU and battery and makes the return worse.
- Slow all polling to every 5 seconds while the tab is hidden. Normal-rate work resumes when it becomes visible.
- Don't reconnect a dropped socket in a hidden tab. Wait until the user returns, then reconnect and resubscribe once.
- Reconnecting once on return avoids a retry loop running in a tab nobody can see.
const POLL_VISIBLE_MS = 1000;
const POLL_HIDDEN_MS = 5000;
const pollInterval = () => (document.hidden ? POLL_HIDDEN_MS : POLL_VISIBLE_MS);
document.addEventListener("visibilitychange", () => {
if (document.hidden) return;
restartPolling(); // back to normal rate
if (socketIsDown()) reconnect(); // the one deferred reconnect
});
function onSocketClose() {
if (document.hidden) return; // don't retry while nobody is looking
scheduleReconnect();
}3. Don't trust a socket just because it says "open"
Mobile browsers and flaky networks can leave a zombie socket. The connection reports readyState OPEN, but nothing is arriving. No close event fires, so your reconnect logic never runs and the screen quietly shows stale prices.
let lastMessageAt = Date.now();
socket.onmessage = () => { lastMessageAt = Date.now(); };
setInterval(() => {
if (document.hidden) return;
if (Date.now() - lastMessageAt > SILENCE_LIMIT_MS) {
socket.close(); // triggers the standard reconnect + replay
}
}, HEARTBEAT_CHECK_MS);4. Fix the gaps in the live chart
After a hidden tab, the chart was missing candles. The socket never dropped, so our "backfill after reconnect" logic never ran. The data was lost while the connection looked healthy, so a reconnect-based fix couldn't catch it.
- Trigger the backfill on the event that actually caused the gap: the tab returning after more than 10 seconds, or the network coming back online.
- Fetch the recent candles and merge them into the series.
- The merge replaces only the overlapping time range. Candles outside that range are untouched, so nothing duplicates and nothing is dropped.
- A short hide, under 10 seconds, skips the fetch because the live feed hasn't missed enough to matter.
function mergeBars(existing: Bar[], fetched: Bar[]): Bar[] {
if (fetched.length === 0) return existing;
const from = fetched[0].time;
const to = fetched[fetched.length - 1].time;
return [
...existing.filter((b) => b.time < from),
...fetched,
...existing.filter((b) => b.time > to),
];
}
document.addEventListener("visibilitychange", async () => {
if (document.hidden) return;
if (Date.now() - hiddenAt > 10_000) backfill();
});
window.addEventListener("online", backfill);Fix a bug where it starts, not where it is easiest to patch. The gap started when the tab was hidden, so that is where the repair belongs, not in reconnect handling.
5. Load data while the user is still reading the previous screen
Our post-login loader waited on five or more API calls, so users sat on a spinner right after logging in. But before reaching Home they spend a few seconds on the risk disclosure page, and that time was being wasted.
// Simplified sketch of the hand-off.
let pending: Promise<FirstLoadData> | null = null;
export function startFirstLoad() {
pending ??= fetchFirstLoadData(); // called from the disclosure page
}
export function takeFirstLoad(): Promise<FirstLoadData> {
const inFlight = pending;
pending = null; // use once, so nothing goes stale
return inFlight ?? fetchFirstLoadData(); // fallback: normal loading
}
// Lazy dashboard code can be fetched during the same idle time.
const preloadDashboard = () => import("./Dashboard");6. Keep one source of truth for each request
A prefetch is only useful if the screen reads what it fetched. If the prefetch and the component describe the same request in two places, they will eventually drift apart, and the cache warm-up silently stops working.
- The prefetch and the screen that displays the data share the same query key and the same query function.
- One definition per request means a change to the key or fetcher applies to both sides at once.
- The failure is quiet. Nothing errors when keys drift, the user just waits again, which makes it easy to miss.
// One definition, imported by both the prefetch and the component.
export const watchlistQuery = (id: string) => ({
queryKey: ["watchlist", id],
queryFn: () => fetchWatchlist(id),
});
// prefetch (before navigation)
queryClient.prefetchQuery(watchlistQuery(id));
// screen
const { data } = useQuery(watchlistQuery(id));Quick reference
- One shared socket: fewer connections, and subscriptions that clean up after themselves.
- Location-tagged subscriptions: closing one screen can't break another.
- Subscriptions outside React state: no renders for non-visual changes, and easy replay.
- Hidden-tab throttling to 5s: less CPU and battery spent on a tab nobody sees.
- Deferred reconnect: no retry loops in the background.
- Heartbeat on last message time: catches sockets that are open but silent.
- Backfill on tab return and network return: closes gaps the socket never reported.
- Range-based merge: no duplicate or dropped candles.
- Prefetch during idle screens: uses time the user was already spending.
- One shared query definition: prefetch and screen can't drift.
What I took from it
- Look at what the user is already waiting on, and use that time.
- Subscriptions need clear ownership, or they leak.
- A "connected" status doesn't mean data is flowing.
- Every fix has to cover the hidden-tab and bad-network cases, because users hit those daily.
Performance work on a real-time app is rarely a rewrite. It's finding every place the app waits, then asking whether it had to.
Honest caveat: some of this I've verified only in code and in the build, and I'm still watching real traffic to measure the gains. I'll share numbers when I have them. The snippets above are simplified sketches of the approach, not copies of production code.
Written by
Mohd Shahid Iqbal
SDE3 Frontend