The Databricks Zerobus Ingest SDK for Java provides a high-performance client for ingesting data directly into Databricks Delta tables using the Zerobus streaming protocol.
- Features
- Architecture
- Requirements
- Quick Start User Guide
- Usage Examples
- Authentication
- API Styles
- Configuration
- Logging
- Error Handling
- API Reference
- Best Practices
- Community and Contributing
- License
- High-throughput ingestion: Optimized for high-volume data ingestion via native Rust backend
- Native performance: JNI bindings to a high-performance Rust implementation
- Automatic recovery: Built-in retry and recovery mechanisms
- Flexible configuration: Customizable stream behavior and timeouts
- Protocol Buffers: Strongly-typed schema using protobuf
- JSON support: Ingest JSON records without Protocol Buffer schemas
- Arrow Flight: Columnar ingestion of Apache Arrow
VectorSchemaRootbatches - Avro (Beta): Ingest Avro record objects (need Java 11+) or pre-encoded datums (see Avro Examples)
- Offset-based API: Low-overhead alternative to CompletableFuture for high throughput
- OAuth 2.0 authentication: Secure authentication with client credentials
- Custom authentication: Supply request headers with
HeadersProvider - External-IdP federation: Authenticate with a token from an external identity provider such as Microsoft Entra ID, with no Databricks OAuth secret
- Framework compatible: Works inside Spring Boot and other frameworks with isolated classloaders
The Java SDK uses JNI (Java Native Interface) to call a high-performance Rust implementation. This architecture provides:
- Lower latency: Direct native calls avoid Java gRPC overhead
- Reduced memory: Offset-based API eliminates CompletableFuture allocation per record
- Better throughput: Optimized Rust async runtime handles network I/O efficiently
┌───────────────────────────────────────────────────────────────┐
│ Java Application │
├───────────────────────────────────────────────────────────────┤
│ ZerobusSdk │ ZerobusProtoStream │ ZerobusJsonStream │
├───────────────────────────────────────────────────────────────┤
│ BaseZerobusStream (JNI) │
├───────────────────────────────────────────────────────────────┤
│ Native Rust SDK (libzerobus_jni) │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Tokio │ │ gRPC/ │ │
│ │ Runtime │ │ HTTP/2 │ │
│ └─────────────┘ └─────────────┘ │
└───────────────────────────────────────────────────────────────┘
- Java: 8 or higher to run a published JAR. Building and testing from source requires JDK 11 or higher.
- Databricks workspace with Zerobus access enabled
This SDK includes native libraries for the following platforms:
| Platform | Architecture | Status |
|---|---|---|
| Linux (glibc) | x86_64 | Supported |
| Linux (glibc) | aarch64 | Supported |
| Linux (musl / Alpine) | x86_64 | Supported |
| Linux (musl / Alpine) | aarch64 | Supported |
| Windows | x86_64 | Supported |
| macOS | x86_64 | Source-build only; the published JNI artifacts currently include Linux and Windows |
| macOS | aarch64 (Apple Silicon) | Source-build only; the published JNI artifacts currently include Linux and Windows |
Linux glibc builds support glibc 2.26 and newer, including Amazon Linux 2.
On Linux, the libc flavor (glibc vs musl) is detected at runtime. To override detection, set
-Dzerobus.libc=musl or -Dzerobus.libc=glibc on the JVM command line.
When using Maven or Gradle (regular JAR, recommended):
- The regular JAR does not bring in
protobuf-java. Declare it in your build file. The SDK is built and tested against protobuf-java 4.33.0, which the fat JAR bundles. From SDK v1.9.0, protobuf-java 3.25.x is supported too, and that release is tested with 3.25.9. Maven uses the version your project declares directly. Gradle picks the highest version in the graph, so if another dependency in your graph brings a newer protobuf-java, force the 3.25.x version you declare (for example withresolutionStrategy.force). Check the resolved version withdependencies. slf4j-apimust be on the classpath. An SLF4J implementation such asslf4j-simple2.0.17 orlogback-classic1.4.14 brings in a matchingslf4j-api. Avoid declaringslf4j-apidirectly: a 2.x declaration overrides the 1.x API that a binding such aslog4j-slf4j-implexpects, and then its logging silently stops.
When using the fat JAR (standalone scripts or CLI tools without a build system):
- No additional dependencies required - all dependencies are bundled. The bundled
protobuf-javais 4.33.0. If your application uses protobuf-java 3.x, use the regular JAR with your build tool instead, because the bundled 4.x protobuf classes take precedence over yours when the fat JAR comes first on the classpath.
When shrinking or obfuscating with ProGuard or R8: keep com.databricks.zerobus.**
(for example -keep class com.databricks.zerobus.** { *; }). The native library binds the SDK's
native methods and the classes it calls back by name, so renamed or removed members make it fail
to load.
When using the regular JAR as a file on the classpath (without Maven or Gradle):
protobuf-java4.33.0slf4j-api2.0.17- An SLF4J implementation such as
slf4j-simple2.0.17 orlogback-classic1.4.14
When using Arrow Flight ingestion (ZerobusArrowStream) — additional dependencies, opt-in:
arrow-vector17.0.0arrow-memory-netty17.0.0- JDK 9+ also requires
--add-opens=java.base/java.nio=ALL-UNNAMED --add-opens=java.base/java.nio=org.apache.arrow.memory.coreon the launcher (seeexamples/arrow/README.md)
<dependency>
<groupId>org.apache.arrow</groupId>
<artifactId>arrow-vector</artifactId>
<version>17.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.arrow</groupId>
<artifactId>arrow-memory-netty</artifactId>
<version>17.0.0</version>
</dependency>When ingesting Avro record objects (ZerobusAvroStream, Beta) — additional dependency, opt-in, and requires Java 11+ at runtime (Apache Avro 1.12 is compiled for Java 11). The pre-encoded byte[] path needs neither:
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.12.2</version>
</dependency>- Java: 8 or higher to run a published JAR. Building and testing from source requires JDK 11 or higher.
- Maven: 3.6 or higher - Download Maven
- Protocol Buffers Compiler (
protoc): not needed on yourPATHto build the SDK. Maven downloads theprotocversion set in the POM. Compiling your own schemas needs a standaloneprotoc; see Define Your Protocol Buffer Schema.
Before using the SDK, you need a Databricks workspace URL, a Delta table, and a service principal. See the monorepo prerequisites for detailed setup instructions.
Regular JAR (with dependency management):
Add the SDK as a dependency in your pom.xml:
<dependencies>
<dependency>
<groupId>com.databricks</groupId>
<artifactId>zerobus-ingest-sdk</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>4.33.0</version>
</dependency>
</dependencies>Or with Gradle (build.gradle):
dependencies {
implementation 'com.databricks:zerobus-ingest-sdk:1.4.0'
implementation 'com.google.protobuf:protobuf-java:4.33.0'
}Add an SLF4J implementation. It brings in slf4j-api, which the SDK uses:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.17</version>
</dependency>Fat JAR (with all dependencies bundled):
If you prefer the self-contained fat JAR with all dependencies included:
<dependencies>
<dependency>
<groupId>com.databricks</groupId>
<artifactId>zerobus-ingest-sdk</artifactId>
<version>1.4.0</version>
<classifier>jar-with-dependencies</classifier>
</dependency>
</dependencies>Or with Gradle:
dependencies {
implementation 'com.databricks:zerobus-ingest-sdk:1.4.0:jar-with-dependencies'
}Note: The fat JAR is typically not needed for Maven/Gradle projects. Use the regular JAR (without classifier) unless you have a specific reason to bundle all dependencies.
Clone and build the SDK:
git clone https://github.com/databricks/zerobus-sdk.git
cd zerobus-sdk/java
mvn clean package -Dzerobus.skipNativeLibCheck=true-Dzerobus.skipNativeLibCheck=true compiles the Java sources without staging JNI
libraries. The JARs in target/ do not include native libraries and cannot ingest
until you either install a published artifact from Maven Central, or stage the JNI
libraries under src/main/resources/native/ and run Maven without that flag.
A release build (natives staged, no skip flag) generates two JAR files in target/:
-
Regular JAR:
zerobus-ingest-sdk-1.4.0.jar(~12MB, includes native libraries)- Contains only the SDK classes
- Requires all dependencies on the classpath
-
Fat JAR:
zerobus-ingest-sdk-1.4.0-jar-with-dependencies.jar(~19MB, includes native libraries + all dependencies)- Contains SDK classes plus all dependencies bundled
- Self-contained, easier to deploy
Which JAR to use?
- Regular JAR: When using Maven/Gradle (recommended)
- Fat JAR: For standalone scripts or CLI tools without a build system
Create a new Maven project:
mkdir my-zerobus-app
cd my-zerobus-appCreate pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-zerobus-app</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Zerobus SDK -->
<dependency>
<groupId>com.databricks</groupId>
<artifactId>zerobus-ingest-sdk</artifactId>
<version>1.4.0</version>
</dependency>
<!-- protobuf-java runtime the SDK is built against; with SDK v1.9.0 or later you can declare 3.25.x instead -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>4.33.0</version>
</dependency>
<!-- SLF4J implementation (brings in the slf4j-api the SDK uses) -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.17</version>
</dependency>
</dependencies>
</project>Create project structure:
mkdir -p src/main/java/com/example
mkdir -p src/main/protoCreate src/main/proto/record.proto:
syntax = "proto2";
package com.example;
option java_package = "com.example.proto";
option java_outer_classname = "Record";
message AirQuality {
optional string device_name = 1;
optional int32 temp = 2;
optional int64 humidity = 3;
}Compile the protobuf with a standalone protoc installed locally. Use the release that matches the protobuf-java runtime your application declares: 33.0 for 4.33.0, or 25.x for 3.25.x (see Dependencies). Download protoc
protoc --java_out=src/main/java src/main/proto/record.protoThis generates src/main/java/com/example/proto/Record.java.
Instead of manually writing and compiling your protobuf schema, you can automatically generate it from an existing Unity Catalog table schema using the included GenerateProto tool.
The GenerateProto tool fetches your table schema from Unity Catalog and generates a corresponding proto2 definition file with the correct type mappings.
First, download the fat JAR:
The proto generation tool requires the fat JAR (all dependencies included):
# Download from Maven Central
wget https://repo1.maven.org/maven2/com/databricks/zerobus-ingest-sdk/1.4.0/zerobus-ingest-sdk-1.4.0-jar-with-dependencies.jar
# Or if you built from source, it's in target/
# cp target/zerobus-ingest-sdk-1.4.0-jar-with-dependencies.jar .Run the tool:
java -jar zerobus-ingest-sdk-1.4.0-jar-with-dependencies.jar \
--uc-endpoint "<your-databricks-workspace-url>" \
--client-id "your-service-principal-application-id" \
--client-secret "your-service-principal-secret" \
--table "main.default.air_quality" \
--output "src/main/proto/record.proto" \
--proto-msg "AirQuality"Parameters:
--uc-endpoint: Your workspace URL from the connection URL table--client-id: Service principal application ID--client-secret: Service principal secret--table: Fully qualified table name (catalog.schema.table)--output: Output path for the generated proto file--proto-msg: (Optional) Name for the protobuf message (defaults to table name)
Example:
For a table defined as:
CREATE TABLE main.default.air_quality (
device_name STRING,
temp INT,
humidity BIGINT
)
USING DELTA;Running the generation tool will create src/main/proto/record.proto:
syntax = "proto2";
message AirQuality {
optional string device_name = 1;
optional int32 temp = 2;
optional int64 humidity = 3;
}The tool writes a proto2 message only. It does not emit package, java_package,
or java_outer_classname. Add those yourself if you need a Java package, then
compile as shown above:
protoc --java_out=src/main/java src/main/proto/record.protoType Mappings:
The tool automatically maps Unity Catalog types to proto2 types:
| Delta Type | Proto2 Type |
|---|---|
| INT, SMALLINT, SHORT | int32 |
| BIGINT, LONG | int64 |
| FLOAT | float |
| DOUBLE | double |
| STRING, VARCHAR | string |
| BOOLEAN | bool |
| BINARY | bytes |
| DATE | int32 |
| TIMESTAMP | int64 |
| ARRAY<type> | repeated type |
| MAP<key, value> | map<key, value> |
STRUCT columns are not generated. Map those fields by hand if needed.
Benefits:
- No manual schema creation required
- Ensures schema consistency between your table and protobuf definitions
- Automatically handles ARRAY and MAP columns (
STRUCTis not generated) - Reduces errors from manual type mapping
- No need to clone the repository - runs directly from the SDK JAR
For detailed documentation and examples, see tools/README.md.
The idiomatic flow is ingest in a loop, then
flush()once at the end. See Acknowledgments and throughput below the example for how acknowledgment works and when to usewaitForOffset()or anAckCallback.
Create src/main/java/com/example/ZerobusClient.java. It reads the connection settings from
environment variables; see the connection URL table
for the ZEROBUS_SERVER_ENDPOINT and DATABRICKS_WORKSPACE_URL formats on each cloud:
package com.example;
import com.databricks.zerobus.*;
import com.example.proto.Record.AirQuality;
public class ZerobusClient {
public static void main(String[] args) throws Exception {
// Configuration
String serverEndpoint = System.getenv("ZEROBUS_SERVER_ENDPOINT");
String workspaceUrl = System.getenv("DATABRICKS_WORKSPACE_URL");
String tableName = System.getenv("ZEROBUS_TABLE_NAME");
String clientId = System.getenv("DATABRICKS_CLIENT_ID");
String clientSecret = System.getenv("DATABRICKS_CLIENT_SECRET");
try (ZerobusSdk sdk = new ZerobusSdk(serverEndpoint, workspaceUrl);
ZerobusProtoStream stream = sdk.streamBuilder()
.table(tableName)
.oauth(clientId, clientSecret)
.compiledProto(AirQuality.getDescriptor().toProto())
.build()
.join()) {
// Ingest in a loop. ingestRecordOffset() returns as soon as the record is
// queued; the SDK sends it and tracks its acknowledgment in the background.
for (int i = 0; i < 100; i++) {
AirQuality record = AirQuality.newBuilder()
.setDeviceName("sensor-" + (i % 10))
.setTemp(20 + (i % 15))
.setHumidity(50 + (i % 40))
.build();
stream.ingestRecordOffset(record); // returns immediately
}
// Confirm everything is durably committed with one barrier.
stream.flush();
System.out.println("Successfully ingested 100 records!");
}
}
}Using Maven:
# First, compile the proto file to generate Java classes
protoc --java_out=src/main/java src/main/proto/record.proto
# Set the connection settings
export ZEROBUS_SERVER_ENDPOINT="<your-zerobus-server-endpoint>"
export DATABRICKS_WORKSPACE_URL="<your-databricks-workspace-url>"
export ZEROBUS_TABLE_NAME="main.default.air_quality"
export DATABRICKS_CLIENT_ID="<your-oauth-client-id>"
export DATABRICKS_CLIENT_SECRET="<your-oauth-client-secret>"
# Compile and run
mvn compile
mvn exec:java -Dexec.mainClass="com.example.ZerobusClient"Or build as standalone JAR:
# Generate proto classes
protoc --java_out=src/main/java src/main/proto/record.proto
# Package into executable JAR (add maven-shade-plugin to pom.xml)
mvn package
# Run the JAR
java -jar target/my-zerobus-app-1.0-SNAPSHOT.jarUsing downloaded JAR (without Maven):
# Generate proto classes
protoc --java_out=src/main/java src/main/proto/record.proto
# Compile
javac -cp "lib/*" -d out src/main/java/com/example/ZerobusClient.java src/main/java/com/example/proto/Record.java
# Run
java -cp "lib/*:out" com.example.ZerobusClientYou should see output like:
Successfully ingested 100 records!
Ingestion is asynchronous. ingestRecordOffset() returns as soon as the record is queued;
the SDK sends it and tracks its acknowledgment in the background. To confirm records are
durably committed, call flush() — it returns once everything queued so far is
acknowledged. The idiomatic flow is ingest in a loop, then flush() (once for a
bounded batch, or periodically for a long-running stream); or register an
AckCallback to be notified as records commit.
Each ingest also returns the record's offset, and waitForOffset(offset) blocks until that
offset is acknowledged — handy when a specific record must be confirmed before continuing
(acks are ordered, so waiting on the last offset confirms the whole run). Just avoid calling
waitForOffset() (or .join() on the deprecated per-record future) after every record in a
tight loop, since that limits throughput to one record per round-trip.
The examples/ directory contains complete working examples organized by stream type:
examples/
├── README.md # Overview and comparison
├── proto/ # ZerobusProtoStream examples
│ ├── README.md
│ ├── SingleRecordExample.java
│ └── BatchIngestionExample.java
├── json/ # ZerobusJsonStream examples
│ ├── README.md
│ ├── SingleRecordExample.java
│ └── BatchIngestionExample.java
├── arrow/ # ZerobusArrowStream example
│ ├── README.md
│ └── ArrowIngestionExample.java
└── legacy/ # ZerobusStream (deprecated)
└── LegacyStreamExample.java
ZerobusSdk.streamBuilder() is the recommended way to create a stream. It exposes a single fluent
API for all stream types and mirrors the Rust SDK's stream_builder():
// Protocol Buffer
try (ZerobusProtoStream protoStream = sdk.streamBuilder()
.table("catalog.schema.table")
.oauth(clientId, clientSecret)
.compiledProto(MyProto.getDescriptor().toProto())
.build()
.join()) {
// ingest...
}
// JSON
try (ZerobusJsonStream jsonStream = sdk.streamBuilder()
.table("catalog.schema.table")
.oauth(clientId, clientSecret)
.json()
.build()
.join()) {
// ingest...
}
// Arrow Flight
try (ZerobusArrowStream arrowStream = sdk.streamBuilder()
.table("catalog.schema.table")
.oauth(clientId, clientSecret)
.arrow(schema)
.build()
.join()) {
// ingest...
}
// Avro (Beta; record objects need Java 11+ and org.apache.avro:avro)
try (ZerobusAvroStream avroStream = sdk.streamBuilder()
.table("catalog.schema.table")
.oauth(clientId, clientSecret)
.avro(schemaJson)
.build()
.join()) {
// ingest...
}Stream configuration is set directly on the builder (for example .maxInflightRecords(50000),
.recovery(true), .recoveryRetries(5)). Arrow-specific options such as .maxInflightBatches(...)
and .ipcCompression(...) are available after calling .arrow(...).
Note:
createJsonStream,createProtoStream, andcreateArrowStreamare deprecated in favor ofstreamBuilder()and will be removed in the next major release.
Best for production systems with type safety and schema validation:
# Single record ingestion
cd examples
SDK_JAR=$(ls ../target/zerobus-ingest-sdk-*-jar-with-dependencies.jar | head -n 1)
# Generate proto class and compile examples
protoc --java_out=proto proto/air_quality.proto
javac -d . -cp "$SDK_JAR" \
proto/com/databricks/zerobus/examples/proto/AirQualityProto.java \
proto/SingleRecordExample.java \
proto/BatchIngestionExample.java
# Run single record example
java -cp ".:$SDK_JAR" \
com.databricks.zerobus.examples.proto.SingleRecordExample
# Run batch example
java -cp ".:$SDK_JAR" \
com.databricks.zerobus.examples.proto.BatchIngestionExampleBest for rapid prototyping and flexible schemas. No Protocol Buffer types required:
cd examples
SDK_JAR=$(ls ../target/zerobus-ingest-sdk-*-jar-with-dependencies.jar | head -n 1)
javac -d . -cp "$SDK_JAR" \
json/SingleRecordExample.java \
json/BatchIngestionExample.java
java -cp ".:$SDK_JAR" \
com.databricks.zerobus.examples.json.SingleRecordExampleClean JSON API - use the stream builder for a simplified experience:
try (ZerobusJsonStream stream = sdk.streamBuilder()
.table(tableName)
.oauth(clientId, clientSecret)
.json()
.build()
.join()) {
stream.ingestRecordOffset("{\"field\": \"value\"}");
stream.flush();
}See examples/README.md for detailed documentation.
Best for columnar data, wide/numeric schemas, or applications that already produce Apache Arrow VectorSchemaRoot batches (Spark, pandas via PyArrow bridges, columnar gateways). Requires the arrow-vector and arrow-memory-netty dependencies plus the JDK 9+ --add-opens flags (see Dependencies and examples/arrow/README.md):
cd examples
ARROW_CP=$(echo ../target/arrow-deps/*.jar | tr ' ' ':')
javac -d . -cp "../target/classes:$ARROW_CP" arrow/ArrowIngestionExample.java
java --add-opens=java.base/java.nio=ALL-UNNAMED \
--add-opens=java.base/java.nio=org.apache.arrow.memory.core \
-cp ".:../target/zerobus-ingest-sdk-*-jar-with-dependencies.jar:$ARROW_CP" \
com.databricks.zerobus.examples.arrow.ArrowIngestionExampleThe bundled example opens three streams in sequence — one per IPC compression codec (NONE, LZ4_FRAME, ZSTD) — and ingests 10 batches × 10 rows on each, demonstrating the full ingestBatch → waitForOffset → flush → close lifecycle.
Schema schema = new Schema(Arrays.asList(
Field.nullable("device_name", ArrowType.LargeUtf8.INSTANCE),
Field.nullable("temp", new ArrowType.Int(32, true))));
try (ZerobusArrowStream stream = sdk.streamBuilder()
.table(tableName)
.oauth(clientId, clientSecret)
.arrow(schema)
.build()
.join();
VectorSchemaRoot batch = VectorSchemaRoot.create(schema, allocator)) {
// populate batch...
stream.ingestBatch(batch);
stream.flush();
}(Beta.) Best when your data is already Avro-native. Declare the writer schema as JSON, then ingest
GenericRecord objects (encoded against the schema) or pre-encoded Avro datums (byte[]). Ingesting
GenericRecords requires Java 11+ and the org.apache.avro:avro dependency; the byte[] path
needs neither.
String schemaJson = "{\"type\":\"record\",\"name\":\"Order\",\"fields\":["
+ "{\"name\":\"id\",\"type\":\"long\"},{\"name\":\"customer\",\"type\":\"string\"}]}";
Schema schema = new Schema.Parser().parse(schemaJson);
try (ZerobusAvroStream stream = sdk.streamBuilder()
.table(tableName)
.oauth(clientId, clientSecret)
.avro(schemaJson)
.build()
.join()) {
for (Order order : orders) {
GenericRecord record = new GenericData.Record(schema);
record.put("id", order.id);
record.put("customer", order.customer);
stream.ingestRecordOffset(record); // GenericRecord, or a pre-encoded byte[]
}
stream.flush(); // confirm durability once, not per record
}A pre-encoded byte[] must be a bare Avro binary datum written with the writer schema. Framed
forms — Avro container files, single-object encoding, and Confluent-framed bytes — are not accepted.
Build records with the Java value each Avro type expects. Date/time, decimal, and uuid logical
types also accept their raw underlying primitive.
| Avro type | Java value |
|---|---|
| boolean / int / long / float / double | Boolean / Integer / Long / Float / Double |
| string | String |
| bytes | java.nio.ByteBuffer |
| record / array / map | GenericRecord / java.util.List / java.util.Map<String,?> |
| enum | GenericData.EnumSymbol |
| fixed | GenericData.Fixed |
| union | the branch value (resolved by its Java type); null for a null branch |
| date | java.time.LocalDate |
| time-millis / time-micros | java.time.LocalTime |
| timestamp-millis / timestamp-micros | java.time.Instant |
| local-timestamp-millis / local-timestamp-micros | java.time.LocalDateTime |
| decimal | java.math.BigDecimal |
| uuid | java.util.UUID |
Notes: a BigDecimal may have fewer fractional digits than the schema scale but not more (Avro
won't round) and must fit the precision. Schema defaults are not applied to unset fields of a
GenericData.Record — set every field, or use GenericRecordBuilder. Each record's schema (nested
records included) must match the writer schema: field order matters and the namespace must match,
though metadata such as avro.java.string or docs is ignored.
OAuth client credentials are the default authentication mechanism. For personal access tokens,
custom identity providers, or externally managed credentials, implement HeadersProvider:
HeadersProvider provider = () -> {
Map<String, String> headers = new HashMap<>();
headers.put("authorization", "Bearer " + fetchToken());
headers.put("x-databricks-zerobus-table-name", tableName);
return headers;
};
try (ZerobusJsonStream stream = sdk.streamBuilder()
.table(tableName)
.headersProvider(provider)
.json()
.build()
.join()) {
// ingest...
}The same provider works with the builder's compiledProto(), avro(), and arrow() format
selectors.
Providers may override invalidate() to clear cached credentials after an authentication
rejection. Implementations must be thread-safe because the SDK can invoke them from internal
threads during creation and recovery.
Use federatedAuth(FederatedToken) to authenticate with a token from an external identity
provider instead of a Databricks OAuth secret. You provide an IdpTokenSupplier that returns the
current IdP token. The SDK exchanges it for a Zerobus-scoped Databricks token (RFC 8693 token
exchange), caches the exchanged token, and refreshes it before it expires. The federation policy
must already be configured in Databricks.
IdpTokenSupplier idpToken = () -> fetchEntraIdToken(); // return the current IdP access token
// Account-level federation: no Databricks service principal. The identity is synced into
// Databricks through automatic identity management.
FederatedToken auth = FederatedToken.accountLevel(idpToken);
// Workload identity federation: a Databricks service principal with a federation policy and no
// secret, named by its client ID.
FederatedToken workloadAuth = FederatedToken.workloadIdentity(idpToken, spClientId);
try (ZerobusJsonStream stream = sdk.streamBuilder()
.table(tableName)
.federatedAuth(auth)
.json()
.build()
.join()) {
// ingest...
}federatedAuth works with every format selector (json(), compiledProto(), avro(), and
arrow()), and recreateStream reuses the stream's FederatedToken.
- Reuse one
FederatedTokenper identity. Exchanged Databricks tokens are cached per table. For account-level federation the cache is perFederatedTokeninstance, so a new instance, even with the same supplier, mints its own token. For workload identity federation it is per service principal client ID, so two instances with the same client ID share a token. - The supplier is called only when a token must be minted (on a cache miss or a proactive refresh), not on every request. It runs on an SDK thread, so it may call the identity provider over the network, but a slow supplier delays stream creation and recovery.
- Errors: an exception from
getToken()is treated as retryable. ThrowNonRetriableExceptionfor a permanent failure. Returningnullor an empty string, or throwing anError, is also a non-retryable error. - Set timeouts on the IdP request. The SDK can't interrupt
getToken(), and the recovery timeout does not bound it. Set connect and read timeouts on the IdP request so a hung call can't stall stream creation. While a call is stuck, the stream waits for it instead of starting another one. - Implementations must be thread-safe: the SDK may call the supplier concurrently for streams on different tables.
See examples/json/FederatedAuthExample.java for a
complete example.
By default the SDK trusts the operating system's CA certificates. To trust a private CA, present a
client certificate for mutual TLS, or check the server certificate against a different name, pass
TlsOptions to a ZerobusSdk built with ZerobusSdk.builder(). These settings apply to the gRPC connection to the Zerobus endpoint only. OAuth and federated token
requests to the workspace URL trust the operating system's CA certificates and the SDK's bundled
public roots, ignore TlsOptions, and present no client certificate. A workspace behind a private CA
must therefore be trusted by the operating system.
TlsOptions tls = TlsOptions.builder()
.trustSystemRoots(false)
.addCaCertificateFile("/etc/zerobus/ca.pem")
.clientIdentityFiles("/etc/zerobus/tls.crt", "/etc/zerobus/tls.key")
.domainName("zerobus.example.com")
.build();
try (ZerobusSdk sdk = ZerobusSdk.builder()
.serverEndpoint(serverEndpoint)
.unityCatalogEndpoint(workspaceUrl)
.tlsOptions(tls)
.build()) {
// Create streams with sdk.streamBuilder()
}trustSystemRoots(false)trusts only the CA certificates you add. At least one CA certificate is required in that case.addCaCertificatePem(...)andclientIdentityPem(certPem, keyPem)take PEM text instead of paths. Use them when the certificates come from a secret store rather than the file system.domainName(...)checks the server certificate against a name other than the endpoint host. Pass a DNS name or an IP address, for examplezerobus.example.com, not a URL. A value with a scheme, a port, a path or query, brackets, whitespace, or a control character fails withIllegalArgumentExceptionwhen the builder is called. Another malformed name passes this check and fails when the SDK sets up TLS for the connection. Whether recovery retries that failure depends on the rest of the TLS configuration.
Certificate files are read each time the SDK opens a connection, so a rotated certificate takes effect without restarting the process. Replace the certificate and its key together, for example by writing both into a new directory and switching a symbolic link to it, as Kubernetes secret volumes do. Use absolute paths.
A missing or unreadable file fails stream creation with a NonRetriableException that names the
file, and the SDK does not retry it. Rotating by deleting a file and then writing its replacement can
therefore fail a stream that is created or recovered during the gap. Switch to the new files with a
single rename or symbolic link change instead. Content the SDK cannot use, such as a file with no
certificate, fails with a ZerobusException, which is retried, because a rotation may be in
progress.
With connectionPerStream(true), each new stream reads the files again and reports any failure.
With connectionPerStream(false), JSON, protobuf and Avro streams share one channel, and the next
stream of those formats reads changed files again. If the SDK cannot apply the new settings locally,
that stream keeps the previous channel without reporting the failure, until local setup succeeds; a
readable certificate or key that the server rejects in the handshake fails the stream. Arrow streams
open their own channel and always read the files themselves.
A HeadersProvider header whose name ends in -bin is sent as binary gRPC metadata. Its value must
be the standard base64 encoding of the bytes, padded or unpadded. The SDK decodes the value before
sending it:
HeadersProvider provider = () -> {
Map<String, String> headers = new HashMap<>();
headers.put("authorization", "Bearer " + fetchToken());
headers.put("x-databricks-zerobus-table-name", tableName);
headers.put("x-context-bin", Base64.getEncoder().encodeToString(contextBytes));
return headers;
};Any other header value is sent as ASCII text. Names beginning with grpc- and ending in -bin are
reserved for gRPC and are rejected.
The SDK provides two ingestion styles:
| Style | Status | Best For | Overhead |
|---|---|---|---|
| Offset-Based | Recommended | All use cases | Minimal - no object allocation |
| Future-Based | Deprecated | Legacy code | CompletableFuture per record |
ZerobusArrowStream is offset-based as well, but ingestBatch(VectorSchemaRoot) returns Optional<Long> (empty for null or zero-row batches) rather than a bare long.
Use ZerobusProtoStream or ZerobusJsonStream for all new code. They use offset-based returns that avoid CompletableFuture allocation overhead.
Each
ingestRecordOffset()call returns as soon as the record is queued; the SDK sends it and tracks its acknowledgment in the background. The idiomatic flow is to ingest in a loop, then confirm durability once — withflush(), or by passing the last offset towaitForOffset()(acks are ordered, so the last offset confirms every prior record). See Acknowledgments and throughput for the full picture.
try (ZerobusProtoStream stream = sdk.streamBuilder()
.table(tableName)
.oauth(clientId, clientSecret)
.compiledProto(AirQuality.getDescriptor().toProto())
.build()
.join()) {
long lastOffset = -1;
// Ingest in a loop
for (int i = 0; i < 1000000; i++) {
AirQuality record = AirQuality.newBuilder()
.setDeviceName("sensor-" + (i % 100))
.setTemp(20 + i % 15)
.setHumidity(50 + i % 40)
.build();
// Returns immediately after queuing
lastOffset = stream.ingestRecordOffset(record);
}
// Confirm all records are acknowledged
stream.waitForOffset(lastOffset);
}Deprecated: Use the offset-based API instead for better performance.
The future-based API is still available for backward compatibility but will be removed in a future release:
// DEPRECATED - use ingestRecordOffset() instead.
// Each ingestRecord() returns immediately; keep the last future and join once after
// the loop to confirm durability (joining after every record limits throughput).
try {
CompletableFuture<Void> lastFuture = null;
for (int i = 0; i < 1000; i++) {
AirQuality record = AirQuality.newBuilder()
.setDeviceName("sensor-" + i)
.setTemp(20 + i % 15)
.build();
lastFuture = stream.ingestRecord(record); // Deprecated; non-blocking
}
if (lastFuture != null) {
lastFuture.join(); // wait once, after the loop
}
} finally {
stream.close();
sdk.close();
}Migration:
// Before (deprecated ZerobusStream): wait once after the loop
CompletableFuture<Void> last = null;
for (AirQuality record : records) {
last = stream.ingestRecord(record);
}
if (last != null) {
last.join();
}
// After (recommended ZerobusProtoStream): queue, then flush once
for (AirQuality record : records) {
stream.ingestRecordOffset(record);
}
stream.flush();
// Batch ingestion:
stream.ingestRecordsOffset(batch);
stream.flush();| Format | Best For | Pros | Cons |
|---|---|---|---|
| Protocol Buffers | Production systems | Type-safe, compact, fast | Requires schema compilation |
| JSON | Prototyping, flexible schemas | Human-readable, no compilation, clean API | Larger payload, slower |
| Arrow Flight | Columnar/analytics workloads, wide/numeric schemas, applications that already produce Arrow data | High throughput, native Apache Arrow types, IPC compression (ZSTD by default; LZ4 or none optional) | Requires arrow-vector + arrow-memory-netty deps and JDK 9+ --add-opens flags |
Use the stream builder for a clean API that doesn't require Protocol Buffer types:
try (ZerobusJsonStream stream = sdk.streamBuilder()
.table("catalog.schema.table")
.oauth(clientId, clientSecret)
.json()
.build()
.join()) {
stream.ingestRecordOffset("{\"device_name\": \"sensor-1\", \"temp\": 25}");
Gson gson = new Gson();
Map<String, Object> data = new HashMap<>();
data.put("device_name", "sensor-2");
data.put("temp", 26);
stream.ingestRecordOffset(data, gson::toJson);
List<String> batch = Arrays.asList(
"{\"device_name\": \"sensor-1\", \"temp\": 25}",
"{\"device_name\": \"sensor-2\", \"temp\": 26}"
);
stream.ingestRecordsOffset(batch);
stream.flush();
}With custom configuration set directly on the builder:
try (ZerobusJsonStream stream = sdk.streamBuilder()
.table(tableName)
.oauth(clientId, clientSecret)
.maxInflightRecords(50000)
.json()
.build()
.join()) {
// ingest...
}| Option | Default | Description |
|---|---|---|
maxInflightRecords |
1000000 | Maximum number of unacknowledged records |
recovery |
true | Enable automatic stream recovery |
recoveryTimeoutMs |
15000 | Timeout for recovery operations (ms) |
recoveryBackoffMs |
2000 | Delay between recovery attempts (ms) |
recoveryRetries |
4 | Maximum number of recovery attempts |
flushTimeoutMs |
300000 | Timeout for flush operations (ms) |
serverLackOfAckTimeoutMs |
60000 | Server acknowledgment timeout (ms) |
ackCallback |
None | Callback invoked on record acknowledgment |
Used with ZerobusArrowStream. Build via ArrowStreamConfigurationOptions.builder().
| Option | Default | Description |
|---|---|---|
maxInflightBatches |
1000 | Maximum number of unacknowledged Arrow batches |
recovery |
true | Enable automatic stream recovery |
recoveryTimeoutMs |
15000 | Timeout for recovery operations (ms) |
recoveryBackoffMs |
2000 | Delay between recovery attempts (ms) |
recoveryRetries |
4 | Maximum number of recovery attempts |
serverLackOfAckTimeoutMs |
60000 | Server acknowledgment timeout (ms) |
flushTimeoutMs |
300000 | Timeout for flush operations (ms) |
connectionTimeoutMs |
30000 | Timeout for establishing a gRPC connection (ms) |
ipcCompression |
IPCCompressionType.ZSTD |
Arrow IPC compression codec on the wire (NONE, LZ4_FRAME, ZSTD). Pass NONE to send uncompressed payloads |
streamPausedMaxWaitTimeMs |
-1 |
Max time to wait in the paused state during graceful close. -1 = full server duration, 0 = immediate recovery, >0 = min(this, server_duration) ms |
ackCallback is not supported for Arrow Flight streams. Configuring it on StreamBuilder before calling ArrowStreamBuilder.build() throws IllegalStateException.
The Databricks Zerobus Ingest SDK for Java uses the standard SLF4J logging framework. The SDK uses slf4j-api, which must be on your classpath. An SLF4J implementation brings it in. You need to add an SLF4J implementation to your classpath to see log output.
Option 1: Using slf4j-simple (simplest for getting started)
Add to your Maven dependencies:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.17</version>
</dependency>Control log levels with system properties:
java -Dorg.slf4j.simpleLogger.log.com.databricks.zerobus=debug -cp "lib/*:out" com.example.ZerobusClientAvailable log levels: trace, debug, info, warn, error
Option 2: Using Logback (recommended for production)
Add to your Maven dependencies:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.14</version>
</dependency>Create logback.xml in your resources directory:
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.databricks.zerobus" level="DEBUG"/>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>Option 3: Using Log4j 2
Add to your Maven dependencies:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.20.0</version>
</dependency>Create log4j2.xml in your resources directory:
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="com.databricks.zerobus" level="debug"/>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>If you don't add an SLF4J implementation, you'll see a warning like:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
The SDK will still work, but no log messages will be output.
At the DEBUG level, the SDK logs:
- Stream lifecycle events (creation, closure)
- SDK initialization
At the INFO level, the SDK logs:
- Native library loading
- Stream flush completion
- Stream closure
At the WARN level, the SDK logs:
- Deprecation warnings
At the ERROR level, the SDK logs:
- Native library loading failures
Note: Most detailed logging (token generation, gRPC, retries) is handled internally by the native Rust SDK and uses its own logging configuration.
The SDK throws two types of exceptions:
ZerobusException: Retriable errors (e.g., network issues, temporary server errors)NonRetriableException: Non-retriable errors (e.g., invalid credentials, missing table)
try {
stream.ingestRecordOffset(record);
} catch (NonRetriableException e) {
// Fatal error - do not retry
logger.error("Non-retriable error: " + e.getMessage());
throw e;
} catch (ZerobusException e) {
// Retriable error - can retry with backoff
logger.warn("Retriable error: " + e.getMessage());
// Implement retry logic
}Main entry point for the SDK.
Constructors:
ZerobusSdk(String serverEndpoint, String unityCatalogEndpoint)
ZerobusSdk(String serverEndpoint, String unityCatalogEndpoint, boolean connectionPerStream)
ZerobusSdk(String serverEndpoint, String unityCatalogEndpoint, String applicationName)
ZerobusSdk(String serverEndpoint, String unityCatalogEndpoint, String applicationName, boolean connectionPerStream)serverEndpoint- The Zerobus gRPC endpoint from the connection URL tableunityCatalogEndpoint- Your Databricks workspace URL, used for Unity Catalog and OAuthapplicationName(optional) - Application identifier appended to the HTTPuser-agentheader, conventionally"<product>/<version>"(e.g."my-app/1.0"). Passnullto omit.connectionPerStream(optional) - Gives each JSON/protobuf stream a dedicated gRPC connection. Constructors without this argument default totrue; passfalseto share one HTTP/2 connection. Arrow Flight streams are unaffected.
HTTP/2 multiplexes logical streams over one TCP connection. On high-throughput
workloads over the public internet, packet loss and TCP retransmissions can
cause head-of-line blocking across every stream on that connection, reducing
aggregate throughput. Dedicated connections isolate that loss. For many
smaller, low-throughput streams, pass false; shared multiplexing is
recommended there to reduce connection overhead.
Static methods:
ZerobusSdkBuilder builder()Returns a ZerobusSdkBuilder for setting the endpoints, the application name,
the connection mode, and TLS options. The constructors above remain available
and create an SDK with the same defaults.
Methods:
StreamBuilder streamBuilder()Returns a fluent StreamBuilder for creating JSON, Protocol Buffer, or Arrow Flight streams. This is the recommended way to create streams.
<RecordType extends Message> CompletableFuture<ZerobusStream<RecordType>> createStream(
TableProperties<RecordType> tableProperties,
String clientId,
String clientSecret,
StreamConfigurationOptions options
)Creates a new Protocol Buffer ingestion stream with custom configuration. Returns a CompletableFuture that completes when the stream is ready. Deprecated — use streamBuilder().
<RecordType extends Message> CompletableFuture<ZerobusStream<RecordType>> createStream(
TableProperties<RecordType> tableProperties,
String clientId,
String clientSecret
)Creates a new Protocol Buffer ingestion stream with default configuration. Returns a CompletableFuture that completes when the stream is ready. Deprecated — use streamBuilder().
CompletableFuture<ZerobusJsonStream> createJsonStream(
String tableName,
String clientId,
String clientSecret
)Creates a new JSON ingestion stream with default configuration. No Protocol Buffer types required. Deprecated — use streamBuilder().
CompletableFuture<ZerobusJsonStream> createJsonStream(
String tableName,
String clientId,
String clientSecret,
StreamConfigurationOptions options
)Creates a new JSON ingestion stream with custom configuration. No Protocol Buffer types required. Deprecated — use streamBuilder().
CompletableFuture<ZerobusProtoStream> recreateStream(ZerobusProtoStream closedStream)Recreates a Proto stream from a closed stream, re-ingesting unacknowledged records and flushing.
CompletableFuture<ZerobusJsonStream> recreateStream(ZerobusJsonStream closedStream)Recreates a JSON stream from a closed stream, re-ingesting unacknowledged records and flushing.
CompletableFuture<ZerobusArrowStream> createArrowStream(
String tableName,
org.apache.arrow.vector.types.pojo.Schema schema,
String clientId,
String clientSecret
)Creates a new Arrow Flight ingestion stream with default configuration. Requires arrow-vector + arrow-memory-netty on the classpath. Deprecated — use streamBuilder().
CompletableFuture<ZerobusArrowStream> createArrowStream(
String tableName,
org.apache.arrow.vector.types.pojo.Schema schema,
String clientId,
String clientSecret,
ArrowStreamConfigurationOptions options
)Same as above with custom configuration. Deprecated — use streamBuilder().
CompletableFuture<ZerobusArrowStream> recreateArrowStream(ZerobusArrowStream closedStream)Recreates an Arrow stream from a closed stream, re-ingesting unacknowledged batches and flushing.
Fluent builder for ZerobusSdk, returned by ZerobusSdk.builder(). Only
serverEndpoint is required.
serverEndpoint(String)- The Zerobus gRPC endpoint. Required.unityCatalogEndpoint(String)- The Databricks workspace URL, used for Unity Catalog and OAuth. Streams that use aHeadersProvidercan omit it.applicationName(String)- Application identifier for theuser-agentheader. Passnullto omit.connectionPerStream(boolean)- Dedicated connection per JSON/protobuf stream. Defaults totrue.tlsOptions(TlsOptions)- TLS settings. Defaults to the operating system's CA certificates.build()- Creates the SDK. ThrowsIllegalStateExceptionif the server endpoint is not set.
Immutable TLS settings, created with TlsOptions.builder() and passed to
ZerobusSdkBuilder.tlsOptions(...). See TLS Configuration.
trustSystemRoots(boolean)- Also trust the operating system's CA certificates. Defaults totrue.addCaCertificatePem(String),addCaCertificateFile(String)- Trust more CA certificates, as PEM text or a PEM file. Call more than once to add several.clientIdentityPem(String certPem, String keyPem),clientIdentityFiles(String certPath, String keyPath)- Client certificate chain and key for mutual TLS.domainName(String)- Server name to check the certificate against. Rejects a pasted URL.build()- Returns the options. ThrowsIllegalStateExceptioniftrustSystemRoots(false)is set without a CA certificate.
toString() reports counts and the kind of client identity. It never includes certificate or key material.
Fluent builder for creating streams, returned by ZerobusSdk.streamBuilder(). Set the table, authentication, and stream configuration, then select a record format to obtain a typed sub-builder whose build() returns the matching stream type.
StreamBuilder table(String tableName)
StreamBuilder oauth(String clientId, String clientSecret)
StreamBuilder headersProvider(HeadersProvider headersProvider)
StreamBuilder federatedAuth(FederatedToken federatedToken)
StreamBuilder recovery(boolean recovery)
StreamBuilder recoveryTimeoutMs(int ms)
StreamBuilder recoveryBackoffMs(int ms)
StreamBuilder recoveryRetries(int n)
StreamBuilder serverLackOfAckTimeoutMs(int ms)
StreamBuilder flushTimeoutMs(int ms)
StreamBuilder maxInflightRecords(int n) // JSON/proto/Avro (not Arrow)
StreamBuilder ackCallback(AckCallback callback) // JSON/proto/Avro (not Arrow)
// Format selection -> typed sub-builder:
JsonStreamBuilder json()
ProtoStreamBuilder compiledProto(DescriptorProto descriptorProto)
AvroStreamBuilder avro(String schemaJson) // Beta; GenericRecord ingestion needs Java 11 + org.apache.avro:avro
ArrowStreamBuilder arrow(Schema schema)Each sub-builder exposes build():
CompletableFuture<ZerobusJsonStream> StreamBuilder.JsonStreamBuilder.build()
CompletableFuture<ZerobusProtoStream> StreamBuilder.ProtoStreamBuilder.build()
CompletableFuture<ZerobusAvroStream> StreamBuilder.AvroStreamBuilder.build()
CompletableFuture<ZerobusArrowStream> StreamBuilder.ArrowStreamBuilder.build()ArrowStreamBuilder additionally supports maxInflightBatches(int), connectionTimeoutMs(long), ipcCompression(IPCCompressionType), and streamPausedMaxWaitTimeMs(long).
Configuring ackCallback before calling ArrowStreamBuilder.build() throws IllegalStateException because Arrow Flight streams do not support ACK callbacks.
Stream for Protocol Buffer ingestion with method-level generics. Use ZerobusSdk.streamBuilder() to create instances.
Single Record Methods:
<T extends Message> long ingestRecordOffset(T record) throws ZerobusExceptionIngests a Protocol Buffer message and returns the offset immediately.
long ingestRecordOffset(byte[] encodedBytes) throws ZerobusExceptionIngests pre-encoded bytes and returns the offset immediately.
Batch Methods:
<T extends Message> Optional<Long> ingestRecordsOffset(Iterable<T> records) throws ZerobusExceptionIngests multiple messages and returns the batch offset.
Optional<Long> ingestRecordsOffset(List<byte[]> encodedRecords) throws ZerobusExceptionIngests multiple pre-encoded byte arrays and returns the batch offset.
Recovery Methods:
List<byte[]> getUnackedRecords() throws ZerobusExceptionReturns unacknowledged records as raw byte arrays.
<T extends Message> List<T> getUnackedRecords(Parser<T> parser) throws ZerobusExceptionReturns unacknowledged records parsed into messages.
List<EncodedBatch> getUnackedBatches() throws ZerobusExceptionReturns unacknowledged records grouped by batch.
Lifecycle Methods: waitForOffset(), flush(), close(), isClosed(), getTableName(), getOptions()
Stream for JSON ingestion with method-level generics. Use ZerobusSdk.streamBuilder().json() to create instances.
Single Record Methods:
<T> long ingestRecordOffset(T object, JsonSerializer<T> serializer) throws ZerobusExceptionIngests an object serialized to JSON and returns the offset immediately.
long ingestRecordOffset(String json) throws ZerobusExceptionIngests a JSON string and returns the offset immediately.
Batch Methods:
<T> Optional<Long> ingestRecordsOffset(Iterable<T> objects, JsonSerializer<T> serializer) throws ZerobusExceptionIngests multiple objects as JSON and returns the batch offset.
Optional<Long> ingestRecordsOffset(Iterable<String> jsonStrings) throws ZerobusExceptionIngests multiple JSON strings and returns the batch offset.
Recovery Methods:
List<String> getUnackedRecords() throws ZerobusExceptionReturns unacknowledged records as JSON strings.
<T> List<T> getUnackedRecords(JsonDeserializer<T> deserializer) throws ZerobusExceptionReturns unacknowledged records deserialized into objects.
List<EncodedBatch> getUnackedBatches() throws ZerobusExceptionReturns unacknowledged records grouped by batch.
Lifecycle Methods: waitForOffset(), flush(), close(), isClosed(), getTableName(), getOptions()
Stream for Avro ingestion (Beta). Use ZerobusSdk.streamBuilder().avro(schemaJson) to create instances. Ingesting GenericRecords requires Java 11+ and org.apache.avro:avro on the classpath; the pre-encoded byte[] path needs neither.
Single Record Methods:
long ingestRecordOffset(GenericRecord record) throws ZerobusExceptionEncodes a record against the writer schema and returns the offset immediately.
long ingestRecordOffset(byte[] encodedBytes) throws ZerobusExceptionIngests a bare, pre-encoded Avro datum (no container/single-object/Confluent framing) and returns the offset immediately.
Batch Methods:
Optional<Long> ingestRecordsOffset(Iterable<? extends GenericRecord> records) throws ZerobusException
Optional<Long> ingestRecordsOffset(List<byte[]> encodedRecords) throws ZerobusExceptionIngests a batch of records (encoded) or bare pre-encoded datums and returns the batch offset.
Recovery Methods:
List<byte[]> getUnackedRecords() throws ZerobusException
List<EncodedBatch> getUnackedBatches() throws ZerobusExceptionReturns unacknowledged records as raw Avro datums, or grouped by batch.
Lifecycle Methods: waitForOffset(), flush(), close(), isClosed(), getTableName(), getOptions()
Stream for Apache Arrow Flight ingestion of VectorSchemaRoot batches. Use ZerobusSdk.streamBuilder().arrow() to create instances. Requires arrow-vector + arrow-memory-netty on the classpath and JDK 9+ --add-opens flags (see Dependencies).
Batch Ingestion:
Optional<Long> ingestBatch(VectorSchemaRoot batch) throws ZerobusExceptionSerializes the batch to Arrow IPC, queues it for transmission, and returns the assigned offset. Returns an empty Optional if the batch is null or has zero rows. The batch's schema must match the schema used to create the stream.
Recovery:
List<byte[]> getUnackedBatches() throws ZerobusExceptionReturns unacknowledged batches as serialized Arrow IPC byte arrays. After the stream is closed, returns cached data captured at close time. Each element can be re-ingested into a recreated stream, or deserialized with ArrowStreamReader.
Lifecycle Methods: waitForOffset(), flush(), close(), isClosed(), getTableName(), getOptions()
Configuration options for ZerobusArrowStream. Build via ArrowStreamConfigurationOptions.builder(). See Arrow Stream Configuration Options for the full table of fields and defaults.
Static Methods:
static ArrowStreamConfigurationOptions getDefault()
static ArrowStreamConfigurationOptionsBuilder builder()Builder methods (chainable):
setMaxInflightBatches(int)
setRecovery(boolean)
setRecoveryTimeoutMs(long)
setRecoveryBackoffMs(long)
setRecoveryRetries(int)
setServerLackOfAckTimeoutMs(long)
setFlushTimeoutMs(long)
setConnectionTimeoutMs(long)
setIpcCompression(IPCCompressionType)
setStreamPausedMaxWaitTimeMs(long)
build()Example:
ArrowStreamConfigurationOptions options = ArrowStreamConfigurationOptions.builder()
.setMaxInflightBatches(2000)
.setIpcCompression(IPCCompressionType.LZ4_FRAME)
.setRecovery(true)
.setRecoveryRetries(5)
.build();Selects the Arrow IPC compression codec applied to each batch on the wire. Set via ArrowStreamConfigurationOptions.builder().setIpcCompression(...).
Values:
NONE— No compression.LZ4_FRAME— LZ4 frame compression. Fast, modest ratio.ZSTD— Zstandard (default). Higher ratio at higher CPU cost.
Compression trades client CPU for fewer bytes on the wire. Pass NONE if client CPU, not network bandwidth, limits throughput.
Legacy stream with class-level generics and Future-based API. Use ZerobusProtoStream instead.
Methods:
CompletableFuture<Void> ingestRecord(RecordType record) throws ZerobusExceptionIngests a record and returns a Future that completes on acknowledgment.
Lifecycle Methods: waitForOffset(), flush(), close(), isClosed()
Accessors:
TableProperties<RecordType> getTableProperties()
StreamConfigurationOptions getOptions()
String getClientId()
String getClientSecret()Configuration for the target table.
Constructor:
TableProperties(String tableName, RecordType defaultInstance)tableName- Fully qualified table name (e.g.,catalog.schema.table)defaultInstance- Protobuf message default instance (e.g.,MyMessage.getDefaultInstance())
Methods:
String getTableName()Returns the table name.
Message getDefaultInstance()Returns the protobuf message default instance.
Configuration options for stream behavior.
Static Methods:
static StreamConfigurationOptions getDefault()Returns default configuration options.
static StreamConfigurationOptionsBuilder builder()Returns a new builder for creating custom configurations.
Builder for creating StreamConfigurationOptions.
Methods:
StreamConfigurationOptionsBuilder setMaxInflightRecords(int maxInflightRecords)Sets the maximum number of unacknowledged records (default: 1000000).
StreamConfigurationOptionsBuilder setRecovery(boolean recovery)Enables or disables automatic stream recovery (default: true).
StreamConfigurationOptionsBuilder setRecoveryTimeoutMs(int recoveryTimeoutMs)Sets the recovery operation timeout in milliseconds (default: 15000).
StreamConfigurationOptionsBuilder setRecoveryBackoffMs(int recoveryBackoffMs)Sets the delay between recovery attempts in milliseconds (default: 2000).
StreamConfigurationOptionsBuilder setRecoveryRetries(int recoveryRetries)Sets the maximum number of recovery attempts (default: 4).
StreamConfigurationOptionsBuilder setFlushTimeoutMs(int flushTimeoutMs)Sets the flush operation timeout in milliseconds (default: 300000).
StreamConfigurationOptionsBuilder setServerLackOfAckTimeoutMs(int serverLackOfAckTimeoutMs)Sets the server acknowledgment timeout in milliseconds (default: 60000).
StreamConfigurationOptionsBuilder setAckCallback(AckCallback ackCallback)Sets a callback to be invoked when records are acknowledged by the server.
StreamConfigurationOptionsBuilder setAckCallback(Consumer<IngestRecordResponse> ackCallback)Deprecated: This callback is no longer invoked by the native Rust backend. Use setAckCallback(AckCallback) instead.
StreamConfigurationOptions build()Builds and returns the StreamConfigurationOptions instance.
Deprecated: This type is only used by the deprecated
Consumer<IngestRecordResponse>callback, which is no longer invoked by the native Rust backend. UseAckCallbackinstead.
Server acknowledgment response containing durability information.
Methods:
long getDurabilityAckUpToOffset()Returns the offset up to which all records have been durably written.
Represents the lifecycle state of a stream.
Note: The native Rust backend does not expose detailed stream states. The deprecated
ZerobusStream.getState()method only returnsOPENEDorCLOSED.
Values:
UNINITIALIZED- Stream created but not yet initializedOPENED- Stream is open and accepting recordsFLUSHING- Stream is flushing pending recordsRECOVERING- Stream is recovering from a failureCLOSED- Stream has been gracefully closedFAILED- Stream has failed and cannot be recovered
Base exception for retriable errors.
Constructors:
ZerobusException(String message)
ZerobusException(String message, Throwable cause)Exception for non-retriable errors (extends ZerobusException).
Constructors:
NonRetriableException(String message)
NonRetriableException(String message, Throwable cause)Interface for serializing objects to JSON strings. Defined in ZerobusJsonStream.
String serialize(T object)Usage with Gson:
Gson gson = new Gson();
stream.ingestRecordOffset(myObject, gson::toJson);Interface for deserializing JSON strings to objects. Defined in ZerobusJsonStream.
T deserialize(String json)Usage with Gson:
List<MyData> unacked = stream.getUnackedRecords(json -> gson.fromJson(json, MyData.class));Authenticates a stream by federating an external IdP token. Pass it to StreamBuilder.federatedAuth(). Instances are immutable. Exchanged tokens are cached per table, and per instance for account-level federation or per client ID for workload identity federation. See External-IdP federation.
static FederatedToken accountLevel(IdpTokenSupplier idpTokenSupplier)
static FederatedToken workloadIdentity(IdpTokenSupplier idpTokenSupplier, String clientId)Supplies the current external IdP token for FederatedToken. Called only when a Databricks token must be minted. Implementations must be thread-safe.
String getToken() throws Exception // throw NonRetriableException for permanent failuresCallback interface for acknowledgment notifications. The callback is invoked once per logical ingest submission, so a batch ingest call produces one callback rather than one per record.
void onAck(long offsetId)Called when a logical ingest submission is acknowledged. Records up to offsetId are durable.
void onError(long offsetId, String errorMessage)Called when an error occurs for the logical ingest submission at offsetId.
Track durability progress without blocking. Register an AckCallback to observe
acknowledgments as they arrive on a background thread while you keep ingesting — a natural
fit for high-throughput or long-running streams where you want progress notifications
rather than blocking on flush() or waitForOffset():
AckCallback callback = new AckCallback() {
@Override public void onAck(long offsetId) {
// records up to offsetId are durable (watermark is monotonic)
}
@Override public void onError(long offsetId, String errorMessage) {
System.err.println("Error at offset " + offsetId + ": " + errorMessage);
}
};
try (ZerobusProtoStream stream = sdk.streamBuilder()
.table(tableName)
.oauth(clientId, clientSecret)
.ackCallback(callback)
.compiledProto(descriptor)
.build()
.join()) {
for (AirQuality record : records) {
stream.ingestRecordOffset(record);
}
stream.flush(); // wait for durability; callbacks may still be running
}Implementations must be thread-safe and lightweight (callbacks run on internal
processing threads). close() waits at most five seconds for in-flight
callbacks; remaining callbacks may still be pending when it returns.
What a callback may do. Keep callbacks to quick, non-blocking work such as logging,
updating metrics, or incrementing counters, and hand anything else (I/O, retries,
re-ingesting records) to another thread or executor. Streams are not thread-safe, so that
thread must not call the stream concurrently with others: queue the work for the thread
that owns the stream, or guard every call with your own lock. A callback must not call
stream or SDK methods that block on native work: ingestRecordOffset,
ingestRecordsOffset, the deprecated ZerobusStream.ingestRecord, ingestBatch (Arrow),
waitForOffset, flush, close, isClosed, getUnackedRecords, getUnackedBatches,
ZerobusSdk.recreateStream, and recreateArrowStream. Called from a callback, these
throw IllegalStateException. A callback should not throw; if it does, the exception is
normally logged at ERROR level through SLF4J (if logging itself fails, it is dropped) and
later callbacks are still delivered.
- Reuse SDK instances: Create one
ZerobusSdkinstance per application - Stream lifecycle: Wrap the SDK and each stream in try-with-resources. Streams hold native resources that the garbage collector does not release.
- Use offset-based API for high throughput:
ingestRecordOffset()avoidsCompletableFutureoverhead - Ingest in a loop, then
flush(): Confirm durability once after a batch withflush()(orwaitForOffset()on the last offset, since acks are ordered). Use per-record waits only when a specific record must be confirmed before continuing. - Batch records when possible: Use
ingestRecordsOffset()for multiple records - Configure
maxInflightRecords: Adjust based on your throughput and memory requirements - Implement proper error handling: Distinguish between retriable and non-retriable errors
- Use
AckCallbackfor monitoring: Track acknowledgment progress without blocking the ingest loop - Proto generation: Use the built-in
GeneratePrototool to generate proto files from table schemas - Choose the right API:
ingestRecordOffset()+ finalflush()/waitForOffset(lastOffset)→ High throughput (recommended)ingestRecordOffset()+waitForOffset()per record → When a specific record must be confirmed before continuingingestRecord().join()→ Deprecated; prefer the offset-based API
- Thread safety:
ZerobusSdkand streams are not thread-safe. Synchronize externally if more than one thread uses the same instance. - Recovery: Use
recreateStream()on a closed stream to re-ingest unacknowledged records. InspectgetUnackedBatches()after close when you need the payloads yourself.
This is an open source project. We welcome contributions, feedback, and bug reports.
- Contributing Guide: Java-specific development setup and workflow.
- General Contributing Guide: Pull request process, commit requirements, and policies.
- Changelog: See the history of changes in the SDK.
- Security Policy: Read about our security process and how to report vulnerabilities.
- Developer Certificate of Origin (DCO): Understand the agreement for contributions.
- Open Source Attributions: See a list of the open source libraries we use.
This SDK is licensed under the Apache License 2.0. See LICENSE for the full text.