Skip to content

Support MQTT 5 Shared Subscriptions via Kafka share groups #1801

Closed

Description

@jfallows

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. noLocal is 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 SHARE stream kind. Begin carries group id, optional member id, topic and filters. Data carries partition offset, timestamp, key, headers (on INIT and FIN) and deliveryCount (0 on the client hop means not reported). An acquired flush after each partition's records carries lockTimeoutMillis and 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. FindCoordinator v6, ShareGroupHeartbeat, Metadata v13 (topic ids), ShareFetch and ShareAcknowledge v1, with ApiVersions negotiated 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 first ShareFetch is 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 plus shareName in MqttTopicFilter. One app subscribe stream per shared subscription. Retained messages are never requested. noLocal is a protocol error. Delivery is at min(message QoS, granted). MQTT 3.1.1 clients get SUBACK 0x80 for a $share filter.
  • Routing: optional share route condition (exact name or * glob). Omitted means no constraint on the share name. A route with share does not match non-shared subscriptions.
  • Session state: MqttSessionState is an enum-switched union (V1, V2). Version 2 carries shareName. Version 1 is written unless a subscription is shared, so rolling upgrades stay safe.
  • Acks: MqttSubscribeFlushEx carries the PUBACK or PUBREC reason code. A PUBREC at 0x80 or above ends the exchange with no PUBREL. MqttPublishFlags gains DUP for 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 (default true). The capability is advertised only when the property is enabled and the binding has options.store. Otherwise CONNACK advertises Shared Subscription Available = 0 and $share is rejected with 0x9E, as today.
  • The share route condition on mqtt-kafka routes, as a topic and share pairing.
  • KafkaSharedProxy opens one SHARE stream, maps data and headers (including fragmented records via deferred), 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.version not enabled) fails the SUBSCRIBE with SUBACK 0x83 and the event BINDING_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>:registry holds <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 deleteShareGroups on 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, SHARE stream, 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, share condition, per-client packet ids.
  • 4. QoS 2 claim tickets: delivery, acks, reconnect recovery, termination cleanup.
  • 5. Lifecycle registry with epochs.
  • 6. mqtt.kafka.proxy example extended (share-group settings, memory store, two shared subscribers in test.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.

  1. feat(binding-kafka): share group stream for Kafka share groups #3109 binding-kafka: share group stream
  2. feat(binding-mqtt): MQTT 5 shared subscriptions in server and client #3110 binding-mqtt: shared subscriptions, server and client
  3. 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
  4. feat(binding-mqtt): acknowledge subscribe after application streams begin #3112 binding-mqtt: SUBACK after application streams begin
  5. fix(binding-mqtt): complete in-flight deliveries when unsubscribing #3113 binding-mqtt: complete in-flight deliveries when unsubscribing
  6. feat(binding-mqtt-kafka): QoS 2 claim tickets for shared subscriptions #3114 binding-mqtt-kafka: QoS 2 claim tickets (with engine test store assertions)
  7. 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
  8. 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.proxy example
  9. 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)
  10. 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)
  11. 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):

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 (KafkaMessagesProxy passes flags(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 available retries 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.
  • $share for MQTT 3.1.1 clients.
  • Optional cleanup of abandoned share groups.
  • Memberships and tickets have no TTL.
  • Malformed shared filters: per-filter SUBACK 0x8F instead of DISCONNECT.
  • mqtt-kafka non-shared: an empty-filters flush is ignored, and highWaterMarks is factory-wide (both to be verified).
  • NullPointerException in MqttKafkaSessionFactory.doData via KafkaSessionStream.sendExpirySignal when 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 with 0x9E. 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 share condition 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

Activity

  1. self-assigned this
    on May 26, 2026
  2. 27 remaining items

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions