web-performance

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Web Performance Skill

Web性能优化指南

Version: 1.0 Stack: Apollo Client/Server + Redis + CloudFront + S3
Performance problems are invisible during development. Local servers are fast. Test data is small. You don't notice the 3MB bundle, the N+1 queries, or the full-table scan until real users on real connections with real data report that the page takes 8 seconds to load. By then, fixing it requires rearchitecting the caching layer, splitting the bundle, and rewriting queries — all at once, under pressure.
Performance patterns applied from the start are cheap. Performance fixes applied after launch are expensive. These rules are the cheap version.

版本: 1.0 技术栈: Apollo Client/Server + Redis + CloudFront + S3
性能问题在开发阶段往往难以察觉。本地服务器速度快,测试数据量小,你不会注意到3MB的代码包、N+1查询或全表扫描,直到真实用户在真实网络环境下使用真实数据时,反馈页面加载需要8秒。到那时再修复,就需要重新架构缓存层、拆分代码包、重写查询——所有工作都要在压力下同时完成。
从项目初期就应用性能优化模式成本很低,而上线后再进行性能修复则代价高昂。本指南提供的就是低成本的性能优化方案。

Core Principles

核心原则

  1. Measure First — Profile before optimizing. Don't guess.
  2. Cache at Every Layer — CDN → API → Database → In-Memory.
  3. Minimize Payload — Send only what's needed.
  4. Defer Non-Critical — Load critical path first, everything else later.
  5. Perceived Performance — Optimistic UI makes things feel faster.

  1. 先测量再优化 —— 优化前先进行性能分析,不要凭猜测行事。
  2. 全层级缓存 —— CDN → API → 数据库 → 内存。
  3. 最小化负载 —— 只发送必要的数据。
  4. 延迟加载非关键资源 —— 优先加载关键路径资源,其余资源稍后加载。
  5. 感知性能优化 —— 乐观UI让用户感觉操作更快捷。

Core Web Vitals Targets

核心Web指标目标

MetricWhat It MeasuresTargetCritical
LCP (Largest Contentful Paint)Main content loaded< 2.5s< 4s
INP (Interaction to Next Paint)Input responsiveness< 200ms< 500ms
CLS (Cumulative Layout Shift)Visual stability< 0.1< 0.25

指标测量内容目标值临界值
LCP(最大内容绘制)主要内容加载完成时间< 2.5秒< 4秒
INP(交互到下一次绘制)输入响应速度< 200毫秒< 500毫秒
CLS(累积布局偏移)视觉稳定性< 0.1< 0.25

Apollo Client Caching

Apollo Client缓存配置

Configure
InMemoryCache
with type policies for pagination merging and computed fields. Use
cache-and-network
as default fetch policy (stale-while-revalidate). Use optimistic updates for mutations to make UI feel instant.
InMemoryCache
配置类型策略,实现分页合并和计算字段。默认使用
cache-and-network
获取策略(stale-while-revalidate模式)。对突变操作使用乐观更新,让UI操作看起来瞬间完成。

Fetch Policies

获取策略

PolicyUse Case
cache-first
Static data (categories, config)
cache-and-network
Data that changes (products, user data)
network-only
Always fresh (order status, real-time)
cache-only
Offline mode, known-cached data
See
assets/caching-patterns.md
for cache configuration, fetch policy examples, and optimistic update patterns.

策略使用场景
cache-first
静态数据(分类、配置信息)
cache-and-network
会变化的数据(商品、用户数据)
network-only
始终需要最新数据(订单状态、实时数据)
cache-only
离线模式、已知已缓存的数据
查看
assets/caching-patterns.md
获取缓存配置、获取策略示例及乐观更新模式。

Redis Caching

Redis缓存优化

Cache-aside pattern: check cache → miss → fetch DB → store in cache. Invalidate on writes. Use tag-based invalidation for list queries.
采用旁路缓存模式:先检查缓存 → 缓存未命中 → 从数据库获取数据 → 存入缓存。写入数据时失效缓存。对列表查询使用基于标签的失效策略。

TTL Guidelines

TTL(过期时间)指南

Data TypeTTLReason
Static config24h+Rarely changes
Product catalog1hChanges occasionally
User sessions30mSecurity balance
Cart data7dUser convenience
Search results5mBalance freshness/speed
Real-time dataNo cacheMust be live
See
assets/caching-patterns.md
for Redis cache service, cache-aside pattern, and invalidation examples.

数据类型TTL原因
静态配置24小时以上极少变更
商品目录1小时偶尔变更
用户会话30分钟安全性与便利性平衡
购物车数据7天提升用户体验
搜索结果5分钟平衡数据新鲜度与速度
实时数据不缓存必须保持实时性
查看
assets/caching-patterns.md
获取Redis缓存服务、旁路缓存模式及失效策略示例。

CloudFront & S3 Optimization

CloudFront & S3优化

Immutable assets (hashed filenames) get 365-day cache. API routes get no CDN caching. Images get resize-on-demand with WebP format, lazy loading, and 2x srcSet for retina.
See
assets/caching-patterns.md
for CDK configuration and image optimization component.

不可变资源(带哈希值的文件名)设置365天缓存。API路由不启用CDN缓存。图片按需调整尺寸,使用WebP格式、懒加载,并为视网膜屏幕提供2x srcSet。
查看
assets/caching-patterns.md
获取CDK配置及图片优化组件。

Bundle Optimization

代码包优化

Route-based code splitting with
React.lazy
. Dynamic imports for heavy libraries (load only when needed). Analyze with
source-map-explorer
.
使用
React.lazy
实现基于路由的代码分割。对大型库使用动态导入(仅在需要时加载)。使用
source-map-explorer
分析代码包。

Bundle Size Guidelines

代码包大小指南

CategoryTargetAction if Exceeded
Initial JS< 100KB gzippedCode split, tree shake
Vendor chunk< 150KB gzippedLazy load, find alternatives
Route chunk< 50KB gzippedSplit further
Total initial load< 200KB gzippedAudit dependencies
See
assets/optimization-patterns.md
for code splitting, dynamic import, and bundle analysis examples.

类别目标值超出后的处理措施
初始JS包压缩后 < 100KB代码分割、摇树优化
第三方依赖包压缩后 < 150KB懒加载、寻找替代方案
路由代码包压缩后 < 50KB进一步拆分
初始加载总大小压缩后 < 200KB审计依赖项
查看
assets/optimization-patterns.md
获取代码分割、动态导入及代码包分析示例。

React Performance

React性能优化

Use
useMemo
for expensive computations,
useCallback
for stable callbacks passed to memoized children, and
memo
for list item components. Don't memoize simple values, always-changing values, or handlers on non-memoized children. Use virtualization for long lists (100+ items).
See
assets/optimization-patterns.md
for memoization, when-NOT-to-memoize, and virtualization examples.

使用
useMemo
处理昂贵的计算,使用
useCallback
为memoized子组件提供稳定的回调函数,使用
memo
优化列表项组件。不要对简单值、频繁变化的值或传递给非memoized子组件的处理函数进行memo化处理。对长列表(100+条数据)使用虚拟化。
查看
assets/optimization-patterns.md
获取memo化、memo化禁用场景及虚拟化示例。

Database Performance

数据库性能优化

Select only needed fields. Use
include
sparingly. Use raw queries for complex aggregations. Add compound indices on filtered/sorted columns.
See
assets/optimization-patterns.md
for Prisma query optimization and index strategy.

仅选择需要的字段。谨慎使用
include
。对复杂聚合查询使用原生SQL。在过滤/排序的列上添加复合索引。
查看
assets/optimization-patterns.md
获取Prisma查询优化及索引策略。

Anti-Patterns

反模式

Anti-PatternProblemFix
Fetching all fieldsOver-fetching, slowSelect only needed fields
No paginationMemory issues, slowCursor-based pagination
Cache everythingStale data, complexityCache strategically by TTL
Premature optimizationWasted effortMeasure first, optimize hotspots
Sync heavy operationsBlocks responseBackground jobs (Bull)
No CDN for static assetsSlow global deliveryCloudFront for static files
Unoptimized imagesHuge downloadsResize, compress, WebP
Blocking bundleSlow initial loadCode split, lazy load

反模式问题修复方案
获取所有字段过度获取数据,速度慢仅选择需要的字段
无分页内存问题,速度慢基于游标分页
缓存所有数据数据过期,复杂度高根据TTL策略性缓存
过早优化浪费精力先测量,再优化热点问题
同步执行重操作阻塞响应使用后台任务(Bull)
静态资源不使用CDN全球分发速度慢为静态文件配置CloudFront
未优化图片下载体积大调整尺寸、压缩、使用WebP格式
阻塞式代码包初始加载慢代码分割、懒加载

Checklist

检查清单

Frontend

前端

  • Code split by route
  • Heavy libraries lazy loaded
  • Images lazy loaded
  • Images optimized (WebP, sized)
  • Bundle < 200KB initial
  • useMemo/useCallback where beneficial
  • Long lists virtualized
  • 按路由进行代码分割
  • 大型库实现懒加载
  • 图片懒加载
  • 图片优化(WebP格式、适配尺寸)
  • 初始代码包大小 < 200KB(压缩后)
  • 在合适场景使用useMemo/useCallback
  • 长列表实现虚拟化

Apollo

Apollo

  • Cache policies configured
  • Pagination merges correctly
  • Optimistic updates for mutations
  • Fetch policy matches data freshness needs
  • 配置缓存策略
  • 分页合并正常工作
  • 突变操作使用乐观更新
  • 获取策略匹配数据新鲜度需求

Redis

Redis

  • Hot data cached
  • TTLs appropriate for data type
  • Cache invalidation on updates
  • Connection pooling configured
  • 热点数据已缓存
  • TTL设置与数据类型匹配
  • 更新数据时失效缓存
  • 配置连接池

Database

数据库

  • Indices on filtered/sorted columns
  • Select only needed fields
  • N+1 queries eliminated (DataLoader)
  • Expensive queries analyzed
  • 在过滤/排序的列上添加索引
  • 仅选择需要的字段
  • 消除N+1查询(使用DataLoader)
  • 分析昂贵查询

CDN

CDN

  • Static assets on CloudFront
  • Immutable assets cached forever
  • Dynamic content not cached at edge
  • HTTPS enforced

  • 静态资源托管在CloudFront
  • 不可变资源设置永久缓存
  • 动态内容不在边缘节点缓存
  • 强制启用HTTPS

When to Consider Alternatives

可选方案参考

SituationConsider
Global real-time dataRedis Pub/Sub or WebSockets
Heavy computationBackground workers (Bull)
Large file uploadsDirect S3 presigned URLs
Search-heavyElasticsearch or Algolia
Edge computing needsCloudFront Functions or Lambda@Edge

场景推荐方案
全球实时数据Redis Pub/Sub 或 WebSockets
重计算任务后台工作进程(Bull)
大文件上传直接使用S3预签名URL
搜索密集型应用Elasticsearch 或 Algolia
边缘计算需求CloudFront Functions 或 Lambda@Edge

References

参考文档

  • assets/caching-patterns.md
    — Apollo cache config, Redis, CloudFront, image optimization
  • assets/optimization-patterns.md
    — Bundle splitting, React memoization, virtualization, DB optimization
  • assets/caching-patterns.md
    —— Apollo缓存配置、Redis、CloudFront、图片优化
  • assets/optimization-patterns.md
    —— 代码包分割、React memo化、虚拟化、数据库优化