There are limits on the size of published SQS messages. A single message can not be larger than 256 KB and a batch of messages (max of 10) also cannot exceed 256 KB. When adding messages to a collection to later publish to an SQS queue, how can I keep track of the message sizes to ensure my request stays under the limit?
I have looked at methods to get the size of an object and I know that the IDs of the failed messages will be available to me after calling sendMessageBatch()
. I don't feel like either of these are very good solutions because the size of the object itself omits the overhead data from the message (that I assume also counts), and I would really like to not have to manage failed messages simply because the batch was too large. I really don't expect my messages to ever be that large but you never know.
Code snippet to batch and send:
List<SendMessageBatchRequestEntry> entries = new LinkedList<>();
And then in a loop:
SendMessageBatchRequestEntry entry = new SendMessageBatchRequestEntry();
entry.setMessageBody(gson.toJson(message));
entry.setMessageAttributes(attributes);
entry.setId(messageId);
// How to make sure `entry` is not larger than 256 KB, and how to
// make sure adding this entry won't cause the batch to exeed 256 KB?
entries.add(entry);
And lastly:
client.sendMessageBatch(queueUrl, entries);