Use Cases
When a single Flink job writes to multiple tables within the same database in one processing cycle, enabling multi-table transaction guarantees:- Cross-table atomic commit: Data written to different table within the same commit cycle becomes visible atomically — all or nothing.
- Source transaction integrity: A complete upstream transaction (for example, from Kafka) is never split across two the database transactions.
- Sub-second data freshness: Data continuously flows into the database via
/api/transaction/load, and is committed at the interval configured bysink.buffer-flush.interval-ms.
- Synchronous writes to a general table and a detail table (for example,
ordersandorder_items) - Event routing to different partition tables (for example,
events_202601,events_202602) - A single job maintaining multiple interrelated downstream result tables
Core Capabilities
Configurations
Multi-table Transaction Configurations
sink.transaction.multi-table.enabled
- Type: Boolean
- Default:
false - Description: Whether to enable the Multi-table Atomic Transaction mode.
sink.transaction.multi-table.buffer-size
- Type: Long
- Default:
134217728(128 MB) - Unit: Bytes
- Description: Global buffer size in bytes for the Multi-table Transaction mode. When the total buffered data across all tables reaches this threshold, a flush is triggered.
sink.transaction.multi-table.mini-switch-interval-ms
- Type: Long
- Default:
-1(auto) - Unit: ms
- Description: Minimum interval (ms) between per-partition chunk switches. Within the interval, source transactions are batched into a single stream-load, bounding HTTP request count.
-1auto-derivesmin(1000, max(500, sink.buffer-flush.interval-ms/4)); a positive value overrides it.
sink.transaction.multi-table.min-switch-bytes
- Type: Long
- Default:
1048576(1 MB) - Unit: Bytes
- Description: An interval-elapsed chunk switch only fires once a region’s active chunk has accumulated at least this many bytes, so low-volume partitions batch more source transactions into one stream-load instead of emitting many tiny requests. Half-full headroom, buffer-size memory pressure, or a full
sink.buffer-flush.interval-mselapsing since the partition last switched all force a switch regardless — so even with a large threshold a continuous low-volume stream is still switched at roughly the flush interval and never withheld indefinitely. Set<=0to disable the size gate and restore the prior per-interval switching behavior. Whenmini-switch-interval-msis equal to (or larger than)sink.buffer-flush.interval-ms, this option has no effect on the txnEnd switch (see Chunk Lifecycle andminiIntervalBatching).
sink.transaction.multi-table.max-txn-bytes
- Type: Long
- Default:
0(unlimited) - Unit: Bytes
- Description: Hard limit in bytes on the in-progress source-transaction data one sink subtask may buffer while waiting for txnEnd. The writer never blocks on bytes that cannot be flushed before txnEnd (see Limitation 7), so a single source transaction may grow past
2 × buffer-size; this option bounds that growth and fails the job with a clear error when exceeded.0means no limit: the TaskManager heap is the only bound.
Load-related Configurations
sink.version
- Recommended Value:
V2 - Description: Required.
V1does not support the transaction Stream Load interface.
sink.semantic
- Recommended Value:
at-least-once - Description: Multi-table mode currently supports
at-least-onceonly.
database-name
- Recommended Value:
* - Description: Wildcard to enable dynamic multi-table routing.
table-name
- Recommended Value:
* - Description: Wildcard to enable dynamic multi-table routing.
sink.buffer-flush.interval-ms
- Recommended Value:
1000 - Description: Controls the commit cycle. You can set it to
1000to achieve the freshness of approximately one second.
sink.http.keep-alive.enabled
- Recommended Value:
true - Description: Recommended. Loads and BEGIN / PREPARE / COMMIT / ROLLBACK reuse HTTP connections instead of opening a new connection for every request. Off by default (see Best Practices 6).
sink.properties.format
- Recommended Value:
json - Description: The data format.
sink.properties.strip_outer_array
- Recommended Value:
true - Description: Whether to strip the outermost array structure.
Interfaces
StarRocksRowData
DefaultStarRocksRowData
User-Implemented Component
Users need to implement aKeyedProcessFunction (referred to as TransactionAssembler in this document) that:
- Keys by source partition and buffers data rows within a transaction
- Emits all rows only when the source transaction is closed (for example, upon receiving
TXN_END) - Sets
transactionEnd=trueon the last row - Sets
sourcePartitionon every row
SinkFunction is needed — the standard connector API (SinkFunctionFactory.createSinkFunction()) handles everything.
Complete Example
Table DDL
Flink Job Code
Data Flow Topology
How It Works
Chunk Lifecycle and miniInterval Batching
Each (partition, table) region has one activeChunk (currently accepting writes) and a FIFO of inactiveChunks (frozen data, pending HTTP load). In multi-table transaction mode, the only way data moves from activeChunk into inactiveChunks is a commit switch, taken only at a clean transaction boundary and, except for the savepoint, applied to all regions of a partition together (lockstepSwitchPartition). It happens at exactly four sites:
-
Task thread, on txnEnd — inside
setCommitAllowed(partition, true), which marks every region of the partition clean and then makes one switch decision for the whole partition (rule below). This is the common path. -
Manager thread, source-idle force-switch —
managerForceSwitchCleanBoundaryRegions()on every scan cycle, for partitions whose regions are all at a clean boundary and at least one holds rows. Under pressure (buffered bytes reachedbuffer-size, or a region’sactiveChunkis half-full) the partition is switched at once; otherwise only when a region holds at leastmin-switch-bytesandminiSwitchIntervalMshas elapsed since the partition’s last switch. Idle data belowmin-switch-bytesis left for the commit cut. - Manager thread, commit cut — at the start of every timer-driven commit and every recycle (see Manager Thread — Time-Driven Commit and Shared Transaction Coordination): switches every clean partition and freezes a commit watermark on every region.
- Manager thread, savepoint — the checkpoint flush force-switches every region after verifying every region is at a clean boundary (see Best Practices 3).
activeChunk and is batched with later ones:
-
at least
miniSwitchIntervalMshas elapsed since the partition’s last switch and at least one of its regions’activeChunkholds at leastsink.transaction.multi-table.min-switch-bytes(default 1 MB;<= 0disables this size check); -
a full
commitIntervalhas elapsed since the partition’s last switch (the freshness upper bound, so the size gate never defers completed data indefinitely); -
a region’s
activeChunkreached half of the write-block cap (that is,buffer-sizebytes); -
buffered bytes across all regions reached
buffer-size.
miniSwitchIntervalMs is min(1000 ms, max(500 ms, commitInterval / 4)), so a 2-second commit interval batches at 500 ms while a 4-second-or-longer interval caps batching at 1 second (an explicit sink.transaction.multi-table.mini-switch-interval-ms overrides this). Within that window multiple completed source transactions accumulate into the same activeChunk (N:1 mapping) and are frozen together on the next switch.
The size gate only matters while miniSwitchIntervalMs is shorter than commitInterval. If mini-switch-interval-ms is set equal to (or larger than) sink.buffer-flush.interval-ms — or is auto-derived to 500 ms for a commit interval of 500 ms or less — the freshness bound is reached no later than the interval, so every txnEnd after the interval switches regardless of size and min-switch-bytes has no effect on the txnEnd path.
Two pieces of state drive these decisions:
- The partition’s last switch time (kept per partition by the manager, so all regions of a partition batch together). Initially 0, so the very first txnEnd of a partition always triggers a switch.
-
activeChunkCleanBoundary(per region) —trueif the most recent task-thread event on this region was either a txnEnd or a switch.falseafter anywrite(). The manager-thread switches re-check this flag on every region of the partition under the regions’ write locks and skip the partition if any region is dirty, so they can never freeze partial source-transaction data.
Task Thread — Write and txnEnd
write() and setCommitAllowed() events, which is why both the cleanBoundary mark and the conditional switch must run here (not deferred to the manager thread): cleanBoundary must reflect the most recent task-thread event at all times, or the manager’s idle-fallback could race a write and freeze partial data.
6.3 Manager Thread — Time-Driven Commit
The manager thread runs a scan loop atscanningFrequency. Each iteration:
-
Ensure shared transaction: open a new one (eager) or proactively recycle the current one if it is approaching the server-side timeout (80% of
timeoutheader, default 480 s). -
Source-idle fallback: force-switch any partition whose regions are all at a clean boundary once it has accumulated
min-switch-bytesandminiSwitchIntervalMshas elapsed since its last switch, or at once under memory pressure (see Chunk Lifecycle andminiIntervalBatching). Below the size threshold the idle data is not switched here — the time-driven commit below cuts and commits it instead (see step 3), so a source that pauses still becomes visible within onecommitInterval. This handles the “source paused after a few txnEnds” case where the task thread stopped before issuing a fresh switch. -
Time-driven commit trigger: call
tryStartTimerDrivenCommit(), which setscommitInFlight=trueif both conditions hold:-
now - lastCommitTimeMs >= commitInterval(the configuredsink.buffer-flush.interval-ms). -
There is data to commit —
txnCoordinator.hasDataLoaded()is true, at least one region has pending inactiveChunks, or some partition is entirely at a clean boundary with buffered active rows (deferred below the size gate) that the commit cut will freeze. This last check is evaluated at partition scope, so a lone clean region whose sibling table is still mid-transaction does not arm a commit cycle that cannot make progress.
-
-
Autonomous flush: drain any region whose
inactiveChunksis non-empty via theFlushAndCommitStrategy. Multi-table mode’sflush()only streams out already-frozen inactive chunks — it never touchesactiveChunk. This preserves the invariant that every chunk reaching the database under the shared label comes from completed source transactions.
commitInFlight=true the main loop enters processMultiTableCommit. Its first step is the commit cut, which decides what goes into this label. The cut works per partition and does not wait for every partition to reach a clean boundary. Under the partition’s region write locks (so a concurrent txnEnd switch cannot land in between):
- A clean partition (every region at a clean boundary, at least one with rows) is switched in lockstep, then every region’s commit watermark is set to its newest switched chunk.
-
A dirty partition (any region mid-transaction) is not switched; its regions’ watermarks are set at their last switch. The chunks it switched earlier are committed now, and its
activeChunk(the in-progress source transaction plus any completed transactions batched with it) goes into the next shared transaction.
SharedTransactionCoordinator, lifts the watermarks, updates lastCommitTimeMs, resets the tracker, and opens a new shared transaction for the next cycle.
Shared Transaction Coordination
All tables within the same commit cycle share a single the database transaction managed bySharedTransactionCoordinator:
- Eager transaction opening: A shared transaction is opened eagerly before any autonomous flush, so all HTTP loads use the shared label. This eliminates the data-loss window where an independent-label flush could be orphaned when a shared transaction later overwrites the label.
-
Unified commit: After all regions’ data is loaded, a single
POST /api/transaction/commitis executed for the shared label. Multi-table transactions skip thepreparestep because the database does not supportTXN_PREPAREin multi-table mode. -
Transaction recycling: If the shared transaction has been open (measured from its BEGIN, not from its last load) longer than 80% of the BEGIN
timeoutheader (default: 480s for the 600s the connector sends), it is proactively recycled (commit-or-rollback + reopen) to prevent server-side timeout errors. The recycle uses the same per-partition commit cut as the timer-driven commit, so a partition that is mid-transaction is simply carried into the next label. Recycle fails fast only if a partition has written data without receiving any txnEnd since the last commit. Recycling is best-effort: it waits while a commit cycle is in flight or any region is still loading or retrying, so a load that never returns (possible with the defaultsink.socket.timeout-ms=-1) can still let the label reach its deadline. Set a finitesink.socket.timeout-msto bound this.
6.5 PartitionCommitTracker (Safety Bookkeeping)
In the current design, commit timing is driven entirely by the commit interval and the per-region clean-boundary flags.PartitionCommitTracker is reduced to an informational/safety aid:
-
onWrite(partition)registers a partition asACTIVEon first write. -
onTxnEnd(partition)transitions the partition toTXN_END_SEEN(sticky — subsequent writes do not demote it back toACTIVE). -
getPartitionsWithoutTxnEnd()lists partitions that have written data but never received a txnEnd. Used by savepoint and recycle to fail fast on upstream contract violations (a source transaction that never closed). -
reset()clears all partitions at the end of a commit cycle.
SWITCHED state, and does not manage pending txnEnd signals. Partitions that stop producing data after a commit are simply cleared by reset(); if they resume later, the next onWrite re-registers them.
Autonomous Flush with Shared Labels
When a region’sinactiveChunks becomes non-empty, the manager thread’s autonomous-flush loop streams it to the database via /api/transaction/load under the current shared label. Because the shared transaction is always opened before any data is loaded, there is no window where data could be loaded under an independent (orphaned) label. In multi-table mode, flush() never triggers a switchChunk — it only drains already-frozen inactive chunks — so the invariant “every chunk reaching the database under the shared label comes from completed source transactions” holds unconditionally.
Safety Guarantees
N:1 Transaction Mapping
Multiple source transactions can accumulate in a single the database transaction via the miniInterval batching mechanism:commitInterval=1 s (so the auto-derived miniInterval=500 ms), the connector issues at most ~2 load calls per second instead of ~100; with the default min-switch-bytes size gate a low-volume stream batches even further, down to about one load per commitInterval (the freshness bound at which a below-threshold chunk is still switched).
Limitations
-
Requires
sink.version=V2: V1 does not support transaction stream load. - At-least-once only: Failed retries may produce duplicate writes. Multi-table mode guarantees all tables within the same batch succeed or fail together, but does not provide global exactly-once. For PRIMARY KEY tables, duplicate writes are idempotent (upsert).
- All tables must be in the same database: the database multi-table transactions are database-scoped; cross-database transactions are not supported.
-
Transaction scope is per sink subtask + per partition: Each sink subtask maintains its own the database transaction independently. Atomicity is guaranteed within a single source transaction (all rows for one txnEnd on one partition, across all tables that partition writes to). Data visibility across different source partitions can interleave: once partition P0’s source transaction has fully arrived and the commit interval has elapsed, P0’s data is committed even if partition P1’s source transaction is still in progress. Applications that require cross-partition atomicity at the database level must either use a single source partition or coordinate commits upstream. In short, the source-transaction guarantee holds per lane only, where a lane is one
sourcePartitionon one sink subtask. Everything committed under one label, including rows from several lanes, becomes visible atomically, but nothing controls which source transactions of different lanes end up in the same label: a related transaction on another lane can land in an earlier or later label, and lanes on different sink subtasks never share a label. -
Data visibility latency: Governed by
sink.buffer-flush.interval-ms(the commit interval). A completed source transaction is first frozen out of theactiveChunk— either as soon as the partition reachessink.transaction.multi-table.min-switch-bytes(default 1 MB), or, for a low-volume partition below that threshold, at most onecommitIntervalafter its last switch (the freshness bound enforced on the task thread at txnEnd) — and is then published by the next time-driven commit. So in a continuously flowing CDC stream an individual row becomes visible within roughly onecommitIntervalwhen the partition is busy enough to reach the size gate, and within up to twocommitIntervalwindows in the low-volume worst case (one to freeze the below-threshold chunk, one to commit it). During a source pause, previously-committed data remains visible and the last idle sub-threshold chunk is committed within one morecommitIntervalvia the time-driven commit’s clean-boundary detection. Setmin-switch-bytes <= 0to switch on every interval (lowest latency, more/smaller loads). -
Depends on cluster transaction settings: Monitor running txn limits, the transaction timeout, and label retention. The transaction timeout is the
timeoutheader the connector sends on BEGIN — 600 s unlesssink.properties.timeoutoverrides it — and the database treats it as an absolute deadline measured from BEGIN, not an idle timeout: loads into the label do not extend it. The connector recycles the shared transaction at 80% of it (480 s by default). Ensuresink.buffer-flush.interval-msis significantly shorter than this timeout. -
activeChunk memory growth under large source transactions: Because multi-table mode disables chunk-size-triggered internal switching (to preserve the clean-transaction-boundary invariant),
activeChunkcan grow until the next txnEnd arrives.sink.transaction.multi-table.buffer-size(soft) and2 × buffer-size(hard, viablockIfCacheFull) only bound the flushable part of the buffer — frozen chunks and all-clean partitions. Bytes that cannot leave the buffer before a txnEnd (the in-progress transaction itself, plus completed rows of sibling tables in the same partition that the lockstep rule holds back) are never waited on: once the buffer is at the hard cap and nothing is flushable, the writer logs a WARN (Write-block cap ... reached with nothing flushable) and keeps buffering until txnEnd, after which the partition is switched and drained. So a single source transaction may exceed2 × buffer-size; its size is bounded only bysink.transaction.multi-table.max-txn-bytes(default unlimited) and the TaskManager heap. Size the heap for the largest expected source transaction times the number of sink subtasks per TaskManager, setmax-txn-bytesif you prefer a clear failure over heap pressure, and split unbounded transactions (bulk bootstraps) upstream. At switch time a frozen chunk larger than the load body limit — the smaller ofsink.chunk-limit(3 GB by default) andsink.transaction.multi-table.buffer-size— is re-cut into several load requests under the same shared label, so no single/api/transaction/loadbody exceeds that limit, except for a single row that is itself larger than it. - Cross-database writes are rejected: Multi-table transactions validate that all regions belong to the same database. Writing to tables in different databases within the same commit cycle will throw an error.
-
Incompatible with merge commit:
sink.properties.enable_merge_commit=truecannot be combined withsink.transaction.multi-table.enabled=true. Merge commit routes writes throughMergeCommitManager, which lacks the partition-awarewrite(int, ...)/setCommitAllowed(int, ...)hooks that multi-table mode relies on for transaction boundaries. The connector fails fast at validation time if both are enabled. -
Exactly one upstream producer per
sourcePartition: Clean boundaries are positional — a partition is at a clean boundary iff the last row the sink subtask received for it carried txnEnd; the connector does not track which source transaction a row belongs to. If two producers (two assembler subtasks, or two sources whose partition numbers collide, such as partition 0 of two Kafka topics) emit rows with the samesourcePartition, their rows interleave at the sink, one producer’s txnEnd marks the partition clean while the other’s transaction is still in progress, and the next switch can commit that transaction partially. Key the TransactionAssembler by the same value the sink keys by, and makesourcePartitionunique across all sources. -
Aligned checkpoints only: The checkpoint flush requires every region to be at a clean boundary when the barrier reaches the sink (see Best Practices 3). Aligned checkpoints guarantee this, because the assembler emits a whole source transaction within one
processElement()call and the barrier cannot fall between its rows. Unaligned checkpoints (execution.checkpointing.unaligned.enabled;execution.checkpointing.unalignedbefore Flink 1.20) let the barrier overtake in-flight rows and reach the sink mid-transaction. This includes the aligned-then-unaligned mode, where unaligned checkpoints are enabled together withexecution.checkpointing.aligned-checkpoint-timeoutand a checkpoint switches to unaligned once the timeout expires; the timeout has no effect while unaligned checkpoints are disabled. The checkpoint then fails, the open label is rolled back and the job fails over. -
Data-quality rejections abort the whole label: For a multi-table transaction, the database applies strict mode and
max_filter_ratioat commit, not at each/api/transaction/load. A rejection fails the commit and aborts the whole label — every table’s rows in that commit cycle, not only the table with the bad rows. The connector reports a commit failure and the job fails over; the same rows are replayed, so it keeps failing until the rows or the load settings are fixed. -
StarRocks v4.1.6 and earlier can report a failed multi-table commit as OK: On these versions a multi-table commit that failed on the server can be returned to the client as
OK. The connector then treats the label as committed, so the rows of that commit cycle can be silently missing. Fixed by the database PR #80351 (CelerData backport: commit1ceb0763cf).
Monitoring and Troubleshooting
Recommended metrics:- On the Flink Side
- Checkpoint success rate
- Checkpoint duration
- Sink flush/commit latency
- On the database Side
- Running/prepared txn count
- Txn timeout occurrences
- Label conflicts
- On the Connector Side
- The
sharedTxnLatencyMshistogram: the time from when the earliest row of a shared transaction entered the sink buffer until the transaction committed. Each commit also logs it per label:[MultiTxn] SharedTransaction committed successfully: label=<label>, firstRowTimeMs=<epoch ms>, latencyMs=<ms>(both-1when unknown).
- The
Common issues
transaction not existed
- Cause: the database transaction timeout
- Solution: The connector automatically recycles the shared transaction at 80% of the BEGIN
timeout(measured from BEGIN). If this still occurs, check whethersink.properties.timeoutis too short, the flush interval is too large, or a load hung past the deadline (set a finitesink.socket.timeout-ms).
too many running txns
- Cause: There are excessive concurrent transactions.
- Solution: Reduce sink parallelism or increase the value of the database FE configuration
max_running_txn_num_per_db.
Transaction start failed
- Cause: The
beginTransactionHTTP call failed - Solution: Verify load-url connectivity and the version (v4.0 or later is required).
High data visibility latency
- Cause: Commit conditions are not met.
- Solution: Verify upstream data has correct
transactionEnd=truemarkers; for a low-volume partition belowmin-switch-bytes, expect up to ~2×commitIntervalper row (one interval to freeze the below-threshold chunk, one to commit it). If latency exceeds this budget, check the manager thread is not stuck in a recycle or in-flight load (seeStarRocks-Sink-Managerlogs), or lowermin-switch-bytes.
Write-block cap ... reached with nothing flushable (WARN)
- Cause: A source transaction, plus completed rows of sibling tables held back until its txnEnd, exceeds
2 × buffer-size; the writer keeps buffering until txnEnd instead of blocking. - Solution: Expected under a large source transaction; the data is committed once its txnEnd arrives. Watch TaskManager heap. Set
sink.transaction.multi-table.max-txn-bytesif you prefer a hard failure, or split the transaction upstream.
would exceed sink.transaction.multi-table.max-txn-bytes
- Cause: A source transaction is larger than the configured hard limit.
- Solution: Raise
max-txn-bytes(or set it to0for unlimited) or split the source transaction upstream.
Cross-database write error
- Cause: Tables in different databases are in same commit cycle.
- Solution: Ensure all tables written in the same job belong to the same database.
Best Practices
-
TransactionAssembler contract:
- Emit rows only after the source transaction is fully closed.
- The last row must have
setTransactionEnd(true). - Every row must have
setSourcePartition(partition). - All rows must be emitted synchronously within a single
processElement()call.
-
keyBy before sink is mandatory:
rows.keyBy(DefaultStarRocksRowData::getSourcePartition).addSink(sink)— omitting this breaks within-partition transaction ordering. EachsourcePartitionvalue must also come from exactly one upstream producer (see Limitation 10). -
Checkpoints also commit: Data visibility is governed by
sink.buffer-flush.interval-ms(for example, 1000ms), but checkpoints are not decoupled from commit. In at-least-once modesnapshotStatecallsflush(), which blocks the task thread until the whole buffer — including completed transactions still batched inactiveChunk— is loaded and the open shared label is committed. The flush has a budget of 1.1 × the transaction timeout (660 s by default), but it is checked only between waits and is not a hard cap: the drain waits for every in-flight/api/transaction/loadwithout a deadline, and with the defaultsink.socket.timeout-ms=-1a load whose response never arrives can keep the checkpoint, and the task thread, blocked indefinitely. Set a finitesink.socket.timeout-ms, longer than the slowest expected load, so that a hung load fails the job instead. If the barrier arrives while any partition is mid-transaction, the flush throws, the open label is rolled back and the job fails over (see Limitations 10 and 11). A larger checkpoint interval (for example, 60 seconds) means fewer of these forced commits. - Keep routing strategies stable: Avoid single transactions writing to an excessive number of distinct tables, which increases transaction duration and failure probability.
- Fault injection testing before production: Kill TaskManagers / introduce network jitter and verify data correctness after checkpoint recovery.
-
Enable HTTP keep-alive: Set
sink.http.keep-alive.enabled=true. A shared transaction sends a BEGIN, many loads and a COMMIT, and without keep-alive each of them opens a new TCP (and TLS) connection. A connection that fails during any of these requests fails the whole shared transaction, which rolls back every table in it and fails the job over, so fewer new connections means fewer such failures, for example behind a load balancer that can reset new connections. With keep-alive on, a request on a reused connection that the server or a load balancer closed is sent again on a new connection where that cannot write data twice. Keepsink.http.keep-alive.idle-timeout-ms(default 60000) shorter than the idle timeout of every proxy or load balancer between Flink and the database; an AWS Network Load Balancer drops connections idle for 350 seconds by default.