This topic describes how to calculate the size of events that are published by the PutEvents operation. You can add multiple events to a single request to improve efficiency.

Scenarios

You can call the PutEvents operation to add custom events to EventBridge. Before you call the PutEvents operation to add multiple events, you can calculate the total size of all events to ensure that the event size does not exceed 256 KB. Then, you can add these events to a single request to improve efficiency.

The following section shows how to calculate the event size.

Calculation method

Use the following parameters to calculate the size of CloudEvent:

  • time: the data size is generally 36 bytes.
  • specversion: measured by the number of bytes encoded in UTF-8.
  • id: measured by the number of bytes encoded in UTF-8.
  • type: measured by the number of bytes encoded in UTF-8.
  • source: measured by the number of bytes encoded in UTF-8.
  • subject: measured by the number of bytes encoded in UTF-8.
  • dataschema: measured by the number of bytes encoded in UTF-8.
  • datacontenttype: measured by the number of bytes encoded in UTF-8.
  • data: measured by the length of byte[].

Sample code

The following Java sample code is used to calculate the size of a single CloudEvent:

int getSize(CloudEvent event) {
    int size = 0;
    if (event.getTime() != null) {
        size += 36;
    }
    size += event.getSpecversion().getBytes(StandardCharsets.UTF_8).length;
    size += event.getId().getBytes(StandardCharsets.UTF_8).length;
    size += event.getType().getBytes(StandardCharsets.UTF_8).length;
    size += event.getSource().toString().getBytes(StandardCharsets.UTF_8).length;
    size += event.getSubject().getBytes(StandardCharsets.UTF_8).length;
    size += event.getDataschema().toString().getBytes(StandardCharsets.UTF_8).length;
    size += event.getDatacontenttype().getBytes(StandardCharsets.UTF_8).length;
    size += event.getData().length;   
    return size;
}