API Optimization
API Optimization covers pagination, debouncing, cancellation, caching, deduplication, payload reduction, retries, and measurement.
Course: React — Routing & API Integration Lesson: 14
Learning objectives
Improve perceived and actual API performance using pagination, debouncing, caching, request cancellation, deduplication, batching, and careful retry policies.
Optimize the full request path
API performance is not only frontend code speed. It depends on network latency, server processing, database queries, payload size, caching, and rendering work.
User interaction-> Browser request-> Network / gateway-> Backend service-> Database / downstream services-> Response transfer-> Parse + state update-> React render
Measure where time is spent before choosing an optimization.
Pagination
Avoid downloading thousands of records when the screen displays only a small subset. Use server-side pagination with a documented contract such as page, pageSize, cursor, or nextCursor. Cursor pagination can be more stable for frequently changing datasets.
Debounce search
A search box can generate a request for every keystroke. Debouncing waits until the user pauses typing:
function useDebouncedValue(value, delay = 300) {const [debounced, setDebounced] = useState(value);useEffect(() => {const timer = setTimeout(() => setDebounced(value), delay);return () => clearTimeout(timer);}, [value, delay]);return debounced;}
Use the debounced value for API requests. The delay is a product decision; measure and tune it.
Cancel obsolete requests
When a user changes filters quickly, earlier requests may finish after later ones. Use AbortController or the data library's cancellation mechanism to avoid unnecessary work and stale updates.
Cache and deduplicate
Caching can avoid repeated requests for data that remains fresh. Deduplication can prevent multiple components from issuing the same request simultaneously. A server-state library may provide cache keys, stale-time policies, invalidation, and background refetching.
Cache keys must include every input that changes the result, such as tenant, user scope, filters, and pagination. Clear or isolate user-specific cache on logout or tenant switch.
Reduce payload and round trips
- Request only fields needed by the screen when the API supports it.
- Use pagination and filtering on the server.
- Consider endpoint aggregation or batching when multiple dependent calls create excessive latency.
- Compress responses at the server/gateway.
- Avoid sequential calls when independent requests can safely run in parallel.
- Use appropriate cache headers and conditional requests where supported.
Retry and rate limits
Retry transient failures with bounded backoff and jitter where appropriate. Respect Retry-After for 429 responses when provided. Do not retry unsafe mutations automatically unless the backend supports idempotency.
Measure
Track request duration, failure rate, payload size, cache hit rate, and user-perceived loading time. Use browser network tools and backend observability together.
Common mistakes
- Optimizing without measuring.
- Fetching the entire dataset for a paginated table.
- Debouncing but not cancelling stale requests.
- Caching data across users or tenants incorrectly.
- Retrying every failure immediately.
- Parallelizing requests that have dependencies.
Best practices
Start with measurement, use server-side pagination, debounce high-frequency input, cancel obsolete work, define cache freshness and invalidation, and coordinate frontend and backend optimization.
Interview questions & answers
Interview preparation
5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1What is request debouncing?
BeginnerModel answer
Waiting until high-frequency input (like search typing) pauses before firing the API request, reducing wasted calls.
2What makes a cache key correct?
BeginnerModel answer
It must include every input that changes the result—tenant, user scope, filters, pagination—and be cleared or isolated on logout/tenant switch.
Intermediate
3What is the difference between pagination and infinite scrolling?
IntermediateModel answer
Pagination loads discrete pages via page/cursor contracts.
Infinite scrolling appends the next page as the user nears the end—both should still be server-driven for large datasets.
4Why should retries use backoff and consider idempotency?
IntermediateModel answer
Immediate retries can amplify outages and duplicate unsafe mutations; bounded backoff/jitter and idempotent operations keep recovery safe.
Advanced
5How can stale responses overwrite current results?
AdvancedModel answer
If an older request finishes after a newer one, it can call setState with outdated data unless cancelled or ignored.
Practice
Optimize an order search page with debounced filters, server pagination, request cancellation, cache-aware refresh, and instrumentation for request duration.