跪拜 Guibai
← Back to the summary

Optimize Paginated Lists: Cache Promises, Patch Rows, and Cut Count Queries

In modern frontend admin projects, the list page is the most common business page: table filtering, pagination switching, detail editing - every admin system has to handle it. But when a list page becomes slow, the problem often isn't in a single point:

These three issues require completely different handling; it's hard to cover them with a single "convenient fix" patch. This article splits them into request caching, single-row refresh, and total count calculation, and provides code that can be used directly.

Scope: The examples are based on Vue 3, TypeScript, axios, and an Express-style Node.js service. The cache key, request race, invalidation scope, and count degradation ideas also apply to React or other backend frameworks, but the request cancellation API must be replaced with the corresponding runtime.

1. Request Interface Caching

When accessing a specific page, cache the corresponding paginated data. When switching back to a cached page number, read the cached data directly:

1.1. Optimizing the Request Method Wrapper

Request and Response Interceptor Wrappers

Canceling Duplicate Requests

Caching Request Results

Note: The cache key must distinguish between different filters, sort orders, page numbers, and page sizes on the same API. It is recommended to use JSON.stringify to generate the key in a fixed field order; don't just concatenate user input. Otherwise, a=1&b=12 and a=12&b=1 might produce the same string.

// utils/requestCache.ts
interface CachedRequestConfig {
  method?: string
  url?: string
  params?: Record<string, unknown>
  data?: unknown
}

export function createRequestKey(config: CachedRequestConfig) {
  return JSON.stringify({
    method: (config.method ?? 'get').toLowerCase(),
    url: config.url,
    params: config.params ?? null,
    data: config.data ?? null,
  })
}

Caching the Promise allows repeated triggers for the same page to share a single request. If the first request is still in flight, subsequent triggers wait for the same result, reducing the load on the API.

// utils/axiosPagination.ts
import axios, { type AxiosRequestConfig } from 'axios'
import { createRequestKey } from './requestCache'

interface CachedEntry {
  promise: Promise<unknown>
  expiresAt: number
}

const pendingRequestMap = new Map<string, AbortController>()
const responseCacheMap = new Map<string, CachedEntry>()

interface PaginationRequestConfig extends AxiosRequestConfig {
  cache?: boolean
  cacheTTL?: number
}

export const http = axios.create({ timeout: 10_000 })

http.interceptors.request.use((config) => {
  const paginationConfig = config as PaginationRequestConfig
  const key = createRequestKey(paginationConfig)

  if (paginationConfig.cache) {
    const cached = responseCacheMap.get(key)
    if (cached && cached.expiresAt > Date.now()) {
      paginationConfig.adapter = () => cached.promise
      return config
    }

    if (cached) responseCacheMap.delete(key)
  }

  if (pendingRequestMap.has(key)) {
    pendingRequestMap.get(key)!.abort()
    pendingRequestMap.delete(key)
  }

  const controller = new AbortController()
  config.signal = controller.signal
  pendingRequestMap.set(key, controller)

  return config
})

http.interceptors.response.use(
  (response) => {
    const config = response.config as PaginationRequestConfig
    const key = createRequestKey(config)
    pendingRequestMap.delete(key)

    if (config.cache) {
      responseCacheMap.set(key, {
        promise: Promise.resolve(response),
        expiresAt: Date.now() + (config.cacheTTL ?? 30_000),
      })
    }

    return response
  },
  (error) => {
    const config = error.config as PaginationRequestConfig | undefined
    if (config) pendingRequestMap.delete(createRequestKey(config))
    return Promise.reject(error)
  },
)

export function clearPaginationCache(urlPattern?: RegExp) {
  if (!urlPattern) {
    responseCacheMap.clear()
    return
  }

  for (const key of responseCacheMap.keys()) {
    if (urlPattern.test(key)) responseCacheMap.delete(key)
  }
}

The following data needs a more conservative cache policy, and it's best to bypass the old result entirely:

When invalidating the cache, don't just clear the current page. Handle it based on the business impact scope:

function refreshOrderCache(orderId: string) {
  clearPaginationCache(/"url":"\/orders"/)
  return http.patch(`/orders/${orderId}`, { status: 'paid' })
}

If the modification only affects the display of a single row, you can clear only the detail cache; if the modification affects sorting, filter results, or the total amount, you should clear the entire list cache and refresh the current view.

1.2. Business Logic Request Optimization

Pre-request

Cancel Requests

Vue 3's Composition API can encapsulate race control and component lifecycle into a composable:

// composables/usePaginatedList.ts
import { computed, onBeforeUnmount, ref, shallowRef } from 'vue'
import { http } from '@/utils/axiosPagination'

interface PageResponse<T> {
  list: T[]
  total: number
}

export function usePaginatedList<T extends { id: string | number }>(
  url: string,
  initialQuery: Record<string, unknown> = {},
) {
  const query = ref({ page: 1, pageSize: 20, ...initialQuery })
  const list = shallowRef<T[]>([])
  const total = ref(0)
  const loading = ref(false)
  const error = ref<unknown>(null)
  let sequence = 0

  const pageCount = computed(() =>
    Math.max(1, Math.ceil(total.value / Number(query.value.pageSize))),
  )

  async function fetchPage(nextQuery = query.value) {
    const requestId = ++sequence
    loading.value = true
    error.value = null

    try {
      const { data } = await http.get<PageResponse<T>>(url, {
        params: nextQuery,
      })

      if (requestId !== sequence) return
      query.value = nextQuery
      list.value = data.list
      total.value = data.total
    } catch (err) {
      if (requestId === sequence) error.value = err
    } finally {
      if (requestId === sequence) loading.value = false
    }
  }

  function goToPage(page: number) {
    return fetchPage({ ...query.value, page: Math.min(Math.max(1, page), pageCount.value) })
  }

  function changePageSize(pageSize: number) {
    return fetchPage({ ...query.value, page: 1, pageSize })
  }

  function reload() {
    return fetchPage({ ...query.value })
  }

  onBeforeUnmount(() => {
    sequence++
  })

  return { query, list, total, pageCount, loading, error, fetchPage, goToPage, changePageSize, reload }
}

sequence solves the problem of old responses overwriting new ones. For example, if a user quickly switches from page 1 to page 5, and page 5's response arrives first, but page 1's response arrives later, the final display must be page 5.

If you use the old CancelToken from axios, at least ensure that only the last request for the same request key is kept, and cancel all on component unmount. For new projects, it's recommended to use AbortController, which is consistent with the cancellation semantics of the browser's Fetch API.




2. Refreshing a Single Row

When a user goes from the list to the detail page, or opens a detail modal to modify a record, the list needs to reflect that modification. There are three approaches with different costs:

Ps: You can cleverly use the pagination request to update a single row. Just calculate the index of the single row (page: index, size: 1) and handle it easily, without requiring the backend to provide a separate API for updating a single row.

In practice, it's recommended to handle it in two layers:

  1. Display field changes: only modify the current row, don't refetch the entire page. For example, remarks, tags, favorites
  2. Sorting, filtering, permission field changes: first update the current row, then silently refresh the current page. For example, status, amount, approval result

The reason is that modifying a detail page might change the sorting position. If you only replace the current row, the old position's data will remain on the current page, and when the user flips to the real position, they'll see the old data again.

// composables/usePaginatedList.ts
export function patchListItem<T extends { id: string | number }>(
  list: T[],
  updated: Partial<T> & { id: T['id'] },
) {
  const index = list.findIndex((item) => item.id === updated.id)
  if (index === -1) return list

  const nextList = [...list]
  nextList[index] = { ...nextList[index], ...updated }
  return nextList
}

async function refreshSingleRow<
  T extends { id: string | number },
>(composable: ReturnType<typeof usePaginatedList<T>>, orderId: T['id']) {
  const { data } = await http.get<T>(`/orders/${orderId}`)

  composable.list.value = patchListItem(composable.list.value, data)

  const affectsOrder = ['status', 'amount', 'createdAt'].some((key) => key in data)
  if (affectsOrder) await composable.reload()
}

A more common and stable API design is to have the detail page return the operation result, and the list page only updates the snapshot:

const { list, reload, query } = usePaginatedList<Order>('/orders')

async function afterDetailChanged(result: Partial<Order>) {
  list.value = patchListItem(list.value, result)

  if (result.status || result.amount) {
    await reload()
  }
}

If the detail page modification must ensure strong consistency with the list, you can include a version number in the route query or a global event. When the list page returns, compare the version number; if it has changed, refresh only the current page without clearing the scroll position.




3. Optimizing the Total Count in Requests

Long list APIs usually return both list and total. The backend's total can be an expensive count query; if the user sends this request on every page flip, the API spends time on repeated counting. The total count request needs its own design.

Ps: The backend API needs to support the optimized parameter handling, or provide a separate pagination total query interface.

The frontend can make "whether total is needed" an explicit parameter, keeping the default pagination request lightweight:

interface PageQuery {
  page: number
  pageSize: number
  keyword?: string
  status?: 'all' | 'paid' | 'refund'
  withTotal?: boolean
}

async function fetchOrders(query: PageQuery) {
  const { data } = await http.get('/orders', {
    params: {
      ...query,
      withTotal: query.withTotal ?? false,
    },
  })

  return data as {
    list: Order[]
    total: number | null
  }
}

Server-side handling:

app.get('/orders', async (req, res) => {
  const { page, pageSize, keyword, status, withTotal } = req.query
  const filters = buildOrderFilters({ keyword, status })

  const [list, total] = await Promise.all([
    orderRepository.findPage({
      filters,
      page: Number(page),
      pageSize: Number(pageSize),
    }),
    withTotal === 'true' ? countService.getOrderTotal(filters) : Promise.resolve(null),
  ])

  res.json({ list, total })
})

The total count can be cached by filter, but not indefinitely. A short TTL plus proactive invalidation is recommended:

const countCache = new Map<string, { value: number; expiresAt: number }>()

export async function getOrderTotal(filters: Record<string, unknown>) {
  const key = JSON.stringify(filters)
  const cached = countCache.get(key)

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

  const value = await orderRepository.count(filters)
  countCache.set(key, { value, expiresAt: Date.now() + 30_000 })
  return value
}

export function invalidateOrderTotal() {
  countCache.clear()
}

When filters change, page size changes, or the user performs a write operation, the total count must be recalculated or actively invalidated. Only when flipping pages under the same filter does the total usually not need to be recalculated.

Large admin systems can also accept approximate values:

SELECT reltuples::bigint AS estimated_rows
FROM pg_class
WHERE relname = 'orders';

Display lists can accept "about 120,000 entries"; financial reports and export progress need exact values. Whether to choose exact or approximate totals should be confirmed by the business side for the tolerance range; the frontend only passes the choice to the API.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

黎大仙

Aren't you killing real-time updates this way? The browser already supports ETag; if you want faster front-end fetches, you could add ETag computation and let the browser use cached data directly. You can't just cache data on the front end—when data updates, you won't get it, and then you have to consider stale time, making it more and more complicated.