api-response-optimization

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Response Optimization

API响应优化

Reduce payload sizes, implement caching, and enable compression for faster APIs.
缩减负载大小、实施缓存并启用压缩,打造更快速的API。

Sparse Fieldsets

稀疏字段集

javascript
// Allow clients to select fields: GET /users?fields=id,name,email
app.get('/users', async (req, res) => {
  const fields = req.query.fields?.split(',') || null;
  const users = await User.find({}, fields?.join(' '));
  res.json(users);
});
javascript
// Allow clients to select fields: GET /users?fields=id,name,email
app.get('/users', async (req, res) => {
  const fields = req.query.fields?.split(',') || null;
  const users = await User.find({}, fields?.join(' '));
  res.json(users);
});

HTTP Caching Headers

HTTP缓存标头

javascript
app.get('/products/:id', async (req, res) => {
  const product = await Product.findById(req.params.id);
  const etag = crypto.createHash('md5').update(JSON.stringify(product)).digest('hex');

  if (req.headers['if-none-match'] === etag) {
    return res.status(304).end();
  }

  res.set({
    'Cache-Control': 'public, max-age=3600',
    'ETag': etag
  });
  res.json(product);
});
javascript
app.get('/products/:id', async (req, res) => {
  const product = await Product.findById(req.params.id);
  const etag = crypto.createHash('md5').update(JSON.stringify(product)).digest('hex');

  if (req.headers['if-none-match'] === etag) {
    return res.status(304).end();
  }

  res.set({
    'Cache-Control': 'public, max-age=3600',
    'ETag': etag
  });
  res.json(product);
});

Response Compression

响应压缩

javascript
const compression = require('compression');

app.use(compression({
  filter: (req, res) => {
    if (req.headers['x-no-compression']) return false;
    return compression.filter(req, res);
  },
  level: 6  // Balance between speed and compression
}));
javascript
const compression = require('compression');

app.use(compression({
  filter: (req, res) => {
    if (req.headers['x-no-compression']) return false;
    return compression.filter(req, res);
  },
  level: 6  // Balance between speed and compression
}));

Performance Targets

性能指标目标

MetricTarget
Response time<100ms (from 500ms)
Payload size<50KB (from 500KB)
Server CPU<30% (from 80%)
指标目标
响应时间<100毫秒(原500毫秒)
负载大小<50KB(原500KB)
服务器CPU占用<30%(原80%)

Optimization Checklist

优化检查清单

  • Remove sensitive/unnecessary fields from responses
  • Implement sparse fieldsets
  • Add ETag/Last-Modified headers
  • Enable gzip/brotli compression
  • Use pagination for collections
  • Eager load to prevent N+1 queries
  • Monitor with APM tools
  • 从响应中移除敏感/不必要字段
  • 实施稀疏字段集
  • 添加ETag/Last-Modified标头
  • 启用gzip/brotli压缩
  • 对集合使用分页
  • 预加载以避免N+1查询
  • 使用APM工具进行监控

Best Practices

最佳实践

  • Cache immutable resources aggressively
  • Use short TTL for frequently changing data
  • Invalidate cache on writes
  • Compress responses >1KB
  • Profile before optimizing
  • 对不可变资源进行激进缓存
  • 对频繁变更的数据使用短TTL
  • 写入操作时使缓存失效
  • 对大于1KB的响应进行压缩
  • 优化前先进行性能分析