DynamoDB Scaling
On-demand vs provisioned, autoscaling, hot partitions y batching
DynamoDB tiene dos modos de capacidad: On-Demand (pagas por cada operación de lectura/escritura) y Provisioned (defines RCUs y WCUs por segundo, más barato si el tráfico es predecible). On-Demand es más caro pero no requiere planificación: escala instantáneamente a cualquier tráfico. Provisioned requiere dimensionar correctamente y configurar autoscaling para manejar picos.
El autoscaling en Provisioned mode ajusta la capacidad según el uso real. Defines un target de utilización (ej. 70% de RCUs usados) y un rango min-max. DynamoDB Application Auto Scaling aumenta la capacidad cuando el uso supera el 70% y la reduce cuando baja. El problema es que el escalado tarda 1-5 minutos: si el tráfico sube bruscamente, puede haber throttling antes de que el autoscaling reaccione.
Las hot partitions ocurren cuando una partition key concentra desproporcionadamente más tráfico que otras. Si tu tabla tiene 100 particiones y el 90% de las reads van a la partición del usuario 'admin', esa partición se convierte en hot. DynamoDB distribuye la capacidad uniformemente entre particiones; una hot partition agota su cuota antes que las demás y se throttlea, incluso si la capacidad total de la tabla es suficiente.
El batch writing (BatchWriteItem y BatchGetItem) reduce el número de llamadas a la API cuando necesitas insertar o leer múltiples items. BatchWriteItem acepta hasta 25 items por llamada. BatchGetItem acepta hasta 100 items por llamada. Reduce latencia total y costos de llamadas a la API. DynamoDB procesa los items del batch en paralelo internamente.
import boto3
from boto3.dynamodb.conditions import Key
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('user_events')
# === BATCH WRITE (up to 25 items per call) ===
def batch_write_events(events: list[dict]) -> None:
# Split into chunks of 25 (DynamoDB BatchWriteItem limit)
chunks = [events[i:i+25] for i in range(0, len(events), 25)]
with table.batch_writer() as batch:
for event in events:
batch.put_item(Item={
'user_id': event['user_id'],
'event_id': event['id'],
'event_type': event['type'],
'timestamp': event['timestamp'],
'data': event['data']
})
# batch_writer handles chunking and unprocessed items automatically
# === BATCH GET (up to 100 items per call) ===
def batch_get_users(user_ids: list[str]) -> list[dict]:
response = dynamodb.batch_get_item(
RequestItems={
'user_profiles': {
'Keys': [{'user_id': uid} for uid in user_ids],
'ProjectionExpression': 'user_id, name, email, preferences'
}
}
)
items = response['Responses']['user_profiles']
# Handle unprocessed keys (DynamoDB may not return all in one call)
unprocessed = response.get('UnprocessedKeys', {})
while unprocessed:
response = dynamodb.batch_get_item(RequestItems=unprocessed)
items.extend(response['Responses']['user_profiles'])
unprocessed = response.get('UnprocessedKeys', {})
return items
# === AUTOSCALING CONFIGURATION ===
autoscaling = boto3.client('application-autoscaling')
# Register table read capacity as scalable target
autoscaling.register_scalable_target(
ServiceNamespace='dynamodb',
ResourceId='table/user_events',
ScalableDimension='dynamodb:table:ReadCapacityUnits',
MinCapacity=5,
MaxCapacity=1000
)
# Track at 70% utilization
autoscaling.put_scaling_policy(
PolicyName='DynamoDB-ReadCapacity-Tracking',
ServiceNamespace='dynamodb',
ResourceId='table/user_events',
ScalableDimension='dynamodb:table:ReadCapacityUnits',
PolicyType='TargetTrackingScaling',
TargetTrackingScalingPolicyConfiguration={
'TargetValue': 70.0,
'PredefinedMetricSpecification': {
'PredefinedMetricType': 'DynamoDBReadCapacityUtilization'
}
}
)
# === HOT PARTITION MITIGATION ===
# If user_id is the partition key but some users have 10x more traffic:
def get_sharded_partition_key(user_id: str, shard_count: int = 10) -> str:
"""Distribute hot user across multiple partitions."""
import hashlib
shard = int(hashlib.md5(user_id.encode()).hexdigest(), 16) % shard_count
return f'{user_id}#{shard}' # e.g. 'user123#7'Debugging lab
Detecta y corrige el error en el código.
- 01
# Writing 1000 items one by one for item in items: table.put_item(Item=item) # 1000 separate API calls — slow and expensive
- 02
# Table in provisioned mode with no autoscaling # Traffic spikes at 9am every day # Provisioned: 10 WCU (enough for normal traffic) # Spikes: need 100 WCU for 30 minutes # Result: throttling every morning
- 03
# Hot partition: single viral user generates 90% of all reads # Table partition_key='user_id', viral user has 1M followers # All reads go to partition 'viral_user_id'