Frontend Development 12 min read

Cache Strategies for API Layer and Request Timing Visualization in SSR Applications

This article explains how the Autohome front‑end team applied SSR, introduced a flexible API‑layer caching solution and a ServerTiming‑based request‑duration visualization to improve performance, maintainability, and user experience in both Node and browser environments.

HomeTech
HomeTech
HomeTech
Cache Strategies for API Layer and Request Timing Visualization in SSR Applications

The Autohome user‑product front‑end team applied SSR (Server‑Side Rendering) and hybrid rendering techniques to their PC and mobile main sites, achieving significant improvements in page rendering performance, white‑screen time, maintainability, and user experience.

Two main technical topics are covered:

API‑layer cache technology – how to use caching to optimize interface performance.

Request‑duration visualization – how to see interface request times directly in the browser.

Basic Rendering Concepts

The article reviews common rendering modes: SPA (Single Page Application), CSR (Client‑Side Rendering), SSR (Server‑Side Rendering), Prerender/SSG, and SSR‑Hybrid (a combination of server and client rendering to solve SEO and first‑screen speed issues).

API‑Layer Cache Solution

In the SSR architecture, caching is applied at multiple layers (CDN, Nginx reverse proxy, SSR rendering service, and API cache). The API cache layer ensures stable, fast query times, provides disaster recovery by returning historical data, and can be configured per‑endpoint.

Key features include:

One‑click global enable/disable with per‑endpoint overrides.

Support for different storage media (Redis, Node Cache, in‑memory, etc.).

Default activation for GET requests, extensible via advanced configuration.

Optional disaster‑recovery mode when upstream APIs fail.

Automatic synchronization of the cache-control header as cache TTL.

Implementation paths:

Using request/response interceptors to inject cache logic (intrusive).

Creating a custom Axios adapter that wraps the original adapter and adds caching (non‑intrusive, plug‑and‑play).

The team built a custom adapter that can be enabled with a single line of code without modifying existing business logic.

Example of a minimal custom adapter:

module.exports = function customAdapter(config) {
  return new Promise(function dispatchRequest(resolve, reject) {
    // ...other code
  });
};

Integration via an NPM package:

import { installCache, installRequest } from '@ace/request';

const { adapter } = installCache({
  ttl: 3 * 1000,
  // ...other cache parameters
});

// Integrate the adapter into an existing project
const reqIns = axios.create({
  baseURL: 'https://api.autohome.com.cn',
  adapter, // custom adapter
  // other options
});

Request‑Duration Visualization

Traditional performance monitoring relied on logging, which is cumbersome and delayed. The team introduced ServerTiming headers to expose request durations directly in the browser’s DevTools.

A Webpack loader (ServerTiming‑Loader) injects timing code during the build phase without touching business code, adding ServerTiming headers to responses.

In Next.js projects, the loader identifies getServerSideProps functions (using Babel AST parsing) and wraps them with timing logic:

/**
 * Define a new getServerSideProps that records duration
 */
const getServerPropsTempl = astTempl(`
  /**
   * Append getServerSideProps timing to Chrome Tools / Timing
   */
  const getPropsWithTimingLoader = async (cxt) => {
    const startTime = Date.now();
    const returnProps = await originalGetServerSideProps(cxt);
    const { res } = cxt;

    setServerTimingHeader(res, {
      key: 'API',
      value: `dur=${Date.now() - startTime}`,
    });
    return returnProps;
  };

  export const getServerSideProps = getPropsWithTimingLoader;
`, { placeholderPattern: false });

The AST traversal also handles different export syntaxes:

export const getServerSideProps = async () => {
  // ...code
};
export async function getServerSideProps() {
  // ...code
}

Unmatched patterns are left unchanged to preserve functionality.

Conclusion

By leveraging Axios’s dual‑environment support, custom adapters, and ServerTiming instrumentation, the team achieved non‑intrusive API caching, fine‑grained configuration, multi‑instance Redis sharing, and real‑time request‑duration tracking visible in browser DevTools, significantly enhancing SSR application performance.

References

Axios – https://github.com/axios/axios

Next.js – https://nextjs.org/

Server‑Timing – https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Server-Timing

Babel – https://babeljs.io/

Webpack – https://webpack.js.org/

NPM docs – https://docs.npmjs.com/cli/v8/configuring-npm/package-json

SSRaxiosNext.jsfrontend performanceAPI CachingServerTiming
HomeTech
Written by

HomeTech

HomeTech tech sharing

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.