Multiple Subscribers
Fan-out events to multiple independent subscribers.
Overview
Two delivery models, one page
This page is the overview of subscribing more than one consumer to the same channel. KubeMQ Events give you two distinct delivery models — pick the one your scenario needs:
- Fan-Out — broadcast: every subscriber gets its own copy of each event.
- Consumer Group — load-balance: subscribers sharing a group name split events among themselves.
When multiple consumers subscribe to the same channel, which delivery model you get depends on group on the EventsSubscription you pass to subscribe_to_events. Leaving group unset gives each subscription its own independent feed — broadcast, where every subscriber sees every event. Setting the same group value on multiple subscriptions pools them into one logical worker — load balancing, where the broker routes each event to only one member. The example below leaves group unset on both subscribers, so you can see the broadcast side in action; see the linked pages above for the full write-up of each mode.
Gotchas: Events pub/sub has no durability — a subscriber that hasn't finished subscribing yet, or that disconnects, simply misses events published in that window; there's no redelivery. Setting group on one subscriber on the same channel silently turns broadcast into load-balancing for it. Both subscriptions here also share one cancellation_token, so cancelling it stops every subscriber at once.
Prerequisites
- KubeMQ server running on
localhost:50000 - Ruby SDK installed (
gem install kubemq)
Code
require 'kubemq'
address = ENV.fetch('KUBEMQ_ADDRESS', 'localhost:50000')
channel = 'ruby-events.multiple-subscribers'
begin
client = KubeMQ::PubSubClient.new(address: address, client_id: 'multi-sub-example')
puts "Connected to #{address}"
cancel = KubeMQ::CancellationToken.new
sub1 = KubeMQ::PubSub::EventsSubscription.new(channel: channel)
client.subscribe_to_events(sub1, cancellation_token: cancel, on_error: ->(e) { puts "Error: #{e.message}" }) do |event|
puts "Subscriber-1 received: #{event.metadata}"
end
sub2 = KubeMQ::PubSub::EventsSubscription.new(channel: channel)
client.subscribe_to_events(sub2, cancellation_token: cancel, on_error: ->(e) { puts "Error: #{e.message}" }) do |event|
puts "Subscriber-2 received: #{event.metadata}"
end
sleep 1
msg = KubeMQ::PubSub::EventMessage.new(channel: channel, metadata: 'broadcast event', body: 'data')
client.send_event(msg)
sleep 2
rescue KubeMQ::Error => e
puts "KubeMQ error: #{e.message}"
ensure
cancel&.cancel
client&.close
puts 'Done'
endHow It Works
- Two subscribers without a group — both receive each event (fan-out delivery).
- This contrasts with consumer groups where only one member receives each event.
- Use fan-out when every subscriber needs to process every event independently.
- Review timeouts, channel names, and client IDs before running against shared environments.
Related
Was this page helpful?