Skip to content

[client-v2] Optimize RowBinaryFormatWriter by precompiling column serializers and reducing Object[] row-staging overhead #3289

Description

@Harry262530

Description
While testing RowBinaryFormatWriter for our use case, we identified several bottlenecks in its current serialization path. The writer initially took approximately 684 seconds to process the workload. After addressing these bottlenecks, the execution time decreased to approximately 462.47 seconds, representing a 32.39% reduction in runtime.

The main bottlenecks identified are:

Schema-dependent operations are repeated for every column of every row, even though the TableSchema does not change during the writer’s lifetime.
Primitive setters such as setInteger(), setLong(), setFloat(), and setDouble() delegate to setValue(int, Object), causing primitive boxing.
Values for the entire row are staged in an Object[] until commitRow() is called.
The stored values are later unboxed during serialization.
These operations add avoidable CPU, allocation, memory-access, and garbage-collection overhead for large, wide RowBinary workloads.

The proposed improvement is to compile and cache a reusable serialization plan when the writer is constructed. A primitive-specialized or sequential writing path should also be considered to avoid unnecessary Object[] staging, boxing, and unboxing.

Affected component
client-v2
com.clickhouse.client.api.data_formats.RowBinaryFormatWriter
com.clickhouse.client.api.data_formats.RowBinaryFormatSerializer
com.clickhouse.client.api.data_formats.internal.SerializerUtils

Current behavior
Typed setter methods eventually delegate to the generic object setter:

public void setLong(int colIndex, long value) {
setValue(colIndex, value);
}

public void setValue(int colIndex, Object value) {
row[colIndex - 1] = value;

if (!rowStarted) {
    rowStarted = true;
}

}
Because setValue() accepts Object, primitive values are autoboxed
The values are retained in an Object[] until commitRow() is called.
commitRow() then performs another traversal of the row:

List columnList = tableSchema.getColumns();

for (int i = 0; i < row.length; i++) {
ClickHouseColumn column = columnList.get(i);
if (column.hasDefault()&& column.getDefaultValue() != ClickHouseColumn.DefaultValue.DEFAULT) {
continue;
}

if (RowBinaryFormatSerializer.writeValuePreamble(out, defaultSupport, column, row[i])) {
    SerializerUtils.serializeData(out, row[i], column);
}

}

Potential bottlenecks
1: Primitive boxing
Typed methods such as setInteger(), setLong(), and setDouble() delegate to:
setValue(int colIndex, Object value)
This boxes primitives and stores them in an Object[], adding allocation, reference indirection, later unboxing, and possible GC overhead.

2: Multiple passes over every row

Each row is:

  • Written into Object[]
  • Traversed again by commitRow()
  • Cleared using Arrays.fill(row, null)
    A schema-ordered writer could serialize values directly without staging the complete row.

Repeated type dispatch

3: For every cell, commitRow() calls:

SerializerUtils.serializeData(out, row[i], column);
The column type is static, but the serializer path is selected repeatedly for every row.

4: Repeated schema metadata processing

commitRow() repeatedly performs:
tableSchema.getColumns();
columnList.get(i);
column.hasDefault();
column.getDefaultValue();

Writable columns and other static metadata could be resolved once when the writer is created.

Activity

  1. Harry262530 commented on Nov 3, 2026

    @Harry262530
    Author

    I have also attached a benchmarking script that can be usefull to demonstrate the improved performance

    rowbinary-writer-benchmark.zip

  2. bineetsingh30 commented on Nov 4, 2026

    @bineetsingh30

    Hi, I am part of the same company as @Harry262530. We would like to contribute to the issue. @chernser can we improve this and raise a merge request

  3. polyglotAI-bot commented on Nov 27, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — maintainer decision
    A contributor offers a PR (comment of 2026-11-04) and has no answer yet. Decide whether to accept it, and whether a write path that needs the values in column order is in scope.

    • Category: Performance
    • Classification: impact: Performance · area: Data types & formats (RowBinary)
    • Status on main: Reproduced on main — for 20 Int64 columns, the writer takes 2.4 times the time of the per-value write that it calls, and allocates 48 B for each value.
    • Breaking change: No — can be done without a break, if the setters stay usable in any column order. The class is marked "Experimental API".
    • Duplicates / related: No others

    Analysis: The issue describes the path correctly: setLong boxes the value into the Object[] row (client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatWriter.java:142-144, :81-86), and commitRow reads the schema and selects the serializer again for each cell (RowBinaryFormatWriter.java:89-104). The issue does not name the other half of the 48 B: BinaryStreamUtils.writeInt64, which SerializerUtils calls for each Int64 value, allocates a new 8-byte array on each call (clickhouse-data/src/main/java/com/clickhouse/data/format/BinaryStreamUtils.java:820-824).

    Reproduction: complete program and output
    import com.clickhouse.client.api.Client;
    import com.clickhouse.client.api.data_formats.RowBinaryFormatWriter;
    import com.clickhouse.client.api.metadata.TableSchema;
    import com.clickhouse.data.ClickHouseFormat;
    import com.clickhouse.data.format.BinaryStreamUtils;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.lang.management.ManagementFactory;
    
    public class Repro {
        static final String URL = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
        static final String PASSWORD = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
        static final int ROWS = 1_000_000;
        static final int COLS = 20;
    
        /** Discards the bytes, so that only the serialization is measured. */
        static final class NullOut extends OutputStream {
            long n;
            @Override public void write(int b) { n++; }
            @Override public void write(byte[] b, int off, int len) { n += len; }
        }
    
        interface Body { void run(OutputStream out) throws IOException; }
    
        public static void main(String[] args) throws Exception {
            TableSchema schema;
            try (Client client = new Client.Builder().addEndpoint(URL)
                    .setUsername("default").setPassword(PASSWORD).build()) {
                StringBuilder ddl = new StringBuilder("CREATE TABLE triage_3289 (");
                for (int c = 0; c < COLS; c++) ddl.append(c == 0 ? "" : ", ").append("c").append(c).append(" Int64");
                client.execute("DROP TABLE IF EXISTS triage_3289").get().close();
                client.execute(ddl.append(") ENGINE = Memory").toString()).get().close();
                schema = client.getTableSchema("triage_3289");
                client.execute("DROP TABLE triage_3289").get().close();
            }
            final TableSchema ts = schema;
    
            // The issue's path: typed setter, Object[] staging, commitRow.
            Body writer = out -> {
                RowBinaryFormatWriter w = new RowBinaryFormatWriter(out, ts, ClickHouseFormat.RowBinary);
                for (int r = 0; r < ROWS; r++) {
                    for (int c = 1; c <= COLS; c++) w.setLong(c, 1_000L + r + c);
                    w.commitRow();
                }
            };
            // Contrast: the call that SerializerUtils makes for each Int64 value, without the writer.
            Body writeInt64 = out -> {
                for (int r = 0; r < ROWS; r++)
                    for (int c = 1; c <= COLS; c++) BinaryStreamUtils.writeInt64(out, 1_000L + r + c);
            };
            Body[] bodies = {writer, writeInt64};
            String[] labels = {"RowBinaryFormatWriter setLong + commitRow", "BinaryStreamUtils.writeInt64 only"};
            for (int i = 0; i < 2; i++) for (Body b : bodies) measure(null, b); // warm-up (JIT)
            for (int i = 0; i < bodies.length; i++) measure(labels[i], bodies[i]);
        }
    
        static void measure(String label, Body body) throws IOException {
            com.sun.management.ThreadMXBean mx = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
            long tid = Thread.currentThread().getId();
            NullOut out = new NullOut();
            long a0 = mx.getThreadAllocatedBytes(tid);
            long t0 = System.nanoTime();
            body.run(out);
            long t1 = System.nanoTime();
            long a1 = mx.getThreadAllocatedBytes(tid);
            if (label != null) {
                System.out.printf("%s: %d rows x %d Int64, %d bytes, %.1f ns/row, %.1f B allocated/row%n",
                        label, ROWS, COLS, out.n, (t1 - t0) / (double) ROWS, (a1 - a0) / (double) ROWS);
            }
        }
    }

    Output on main (8480ca001), ClickHouse 26.11.2.4, OpenJDK 17.0.21.1:

    RowBinaryFormatWriter setLong + commitRow: 1000000 rows x 20 Int64, 160000000 bytes, 202.2 ns/row, 960.0 B allocated/row
    BinaryStreamUtils.writeInt64 only: 1000000 rows x 20 Int64, 160000000 bytes, 83.6 ns/row, 480.0 B allocated/row
    

    Automated triage by Polyglot AI. A maintainer makes the final decision.

  4. added
    client
    data-types
    on Nov 27, 2026
  5. bineetsingh30 commented on Nov 27, 2026

    @bineetsingh30

    Hi, I would also like to add that the current API is too loose. It allows people to set columns in any order, update their values even after they are set.

    This means that the Row binary writer must maintain the list of values that were set for the current row.

    We should evaluate that as well as part of this, if it needs to be this loose.

    Because in most cases, as the schema is fixed, and data is streamed for a rows in the same order of columns.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    clientdata-typesperformancev2-feedback

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions