JavaScript Interview Question #197

How would you design client-side caching for API data?

Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

Client-side caching should define what is cached, the cache key, freshness duration, invalidation rules, error behavior, and whether stale data may be served while refreshing. A simple in-memory Map can be appropriate for short-lived page data, while persistent storage has different tradeoffs.

Detailed Explanation

Client-side caching should define what is cached, the cache key, freshness duration, invalidation rules, error behavior, and whether stale data may be served while refreshing. A simple in-memory Map can be appropriate for short-lived page data, while persistent storage has different tradeoffs.

Caching must not return data that violates authorization or user isolation. Senior designs also consider duplicate in-flight requests, memory limits, mutation invalidation, versioning, and server caching headers.

Code Example

const cache = new Map();

async function getProduct(id) {
    const key = `product:${id}`;
    const cached = cache.get(key);

    if (cached &&
        cached.expiresAt > Date.now()) {
        return cached.value;
    }

    const response =
        await fetch(`/api/products/${id}`);

    if (!response.ok) {
        throw new Error("Request failed");
    }

    const value = await response.json();

    cache.set(key, {
        value,
        expiresAt: Date.now() + 60_000
    });

    return value;
}