Repository navigation
Description
Background
MQTT 5 shared subscriptions ($share/<ShareName>/<filter>) deliver each matching message to exactly one session subscribed to that shared subscription. mqtt-kafka rejects them today with reason code 0x9E.
Kafka share groups (KIP-932) give per-record acquisition, acknowledgement and redelivery, so a shared subscription maps onto a share group without owner election, cross-replica routing or partition-bounded parallelism.
Semantics (MQTT 5.0 §4.8.2, §4.4 and §3.10.4, verified against the spec)
- A shared subscription is identified by
(ShareName, filter).$share/g/a/#and$share/g/b/#are distinct subscriptions. - QoS 2, connection breaks mid-delivery: MUST complete delivery to the same client on reconnect. If its session terminates first, MUST NOT send to any other subscriber (
4.8.2-4,4.8.2-5). - QoS 1: MAY wait for reconnect or send to another subscriber at once. SHOULD send to another subscriber if the session terminates.
- PUBACK or PUBREC with reason code ≥ 0x80: MUST discard, never try another subscriber (
4.8.2-6). - Granted QoS is per subscriber. No retained messages are sent.
noLocalis a protocol error (3.8.3-4). - UNSUBSCRIBE: MUST stop adding new matching messages and MUST complete delivery of QoS 1 and 2 messages already started (
3.10.4-2,3.10.4-3). - On reconnect, unacknowledged PUBLISH and PUBREL packets are resent with their original packet identifiers, and a resent PUBLISH has DUP = 1 (
4.4.0-1,3.3.1-1). - The subscription ends, and its undelivered messages are deleted, when no session is subscribed. Offline persistent sessions still count as subscribed.
Design
Kafka mapping
Share group id is <group.id.prefix, ':' replaced by '.'>.share.<ShareName, '%' and ':' escaped>.<base64url filter>.<epoch>, for example zilla.zilla-mqtt-kafka-proxy-north_mqtt_kafka_mapping.share.group.c2Vuc29yLyM.0. The share coordinator keys its state as groupId:topicId:partition, so a group id containing : is rejected by a real broker; the id is therefore dot-separated. The filter is part of the id because filtering happens after broker-side acquisition. The subscription epoch starts a fresh group, at the latest offset, each time the subscription is recreated (see Lifecycle). Verified against Kafka 4.1.1: share names with dots, spaces, colons, percent signs and unicode, and filters of 1000 characters, are accepted.
binding-kafka (implemented)
- Stream contract: a
SHAREstream kind. Begin carries group id, optional member id, topic andfilters. Data carries partition offset, timestamp, key, headers (on INIT and FIN) anddeliveryCount(0 on the client hop means not reported). An acquired flush after each partition's records carrieslockTimeoutMillisand the acquired ranges with delivery counts. An app-to-zilla flush carries ACCEPT, RELEASE or REJECT per record, with an optional correlation and error. - Client factory: one share-group member per stream.
FindCoordinatorv6,ShareGroupHeartbeat,Metadatav13 (topic ids),ShareFetchandShareAcknowledgev1, withApiVersionsnegotiated per connection. The response is decoded in a streaming fashion. Fetch sizing is configuration-driven like the standard client library (client.share.fetch.max.bytes,.max.records,.max.wait.millis,.min.bytes). Acks piggyback on the next fetch and are sent on leave. The emitted lock timeout is conservative, measured from the request send. The firstShareFetchis sent before the reply BEGIN, because the broker fixes the share partition start offset at the first fetch it handles; the reply BEGINs once that fetch is accepted, so a message published right after SUBACK is not lost. - Cache fan-out: the cache_server holds one member per
(binding, group id, topic)per worker and fans out in process. cache_client is a 1:1 pass-through. Records are staged in an ephemeral cache partition log (directory named by SHA-256 of group id and topic, to stay within file name limits) until the acquired flush, filters are evaluated on the complete record, delivery goes to the next attached stream with window, unacknowledged records re-route in process when a stream detaches, and everything outstanding is RELEASEd when the last stream leaves. Expired records, and records with less than a configurable margin of lock left, are RELEASEd.
binding-mqtt (implemented)
- Server:
$share/<ShareName>/<filter>is parsed and validated. The app sees the stripped filter plusshareNameinMqttTopicFilter. One app subscribe stream per shared subscription. Retained messages are never requested.noLocalis a protocol error. Delivery is atmin(message QoS, granted). MQTT 3.1.1 clients get SUBACK0x80for a$sharefilter. - Routing: optional
shareroute condition (exact name or*glob). Omitted means no constraint on the share name. A route withsharedoes not match non-shared subscriptions. - Session state:
MqttSessionStateis an enum-switched union (V1, V2). Version 2 carriesshareName. Version 1 is written unless a subscription is shared, so rolling upgrades stay safe. - Acks:
MqttSubscribeFlushExcarries the PUBACK or PUBREC reason code. A PUBREC at 0x80 or above ends the exchange with no PUBREL.MqttPublishFlagsgainsDUPfor redelivered PUBLISH. - SUBACK waits for the reply BEGIN of every app stream opened for the SUBSCRIBE, so no message published after SUBACK is lost. A reset, abort or END before BEGIN becomes a failure code for that filter, or a disconnect when the stream also carries established filters. Failed filters leave the persisted state. An UNSUBSCRIBE of a pending filter is deferred until its SUBACK.
- UNSUBSCRIBE stops new messages and lets a shared stream drain: it ENDs only after in-flight QoS 1 and 2 acknowledgements complete. (fix(binding-mqtt): complete in-flight shared deliveries before the unsubscribe state write #3127 additionally keeps the subscription in the persisted session state and defers the state write and UNSUBACK until the drain completes, so a disconnect mid-drain restores the subscription and recovers its in-flight QoS 2 deliveries.)
- Client (mqtt server → mqtt client pipeline): QoS 1 and 2 inbound from the upstream broker with de-duplication of retransmitted QoS 2 PUBLISH,
$share/<name>/<filter>sent upstream, acks and reason codes relayed, session state of both versions.
mqtt-kafka (implemented)
zilla.binding.mqtt.kafka.shared.subscription.available(defaulttrue). The capability is advertised only when the property is enabled and the binding hasoptions.store. Otherwise CONNACK advertises Shared Subscription Available = 0 and$shareis rejected with0x9E, as today.- The
shareroute condition on mqtt-kafka routes, as a topic and share pairing. KafkaSharedProxyopens one SHARE stream, maps data and headers (including fragmented records viadeferred), ACCEPTs QoS 0 and expired messages, maps PUBACK to ACCEPT and a reason code of 0x80 or above to REJECT. UNSUBSCRIBE or disconnect ends the SHARE stream.- Packet ids are allocated per client in 1..65535 (wrap, never 0, skipping ids in flight), replacing the factory-wide counter that overflowed uint16 (fix(binding-mqtt-kafka): packet ids are allocated from one factory-wide counter and overflow uint16 #3064).
- A broker without share group support (
share.versionnot enabled) fails the SUBSCRIBE with SUBACK0x83and the eventBINDING_KAFKA_API_VERSION_REJECTED.
QoS 2 claim tickets (implemented)
- Before PUBLISH is delivered, a claim ticket
{packetId, state, topic, partition, offset, shareName, filter}is written to the store under<groupIdPrefix>:tickets:<clientId>(a versioned flyweight union, base64url). Writes are coalesced. The record's frames are held until the write is durable, then the record is ACCEPTed and forwarded. - PUBREC (success) updates the ticket to PUBREL pending and triggers PUBREL. PUBCOMP, or a PUBREC at 0x80 or above, removes it. If the stream ends while a write is pending, the ticket is abandoned so a record released to another member cannot be redelivered to this client.
- On reconnect with the subscription restored, PUBREL-pending tickets replay PUBREL, and PUBLISH-sent tickets re-fetch the record by its exact offset and redeliver with the same packet id and DUP. A record that is gone, expired, or at a different offset drops the ticket. Verified against a real broker for both the PUBLISH-sent and PUBREL-pending cases.
- Tickets are deleted at session termination: Clean Start, END with expiry 0, and the expiry signal.
- Tickets whose subscription is not restored at reconnect stay in the store until session termination and are not redelivered. fix(binding-mqtt): complete in-flight shared deliveries before the unsubscribe state write #3127 closes the UNSUBSCRIBE path that produced them; see follow-ups for what remains.
Lifecycle of a shared subscription (implemented)
A lock-free registry in the store, built on putIfAbsent and replace (#2969), with no Lock:
- Per subscription,
<groupIdPrefix>:share:<ShareName>:<base64url filter>:registryholds<epoch>:<count>. A join increments the count, and bumps the epoch when the count goes 0→1. The first life is epoch 0. A leave decrements the count. - Per client,
<groupIdPrefix>:memberships:<clientId>lists the subscriptions the client has joined, which makes joins idempotent (a persistent session's reconnect does not count twice) and lets session termination leave everything. - Join runs at shared stream BEGIN and feeds the epoch into the group id. Leave runs when a session state write drops a subscription, and for all subscriptions at Clean Start, END with expiry 0 and the expiry signal.
- Compare-and-set loops are bounded (16 attempts). Exhaustion or an unreadable value refuses the subscription before BEGIN. Ordering fails safe: a crash leaves the count too high, so a backlog is retained and never wrongly dropped.
- A new life uses a new share group, so a stale backlog is abandoned with no skip cost. If all sessions are offline, the backlog accumulates and is delivered on reconnect, bounded by topic retention and message expiry. Verified against a real broker: after the last member left, a new subscriber started a new epoch and received no backlog.
- Zilla never deletes share groups. Abandoned epochs are small, and share groups never expire on their own. Optional best-effort
deleteShareGroupson the old epoch is a follow-up.
Kafka requirements
Kafka 4.1+ with the share.version=1 feature (kafka-features.sh --bootstrap-server … upgrade --feature share.version=1); share groups are a preview in 4.1. A single broker also needs share.coordinator.state.topic.replication.factor=1 and share.coordinator.state.topic.min.isr=1. The first member of a new group sees SUBACK after about one share heartbeat interval (5 s); later members after 1–2 s. The broker, not Zilla, balances load across members, so the split can be uneven.
Prerequisites (merged)
Store contract: atomic increment, replace and multi-key operations (#2960, PR #2969). The engine's type: test store gained an assertions option of expected mutations for ITs.
Steps
- 1. binding-kafka share protocol,
SHAREstream, cache staging and fan-out, with specs and ITs (ClientShareIT,CacheShareIT). - 2. binding-mqtt: server and client sides, reason codes, session state union, QoS 2 de-duplication, SUBACK gating and the UNSUBSCRIBE drain, with the hardening they needed.
- 3. mqtt-kafka QoS 0 and 1: per-binding capability,
KafkaSharedProxy,sharecondition, per-client packet ids. - 4. QoS 2 claim tickets: delivery, acks, reconnect recovery, termination cleanup.
- 5. Lifecycle registry with epochs.
- 6.
mqtt.kafka.proxyexample extended (share-group settings, memory store, two shared subscribers intest.sh), factories run against Kafka 4.1.1 (load split, group id, QoS 2 recovery, epoch bump, broker without share groups), and documented in aklivity-docs (binding reference, concept, guide, use case).
Pull requests
Stacked, each based on the previous one (merge in order); the first is based on develop.
- feat(binding-kafka): share group stream for Kafka share groups #3109 binding-kafka: share group stream
- feat(binding-mqtt): MQTT 5 shared subscriptions in server and client #3110 binding-mqtt: shared subscriptions, server and client
- feat(binding-mqtt-kafka): shared subscriptions for QoS 0 and 1 over Kafka share groups #3111 binding-mqtt-kafka: shared subscriptions for QoS 0 and 1
- feat(binding-mqtt): acknowledge subscribe after application streams begin #3112 binding-mqtt: SUBACK after application streams begin
- fix(binding-mqtt): complete in-flight deliveries when unsubscribing #3113 binding-mqtt: complete in-flight deliveries when unsubscribing
- feat(binding-mqtt-kafka): QoS 2 claim tickets for shared subscriptions #3114 binding-mqtt-kafka: QoS 2 claim tickets (with engine test store assertions)
- feat(binding-mqtt-kafka): epoch registry for the lifecycle of a shared subscription #3115 binding-mqtt-kafka: epoch registry for the lifecycle of a shared subscription
- fix(binding-kafka): share stream fixes found against a real broker and mqtt.kafka.proxy example #3154 real-broker share stream fixes and
mqtt.kafka.proxyexample - test(binding-mqtt): cover identical re-subscribe receiving a suback #3155 test: identical re-SUBSCRIBE receives a SUBACK (regression scenarios; the suspected bug is not real)
- fix(binding-mqtt-kafka): bound the QoS 2 recovery fetch at the log end #3156 binding-mqtt-kafka: bound the QoS 2 recovery fetch at the log end (spec-level verification only)
- fix(binding-mqtt): complete in-flight shared deliveries before the unsubscribe state write #3157 binding-mqtt, binding-mqtt-kafka: shared UNSUBSCRIBE drains before the state write and UNSUBACK, so in-flight QoS 2 recovers; no delivery or ticket after the stop flush
- Docs (merge after the stack): aklivity/aklivity-docs#181
Independent PRs against develop, found while verifying against a real broker (not share-related):
- fix(binding-kafka): retry init producer id on retriable errors #3104 fixes mqtt-kafka: concurrent first connects after a fresh Kafka are disconnected with 0x8E (session taken over) #3101: retry
InitProducerIdon coordinator load (fresh Kafka answered concurrent first connects with0x8E). - fix(binding-mqtt): send PUBACK and PUBREC in publish receive order #3106 fixes mqtt-kafka: PUBACKs for pipelined QoS 1 PUBLISH packets are returned out of order #3102: PUBACK and PUBREC in receive order for pipelined QoS 1 and 2.
- fix(binding-mqtt-kafka): act on session offsets fetch only once #3119 fixes mqtt-kafka: reusing a client id right after disconnect can briefly fail to connect #3103: offset-fetch completion ran twice on reconnect, resetting the session with
0x8E.
Follow-ups
- Client-originated QoS 1 and 2 publish in the mqtt client: feat(binding-mqtt): support QoS 1 and 2 for client-originated publish in the mqtt client #3061.
- Non-shared replay on reconnect never sets DUP (
KafkaMessagesProxypassesflags(0)). - Recovery fetch past the log end: fix(binding-mqtt-kafka): bound the QoS 2 recovery fetch at the log end #3122 bounds it at the log end; not verified end to end against a real broker, because the memory store dies with the process and a topic recreate leaves the cache holding the old records. A persistent store is needed to reproduce it.
- Observed, cause not found: after a topic is deleted and recreated, a client whose share stream starts on the new topic id received no records for 30 s even with an empty ticket store (so not recovery). The broker logged
InitializeStateHandler … coordinator is not availableretries for the new topic id, and the share partition start offset had already moved to 1. binding-kafka's share stream was not traced. - Broker restart closes the subscriber's MQTT connection; publishes recover after ~25–30 s.
- Compression support for fetch and share fetch.
- Correlated ack confirms lost when a leader connection aborts.
$sharefor MQTT 3.1.1 clients.- Optional cleanup of abandoned share groups.
- Memberships and tickets have no TTL.
- Malformed shared filters: per-filter SUBACK
0x8Finstead of DISCONNECT. - mqtt-kafka non-shared: an empty-filters flush is ignored, and
highWaterMarksis factory-wide (both to be verified). - NullPointerException in
MqttKafkaSessionFactory.doDataviaKafkaSessionStream.sendExpirySignalwhen a stalled first CONNECT disconnects: mqtt-kafka: NPE in MqttKafkaSessionFactory.doData via KafkaSessionStream.sendExpirySignal when a stalled first CONNECT disconnects #3120. - Slow UNSUBACK for a shared filter with an in-flight QoS 2 delivery (deferred until the drain and the state echo complete).
Acceptance criteria
- With the property enabled and a store configured, a subscribe to
$share/<group>/<filter>is granted rather than rejected with0x9E. With either missing, it is rejected and the capability is not advertised. - A matching message reaches exactly one session in the shared subscription. Subscribers are load-balanced, including more subscribers than partitions.
- An unacknowledged QoS 1 message is redelivered to another subscriber after disconnect.
- QoS 2 delivery completes PUBREL/PUBCOMP to the same client across reconnects, including when it reconnects through another node, and is never sent to another subscriber if the session ends first.
- A route with a
sharecondition matches only shared subscriptions with that name. A shared subscription with no matching route is rejected. - After all sessions leave, a later subscriber does not receive the old backlog and gets live messages immediately.
Related
- Umbrella:
mqtt-kafkafeature (enhanced) #512. Session state: Move MQTT QoS state into mqtt-sessions topic and consolidate session keys #1799. - Store contract: feat(engine): atomic increment and multi-key get and delete on the store #2960 and PR feat(engine)!: atomic increment, replace and multi-key get and delete on the store #2969.
Activity
fix(binding-mqtt): drop messages and end quietly while a shared unsub…
test(binding-mqtt-kafka): recover tickets after a mid-drain disconnec…
test(binding-mqtt-kafka.spec): notify the disconnect barrier from the…
test(binding-mqtt-kafka.spec): continue the recovery server script on…
test(binding-mqtt-kafka.spec): fail the shared unsubscribe state writ…
fix(binding-mqtt-kafka): leave shared memberships once the session st…
test(binding-mqtt.spec): order shared unsubscribe state write and ack…
fix(binding-mqtt): defer shared unsubscribe state write and ack until…
fix(binding-mqtt): drop messages and end quietly while a shared unsub…
test(binding-mqtt-kafka): recover tickets after a mid-drain disconnec…
test(binding-mqtt-kafka.spec): notify the disconnect barrier from the…
test(binding-mqtt-kafka.spec): continue the recovery server script on…
test(binding-mqtt-kafka.spec): fail the shared unsubscribe state writ…
fix(binding-mqtt-kafka): leave shared memberships once the session st…
27 remaining items
test(binding-mqtt-kafka.spec): close the released subscription after …
test(binding-mqtt.spec): order shared unsubscribe state write and ack…
fix(binding-mqtt): defer shared unsubscribe state write and ack until…
fix(binding-mqtt): drop messages and end quietly while a shared unsub…
test(binding-mqtt-kafka): recover tickets after a mid-drain disconnec…
test(binding-mqtt-kafka.spec): notify the disconnect barrier from the…
test(binding-mqtt-kafka.spec): continue the recovery server script on…
test(binding-mqtt-kafka.spec): fail the shared unsubscribe state writ…
fix(binding-mqtt-kafka): leave shared memberships once the session st…
test(binding-mqtt-kafka): release records taken after the unsubscribe…
test(binding-mqtt-kafka.spec): refresh the publish sent recovery scri…
fix(binding-mqtt-kafka): release records taken after the unsubscribe …
test(binding-mqtt-kafka.spec): close the released subscription after …
fix(binding-mqtt): complete in-flight shared deliveries before the un…