Skip to content

BatchElements transform for Java SDK#38369

Open
ganesh-skumar wants to merge 8 commits intoapache:masterfrom
ganesh-skumar:java-batch-elements
Open

BatchElements transform for Java SDK#38369
ganesh-skumar wants to merge 8 commits intoapache:masterfrom
ganesh-skumar:java-batch-elements

Conversation

@ganesh-skumar
Copy link
Copy Markdown

@ganesh-skumar ganesh-skumar commented May 5, 2026

Introduces BatchElements transform for Java SDK with dynamic batching


Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@ganesh-skumar
Copy link
Copy Markdown
Author

Continuing work from my previous PR under a new account due to access issues with @Ganeshsivakumar

Original PR: #38280

No major changes, this PR just picks up where the previous one left off.

@ganesh-skumar ganesh-skumar marked this pull request as ready for review May 5, 2026 06:57
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces the BatchElements transform to the Apache Beam Java SDK. This transform is designed to optimize processing performance for operations with significant fixed costs by grouping elements into batches. It features a sophisticated, self-tuning mechanism that dynamically adjusts batch sizes based on observed processing times, allowing it to adapt to varying workloads while respecting user-defined constraints. The implementation handles both global and windowed PCollections, ensuring correct window isolation for batched elements.

Highlights

  • New BatchElements Transform: Introduced a new PTransform, BatchElements, to the Java SDK, enabling dynamic batching of elements to improve throughput by amortizing fixed processing costs.
  • Dynamic Batching Logic: Implemented a BatchSizeEstimator that uses linear regression on historical processing times to dynamically adjust batch sizes between configured minimum and maximum limits.
  • Window-Aware Batching: Added support for window-aware batching, ensuring that elements from different windows are not mixed within the same batch.
  • Comprehensive Testing: Added a new test suite, BatchElementsTest, covering configuration validation, estimator logic, and pipeline integration tests for both global and windowed contexts.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces the BatchElements transform, which dynamically adjusts batch sizes by profiling downstream processing time using linear regression. The implementation provides a flexible configuration and handles both global and windowed data. Several critical issues were identified: a unit mismatch in the batch size estimator (seconds vs. milliseconds), a window contamination bug in the eviction logic of WindowAwareBatchingDoFn, and the need for higher precision timing using System.nanoTime(). Additionally, it is recommended to use the existing Random instance for jitter and to increase the MAX_LIVE_WINDOWS limit to improve performance in complex windowing scenarios.

Comment on lines +396 to +401
target = Math.min(target, (config.targetBatchDurationSecsWithFixedCost - a) / b);
}

// 2: b*x = targetDurationSecs
if (config.targetBatchDurationSecs > 0) {
target = Math.min(target, config.targetBatchDurationSecs / b);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There is a unit mismatch in the batch size calculation. The configuration parameters targetBatchDurationSecs and targetBatchDurationSecsWithFixedCost are defined in seconds, but the regression coefficients a (fixed cost) and b (per-element cost) are derived from System.currentTimeMillis(), meaning they are in milliseconds. This results in the estimator calculating a target batch size that is 1000x smaller than intended. You should convert the target durations to milliseconds before performing the calculation.

Copy link
Copy Markdown
Author

@ganesh-skumar ganesh-skumar May 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

converts both to milliseconds in new commit

Map.Entry<BoundedWindow, SizedBatch<T>> largest =
batches.entrySet().stream().max(Comparator.comparingInt(e -> e.getValue().size)).get();

try (BatchSizeEstimator.Stopwatch sw = estimator.recordTime(largest.getValue().size)) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

This eviction logic causes cross-window data contamination. In Beam, receiver.output() called within processElement automatically associates the output with the current element's window. By evicting and outputting a batch from a different window (largest.getKey()), those elements will be incorrectly re-assigned to the current window. To correctly output elements to a different window, you must do so within finishBundle using the FinishBundleContext, or use a more advanced API that allows specifying the window for each output.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Attaches correct window value before emitting

Comment on lines +288 to +293
this.startTime = System.currentTimeMillis();
}

@Override
public void close() {
long elapsed = System.currentTimeMillis() - startTime;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

System.currentTimeMillis() lacks the precision required for profiling fast operations like element batching, as it often has a resolution of 1ms or more (depending on the OS). For small batches that process quickly, this will frequently result in zero-duration measurements, which negatively impacts the accuracy of the linear regression. It is highly recommended to use System.nanoTime() for more precise micro-benchmarking.

// add jitter to avoid any single batch size
int jitter = data.size() % 2;
if (data.size() > 10) {
target += (int) (target * config.variance * 2 * (Math.random() - 0.5));
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The class already maintains a Random instance. It is better to use random.nextDouble() for consistency and to allow for potential reproducibility in tests if a seed is provided.

Suggested change
target += (int) (target * config.variance * 2 * (Math.random() - 0.5));
target += (int) (target * config.variance * 2 * (random.nextDouble() - 0.5));

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

committed

private Map<BoundedWindow, SizedBatch<T>> batches;
private int targetBatchSize;

private static final int MAX_LIVE_WINDOWS = 10;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The MAX_LIVE_WINDOWS limit of 10 is extremely low for many Beam use cases, such as pipelines with sliding windows or significant data out-of-orderness. When this limit is reached, the transform will aggressively evict batches, leading to very small batch sizes and poor efficiency. Consider increasing this default significantly (e.g., to 1000) or making it a configurable parameter in BatchConfig.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Goal is to match python's BatchElements implementation.

@ganesh-skumar
Copy link
Copy Markdown
Author

Hi Jack, could you please review this PR when you have some time.
R: @jrmccluskey

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 5, 2026

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants