Discussion threadhere 
Vote thread
JIRAhere
Release<Flink Version>

1. Motivation

Kafka consumer groups expose an offset frontier per topic partition. Flink checkpoints that frontier and seeks back to it during recovery. This is efficient for ordered streams, but concurrency is tied to the number of partitions and a slow record can hold back later records in the same partition.

Kafka share groups, introduced by KIP-932, replace exclusive partition ownership with broker-managed record delivery state. Multiple consumers can acquire records from the same partition. Each acquired record is later accepted, released, or rejected.

The change is best understood as:

consumer group: checkpointed partition offset -> replay from offset

share group: broker record state -> acknowledge each acquired record

The goal of this FLIP is to integrate that record-state model with Flink checkpoints for Kafka - Flink - Kafka stream pipeline.

1.1 Use cases

  1. Background jobs - email delivery, report generation, media processing, and workflow steps.
  2. Burst-heavy events - webhooks, payment callbacks, alerts, and order work queues.
  3. Command dispatch - many producers sending independent work to a horizontally scaled service.
  4. Stream processing with uneven record cost - records from one partition can be processed concurrently without increasing the topic partition count.

1.2 Guarantee vocabulary

The proposal separates three properties:

  • No source loss - a record is not made terminal until the processing decision is durable.
  • At-least-once processing - failure may execute or emit a result more than once.
  • Exactly-once observable effect - committed output and terminal source acknowledgement are governed by one atomic decision.

Exactly-once does not mean that user code executes once. Flink may execute user code again after recovery. It means that a supported sink exposes one committed effect.

Guarantee ladder

1.3 Goals

  • Add a Flink source backed by KafkaShareConsumer in explicit acknowledgement mode.
  • Bind terminal acknowledgements to completed Flink checkpoints.
  • Define the narrow Kafka-to-Kafka exactly-once path enabled by KIP-1289.
  • Define failure, recovery, rescaling, and ownership rules before declaring the connector production ready.
  • Batch acknowledgements by topic partition so throughput remains close to normal Kafka batching.
  • Keep existing KafkaSource and KafkaSink behavior unchanged.

1.4 Non-goals

  • The FLIP does not claim that KIP-1289 makes an external database transaction atomic with Kafka.
  • The FLIP does not promise exactly-once for an arbitrary Flink DAG merely because the source and one sink use transactions.
  • The FLIP does not remove the need for idempotency, 2PC, or deduplication in external sinks.
  • The FLIP does not treat the current prototype branch as a finished public API.

2. Kafka protocol model

2.1 KIP-932 record delivery state

The broker, not the Flink source, chooses which records to deliver. The source does not seek to a checkpointed offset during recovery. Kafka persists share delivery state in __share_group_state.

The relevant lifecycle is:

AVAILABLE -> ACQUIRED -> ACKNOWLEDGED

Failure or an explicit release uses:

ACQUIRED -> AVAILABLE -> redelivery

A reject may use:

ACQUIRED -> ARCHIVING -> ARCHIVED

The delivery-count limit is a terminal policy, not a retry guarantee. If the limit is exhausted and no usable dead-letter path exists, an at-least-once claim becomes false for that record. Production deployments therefore need a deliberate delivery limit, DLQ policy, alerts, and an operator recovery procedure.

2.2 KIP-1289 transactional acknowledgement

KIP-1289 adds a transaction-owned intermediate state:

ACQUIRED -> TX_PENDING

The final transition depends on the Kafka transaction outcome:

  • COMMIT + ACCEPT -> ACKNOWLEDGED
  • COMMIT + REJECT -> ARCHIVING or ARCHIVED
  • ABORT -> AVAILABLE

Share record state

The Kafka branch implements this with:

  • ShareConsumer.shareGroupMetadata() for group ID, member ID, and member epoch.
  • ShareConsumer.acknowledgementsForTransaction() to drain locally acknowledged ranges.
  • Producer.sendShareAcknowledgementsToTransaction(...) to stage them in an open producer transaction.
  • TxnShareAcknowledge requests sent to each source partition leader.
  • SharePartitionManager.acknowledgeTransactional(...) to persist TX_PENDING state.
  • transaction markers delivered to the relevant __share_group_state partitions.
  • ShareCoordinatorService.completeTransaction(...) to materialize the final share state.

The public consumer API remains per record. acknowledgeAll(...) exists only in Kafka client internals and must not appear as a public FLIP API.

2.3 Durable metadata ownership

DataDurable ownerPurpose
Consumer or share-group control metadata__consumer_offsetsMembership, epochs, assignments, and coordinator-managed group metadata
Share record delivery state__share_group_stateAVAILABLE, ACQUIRED, TX_PENDING, ACKNOWLEDGED, ARCHIVED, delivery count, and staged transaction fields
Transaction decision__transaction_stateProducer epoch, transaction participants, and COMMIT or ABORT decision
User outputOutput topic partitionsData visible according to consumer isolation level

__consumer_offsets does not store the per-record acknowledgement state used for queue semantics. That state belongs to __share_group_state.

2.4 Feature gates and current prototype status

Transactional share acknowledgement requires transaction version 2 and share version 3 in the audited Kafka branch. Share version 3 is not the branch's latest production level. The protocol must therefore be treated as unstable until the Kafka KIP is accepted, protocol IDs are conflict-free, generated messages build, and the feature is promoted.

The audited branch currently assigns API key 94 to both TxnShareAcknowledge and UnregisterController. Protocol generation fails with a duplicate-key error. The FLIP must not publish API key 94 as final.

3. Proposed Flink architecture

Component ownership

3.1 Source reader

The share source uses KafkaShareConsumer in explicit acknowledgement mode.

The split fetcher thread owns all calls to the consumer because the Kafka consumer is not thread-safe. The Flink mailbox thread must communicate checkpoint actions through fetcher tasks rather than calling the consumer directly.

Responsibilities:

  1. Poll share records.
  2. Emit records with a stable internal acknowledgement identity.
  3. Track the exact records covered by each checkpoint boundary.
  4. Renew acquisition locks while records remain eligible for the current checkpoint.
  5. On completed at-least-once checkpoints, send non-transactional ACCEPT acknowledgements.
  6. On the exactly-once Kafka path, transfer compact acknowledgement ranges to the transaction owner.

The source checkpoints subscription and acknowledgement ownership metadata, not a seek offset. Recovery still needs enough Flink state to reconstruct which checkpoint or transaction owned each pending decision. "No partition offsets" does not mean "no connector recovery state."

3.2 Thread model

Thread or event loopResponsibility
Flink mailbox threadEmits records, snapshots operator state, and receives checkpoint notifications
Flink split fetcher threadOwns KafkaShareConsumer, poll, explicit acknowledge, commit, and renew tasks
Kafka consumer network threadShare heartbeat, fetch sessions, coordinator requests, and network progress
Kafka producer sender threadProduce, transactional requests, retries, and response handling
Broker request-handler threadValidates TxnShareAcknowledge and dispatches coordinator work
Group coordinator event loopValidates share member ID and member epoch
Share coordinator event loopPersists staged and final share state
Transaction coordinatorPersists transaction state and resolves COMMIT or ABORT
TxnMarkerSenderThread-<brokerId>Sends and retries transaction markers to transaction participants

3.3 At-least-once checkpoint path

The simple path is:

poll -> process -> checkpoint durable -> ACCEPT -> commitSync

If Flink fails before ACCEPT, Kafka eventually makes the record available for redelivery. If Flink fails after checkpoint completion but before receiving the acknowledgement response, duplicate processing is allowed.

The existing page proposes pausing the fetcher from barrier arrival until checkpoint completion. This provides one frozen in-flight set, but it has two problems:

  • throughput and acquisition stop for the full checkpoint duration;
  • a paused poll loop also stops poll-driven RENEW calls, so locks may expire during a slow checkpoint.

The implementation must choose one of these explicit designs:

  1. Baseline design - allow one outstanding checkpoint, pause acquisition, and run a separate periodic RENEW task while paused.
  2. Pipelined design - continue polling, associate acknowledgement ranges with checkpoint IDs, and checkpoint bounded pending-ack ownership.

The baseline is simpler and safer for the first implementation. The pipelined design is the path to high throughput and multiple concurrent checkpoints.

3.4 Exactly-once Kafka-to-Kafka path

For the supported narrow path, output records and share acknowledgements are participants in the same Kafka producer transaction.

output Produce + TxnShareAcknowledge -> one producer transaction -> one COMMIT or ABORT

The checkpoint sequence is:

Checkpoint happy path

Important ordering:

  1. User output is sent through the transactional producer.
  2. The consumer locally marks ACCEPT or REJECT decisions.
  3. acknowledgementsForTransaction() validates and drains the current fetch into range batches.
  4. The producer stages those batches with sendShareAcknowledgementsToTransaction(...).
  5. The source broker validates membership and changes matching records from ACQUIRED to TX_PENDING.
  6. Flink snapshots a committable containing the transactional ID and recovery metadata. The optional prepared-2PC prototype also stores prepared state.
  7. After checkpoint completion, the committer resolves the Kafka transaction.
  8. COMMIT makes read-committed output visible and makes accepted input terminal. ABORT hides output and returns the input to AVAILABLE.

This guarantee requires all of the following:

  • the output is Kafka;
  • the output and acknowledgements use the same producer transaction;
  • downstream readers use read_committed when they require committed-only visibility;
  • every acquired input has exactly one acknowledgement owner;
  • no acknowledgement is copied into multiple producer transactions;
  • filtered records and zero-output records still reach a valid acknowledgement decision;
  • the checkpoint contains enough transaction identity to recover an unknown outcome.

3.5 General DAG acknowledgement ownership

An acknowledgement payload cannot simply ride on every user record through an arbitrary graph. A shuffle can move records between TaskManagers. A fan-out can copy one input into two branches. A filter can produce no output. A window can combine many inputs into one output.

The connector therefore needs one logical acknowledgement owner per acquired input.

Acknowledgement ownership

The stable identity should include at least:

share group + topic ID + partition + offset + member ID + member epoch

For range compaction, adjacent offsets may be batched only after they have the same owner, checkpoint, and acknowledgement type.

The first exactly-once release should constrain the supported topology to one in which the connector can prove single ownership. Broader DAG support should be a follow-up unless Flink adds an acknowledgement control channel that survives shuffle, fan-out, union, filtering, rescaling, and checkpoint recovery.

3.6 Separate acknowledgement sink

The connector prototype contains a KafkaShareAckSink that starts an acknowledgement-only transaction. This is useful for control flows, but it is not automatically atomic with a separate output transaction.

output transaction COMMIT -> crash -> acknowledgement transaction not committed -> input redelivered

That ordering prevents source loss, but the already visible output can be produced again. It is at-least-once unless the output sink deduplicates by stable input identity.

The prototype OrderedShareEosCommitter records output-first and acknowledgement-second phases. This improves retry control, but it cannot roll back output after the first commit. The class should not be described as end-to-end exactly-once unless the output is idempotent.

4. Public interfaces

The public API should be separated into a stable at-least-once source and an experimental exactly-once extension.

4.1 DataStream source

KafkaShareGroupSource<String> source = KafkaShareGroupSource.<String>builder()
    .setBootstrapServers("localhost:9092")
    .setTopics("orders")
    .setShareGroupId("order-workers")
    .setDeserializer(
        KafkaRecordDeserializationSchema.valueOnly(StringDeserializer.class))
    .setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
    .build();

The builder must reject incompatible properties such as implicit acknowledgement mode. It must document acquisition timeout, maximum delivery count, DLQ requirements, and supported checkpoint concurrency.

4.2 SQL and Table API

CREATE TABLE orders (
    id BIGINT,
    amount DOUBLE
) WITH (
    'connector' = 'kafka',
    'topic' = 'orders',
    'properties.bootstrap.servers' = 'localhost:9092',
    'scan.share-group.id' = 'order-workers',
    'scan.delivery-guarantee' = 'at-least-once',
    'format' = 'json'
);

Exactly-once should not be exposed as a single SQL option until the planner can prove or construct a supported acknowledgement-owner path to the sink.

4.3 Exactly-once API status

The current connector branch contains prototypes such as ShareAckPayload, SameTransactionShareAckKafkaWriter, KafkaShareAckSink, ShareAckTransactionWriter, and OrderedShareEosCommitter. These classes validate pieces of the design but are not yet a coherent public API.

The revised FLIP should mark this interface as unresolved and choose one of two scopes before voting:

  • Narrow scope - a composite Kafka share source to Kafka sink API that owns both output and acknowledgement in one transaction.
  • General scope - a Flink runtime acknowledgement-control abstraction that can preserve ownership through arbitrary DAGs.

The narrow scope is implementable in the connector. The general scope likely needs Flink core and planner work.

5. Fault tolerance and recovery

Failure windows

Failure pointDurable truthRecovery actionGuarantee
Before local acknowledgement extractionRecord remains ACQUIREDLock timeout or release -> redeliveryAt-least-once
After extraction, before Kafka stagingNo broker transaction owns the ackRestore checkpoint -> redeliveryAt-least-once
Partial staging failurePer-partition response identifies staged and failed rangesRetry the same transaction and payload; conflicting payload failsNo guessed success
TX_PENDING, checkpoint abortsStaged share state names producer ID and epochAbort transaction -> AVAILABLEOutput hidden, input redelivered
Checkpoint durable, TaskManager fails before commitFlink has a committable or prepared transaction identityRecover producer and resolve the same transactionExactly-once effect if recovery is bounded
EndTxn response is lostTransaction coordinator owns the decisionRetry or recover the same transaction; never start an unrelated ack transactionNo split-brain decision
Source leader fails while TX_PENDING__share_group_state contains staged stateNew leader reloads state and waits for marker outcomeSafe failover
Share coordinator failsReplicated share-state log is source of truthNew coordinator replays state and completes markerSafe failover
Transaction coordinator fails__transaction_state contains transaction stateNew coordinator resumes decision and marker deliverySafe failover
Marker reaches only some participantsCoordinator retains incomplete marker workTxnMarkerSenderThread retries remaining participantsAtomic decision, delayed completion
Stale member epochBroker rejects the staging requestFail or reacquire under current membership; do not acknowledge stale ownershipFencing prevents wrong-owner ack
Producer fencedTransaction can no longer be safely controlled by this writerFail the checkpoint and recover with the valid ownerNo unsafe commit
Rescale changes subtask routingAck identity is stable, subtask number is notRedistribute checkpointed ownership and recover transaction IDs deterministicallyRequires explicit design
Output commit succeeds, separate ack commit failsOutput is already visibleRetry ack; redelivery can reproduce outputAt-least-once unless output deduplicates
Delivery count reaches limitBroker may archive the recordSend to DLQ and alert; operator replay must be definedNo-loss claim is conditional
Prepared 2PC owner is lostPrototype suppresses timeout for the distributed 2PC transactionRecover and complete by transaction identityCan block indefinitely without an operator recovery mechanism

5.1 Unknown transaction outcomes

The connector must never infer ABORT from a timeout after a commit may have reached the coordinator. It must recover the transaction by stable transactional ID and stored prepared state.

The prototype adds prepared transaction recovery to KafkaCommittable. This is promising, but it also configures distributed 2PC transactions with no coordinator timeout. An orphan can therefore hold records in TX_PENDING and may hold a read_committed last stable offset. Production design needs bounded ownership through lease, coordinator timeout, operator tooling, or a proof that Flink always recovers the transaction.

5.2 Source-leader cache convergence

Transaction completion is durably written by the share coordinator. A source broker may still cache TX_PENDING briefly. The audited Kafka code invalidates local state during marker handling and can evict or reload stale state on the next ShareFetch. This is safe for correctness but can add redelivery latency. Best-effort cross-broker notification is a latency optimization, not the durability boundary.

6. Throughput and latency pattern

The fast path should be:

poll many records -> process concurrently -> compact offsets into ranges -> stage once per checkpoint -> one transaction decision

6.1 Throughput rules

  • Keep public acknowledgement per record, but compact adjacent offsets into broker batches.
  • Do not issue a synchronous transactional acknowledgement RPC per record.
  • Preserve Kafka producer batching and compression for output.
  • Group staging by source partition leader.
  • Add each unique __share_group_state partition once as a transaction participant.
  • Bound pending acknowledgement bytes and records. Apply source backpressure before memory becomes unbounded.
  • Start with one outstanding checkpoint for simple ownership. Add pipelining only with checkpoint-tagged ack sets and recovery tests.
  • Avoid carrying large acknowledgement payloads through every user record. Carry a stable identity and keep compact owner state in the connector control path.

6.2 Latency rules

  • Checkpoint interval places a lower bound on terminal acknowledgement latency.
  • Acquisition timeout must exceed normal processing time, checkpoint duration, renew jitter, coordinator retry time, and a safety margin.
  • A separate renew scheduler is required if acquisition is paused.
  • Long Kafka transactions delay output visibility for read-committed consumers.
  • Marker fan-out grows with output partitions plus unique share-state partitions.
  • Coordinator and source-leader retry backoff must be visible as metrics.

6.3 Proposed metrics

The current audited branches do not provide a complete metric set for this integration. The FLIP should require:

  • acquired records and bytes;
  • pending acknowledgement records, ranges, bytes, and oldest age;
  • renew request rate, latency, and failures;
  • transactional ack staging latency and retries;
  • TX_PENDING records and age;
  • member-epoch fencing and producer-fencing counts;
  • checkpoint-to-ack completion latency;
  • delivery count distribution, archive count, and DLQ failures;
  • recovered transactions, unknown outcomes, and marker retry age.

7. Compatibility and migration

Existing KafkaSource, KafkaSink, and SQL configurations remain unchanged when scan.share-group.id is absent.

Consumer groups and share groups are different processing models. Migration is a semantic change, not only a configuration change.

WorkloadRecommended modelReason
Ordered partition streamExisting KafkaSourceStable offset frontier, ordering, replay, mature EOS integration
Independent queue workShare source, at-least-onceElastic consumers and per-record delivery state
Kafka input to Kafka output with constrained ownershipShare source + same-transaction Kafka sinkKIP-1289 can atomically bind output and source ack
External database or object storeShare source + sink 2PC or idempotencyKafka transaction cannot directly commit the external system
Arbitrary fan-out, join, and multi-sink DAGNot supported for EOS in the first releaseOne ack owner and one atomic outcome are not yet proven

The final Kafka version requirement must be stated only after KIP-1289 lands and share version 3 becomes a supported production feature. "Kafka 4.0+" is sufficient for basic KIP-932 share groups but not for transactional acknowledgements.

8. Test plan

8.1 Unit tests

  • Per-record ACCEPT, RELEASE, REJECT, and RENEW behavior.
  • Offset-range compaction without crossing acknowledgement type, checkpoint, owner, or gaps.
  • Checkpoint ownership snapshot and restore.
  • Renew continues while acquisition is paused.
  • Payload retry is idempotent and conflicting payloads fail.
  • Staging occurs before transaction prepare.
  • A prepare failure retains payload for retry.
  • Zero-output, filter, fan-out, and duplicate-owner cases.
  • Serialization compatibility for committables and source state.

8.2 Integration tests

  • Kafka-to-Kafka same-transaction happy path with read_committed output.
  • Failure before staging, after staging, after prepare, during EndTxn, and during marker delivery.
  • Source leader, share coordinator, and transaction coordinator failover.
  • TaskManager failure with automatic restart enabled.
  • Rescaling up and down while records are ACQUIRED and TX_PENDING.
  • Multiple records per poll and multiple source partitions per transaction.
  • More than one sink subtask and routing that moves records across TaskManagers.
  • Filtered records with no output and fan-out records with multiple outputs.
  • Delivery limit and DLQ failure.
  • Orphaned prepared transaction detection and operator recovery.

8.3 Chaos and performance tests

  • Kill brokers and TaskManagers at every numbered step in the happy-path sequence.
  • Inject delayed, duplicated, and lost responses.
  • Compare throughput against the existing offset source at equal record size and processing cost.
  • Measure checkpoint duration, transaction duration, renew overhead, marker fan-out, and recovery time.
  • Run a long soak test with coordinator leadership movement and periodic rescaling.
  • Verify no missing stable input IDs. For EOS tests, also verify no duplicate committed output IDs.

9. Prototype evidence and known gaps

The code branches provide evidence for the core protocol, but the FLIP should disclose the following before a vote:

  1. Kafka protocol generation fails because API key 94 is duplicated.
  2. The connector branch does not compile because FlinkKafkaShareAckTransactionalProducer calls a missing markShareAcksStaged() method.
  3. There is no production KafkaShareGroupSource, builder, reader, enumerator, or SQL factory integration in the connector branch.
  4. SameTransactionShareAckKafkaWriter is package-private and is not wired into normal KafkaSink construction.
  5. KafkaShareAckSink uses a separate transaction and therefore is not atomic with an arbitrary output sink.
  6. OrderedShareEosCommitter is unit-tested but is not wired into a production sink topology.
  7. The integration test uses a custom legacy RichParallelSourceFunction, max.poll.records=1, no restart strategy, and a custom sink wrapper. It proves a narrow happy path, not recovery of a general Flink job.
  8. Kafka API access in the connector uses reflection because the dependency does not yet expose a stable KIP-1289 API.
  9. Share version 3 is not the Kafka branch's latest production feature level.
  10. Prepared distributed 2PC transactions have no timeout in the prototype, which creates an orphan-liveness risk.

These are implementation gaps, not reasons to reject the architecture. They define the work needed before claiming production readiness.

10. Rejected alternatives

10.1 Acknowledge immediately after user function execution

Rejected because Flink state and downstream output may not be durable. Failure after ACCEPT can lose the only replayable copy.

10.2 Store only subscription state and rely entirely on the Kafka client in-flight map

Rejected for pipelined checkpoints and general DAGs. The client map does not encode Flink checkpoint ownership after process recovery.

10.3 Commit output first and acknowledgement second, then call it exactly-once

Rejected as a general EOS claim. A crash between commits exposes output and redelivers input.

10.4 Copy acknowledgement payload onto every downstream record

Rejected because fan-out creates multiple owners, filtering drops the decision, and shuffles move ownership without a durable control protocol.

10.5 Use __consumer_offsets for per-record share state

Rejected because Kafka share delivery state is persisted by the share coordinator in __share_group_state. __consumer_offsets remains control metadata, not the record-state ledger.

11. Rough draft

Kafka branch kip-1289-txn-ack-share-groups: https://github.com/apache/kafka/pull/22357 


Flink connector Kafka PR: github.com/apache/flink-connector-kafka/pull/271

  • Same transaction prototype - SameTransactionShareAckKafkaWriter.java
  • Ack payload and staging - ShareAckPayload.java, ShareAckPayloadStager.java, ShareAckPayloadBuffer.java
  • Separate ack sink - KafkaShareAckSink.java, KafkaShareAckSinkWriter.java, ShareAckTransactionWriter.java
  • Ordered two-transaction prototype - OrderedShareEosCommitter.java, ShareEosCheckpointLedger.java
  • Prepared recovery - ExactlyOnceKafkaWriter.java, KafkaCommittable.java, KafkaCommittableSerializer.java, KafkaCommitter.java
  • Narrow integration test - KafkaShareEosPipelineITCase.java