
How We Cut API Calls by 85%: 4 Phases, Zero Data Loss (2026)
We were burning 15,000 API calls/day against a 2,000 budget. Here's how we fixed it in four phases — and improved the user experience along the way.
Nydar was making 15,000 API calls per day to our primary market data provider against a daily budget of 2,000. We were overshooting by 7.5x. Not by a little. Not by double. By seven and a half times our allocation. We diagnosed the problem, fixed it in four phases over 48 hours, and ended up with a better product than we started with — all without users noticing anything had changed.
If you're building any application that depends on rate-limited external APIs, this post is the full breakdown of how we went from 14,898 daily calls to under 2,000. The techniques aren't complicated, but the order matters, and the gotchas are real.
The data was still flowing because the provider throttles gradually rather than hard-blocking, but we were living on borrowed time. One policy change and our entire stock data pipeline goes dark. No quotes, no heatmaps, no analyst ratings, no institutional holdings. Everything that makes Nydar useful for stock traders — gone.
Why Not Just Buy More API Quota?
The obvious question. Our data provider offers paid tiers with higher limits. Two reasons we didn't upgrade.
First, the economics don't work at our stage. We're a growing platform, not a hedge fund. Moving to a plan covering 15,000 calls/day would cost more per month than our entire server infrastructure. According to RapidAPI's 2024 State of APIs report, the average API cost for financial data providers ranges from $200-2,000/month depending on call volume, and our usage pattern put us at the high end.
Second — and more importantly — buying more quota doesn't fix the underlying problem. If the architecture is making 7.5x more calls than necessary, paying for the rate limit just means paying 7.5x more than we should. Fix the root cause first. Scale second.
How Does Nydar's Data Pipeline Work?
Nydar supports three asset classes: stocks, crypto, and forex. Each has different data providers, different update frequencies, and different trading hours. The architecture:
- External APIs — providers for market data, quotes, analytics
- Backend data sources — Python classes wrapping each provider with authentication and caching
- In-memory cache layer — a dictionary with TTL-based expiration. No Redis, no external cache.
- REST endpoints — FastAPI routes that widgets call to get data
- WebSocket layer — persistent connection pushing real-time updates at configurable intervals
- Frontend widgets — 40+ customizable widgets rendering the data
Every API call happens at layer 2. The cache at layer 3 is supposed to prevent redundant calls. The WebSocket at layer 5 determines polling frequency. The waste was happening because layers 2, 3, and 5 weren't coordinating properly.
The Audit That Changed Everything
It started at 11 PM on a Tuesday. A routine check showed we'd used 14,898 of our 2,000 daily allocation. That's not a typo.
The system was behaving exactly as designed. The problem wasn't a bug — it was architecture. Nydar aggregates real-time data from multiple providers — live quotes, order books, analyst ratings, institutional filings, options chains, earnings calendars. Each feature makes API calls. Individually, each one is reasonable. Collectively, they were drowning us.
We rebuilt the API usage tracker with per-endpoint, per-symbol granularity. Let it run 24 hours, then looked at the results:
| Source | Calls/hour | The problem | |--------|-----------|-------------| | Forex rate lookups | ~991 | Each of 15 pairs hit the bulk rates endpoint individually — but that endpoint returns every rate in one response | | Heatmap quotes | ~3,843 | 25 individual stock quotes per refresh, fired sequentially, with 60-second cache | | WebSocket polling | ~480 | Polling every 30 seconds even when US market was closed | | Public snapshot | ~240 | Fetching 4 stock quotes every 120 seconds with no market-hours check | | TwelveData duplication | uncounted | A method bypassing cache entirely, duplicating what another method already does |
Four categories of waste: redundant calls, unnecessary calls, excessive calls, and duplicate calls.
How Did the Forex Fix Deliver a 93% Reduction?
The forex issue was the single most absurd finding. Our data provider has a /forex/rates endpoint — pass it a base currency like EUR, and it returns exchange rates for every quote currency in one response. EUR/USD, EUR/GBP, EUR/JPY, all of them. One call, all the data.
We were calling it once per pair. Fetching EUR/USD, EUR/GBP, and EUR/JPY meant three separate calls to the same endpoint, each returning identical data, extracting one rate and throwing away the rest. Multiply by 15 active forex pairs refreshing every 60 seconds: nearly a thousand wasted calls per hour.
The fix was embarrassingly simple: call /forex/rates?base=EUR once, cache the full response for 60 seconds, and have all EUR-based pair lookups read from that cache. One call instead of fifteen. A 93% reduction in forex API usage from a single architectural insight.
This is why auditing matters. The forex widget looked lightweight from the outside. Underneath, it was the most expensive feature per data point.
Phase 1: Stop the Bleeding
With audit data in hand, we tackled the four biggest offenders in order of impact.
Forex bulk caching — one call per base currency instead of one per pair. Forex API usage dropped from ~900 calls/hour to ~60.
Market hours gating — built an is_stock_market_open() utility that checks whether the US market is in regular trading hours (9:30 AM to 4:00 PM Eastern, accounting for DST). When closed, stock endpoints return stale cached data with a "market_closed": true flag. No API call at all.
This eliminated roughly 4,000 calls per day happening between market close and open. For 17.5 hours out of every 24, we were making API calls for data that literally cannot change. Pure waste.
But this one almost killed us.
The midnight UTC war story
Our first implementation used is_stock_market_active() instead of is_stock_market_open(). The "active" version includes pre-market (4 AM-9:30 AM ET) and after-hours (4 PM-8 PM ET). Seemed like the responsible choice.
The daily API counter resets at midnight UTC. Midnight UTC is 7 PM Eastern — right in the middle of after-hours. So every night:
- 11:59 PM UTC: Counter at 1,987 of 2,000. Throttled. Fine.
- 12:00 AM UTC (7 PM ET): Counter resets.
is_stock_market_active()returns true because after-hours runs until 8 PM ET. - 12:00:01 AM UTC: System thinks market is active with a fresh budget. Full-speed polling begins.
We had a widget polling 50 symbols every 30 seconds via the bulk tickers endpoint. At full speed with a fresh counter, it burned through 2,000 calls in under 30 minutes. By 12:30 AM UTC — still in after-hours — our entire daily quota was gone.
The fix was a one-word change: is_stock_market_active() to is_stock_market_open(). Regular hours only. Pre-market and after-hours data is genuinely useful, but not at the cost of your entire daily budget. This kind of timezone-arithmetic bug is documented in a 2023 ACM paper on temporal API failures as one of the most common causes of unexpected API overage charges.
Heatmap optimization — switched from sequential fetches to asyncio.gather() for parallel execution, bumped cache from 60s to 180s. Response time dropped from 5 seconds to under 1 second. Users were seeing a blank heatmap for five seconds on every refresh. Now it snaps in.
TwelveData deduplication — routed an uncached method through the cached path. Usage dropped ~50%.
WebSocket back-off — during market hours, polls every 30 seconds. Outside regular hours, backs off to 5 minutes. Still polling for corporate events or overnight moves, but at 1/10th the frequency.
Combined: estimated 60-70% reduction.
Phase 2: Graceful Degradation When You Hit the Wall
Even with a 70% reduction, there will be days when traffic spikes or someone has 40 widgets open. You'll hit your ceiling eventually. The question is: what does the user see?
Before our work, the answer was broken widgets. API calls failed with HTTP errors, the frontend showed generic error states or infinite spinners. Terrible.
We built three layers of protection.
Layer 1: Backend quota guard. Before every API call, we check a daily counter. If exhausted, we raise a typed QuotaExhaustedError immediately — no network call, no wasted time. This check happens in a single method that all 17+ endpoints flow through. One chokepoint, complete coverage.
Layer 2: Global exception handler. A FastAPI handler catches QuotaExhaustedError from any route and returns a structured 429 response. We also dealt with a provider quirk: our provider returns HTTP 403 when rate-limited, not the standard 429. Python's response.raise_for_status() turns 403 into a generic error, which was getting logged as a server error throughout the codebase. We built a _check_response() method that intercepts 403/429 and converts them to QuotaExhaustedError.
Layer 3: Frontend intelligence. An Axios interceptor catches 429 responses and rewrites the message to "Daily data limit reached — resets at midnight UTC." But we went further. Each widget has a smart WidgetErrorState component that checks context first. If the market is closed and there's a quota error, the user sees "Market Closed" with last known values — not "quota exhausted."
From the user's perspective, there's nothing wrong. The market is closed. That's why the numbers aren't moving. Showing a quota error would be technically accurate but experientially misleading. Ten widgets now use this dispatcher: Chart, VolumeProfile, MarketBreadth, IPO, ShortSqueeze, OrderFlow, OrderBook, AggregatedBook, LiquidationMap, and VolumeDelta.
What Does a User Actually See Before and After?
Here's what happened when someone opened Nydar at 10 PM on a Tuesday before the optimization:
- Chart widget: Loading spinner for 5 seconds, then "Error loading data"
- Order book: Infinite spinner
- Heatmap: Loaded after 5 seconds with random gaps where stock quotes failed
- Market breadth: "Something went wrong"
- Volume profile: Empty canvas
After:
- Chart widget: Day's chart with a "Market Closed" badge and closing price
- Order book: Last known state with "Market Closed" indicator
- Heatmap: Loads in under a second showing end-of-day sector performance
- Market breadth: Day's final breadth reading with closing timestamp
- Volume profile: Full day's volume profile — actually more useful at end of day
Every widget shows data. Every widget explains its state. No spinners, no errors, no confusion. The platform feels alive even when the market isn't.
Phase 3: Observability
The is_stock_market_active() bug taught us that we needed much better visibility into what the system was doing.
Per-endpoint, per-symbol tracking. Not just "you made 2,000 calls today" but "the heatmap endpoint made 847 calls, 340 of which were for AAPL." This resolution lets you spot anomalies instantly.
Rotating log files. Dedicated logs/api_usage.log with a rotating handler: 10MB per file, 5 files max. Roughly a week of history without unbounded disk growth. Every API call logged with timestamp, endpoint, symbol, and cache status.
Admin endpoint. Enriched /api/admin/api-usage to return top consumers, per-endpoint breakdowns, cache hit rates, and exhaustion status. A JSON endpoint we curl when we need to check things. It saved us on the first day — caught the midnight UTC regression within hours.
Throttled persistence. Stats accumulate in memory and flush to disk every 30 seconds, with an explicit flush on shutdown. One of those boring-but-essential details that separates production systems from prototypes.
Phase 4: Edge Cases and Defensive Coding
The paranoia phase. The kind of work that doesn't show up in metrics but prevents 3 AM pages.
Silent quota propagation. When QuotaExhaustedError gets raised inside a method, it can get caught by a generic except Exception block higher up the stack. Those blocks log at ERROR level. Quota exhaustion isn't an error — it's expected behaviour. With 15 forex pairs refreshing every 30 seconds, that's potentially 1,800 false-alarm ERROR entries per hour.
The fix is tedious but essential: add except QuotaExhaustedError: raise before every except Exception block in every method that might transitively call an API. The quota error punches through generic handlers and gets caught only by the global handler where it belongs.
Premium interest capture. When users encounter quota exhaustion during market hours (rare now, but happens on high-traffic days), they see a subtle call-to-action for premium access. The users who hit quota limits are, by definition, the most active users — multiple widgets open, checking data frequently, trading during peak hours. Exactly the people we want to talk to about a premium tier. The quota limit acts as a natural filter for our highest-value users.
We didn't plan this. It emerged from asking "what should the user see when we hit the wall?" and realising the answer isn't just an error message.
The Final Numbers
| Metric | Before | After | Change | |--------|--------|-------|--------| | Daily API calls | ~14,898 | <2,000 | -85% | | Forex calls/hour | ~991 | ~60 | -94% | | Off-hours waste | ~4,000/day | 0 | -100% | | Heatmap response time | ~5 seconds | <1 second | -80% | | Error logs from quota events | ~1,800/hour | 0 | -100% | | User-facing errors on quota | Broken widgets | "Market Closed" or graceful CTA | qualitative |
During market hours, data freshness is identical to before — we didn't increase any cache TTLs that affect real-time trading data. The 180-second heatmap cache is the only user-visible change, and for a sector heatmap, three-minute-old data is perfectly fine.
The DST problem deserves a note
Daylight Saving Time breaks any system that cares about US market hours. The NYSE opens at 9:30 AM Eastern, but "Eastern" means UTC-5 during winter and UTC-4 during summer. Hardcode the offset and your market-hours check breaks twice a year — silently.
We solved this using the browser's Intl.DateTimeFormat API with the America/New_York timezone. The browser handles DST transitions correctly via the IANA timezone database. No external API calls, no timezone libraries, no hardcoded offsets. The frontend knows what time it is in New York without asking anyone. Zero network overhead.
What We Learned
Audit before you optimise. We would have guessed wrong about the biggest offenders. Intuition generates hypotheses. Data tells you where to actually spend your time.
"Active" and "open" aren't the same thing. Pre-market and after-hours sessions exist and traders care about them. But they're not worth burning your entire daily budget on. If you need extended-hours data, budget for it explicitly.
Error states are features. The quota exhaustion UX is arguably better than what we had before. Users see contextual, market-aware status messages instead of generic spinners. A well-designed error state builds trust. A broken widget destroys it.
Typed exceptions beat boolean flags. QuotaExhaustedError as a proper exception type meant every layer could handle quota events explicitly. The global handler catches everything we forgot.
Observability pays for itself on day one. The per-endpoint dashboard caught the is_stock_market_active() regression within hours. Without it, we'd have woken up to another 15,000-call day with no idea why our fix didn't work. Every minute building observability saves hours debugging later.
Cache TTLs are product decisions. How stale can heatmap data be before it misleads a trader? Is 60-second-old data meaningfully different from 180-second-old data for a sector overview? These aren't questions engineers should answer alone. They require understanding what the user is doing with the data.
If you're building a trading platform — or any app aggregating data from rate-limited APIs — the pattern is: measure first, eliminate redundancy, respect time boundaries, design your error states, and build the dashboard before you need it.
We're now comfortably within budget with headroom for growth. Not bad for 48 hours of work.
Last updated: March 2026
Last updated: 21 March 2026