

# Descripción del rendimiento en caliente de DynamoDB
<a name="warm-throughput"></a>

El *rendimiento en caliente* se refiere al número de operaciones de lectura y escritura que la tabla de DynamoDB puede admitir de modo instantáneo. Estos valores están disponibles de manera predeterminada para todas las tablas y los índices secundarios globales (GSI) y representan cuánto han escalado en función del uso histórico. Si utiliza el modo bajo demanda, o si actualiza el rendimiento aprovisionado a estos valores, la aplicación podrá emitir solicitudes hasta esos valores de forma instantánea.

DynamoDB ajustará automáticamente los valores de rendimiento en caliente a medida que aumente el uso. También puede aumentar estos valores de forma proactiva cuando sea necesario, lo que resulta especialmente útil en los picos de eventos próximos, como lanzamientos de productos o ventas. En el caso de eventos de pico planificados, en los que las tasas de solicitudes para la tabla de DynamoDB podrían aumentar 10 veces, 100 veces o más, ahora puede evaluar si el rendimiento en caliente actual es suficiente para gestionar el tráfico previsto. Si no es así, puede aumentar el valor de rendimiento en caliente sin cambiar la configuración de rendimiento ni el [modo de facturación](capacity-mode.md). Este proceso se denomina *precalentamiento* de una tabla, lo que le permite establecer una línea de base que las tablas pueden admitir al instante. Esto garantiza que las aplicaciones puedan manejar tasas de solicitudes más elevadas desde el momento en que se produzcan. Una vez aumentados, los valores de rendimiento en caliente no se pueden reducir.

Puede aumentar el valor de rendimiento en caliente en el caso de las operaciones de lectura, escritura o ambas. Puede aumentar este valor para las tablas de una sola región, las tablas globales y los GSI nuevos y existentes. En el caso de las tablas globales, esta característica está disponible para la [versión 2019.11.21 (actual)](GlobalTables.md) y la configuración de rendimiento en caliente que establezca se aplicará de forma automática a todas las tablas de réplica de la tabla global. No hay límite en el número de tablas de DynamoDB a las que puede aplicar el precalentamiento en cualquier momento. El tiempo necesario para completar el precalentamiento depende de los valores que establezca y del tamaño de la tabla o el índice. Puede presentar solicitudes de precalentamiento simultáneas y no interferirán en ninguna operación de tabla. Puede precalentar la tabla hasta el límite de cuota de tabla o índice de la cuenta en esa región. Utilice la [consola de Service Quotas](https://console.aws.amazon.com/servicequotas) para comprobar los límites actuales y aumentarlos si es necesario. 

Los valores de rendimiento en caliente están disponibles de forma predeterminada para todas las tablas y los índices secundarios sin costo alguno. No obstante, si aumenta de forma proactiva estos valores de rendimiento en caliente predeterminados para precalentar las tablas, se le cobrarán esas solicitudes. Para obtener más información, consulte los precios de [Amazon DynamoDB](https://aws.amazon.com/dynamodb/pricing/).

Para obtener más información sobre el rendimiento en caliente, consulte los temas siguientes:

**Topics**
+ [Comprobación del rendimiento en caliente actual de la tabla de DynamoDB](check-warm-throughput.md)
+ [Aumento del rendimiento en caliente de la tabla de DynamoDB existente](update-warm-throughput.md)
+ [Creación de una tabla de DynamoDB nueva con rendimiento en caliente más alto](create-table-warm-throughput.md)
+ [Descripción del rendimiento en caliente de DynamoDB en diferentes escenarios](warm-throughput-scenarios.md)

# Comprobación del rendimiento en caliente actual de la tabla de DynamoDB
<a name="check-warm-throughput"></a>

Utilice las siguientes instrucciones de la AWS CLI y de la consola de AWS para comprobar el valor actual de rendimiento en caliente de la tabla o el índice.

## Consola de administración de AWS
<a name="warm-throughput-check-console"></a>

Para comprobar el rendimiento en caliente de la tabla de DynamoDB con la consola de DynamoDB:

1. Inicie sesión en la Consola de administración de AWS y abra la consola de DynamoDB en [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/).

1. En el panel de navegación izquierdo, elija Tables (Tablas).

1. En la página **Tablas**, elija la tabla que desee.

1. Seleccione **Configuración** para ver el valor de rendimiento en caliente actual. Este valor se muestra como unidades de lectura por segundo y unidades de escritura por segundo.

## AWS CLI
<a name="warm-throughput-check-CLI"></a>

En el siguiente ejemplo de la AWS CLI se muestra cómo comprobar el rendimiento en caliente de la tabla de DynamoDB.

1. Ejecute la operación `describe-table` en la tabla de DynamoDB.

   ```
   aws dynamodb describe-table --table-name GameScores
   ```

1. Verá una respuesta similar a la siguiente. La configuración de `WarmThroughput` se mostrará como `ReadUnitsPerSecond` y `WriteUnitsPerSecond`. El `Status` será `UPDATING` cuando se actualice el valor de rendimiento en caliente y `ACTIVE` cuando se establezca el nuevo valor de rendimiento en caliente.

   ```
   {
       "Table": {
           "AttributeDefinitions": [
               {
                   "AttributeName": "GameTitle",
                   "AttributeType": "S"
               },
               {
                   "AttributeName": "TopScore",
                   "AttributeType": "N"
               },
               {
                   "AttributeName": "UserId",
                   "AttributeType": "S"
               }
           ],
           "TableName": "GameScores",
           "KeySchema": [
               {
                   "AttributeName": "UserId",
                   "KeyType": "HASH"
               },
               {
                   "AttributeName": "GameTitle",
                   "KeyType": "RANGE"
               }
           ],
           "TableStatus": "ACTIVE",
           "CreationDateTime": 1726128388.729,
           "ProvisionedThroughput": {
               "NumberOfDecreasesToday": 0,
               "ReadCapacityUnits": 0,
               "WriteCapacityUnits": 0
           },
           "TableSizeBytes": 0,
           "ItemCount": 0,
           "TableArn": "arn:aws:dynamodb:us-east-1:XXXXXXXXXXXX:table/GameScores",
           "TableId": "XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
           "BillingModeSummary": {
               "BillingMode": "PAY_PER_REQUEST",
               "LastUpdateToPayPerRequestDateTime": 1726128388.729
           },
           "GlobalSecondaryIndexes": [
               {
                   "IndexName": "GameTitleIndex",
                   "KeySchema": [
                       {
                           "AttributeName": "GameTitle",
                           "KeyType": "HASH"
                       },
                       {
                           "AttributeName": "TopScore",
                           "KeyType": "RANGE"
                       }
                   ],
                   "Projection": {
                       "ProjectionType": "INCLUDE",
                       "NonKeyAttributes": [
                           "UserId"
                       ]
                   },
                   "IndexStatus": "ACTIVE",
                   "ProvisionedThroughput": {
                       "NumberOfDecreasesToday": 0,
                       "ReadCapacityUnits": 0,
                       "WriteCapacityUnits": 0
                   },
                   "IndexSizeBytes": 0,
                   "ItemCount": 0,
                   "IndexArn": "arn:aws:dynamodb:us-east-1:XXXXXXXXXXXX:table/GameScores/index/GameTitleIndex",
                   "WarmThroughput": {
                       "ReadUnitsPerSecond": 12000,
                       "WriteUnitsPerSecond": 4000,
                       "Status": "ACTIVE"
                   }
               }
           ],
           "DeletionProtectionEnabled": false,
           "WarmThroughput": {
               "ReadUnitsPerSecond": 12000,
               "WriteUnitsPerSecond": 4000,
               "Status": "ACTIVE"
           }
       }
   }
   ```

# Aumento del rendimiento en caliente de la tabla de DynamoDB existente
<a name="update-warm-throughput"></a>

Una vez que haya comprobado el valor actual de rendimiento en caliente de la tabla de DynamoDB, puede actualizarlo con los siguientes pasos:

## Consola de administración de AWS
<a name="warm-throughput-update-console"></a>

Para comprobar el valor de rendimiento en caliente de la tabla de DynamoDB mediante la consola de DynamoDB:

1. Inicie sesión en la Consola de administración de AWS y abra la consola de DynamoDB en [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/).

1. En el panel de navegación izquierdo, elija Tables (Tablas).

1. En la página **Tablas**, elija la tabla que desee.

1. En el campo **Rendimiento en caliente**, seleccione **Editar**.

1. En la página **Editar rendimiento en caliente**, seleccione **Aumentar el rendimiento en caliente**.

1. Ajuste las **unidades de lectura por segundo** y las **unidades de escritura por segundo**. Estas dos configuraciones definen el rendimiento que la tabla puede gestionar al instante.

1. Seleccione **Guardar**.

1. Las **unidades de lectura por segundo** y las **unidades de escritura por segundo** se actualizarán en el campo **Rendimiento en caliente** cuando la solicitud termine de procesarse.
**nota**  
La actualización del valor de rendimiento en caliente es una tarea asíncrona. El `Status` cambiará de `UPDATING` a `ACTIVE` cuando se complete la actualización.

## AWS CLI
<a name="warm-throughput-update-CLI"></a>

En el siguiente ejemplo de la AWS CLI se muestra cómo actualizar el valor de rendimiento en caliente de la tabla de DynamoDB.

1. Ejecute la operación `update-table` en la tabla de DynamoDB.

   ```
   aws dynamodb update-table \
       --table-name GameScores \
       --warm-throughput ReadUnitsPerSecond=12345,WriteUnitsPerSecond=4567 \
       --global-secondary-index-updates \
           "[
               {
                   \"Update\": {
                       \"IndexName\": \"GameTitleIndex\",
                       \"WarmThroughput\": {
                           \"ReadUnitsPerSecond\": 88,
                           \"WriteUnitsPerSecond\": 77
                       }
                   }
               }
           ]" \
       --region us-east-1
   ```

1. Verá una respuesta similar a la siguiente. La configuración de `WarmThroughput` se mostrará como `ReadUnitsPerSecond` y `WriteUnitsPerSecond`. El `Status` será `UPDATING` cuando se actualice el valor de rendimiento en caliente y `ACTIVE` cuando se establezca el nuevo valor de rendimiento en caliente.

   ```
   {
       "TableDescription": {
           "AttributeDefinitions": [
               {
                   "AttributeName": "GameTitle",
                   "AttributeType": "S"
               },
               {
                   "AttributeName": "TopScore",
                   "AttributeType": "N"
               },
               {
                   "AttributeName": "UserId",
                   "AttributeType": "S"
               }
           ],
           "TableName": "GameScores",
           "KeySchema": [
               {
                   "AttributeName": "UserId",
                   "KeyType": "HASH"
               },
               {
                   "AttributeName": "GameTitle",
                   "KeyType": "RANGE"
               }
           ],
           "TableStatus": "ACTIVE",
           "CreationDateTime": 1730242189.965,
           "ProvisionedThroughput": {
               "NumberOfDecreasesToday": 0,
               "ReadCapacityUnits": 20,
               "WriteCapacityUnits": 10
           },
           "TableSizeBytes": 0,
           "ItemCount": 0,
           "TableArn": "arn:aws:dynamodb:us-east-1:XXXXXXXXXXXX:table/GameScores",
           "TableId": "XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
           "GlobalSecondaryIndexes": [
               {
                   "IndexName": "GameTitleIndex",
                   "KeySchema": [
                       {
                           "AttributeName": "GameTitle",
                           "KeyType": "HASH"
                       },
                       {
                           "AttributeName": "TopScore",
                           "KeyType": "RANGE"
                       }
                   ],
                   "Projection": {
                       "ProjectionType": "INCLUDE",
                       "NonKeyAttributes": [
                           "UserId"
                       ]
                   },
                   "IndexStatus": "ACTIVE",
                   "ProvisionedThroughput": {
                       "NumberOfDecreasesToday": 0,
                       "ReadCapacityUnits": 50,
                       "WriteCapacityUnits": 25
                   },
                   "IndexSizeBytes": 0,
                   "ItemCount": 0,
                   "IndexArn": "arn:aws:dynamodb:us-east-1:XXXXXXXXXXXX:table/GameScores/index/GameTitleIndex",
                   "WarmThroughput": {
                       "ReadUnitsPerSecond": 50,
                       "WriteUnitsPerSecond": 25,
                       "Status": "UPDATING"
                   }
               }
           ],
           "DeletionProtectionEnabled": false,
           "WarmThroughput": {
               "ReadUnitsPerSecond": 12300,
               "WriteUnitsPerSecond": 4500,
               "Status": "UPDATING"
           }
       }
   }
   ```

## AWS SDK
<a name="warm-throughput-update-SDK"></a>

En los siguientes ejemplos del SDK se muestra cómo actualizar el valor de rendimiento en caliente de la tabla de DynamoDB.

------
#### [ Java ]

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndexUpdate;
import software.amazon.awssdk.services.dynamodb.model.UpdateGlobalSecondaryIndexAction;
import software.amazon.awssdk.services.dynamodb.model.UpdateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.WarmThroughput;

...
public static WarmThroughput buildWarmThroughput(final Long readUnitsPerSecond,
                                                 final Long writeUnitsPerSecond) {
    return WarmThroughput.builder()
            .readUnitsPerSecond(readUnitsPerSecond)
            .writeUnitsPerSecond(writeUnitsPerSecond)
            .build();
}

public static void updateDynamoDBTable(DynamoDbClient ddb,
                                       String tableName,
                                       Long tableReadUnitsPerSecond,
                                       Long tableWriteUnitsPerSecond,
                                       String globalSecondaryIndexName,
                                       Long globalSecondaryIndexReadUnitsPerSecond,
                                       Long globalSecondaryIndexWriteUnitsPerSecond) {

    final WarmThroughput tableWarmThroughput = buildWarmThroughput(tableReadUnitsPerSecond, tableWriteUnitsPerSecond);
    final WarmThroughput gsiWarmThroughput = buildWarmThroughput(globalSecondaryIndexReadUnitsPerSecond, globalSecondaryIndexWriteUnitsPerSecond);

    final GlobalSecondaryIndexUpdate globalSecondaryIndexUpdate = GlobalSecondaryIndexUpdate.builder()
            .update(UpdateGlobalSecondaryIndexAction.builder()
                    .indexName(globalSecondaryIndexName)
                    .warmThroughput(gsiWarmThroughput)
                    .build()
            ).build();

    final UpdateTableRequest request = UpdateTableRequest.builder()
            .tableName(tableName)
            .globalSecondaryIndexUpdates(globalSecondaryIndexUpdate)
            .warmThroughput(tableWarmThroughput)
            .build();

    try {
        ddb.updateTable(request);
    } catch (DynamoDbException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    System.out.println("Done!");
}
```

------
#### [ Python ]

```
from boto3 import resource
from botocore.exceptions import ClientError

def update_dynamodb_table_warm_throughput(table_name, table_read_units, table_write_units, gsi_name, gsi_read_units, gsi_write_units, region_name="us-east-1"):
    """
    Updates the warm throughput of a DynamoDB table and a global secondary index.

    :param table_name: The name of the table to update.
    :param table_read_units: The new read units per second for the table's warm throughput.
    :param table_write_units: The new write units per second for the table's warm throughput.
    :param gsi_name: The name of the global secondary index to update.
    :param gsi_read_units: The new read units per second for the GSI's warm throughput.
    :param gsi_write_units: The new write units per second for the GSI's warm throughput.
    :param region_name: The AWS Region name to target. defaults to us-east-1
    """
    try:
        ddb = resource('dynamodb', region_name)
        
        # Update the table's warm throughput
        table_warm_throughput = {
            "ReadUnitsPerSecond": table_read_units,
            "WriteUnitsPerSecond": table_write_units
        }

        # Update the global secondary index's warm throughput
        gsi_warm_throughput = {
            "ReadUnitsPerSecond": gsi_read_units,
            "WriteUnitsPerSecond": gsi_write_units
        }

        # Construct the global secondary index update
        global_secondary_index_update = [
            {
                "Update": {
                    "IndexName": gsi_name,
                    "WarmThroughput": gsi_warm_throughput
                }
            }
        ]

        # Construct the update table request
        update_table_request = {
            "TableName": table_name,
            "GlobalSecondaryIndexUpdates": global_secondary_index_update,
            "WarmThroughput": table_warm_throughput
        }

        # Update the table
        ddb.update_table(**update_table_request)
        print("Table updated successfully!")
    except ClientError as e:
        print(f"Error updating table: {e}")
        raise e
```

------
#### [ Javascript ]

```
import { DynamoDBClient, UpdateTableCommand } from "@aws-sdk/client-dynamodb";

async function updateDynamoDBTableWarmThroughput(
  tableName,
  tableReadUnits,
  tableWriteUnits,
  gsiName,
  gsiReadUnits,
  gsiWriteUnits,
  region = "us-east-1"
) {
  try {
    const ddbClient = new DynamoDBClient({ region: region });

    // Construct the update table request
    const updateTableRequest = {
      TableName: tableName,
      GlobalSecondaryIndexUpdates: [
        {
            Update: {
                IndexName: gsiName,
                WarmThroughput: {
                    ReadUnitsPerSecond: gsiReadUnits,
                    WriteUnitsPerSecond: gsiWriteUnits,
                },
            },
        },
      ],
      WarmThroughput: {
          ReadUnitsPerSecond: tableReadUnits,
          WriteUnitsPerSecond: tableWriteUnits,
      },
    };

    const command = new UpdateTableCommand(updateTableRequest);
    const response = await ddbClient.send(command);
    console.log(`Table updated successfully! Response: ${response}`);
  } catch (error) {
    console.error(`Error updating table: ${error}`);
    throw error;
  }
}
```

------

# Creación de una tabla de DynamoDB nueva con rendimiento en caliente más alto
<a name="create-table-warm-throughput"></a>

Puede ajustar los valores de rendimiento en caliente cuando cree la tabla de DynamoDB según los pasos que se indican a continuación. Estos pasos también se aplican al crear una [tabla global](GlobalTables.md) o un [índice secundario](SecondaryIndexes.md).

## Consola de administración de AWS
<a name="warm-throughput-create-console"></a>

Para crear una tabla de DynamoDB y ajustar los valores de rendimiento en caliente a través de la consola:

1. Inicie sesión en la Consola de administración de AWS y abra la consola de DynamoDB en [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/).

1. Seleccione **Crear tabla**.

1. Elija un **nombre de tabla**, una **clave de partición** y una **clave de clasificación (opcional)**.

1. En **Configuración de la tabla**, elija **Personalizar configuración**.

1. En el campo **Rendimiento en caliente**, seleccione **Aumentar el rendimiento en caliente**.

1. Ajuste las **unidades de lectura por segundo** y las **unidades de escritura por segundo**. Estas dos configuraciones definen el rendimiento máximo que la tabla puede gestionar al instante.

1. Continúe agregando los detalles de tabla restantes y, a continuación, seleccione **Crear tabla**.

## AWS CLI
<a name="warm-throughput-create-CLI"></a>

En el siguiente ejemplo de la AWS CLI se muestra cómo crear una tabla de DynamoDB con valores de rendimiento en caliente personalizados.

1. Ejecute la operación `create-table` para crear la siguiente tabla de DynamoDB.

   ```
   aws dynamodb create-table \
       --table-name GameScores \
       --attribute-definitions AttributeName=UserId,AttributeType=S \
                               AttributeName=GameTitle,AttributeType=S \
                               AttributeName=TopScore,AttributeType=N  \
       --key-schema AttributeName=UserId,KeyType=HASH \
                    AttributeName=GameTitle,KeyType=RANGE \
       --provisioned-throughput ReadCapacityUnits=20,WriteCapacityUnits=10 \
       --global-secondary-indexes \
           "[
               {
                   \"IndexName\": \"GameTitleIndex\",
                   \"KeySchema\": [{\"AttributeName\":\"GameTitle\",\"KeyType\":\"HASH\"},
                                   {\"AttributeName\":\"TopScore\",\"KeyType\":\"RANGE\"}],
                   \"Projection\":{
                       \"ProjectionType\":\"INCLUDE\",
                       \"NonKeyAttributes\":[\"UserId\"]
                   },
                   \"ProvisionedThroughput\": {
                       \"ReadCapacityUnits\": 50,
                       \"WriteCapacityUnits\": 25
                   },\"WarmThroughput\": {
                       \"ReadUnitsPerSecond\": 1987,
                       \"WriteUnitsPerSecond\": 543
                   }
               }
           ]" \
       --warm-throughput ReadUnitsPerSecond=12345,WriteUnitsPerSecond=4567 \
       --region us-east-1
   ```

1. Verá una respuesta similar a la siguiente. La configuración de `WarmThroughput` se mostrará como `ReadUnitsPerSecond` y `WriteUnitsPerSecond`. El `Status` será `UPDATING` cuando se actualice el valor de rendimiento en caliente y `ACTIVE` cuando se establezca el nuevo valor de rendimiento en caliente.

   ```
   {
       "TableDescription": {
           "AttributeDefinitions": [
               {
                   "AttributeName": "GameTitle",
                   "AttributeType": "S"
               },
               {
                   "AttributeName": "TopScore",
                   "AttributeType": "N"
               },
               {
                   "AttributeName": "UserId",
                   "AttributeType": "S"
               }
           ],
           "TableName": "GameScores",
           "KeySchema": [
               {
                   "AttributeName": "UserId",
                   "KeyType": "HASH"
               },
               {
                   "AttributeName": "GameTitle",
                   "KeyType": "RANGE"
               }
           ],
           "TableStatus": "CREATING",
           "CreationDateTime": 1730241788.779,
           "ProvisionedThroughput": {
               "NumberOfDecreasesToday": 0,
               "ReadCapacityUnits": 20,
               "WriteCapacityUnits": 10
           },
           "TableSizeBytes": 0,
           "ItemCount": 0,
           "TableArn": "arn:aws:dynamodb:us-east-1:XXXXXXXXXXXX:table/GameScores",
           "TableId": "XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
           "GlobalSecondaryIndexes": [
               {
                   "IndexName": "GameTitleIndex",
                   "KeySchema": [
                       {
                           "AttributeName": "GameTitle",
                           "KeyType": "HASH"
                       },
                       {
                           "AttributeName": "TopScore",
                           "KeyType": "RANGE"
                       }
                   ],
                   "Projection": {
                       "ProjectionType": "INCLUDE",
                       "NonKeyAttributes": [
                           "UserId"
                       ]
                   },
                   "IndexStatus": "CREATING",
                   "ProvisionedThroughput": {
                       "NumberOfDecreasesToday": 0,
                       "ReadCapacityUnits": 50,
                       "WriteCapacityUnits": 25
                   },
                   "IndexSizeBytes": 0,
                   "ItemCount": 0,
                   "IndexArn": "arn:aws:dynamodb:us-east-1:XXXXXXXXXXXX:table/GameScores/index/GameTitleIndex",
                   "WarmThroughput": {
                       "ReadUnitsPerSecond": 1987,
                       "WriteUnitsPerSecond": 543,
                       "Status": "UPDATING"
                   }
               }
           ],
           "DeletionProtectionEnabled": false,
           "WarmThroughput": {
               "ReadUnitsPerSecond": 12345,
               "WriteUnitsPerSecond": 4567,
               "Status": "UPDATING"
           }
       }
   }
   ```

## AWS SDK
<a name="warm-throughput-create-SDK"></a>

En los siguientes ejemplos del SDK se muestra cómo crear una tabla de DynamoDB con valores de rendimiento en caliente personalizados.

------
#### [ Java ]

```
import software.amazon.awscdk.services.dynamodb.ProjectionType;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.Projection;
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.model.WarmThroughput;
...

public static WarmThroughput buildWarmThroughput(final Long readUnitsPerSecond,
                                                 final Long writeUnitsPerSecond) {
    return WarmThroughput.builder()
            .readUnitsPerSecond(readUnitsPerSecond)
            .writeUnitsPerSecond(writeUnitsPerSecond)
            .build();
}
private static AttributeDefinition buildAttributeDefinition(final String attributeName, 
                                                            final ScalarAttributeType scalarAttributeType) {
    return AttributeDefinition.builder()
            .attributeName(attributeName)
            .attributeType(scalarAttributeType)
            .build();
}
private static KeySchemaElement buildKeySchemaElement(final String attributeName, 
                                                      final KeyType keyType) {
    return KeySchemaElement.builder()
            .attributeName(attributeName)
            .keyType(keyType)
            .build();
}
public static void createDynamoDBTable(DynamoDbClient ddb,
                                       String tableName,
                                       String partitionKey,
                                       String sortKey,
                                       String miscellaneousKeyAttribute,
                                       String nonKeyAttribute,
                                       Long tableReadCapacityUnits,
                                       Long tableWriteCapacityUnits,
                                       Long tableWarmReadUnitsPerSecond,
                                       Long tableWarmWriteUnitsPerSecond,
                                       String globalSecondaryIndexName,
                                       Long globalSecondaryIndexReadCapacityUnits,
                                       Long globalSecondaryIndexWriteCapacityUnits,
                                       Long globalSecondaryIndexWarmReadUnitsPerSecond,
                                       Long globalSecondaryIndexWarmWriteUnitsPerSecond) {

    // Define the table attributes
    final AttributeDefinition partitionKeyAttribute = buildAttributeDefinition(partitionKey, ScalarAttributeType.S);
    final AttributeDefinition sortKeyAttribute = buildAttributeDefinition(sortKey, ScalarAttributeType.S);
    final AttributeDefinition miscellaneousKeyAttributeDefinition = buildAttributeDefinition(miscellaneousKeyAttribute, ScalarAttributeType.N);
    final AttributeDefinition[] attributeDefinitions = {partitionKeyAttribute, sortKeyAttribute, miscellaneousKeyAttributeDefinition};

    // Define the table key schema
    final KeySchemaElement partitionKeyElement = buildKeySchemaElement(partitionKey, KeyType.HASH);
    final KeySchemaElement sortKeyElement = buildKeySchemaElement(sortKey, KeyType.RANGE);
    final KeySchemaElement[] keySchema = {partitionKeyElement, sortKeyElement};

    // Define the provisioned throughput for the table
    final ProvisionedThroughput provisionedThroughput = ProvisionedThroughput.builder()
            .readCapacityUnits(tableReadCapacityUnits)
            .writeCapacityUnits(tableWriteCapacityUnits)
            .build();

    // Define the Global Secondary Index (GSI)
    final KeySchemaElement globalSecondaryIndexPartitionKeyElement = buildKeySchemaElement(sortKey, KeyType.HASH);
    final KeySchemaElement globalSecondaryIndexSortKeyElement = buildKeySchemaElement(miscellaneousKeyAttribute, KeyType.RANGE);
    final KeySchemaElement[] gsiKeySchema = {globalSecondaryIndexPartitionKeyElement, globalSecondaryIndexSortKeyElement};

    final Projection gsiProjection = Projection.builder()
            .projectionType(String.valueOf(ProjectionType.INCLUDE))
            .nonKeyAttributes(nonKeyAttribute)
            .build();
    final ProvisionedThroughput gsiProvisionedThroughput = ProvisionedThroughput.builder()
            .readCapacityUnits(globalSecondaryIndexReadCapacityUnits)
            .writeCapacityUnits(globalSecondaryIndexWriteCapacityUnits)
            .build();
    // Define the warm throughput for the Global Secondary Index (GSI)
    final WarmThroughput gsiWarmThroughput = buildWarmThroughput(globalSecondaryIndexWarmReadUnitsPerSecond, globalSecondaryIndexWarmWriteUnitsPerSecond);
    final GlobalSecondaryIndex globalSecondaryIndex = GlobalSecondaryIndex.builder()
            .indexName(globalSecondaryIndexName)
            .keySchema(gsiKeySchema)
            .projection(gsiProjection)
            .provisionedThroughput(gsiProvisionedThroughput)
            .warmThroughput(gsiWarmThroughput)
            .build();

    // Define the warm throughput for the table
    final WarmThroughput tableWarmThroughput = buildWarmThroughput(tableWarmReadUnitsPerSecond, tableWarmWriteUnitsPerSecond);

    final CreateTableRequest request = CreateTableRequest.builder()
            .tableName(tableName)
            .attributeDefinitions(attributeDefinitions)
            .keySchema(keySchema)
            .provisionedThroughput(provisionedThroughput)
            .globalSecondaryIndexes(globalSecondaryIndex)
            .warmThroughput(tableWarmThroughput)
            .build();

    CreateTableResponse response = ddb.createTable(request);
    System.out.println(response);
}
```

------
#### [ Python ]

```
from boto3 import resource
from botocore.exceptions import ClientError

def create_dynamodb_table_warm_throughput(table_name, partition_key, sort_key, misc_key_attr, non_key_attr, table_provisioned_read_units, table_provisioned_write_units, table_warm_reads, table_warm_writes, gsi_name, gsi_provisioned_read_units, gsi_provisioned_write_units, gsi_warm_reads, gsi_warm_writes, region_name="us-east-1"):
    """
    Creates a DynamoDB table with a warm throughput setting configured.

    :param table_name: The name of the table to be created.
    :param partition_key: The partition key for the table being created.
    :param sort_key: The sort key for the table being created.
    :param misc_key_attr: A miscellaneous key attribute for the table being created.
    :param non_key_attr: A non-key attribute for the table being created.
    :param table_provisioned_read_units: The newly created table's provisioned read capacity units.
    :param table_provisioned_write_units: The newly created table's provisioned write capacity units.
    :param table_warm_reads: The read units per second setting for the table's warm throughput.
    :param table_warm_writes: The write units per second setting for the table's warm throughput.
    :param gsi_name: The name of the Global Secondary Index (GSI) to be created on the table.
    :param gsi_provisioned_read_units: The configured Global Secondary Index (GSI) provisioned read capacity units.
    :param gsi_provisioned_write_units: The configured Global Secondary Index (GSI) provisioned write capacity units.
    :param gsi_warm_reads: The read units per second setting for the Global Secondary Index (GSI)'s warm throughput.
    :param gsi_warm_writes: The write units per second setting for the Global Secondary Index (GSI)'s warm throughput.
    :param region_name: The AWS Region name to target. defaults to us-east-1
    """
    try:
        ddb = resource('dynamodb', region_name)
        
        # Define the table attributes
        attribute_definitions = [
            { "AttributeName": partition_key, "AttributeType": "S" },
            { "AttributeName": sort_key, "AttributeType": "S" },
            { "AttributeName": misc_key_attr, "AttributeType": "N" }
        ]
        
        # Define the table key schema
        key_schema = [
            { "AttributeName": partition_key, "KeyType": "HASH" },
            { "AttributeName": sort_key, "KeyType": "RANGE" }
        ]
        
        # Define the provisioned throughput for the table
        provisioned_throughput = {
            "ReadCapacityUnits": table_provisioned_read_units,
            "WriteCapacityUnits": table_provisioned_write_units
        }
        
        # Define the global secondary index
        gsi_key_schema = [
            { "AttributeName": sort_key, "KeyType": "HASH" },
            { "AttributeName": misc_key_attr, "KeyType": "RANGE" }
        ]
        gsi_projection = {
            "ProjectionType": "INCLUDE",
            "NonKeyAttributes": [non_key_attr]
        }
        gsi_provisioned_throughput = {
            "ReadCapacityUnits": gsi_provisioned_read_units,
            "WriteCapacityUnits": gsi_provisioned_write_units
        }
        gsi_warm_throughput = {
            "ReadUnitsPerSecond": gsi_warm_reads,
            "WriteUnitsPerSecond": gsi_warm_writes
        }
        global_secondary_indexes = [
            {
                "IndexName": gsi_name,
                "KeySchema": gsi_key_schema,
                "Projection": gsi_projection,
                "ProvisionedThroughput": gsi_provisioned_throughput,
                "WarmThroughput": gsi_warm_throughput
            }
        ]
        
        # Define the warm throughput for the table
        warm_throughput = {
            "ReadUnitsPerSecond": table_warm_reads,
            "WriteUnitsPerSecond": table_warm_writes
        }
        
        # Create the DynamoDB client and create the table
        response = ddb.create_table(
            TableName=table_name,
            AttributeDefinitions=attribute_definitions,
            KeySchema=key_schema,
            ProvisionedThroughput=provisioned_throughput,
            GlobalSecondaryIndexes=global_secondary_indexes,
            WarmThroughput=warm_throughput
        )
        
        print(response)
    except ClientError as e:
        print(f"Error creating table: {e}")
        raise e
```

------
#### [ Javascript ]

```
import { DynamoDBClient, CreateTableCommand } from "@aws-sdk/client-dynamodb";

async function createDynamoDBTableWithWarmThroughput(
  tableName,
  partitionKey,
  sortKey,
  miscKeyAttr,
  nonKeyAttr,
  tableProvisionedReadUnits,
  tableProvisionedWriteUnits,
  tableWarmReads,
  tableWarmWrites,
  indexName,
  indexProvisionedReadUnits,
  indexProvisionedWriteUnits,
  indexWarmReads,
  indexWarmWrites,
  region = "us-east-1"
) {
  try {
    const ddbClient = new DynamoDBClient({ region: region });
    const command = new CreateTableCommand({
      TableName: tableName,
      AttributeDefinitions: [
          { AttributeName: partitionKey, AttributeType: "S" },
          { AttributeName: sortKey, AttributeType: "S" },
          { AttributeName: miscKeyAttr, AttributeType: "N" },
      ],
      KeySchema: [
          { AttributeName: partitionKey, KeyType: "HASH" },
          { AttributeName: sortKey, KeyType: "RANGE" },
      ],
      ProvisionedThroughput: {
          ReadCapacityUnits: tableProvisionedReadUnits,
          WriteCapacityUnits: tableProvisionedWriteUnits,
      },
      WarmThroughput: {
          ReadUnitsPerSecond: tableWarmReads,
          WriteUnitsPerSecond: tableWarmWrites,
      },
      GlobalSecondaryIndexes: [
          {
            IndexName: indexName,
            KeySchema: [
                { AttributeName: sortKey, KeyType: "HASH" },
                { AttributeName: miscKeyAttr, KeyType: "RANGE" },
            ],
            Projection: {
                ProjectionType: "INCLUDE",
                NonKeyAttributes: [nonKeyAttr],
            },
            ProvisionedThroughput: {
                ReadCapacityUnits: indexProvisionedReadUnits,
                WriteCapacityUnits: indexProvisionedWriteUnits,
            },
            WarmThroughput: {
                ReadUnitsPerSecond: indexWarmReads,
                WriteUnitsPerSecond: indexWarmWrites,
            },
          },
      ],
    });
    const response = await ddbClient.send(command);
    console.log(response);
  } catch (error) {
    console.error(`Error creating table: ${error}`);
    throw error;
  }
}
```

------

# Descripción del rendimiento en caliente de DynamoDB en diferentes escenarios
<a name="warm-throughput-scenarios"></a>

A continuación se presentan algunos escenarios diferentes que puede encontrar al trabajar con rendimiento en caliente de DynamoDB.

**Topics**
+ [Rendimiento en caliente y patrones de acceso desiguales](#warm-throughput-scenarios-uneven)
+ [Rendimiento en caliente para una tabla aprovisionada](#warm-throughput-scenarios-provisioned)
+ [Rendimiento en caliente de una tabla bajo demanda](#warm-throughput-scenarios-ondemand)
+ [Rendimiento en caliente para una tabla bajo demanda con el máximo rendimiento configurado](#warm-throughput-scenarios-max)

## Rendimiento en caliente y patrones de acceso desiguales
<a name="warm-throughput-scenarios-uneven"></a>

Una tabla puede tener un rendimiento en caliente de 30 000 unidades de lectura por segundo y de 10 000 unidades de escritura por segundo, pero aún así podría experimentar una limitación en las lecturas o escrituras antes de llegar a esos valores. Se debe probablemente a una partición activa. Aunque DynamoDB puede seguir escalando para soportar un rendimiento prácticamente ilimitado, cada partición individual está limitada a 1000 unidades de escritura por segundo y 3000 unidades de lectura por segundo. Si la aplicación dirige demasiado tráfico a una pequeña parte de las particiones de la tabla, puede producirse una limitación incluso antes de alcanzar los valores de rendimiento en caliente de la tabla. Recomendamos seguir las [prácticas recomendadas de DynamoDB](bp-partition-key-design.md) para garantizar una escalabilidad fluida y evitar las particiones en caliente.

## Rendimiento en caliente para una tabla aprovisionada
<a name="warm-throughput-scenarios-provisioned"></a>

Considere una tabla aprovisionada que tiene un rendimiento en caliente de 30 000 unidades de lectura por segundo y 10 000 unidades de escritura por segundo, pero que actualmente tiene un rendimiento aprovisionado de 4000 RCU y 8000 WCU. Puede escalar instantáneamente el rendimiento aprovisionado de la tabla hasta 30 000 RCU o 10 000 WCU actualizando la configuración de rendimiento aprovisionada. A medida que aumente el rendimiento en caliente aprovisionado por encima de estos valores, el rendimiento en caliente se ajustará automáticamente a los nuevos valores superiores, porque habrá establecido un nuevo rendimiento pico. Por ejemplo, si establece el rendimiento en caliente aprovisionado en 50 000 RCU, el rendimiento en caliente aumentará a 50 000 unidades de lectura por segundo.

```
"ProvisionedThroughput": 
    {
        "ReadCapacityUnits": 4000,
        "WriteCapacityUnits": 8000 
    }
"WarmThroughput": 
    { 
        "ReadUnitsPerSecond": 30000,
        "WriteUnitsPerSecond": 10000
    }
```

## Rendimiento en caliente de una tabla bajo demanda
<a name="warm-throughput-scenarios-ondemand"></a>

Una nueva tabla bajo demanda comienza con un rendimiento en caliente de 12 000 unidades de lectura por segundo y 4000 unidades de escritura por segundo. La tabla puede acomodar de forma instantánea un tráfico sostenido hasta estos niveles. Cuando las solicitudes superen las 12 000 unidades de lectura por segundo o las 4000 unidades de escritura por segundo, el rendimiento en caliente se ajustará automáticamente a valores superiores.

```
"WarmThroughput": 
    { 
        "ReadUnitsPerSecond": 12000,
        "WriteUnitsPerSecond": 4000
    }
```

## Rendimiento en caliente para una tabla bajo demanda con el máximo rendimiento configurado
<a name="warm-throughput-scenarios-max"></a>

Considere una tabla bajo demanda con un rendimiento en caliente de 30 000 unidades de lectura por segundo, pero con un [rendimiento máximo](on-demand-capacity-mode-max-throughput.md) configurado en 5000 unidades de solicitud de lectura (RRU). En este caso, el rendimiento de la tabla se limitará al máximo de las 5000 RRU que ha establecido. Cualquier solicitud de rendimiento que supere este máximo se limitará. No obstante, puede modificar en cualquier momento el rendimiento máximo específico de la tabla en función de las necesidades de la aplicación.

```
"OnDemandThroughput": 
    {
        "MaxReadRequestUnits": 5000,
        "MaxWriteRequestUnits": 4000
    }
"WarmThroughput": 
    { 
        "ReadUnitsPerSecond": 30000,
        "WriteUnitsPerSecond": 10000
    }
```