I have a Java-based backend app which issues a getItem request to my DynamoDB table based on a request from my user. Occasionally my user sends a request to my app which ends up sending a getItem request to DynamoDB which hits the maximum size limit of the key below (quote from https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html ):
For a simple primary key, the maximum length of the first attribute value (the partition key) is 2048 bytes.
I get this error from the DynamoDB SDK when that happens: One or more parameter values were invalid: Size of hashkey has exceeded the maximum size limit of 2048 bytes
Now I need to implement a validation for this situation where my user sends a request which hits the limit to avoid the error. My question here is: what is the right way to implement this validation in my app? Judging by the documentation linked above, DynamoDB seems to be using UTF-8 internally, so will something like below be fine?
boolean isPartitionKeySizeValid(String partitionKey) {
int size = partitionKey.getBytes(StandardCharsets.UTF_8).length;
return 1 <= size && size <= 2048;
}
My app uses the com.amazonaws:aws-java-sdk-dynamodb
library to interact with DynamoDB.
2
Answers
Yes simply counting the byte length will allow you to avoid hitting the 2KB partition key value limit.
If your table does not use a sort key, the 2048 bytes should fit in the length of the partition-key name, in addition to the UTF-8-encoded value. For a composite key, the length is limited to 1024.