Skip to content

[PubsubIO] Batch bounded writes by the encoded request size - #39886

Open
1fanwang wants to merge 5 commits into
apache:masterfrom
1fanwang:pubsub-bounded-batch-size-28011
Open

1fanwang wants to merge 5 commits into
apache:masterfrom
1fanwang:pubsub-bounded-batch-size-28011

Conversation

@1fanwang

@1fanwang 1fanwang commented Aug 25, 2026 •

Copy link
Copy Markdown

A bounded PubsubIO write can send a publish request that Pub/Sub rejects for being over its 10 MB limit (limits). The writer ends a batch by adding up the payload, attribute and ordering key sizes of its messages, and that sum is not the size of the request the client sends. In the reproducer below, 100 messages that each carry 100 maximum-size attributes go out as one 12.9 MB request, and attribute values made of control characters, which JSON writes as six-byte escapes, make it 64 MB.

Each client now reports what a message adds to the request it sends: the JSON body for REST, the protobuf encoding for gRPC. The writer starts a new request before the next message would pass 10 MB, and fails before publishing anything when a message cannot fit in a request at all. withMaxBatchBytesSize now bounds the encoded request, and 10 MB is its default, up from 7.5 MB.

Pub/Sub does not document whether its limit applies to the REST body or to the transcoded protobuf (#31800), so each client measures what it sends. The per-message validator that runs before the writer is unchanged.

Fixes #28011

Testing Done

The reproducer writes 100 messages, each with 100 maximum-size attributes, through a bounded PubsubIO write on the direct runner: once with plain attribute values and once with control-character values. A local HTTP server stands in for Pub/Sub. It reads each publish request that the real JSON client sends and answers 400 to any request over 10,000,000 bytes. Nothing talks to live Pub/Sub, and the gRPC client is not part of this run; PubsubGrpcClientTest compares its sizes with the serialized request.

Before: the main sources from base commit 0fa1aca.

export JAVA_HOME=/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home
export PATH="$JAVA_HOME/bin:$PATH"
git checkout 0fa1aca27e7d234bef53bc2409b833629457fb7b -- sdks/java/io/google-cloud-platform/src/main
CP=$(./gradlew -q -I cp.init.gradle.kts :sdks:java:io:google-cloud-platform:printTestRuntimeClasspath)
java -Xmx2g -cp "$CP" PubsubBatchRepro.java
maximum-size attributes:
  request 1: 100 messages, 12864114 bytes -> 400 Request payload size exceeds the limit
  pipeline failed: 400 Bad Request
control-character attributes:
  request 1: 100 messages, 64064114 bytes -> 400 Request payload size exceeds the limit
  pipeline failed: 400 Bad Request

After: the main sources from this branch.

git checkout 3679c9763e112a6a352812a3be4fc20a52ea0740 -- sdks/java/io/google-cloud-platform/src/main
CP=$(./gradlew -q -I cp.init.gradle.kts :sdks:java:io:google-cloud-platform:printTestRuntimeClasspath)
java -Xmx2g -cp "$CP" PubsubBatchRepro.java
maximum-size attributes:
  request 1: 77 messages, 9905371 bytes -> 200
  request 2: 23 messages, 2958757 bytes -> 200
  pipeline finished
control-character attributes:
  request 1: 15 messages, 9609629 bytes -> 200
  request 2: 15 messages, 9609629 bytes -> 200
  request 3: 15 messages, 9609629 bytes -> 200
  request 4: 15 messages, 9609629 bytes -> 200
  request 5: 15 messages, 9609629 bytes -> 200
  request 6: 15 messages, 9609629 bytes -> 200
  request 7: 10 messages, 6406424 bytes -> 200
  pipeline finished
Reproducer source: PubsubBatchRepro.java
import com.google.gson.JsonParser;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayInputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.GZIPInputStream;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.extensions.gcp.auth.NoopCredentialFactory;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubMessage;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubMessageWithAttributesCoder;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.Flatten;
import org.apache.beam.sdk.transforms.GroupByKey;
import org.apache.beam.sdk.transforms.Values;
import org.apache.beam.sdk.transforms.WithKeys;

/** Writes 100 messages with 100 maximum-size attributes through a bounded PubsubIO write. */
public class PubsubBatchRepro {
  private static final int REQUEST_LIMIT = 10_000_000;

  public static void main(String[] args) throws Exception {
    run("maximum-size attributes", 'v');
    run("control-character attributes", (char) 1);
  }

  private static void run(String name, char attributeValue) throws Exception {
    AtomicInteger requests = new AtomicInteger();
    HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
    server.createContext(
        "/",
        exchange -> {
          byte[] body = exchange.getRequestBody().readAllBytes();
          if ("gzip".equals(exchange.getRequestHeaders().getFirst("Content-Encoding"))) {
            body = new GZIPInputStream(new ByteArrayInputStream(body)).readAllBytes();
          }
          int messages =
              JsonParser.parseString(new String(body, StandardCharsets.UTF_8))
                  .getAsJsonObject()
                  .getAsJsonArray("messages")
                  .size();
          boolean accepted = body.length <= REQUEST_LIMIT;
          System.out.printf(
              "  request %d: %d messages, %d bytes -> %s%n",
              requests.incrementAndGet(),
              messages,
              body.length,
              accepted ? "200" : "400 Request payload size exceeds the limit");
          byte[] response =
              (accepted
                      ? "{\"messageIds\":["
                          + String.join(",", Collections.nCopies(messages, "\"id\""))
                          + "]}"
                      : "{\"error\":{\"code\":400,\"status\":\"INVALID_ARGUMENT\","
                          + "\"message\":\"Request payload size exceeds the limit: 10000000 bytes.\"}}")
                  .getBytes(StandardCharsets.UTF_8);
          exchange.getResponseHeaders().add("Content-Type", "application/json");
          exchange.sendResponseHeaders(accepted ? 200 : 400, response.length);
          exchange.getResponseBody().write(response);
          exchange.close();
        });
    server.start();

    Map<String, String> attributes = new HashMap<>();
    for (int i = 0; i < 100; i++) {
      attributes.put(String.format("%0256d", i), String.valueOf(attributeValue).repeat(1024));
    }
    List<PubsubMessage> messages = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
      messages.add(new PubsubMessage(new byte[10], attributes));
    }

    PubsubOptions options = PipelineOptionsFactory.create().as(PubsubOptions.class);
    options.setCredentialFactoryClass(NoopCredentialFactory.class);
    options.setPubsubRootUrl("http://localhost:" + server.getAddress().getPort());
    Pipeline pipeline = Pipeline.create(options);
    // One key puts every message into the same bundle, so the writer batches all of them.
    pipeline
        .apply(Create.of(messages).withCoder(PubsubMessageWithAttributesCoder.of()))
        .apply(WithKeys.of("one key"))
        .apply(GroupByKey.create())
        .apply(Values.<Iterable<PubsubMessage>>create())
        .apply(Flatten.<PubsubMessage>iterables())
        .apply(PubsubIO.writeMessages().to("projects/project/topics/topic"));

    System.out.println(name + ":");
    try {
      pipeline.run().waitUntilFinish();
      System.out.println("  pipeline finished");
    } catch (RuntimeException e) {
      Throwable root = e;
      while (root.getCause() != null) {
        root = root.getCause();
      }
      System.out.println("  pipeline failed: " + root.getMessage().lines().findFirst().get());
    } finally {
      server.stop(0);
    }
  }
}
Reproducer source: cp.init.gradle.kts
allprojects {
    afterEvaluate {
        if (path == ":sdks:java:io:google-cloud-platform") {
            val testRuntime = configurations.getByName("testRuntimeClasspath")
            val mainOutput = extensions.getByType<SourceSetContainer>()["main"].output
            tasks.register("printTestRuntimeClasspath") {
                dependsOn("classes")
                inputs.files(testRuntime)
                doLast { println(mainOutput.asPath + ":" + testRuntime.asPath) }
            }
        }
    }
}

Signed-off-by: 1fanwang <1fannnw@gmail.com>
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @kennknowles for label java.

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Reminder, please take a look at this pr: @kennknowles

@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment assign to next reviewer:

R: @ahmedabu98 for label java.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

@kennknowles

Copy link
Copy Markdown
Member

R: @sjvanrossum

Since you made some of the surrounding comments, are you able to review this?

@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment assign set of reviewers

@sjvanrossum

Copy link
Copy Markdown
Contributor

If I'm not mistaken, the default value of maxPublishBatchByteSize (7.5 MB) already factors in most of the expected overhead, but a batch with every field other than data pushed to their maximum limits may still exceed the 2.5 MB that's left. The most conservative safe limit on data alone is closer to 7.2 MB iirc.
We could raise the default value of maxPublishBatchByteSize to 10 MB and use the validated message size, but you may still exceed the total payload size accepted by the API because gRPC adds more overhead to the attributes map during encoding.
Not raising maxPublishBatchByteSize and merging this PR as is would mean that we're effectively capping the encoded batch payload size to 75% of what Pub/Sub supports.

I recall that the Pub/Sub team was going to raise the maximum payload size from 10 MB to 10 MiB. If they did, then the unaccounted overhead above 2.5 MB should fit in the additional ~0.5 MB that you get out of 10 MiB.

TL;DR The proposed change leaves 25% of the maximum accepted payload size unused and raising the default maximum accepted payload size may still lead to a rejection of the batch publish request.

…tch-size-28011

Signed-off-by: 1fanwang <1fannnw@gmail.com>
@github-actions github-actions Bot added the size/s S: 10-49 lines changed label Nov 10, 2026
@kennknowles

Copy link
Copy Markdown
Member

OK so that sounds like something we shouldn't do. Is there a way to just make this all more precise byte tracking and less offline math?

Each client reports the bytes a message adds to the publish request it
sends: the JSON body for REST, the protobuf encoding for gRPC. The
writer cuts batches against the 10 MB request limit with those sizes,
and a message that cannot fit a request fails before anything is
published.

Fixes apache#28011

Signed-off-by: 1fanwang <1fannnw@gmail.com>
@1fanwang 1fanwang changed the title [PubsubIO] Account for message metadata in bounded write batch size [PubsubIO] Batch bounded writes by the encoded request size Nov 17, 2026
…tch-size-28011

Signed-off-by: 1fanwang <1fannnw@gmail.com>

# Conflicts:
#	CHANGES.md
@1fanwang

Copy link
Copy Markdown
Author

Is there a way to just make this all more precise byte tracking and less offline math?

Yes. Each client now reports the exact bytes a message adds to the request it sends, the JSON body for REST and the protobuf for gRPC, and the writer cuts batches against the 10 MB limit with those sizes, so the batching does no offline sums. The per-message validator that runs first is unchanged. The PR description has a before and after run.

3679c97

@github-actions github-actions Bot added size/l L: 250-999 lines changed and removed size/s S: 10-49 lines changed labels Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: PubsubIO used in batch incorrect batch cutoff size

3 participants