DynamoDB容量模式 #

一、容量模式概述 #

1.1 两种容量模式 #

text
DynamoDB容量模式:
├── 按需模式(On-Demand)
│   ├── 自动扩展
│   ├── 按请求计费
│   └── 无需容量规划
└── 预置模式(Provisioned)
    ├── 固定容量
    ├── 可预测成本
    └── 支持Auto Scaling

1.2 模式对比 #

特性 按需模式 预置模式
容量规划 不需要 需要
扩展方式 自动 手动/Auto Scaling
成本可预测性 较低 较高
适用场景 不可预测流量 可预测流量
限流 可能(突发) 可能(超限)

二、按需模式 #

2.1 启用按需模式 #

创建表时:

bash
aws dynamodb create-table \
  --table-name Users \
  --attribute-definitions \
    AttributeName=UserId,AttributeType=S \
  --key-schema \
    AttributeName=UserId,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST

切换到按需模式:

bash
aws dynamodb update-table \
  --table-name Users \
  --billing-mode PAY_PER_REQUEST

2.2 按需模式计费 #

text
计费方式:
├── 读取:$1.25 / 百万请求
├── 写入:$1.25 / 百万请求
├── 数据存储:$0.25 / GB/月
└── 无预置费用

2.3 按需模式限制 #

text
限制:
├── 突发容量:40,000 RCU / 40,000 WCU
├── 突发后可能限流
├── 需要时间适应流量
└── 大流量需提前联系AWS

2.4 适用场景 #

text
适用场景:
├── 流量不可预测
├── 新应用/测试环境
├── 低流量应用
├── 偶发高峰
└── 不想管理容量

三、预置模式 #

3.1 创建预置容量表 #

bash
aws dynamodb create-table \
  --table-name Products \
  --attribute-definitions \
    AttributeName=ProductId,AttributeType=S \
  --key-schema \
    AttributeName=ProductId,KeyType=HASH \
  --provisioned-throughput \
    ReadCapacityUnits=10,WriteCapacityUnits=5

3.2 更新容量 #

bash
aws dynamodb update-table \
  --table-name Products \
  --provisioned-throughput \
    ReadCapacityUnits=20,WriteCapacityUnits=10

3.3 容量单位 #

RCU(读取容量单位):

text
1 RCU:
├── 1次强一致性读取(4KB)
└── 2次最终一致性读取(4KB)

示例:
├── 读取8KB项目(强一致)= 2 RCU
├── 读取8KB项目(最终一致)= 1 RCU
└── 读取1KB项目 = 1 RCU(向上取整)

WCU(写入容量单位):

text
1 WCU:
└── 1次写入(1KB)

示例:
├── 写入5KB项目 = 5 WCU
├── 写入0.5KB项目 = 1 WCU
└── 写入10KB项目 = 10 WCU

3.4 容量规划 #

javascript
function calculateCapacity(readsPerSecond, avgReadSizeKB, writesPerSecond, avgWriteSizeKB) {
  // 计算RCU
  const rcuPerRead = Math.ceil(avgReadSizeKB / 4);
  const totalRCU = readsPerSecond * rcuPerRead;
  
  // 计算WCU
  const wcuPerWrite = Math.ceil(avgWriteSizeKB);
  const totalWCU = writesPerSecond * wcuPerWrite;
  
  return {
    ReadCapacityUnits: Math.ceil(totalRCU),
    WriteCapacityUnits: Math.ceil(totalWCU)
  };
}

// 使用示例
const capacity = calculateCapacity(
  100,  // 每秒100次读取
  2,    // 平均2KB
  50,   // 每秒50次写入
  1     // 平均1KB
);
// { ReadCapacityUnits: 50, WriteCapacityUnits: 50 }

四、Auto Scaling #

4.1 Auto Scaling概念 #

text
Auto Scaling功能:
├── 自动调整容量
├── 基于利用率指标
├── 设置最小/最大值
└── 降低运维成本

4.2 启用Auto Scaling #

使用CLI:

bash
# 创建Auto Scaling目标
aws application-autoscaling register-scalable-target \
  --service-namespace dynamodb \
  --resource-id table/Products \
  --scalable-dimension dynamodb:table:ReadCapacityUnits \
  --min-capacity 5 \
  --max-capacity 100

# 创建扩展策略
aws application-autoscaling put-scaling-policy \
  --service-namespace dynamodb \
  --resource-id table/Products \
  --scalable-dimension dynamodb:table:ReadCapacityUnits \
  --policy-name ProductsReadScalingPolicy \
  --policy-type TargetTrackingScaling \
  --target-tracking-scaling-policy-configuration file://policy.json

policy.json:

json
{
  "PredefinedMetricSpecification": {
    "PredefinedMetricType": "DynamoDBReadCapacityUtilization"
  },
  "TargetValue": 70.0,
  "ScaleOutCooldown": 60,
  "ScaleInCooldown": 60
}

4.3 使用CloudFormation #

yaml
Resources:
  Table:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: Products
      BillingMode: PROVISIONED
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
      AttributeDefinitions:
        - AttributeName: ProductId
          AttributeType: S
      KeySchema:
        - AttributeName: ProductId
          KeyType: HASH

  ReadScalingTarget:
    Type: AWS::ApplicationAutoScaling::ScalableTarget
    Properties:
      MaxCapacity: 100
      MinCapacity: 5
      ResourceId: !Sub table/${Table}
      RoleARN: !Sub arn:aws:iam::${AWS::AccountId}:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable
      ScalableDimension: dynamodb:table:ReadCapacityUnits
      ServiceNamespace: dynamodb

  ReadScalingPolicy:
    Type: AWS::ApplicationAutoScaling::ScalingPolicy
    Properties:
      PolicyName: ProductsReadScalingPolicy
      PolicyType: TargetTrackingScaling
      ScalingTargetId: !Ref ReadScalingTarget
      TargetTrackingScalingPolicyConfiguration:
        TargetValue: 70
        PredefinedMetricSpecification:
          PredefinedMetricType: DynamoDBReadCapacityUtilization
        ScaleOutCooldown: 60
        ScaleInCooldown: 60

4.4 索引Auto Scaling #

bash
# 为GSI配置Auto Scaling
aws application-autoscaling register-scalable-target \
  --service-namespace dynamodb \
  --resource-id table/Products/index/CategoryIndex \
  --scalable-dimension dynamodb:index:ReadCapacityUnits \
  --min-capacity 5 \
  --max-capacity 50

五、模式切换 #

5.1 从预置切换到按需 #

bash
aws dynamodb update-table \
  --table-name Products \
  --billing-mode PAY_PER_REQUEST

注意事项:

text
切换限制:
├── 24小时内只能切换一次
├── 切换后Auto Scaling配置失效
└── 切换需要时间完成

5.2 从按需切换到预置 #

bash
aws dynamodb update-table \
  --table-name Products \
  --billing-mode PROVISIONED \
  --provisioned-throughput \
    ReadCapacityUnits=10,WriteCapacityUnits=5

六、容量规划最佳实践 #

6.1 选择容量模式 #

text
选择建议:
├── 按需模式
│   ├── 流量不可预测
│   ├── 新应用
│   ├── 低流量(<200 RCU/WCU)
│   └── 开发/测试环境
└── 预置模式
    ├── 流量可预测
    ├── 高流量稳定应用
    ├── 成本敏感
    └── 生产环境

6.2 容量估算 #

javascript
function estimateCapacity(metrics) {
  const { avgReads, avgReadSize, avgWrites, avgWriteSize, peakMultiplier } = metrics;
  
  // 基础容量
  const baseRCU = Math.ceil(avgReads * Math.ceil(avgReadSize / 4));
  const baseWCU = Math.ceil(avgWrites * Math.ceil(avgWriteSize));
  
  // 峰值容量
  const peakRCU = Math.ceil(baseRCU * peakMultiplier);
  const peakWCU = Math.ceil(baseWCU * peakMultiplier);
  
  return {
    base: { RCU: baseRCU, WCU: baseWCU },
    peak: { RCU: peakRCU, WCU: peakWCU },
    recommendation: {
      minCapacity: { RCU: baseRCU, WCU: baseWCU },
      maxCapacity: { RCU: peakRCU * 2, WCU: peakWCU * 2 }
    }
  };
}

6.3 监控和调整 #

text
监控指标:
├── ConsumedReadCapacityUnits
├── ConsumedWriteCapacityUnits
├── ReadThrottleEvents
├── WriteThrottleEvents
└── 调整策略
    ├── 监控利用率
    ├── 定期评估
    └── 根据业务变化调整

七、成本优化 #

7.1 按需模式成本优化 #

text
优化建议:
├── 监控请求量
├── 评估是否切换到预置
├── 优化查询减少请求
└── 使用缓存减少读取

7.2 预置模式成本优化 #

text
优化建议:
├── 使用Auto Scaling
├── 设置合理的目标利用率
├── 监控实际使用量
├── 定期调整容量
└── 考虑预留容量

7.3 成本对比 #

javascript
function compareCosts(requests, capacity) {
  const onDemandReadCost = (requests.reads / 1000000) * 1.25;
  const onDemandWriteCost = (requests.writes / 1000000) * 1.25;
  const onDemandTotal = onDemandReadCost + onDemandWriteCost;
  
  const provisionedReadCost = (capacity.rcu * 0.00013 * 730);  // 月小时数
  const provisionedWriteCost = (capacity.wcu * 0.00065 * 730);
  const provisionedTotal = provisionedReadCost + provisionedWriteCost;
  
  return {
    onDemand: onDemandTotal,
    provisioned: provisionedTotal,
    recommendation: onDemandTotal < provisionedTotal ? 'on-demand' : 'provisioned'
  };
}

八、总结 #

容量模式要点:

特性 按需模式 预置模式
容量规划 不需要 需要
扩展 自动 Auto Scaling
成本 按请求 按容量
适用 不可预测流量 可预测流量

下一步,让我们学习监控与告警!

最后更新:2026-03-27