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:
- Duplicate requests are sent repeatedly; the same page of data is fetched multiple times
- After modifying a record in the detail page, the entire page is forced to refresh
- Every page flip makes the backend recalculate
total
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:
- Cache paginated data separately
- Cache request results
1.1. Optimizing the Request Method Wrapper
Request and Response Interceptor Wrappers
- request interceptor:
- Add login token
- Store axios cancel token for later use
- response interceptor:
- Global error handling for request responses
Canceling Duplicate Requests
_pendingRequestSetstores currently in-flight requests- The set's key is composed of [method, url, params, data] using string concatenation
- In the request interceptor/adapter logic, check
_pendingRequestSet- If the assembled key already exists in
_pendingRequestSet, use the axios cancel token generated in the request interceptor to cancel the request
- If the assembled key already exists in
Caching Request Results
_responseCacheMapstores response results- Same as the request, the key is composed of [method, url, params, data] using string concatenation
- In the response interceptor/adapter logic, check based on the request config parameters
- If the cache flag is enabled, first try to get the cached response via
_responseCacheMap.get(key)- If not present: use
_responseCacheMap.set(key, responsePromise)to cache the promise of the current request result - If present: return the previously cached response promise directly
- If not present: use
- If the cache flag is enabled, first try to get the cached response via
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:
- A list after the user just performed an add, modify, or delete
- Strong real-time fields like approval status, inventory, amount
- Search, monitoring, and risk-control pages that use
cache: false
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
- Before navigating to a page, send the request ahead of time, and store the wrapped request in a global request-promise map. Use the async processing time of the request to switch routes.
- After the page switch, get the corresponding request-promise from the global map in the route hook.
Cancel Requests
- Use hooks and axios's cancelToken:
- Create a dedicated cancelToken before sending the request and cache it
- In the component's unmount event (beforeDestroy/destroyed), use cancelToken to cancel requests managed by that component
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:
- The simple but brutal approach: refresh the entire page
- The more civilized approach: call the refresh list/table API to refresh the data
- The elegant approach: only refresh the specific row that was modified
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:
- Display field changes: only modify the current row, don't refetch the entire page. For example, remarks, tags, favorites
- 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.
- A separate request to get the total number of records
- The original request adds a parameter to control whether to calculate and return the total
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.
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.