private void writeToPubsub(
      Time batchTime, int partitionId, Iterator<AggregateResult> aggregateResultIterator)
      throws IOException {
    String timestamp = ISODateTimeFormat.dateTime().print(batchTime.milliseconds());
    String batchId =
        getFormatterPrefix().print(batchTime.milliseconds())
            + batchTime.milliseconds()
            + "-"
            + partitionId;

    TreeMap<String, Object> batchMap = new TreeMap<>();
    batchMap.put("batch_id", batchId);

    List<Map<String, Object>> batches = new LinkedList<>();
    while (aggregateResultIterator.hasNext()) {
      AggregateResult aggrResult = aggregateResultIterator.next();
      TreeMap<String, Object> map = new TreeMap<>();
      map.putAll(aggrResult.getDimensions());
      map.putAll(aggrResult.getMetrics());
      map.put(WINDOW_TIMESTAMP_KEY, timestamp);
      batches.add(map);
    }

    if (batches.isEmpty()) return;
    batchMap.put("aggregated_result", batches);
    pubsubManager.writeAggregatedOutput(topic, objectMapper.writeValueAsString(batchMap));
  }