web-performance
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWeb 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
核心原则
- Measure First — Profile before optimizing. Don't guess.
- Cache at Every Layer — CDN → API → Database → In-Memory.
- Minimize Payload — Send only what's needed.
- Defer Non-Critical — Load critical path first, everything else later.
- Perceived Performance — Optimistic UI makes things feel faster.
- 先测量再优化 —— 优化前先进行性能分析,不要凭猜测行事。
- 全层级缓存 —— CDN → API → 数据库 → 内存。
- 最小化负载 —— 只发送必要的数据。
- 延迟加载非关键资源 —— 优先加载关键路径资源,其余资源稍后加载。
- 感知性能优化 —— 乐观UI让用户感觉操作更快捷。
Core Web Vitals Targets
核心Web指标目标
| Metric | What It Measures | Target | Critical |
|---|---|---|---|
| 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 with type policies for pagination merging and computed fields. Use as default fetch policy (stale-while-revalidate). Use optimistic updates for mutations to make UI feel instant.
InMemoryCachecache-and-network为配置类型策略,实现分页合并和计算字段。默认使用获取策略(stale-while-revalidate模式)。对突变操作使用乐观更新,让UI操作看起来瞬间完成。
InMemoryCachecache-and-networkFetch Policies
获取策略
| Policy | Use Case |
|---|---|
| Static data (categories, config) |
| Data that changes (products, user data) |
| Always fresh (order status, real-time) |
| Offline mode, known-cached data |
See for cache configuration, fetch policy examples, and optimistic update patterns.
assets/caching-patterns.md| 策略 | 使用场景 |
|---|---|
| 静态数据(分类、配置信息) |
| 会变化的数据(商品、用户数据) |
| 始终需要最新数据(订单状态、实时数据) |
| 离线模式、已知已缓存的数据 |
查看获取缓存配置、获取策略示例及乐观更新模式。
assets/caching-patterns.mdRedis 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 Type | TTL | Reason |
|---|---|---|
| Static config | 24h+ | Rarely changes |
| Product catalog | 1h | Changes occasionally |
| User sessions | 30m | Security balance |
| Cart data | 7d | User convenience |
| Search results | 5m | Balance freshness/speed |
| Real-time data | No cache | Must be live |
See for Redis cache service, cache-aside pattern, and invalidation examples.
assets/caching-patterns.md| 数据类型 | TTL | 原因 |
|---|---|---|
| 静态配置 | 24小时以上 | 极少变更 |
| 商品目录 | 1小时 | 偶尔变更 |
| 用户会话 | 30分钟 | 安全性与便利性平衡 |
| 购物车数据 | 7天 | 提升用户体验 |
| 搜索结果 | 5分钟 | 平衡数据新鲜度与速度 |
| 实时数据 | 不缓存 | 必须保持实时性 |
查看获取Redis缓存服务、旁路缓存模式及失效策略示例。
assets/caching-patterns.mdCloudFront & 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 for CDK configuration and image optimization component.
assets/caching-patterns.md不可变资源(带哈希值的文件名)设置365天缓存。API路由不启用CDN缓存。图片按需调整尺寸,使用WebP格式、懒加载,并为视网膜屏幕提供2x srcSet。
查看获取CDK配置及图片优化组件。
assets/caching-patterns.mdBundle Optimization
代码包优化
Route-based code splitting with . Dynamic imports for heavy libraries (load only when needed). Analyze with .
React.lazysource-map-explorer使用实现基于路由的代码分割。对大型库使用动态导入(仅在需要时加载)。使用分析代码包。
React.lazysource-map-explorerBundle Size Guidelines
代码包大小指南
| Category | Target | Action if Exceeded |
|---|---|---|
| Initial JS | < 100KB gzipped | Code split, tree shake |
| Vendor chunk | < 150KB gzipped | Lazy load, find alternatives |
| Route chunk | < 50KB gzipped | Split further |
| Total initial load | < 200KB gzipped | Audit dependencies |
See for code splitting, dynamic import, and bundle analysis examples.
assets/optimization-patterns.md| 类别 | 目标值 | 超出后的处理措施 |
|---|---|---|
| 初始JS包 | 压缩后 < 100KB | 代码分割、摇树优化 |
| 第三方依赖包 | 压缩后 < 150KB | 懒加载、寻找替代方案 |
| 路由代码包 | 压缩后 < 50KB | 进一步拆分 |
| 初始加载总大小 | 压缩后 < 200KB | 审计依赖项 |
查看获取代码分割、动态导入及代码包分析示例。
assets/optimization-patterns.mdReact Performance
React性能优化
Use for expensive computations, for stable callbacks passed to memoized children, and 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).
useMemouseCallbackmemoSee for memoization, when-NOT-to-memoize, and virtualization examples.
assets/optimization-patterns.md使用处理昂贵的计算,使用为memoized子组件提供稳定的回调函数,使用优化列表项组件。不要对简单值、频繁变化的值或传递给非memoized子组件的处理函数进行memo化处理。对长列表(100+条数据)使用虚拟化。
useMemouseCallbackmemo查看获取memo化、memo化禁用场景及虚拟化示例。
assets/optimization-patterns.mdDatabase Performance
数据库性能优化
Select only needed fields. Use sparingly. Use raw queries for complex aggregations. Add compound indices on filtered/sorted columns.
includeSee for Prisma query optimization and index strategy.
assets/optimization-patterns.md仅选择需要的字段。谨慎使用。对复杂聚合查询使用原生SQL。在过滤/排序的列上添加复合索引。
include查看获取Prisma查询优化及索引策略。
assets/optimization-patterns.mdAnti-Patterns
反模式
| Anti-Pattern | Problem | Fix |
|---|---|---|
| Fetching all fields | Over-fetching, slow | Select only needed fields |
| No pagination | Memory issues, slow | Cursor-based pagination |
| Cache everything | Stale data, complexity | Cache strategically by TTL |
| Premature optimization | Wasted effort | Measure first, optimize hotspots |
| Sync heavy operations | Blocks response | Background jobs (Bull) |
| No CDN for static assets | Slow global delivery | CloudFront for static files |
| Unoptimized images | Huge downloads | Resize, compress, WebP |
| Blocking bundle | Slow initial load | Code 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
可选方案参考
| Situation | Consider |
|---|---|
| Global real-time data | Redis Pub/Sub or WebSockets |
| Heavy computation | Background workers (Bull) |
| Large file uploads | Direct S3 presigned URLs |
| Search-heavy | Elasticsearch or Algolia |
| Edge computing needs | CloudFront Functions or Lambda@Edge |
| 场景 | 推荐方案 |
|---|---|
| 全球实时数据 | Redis Pub/Sub 或 WebSockets |
| 重计算任务 | 后台工作进程(Bull) |
| 大文件上传 | 直接使用S3预签名URL |
| 搜索密集型应用 | Elasticsearch 或 Algolia |
| 边缘计算需求 | CloudFront Functions 或 Lambda@Edge |
References
参考文档
- — Apollo cache config, Redis, CloudFront, image optimization
assets/caching-patterns.md - — Bundle splitting, React memoization, virtualization, DB optimization
assets/optimization-patterns.md
- —— Apollo缓存配置、Redis、CloudFront、图片优化
assets/caching-patterns.md - —— 代码包分割、React memo化、虚拟化、数据库优化
assets/optimization-patterns.md