# Multicast Events (/learn/events/tutorials/multicast)



## What You Will Build [#what-you-will-build]

An order processing system where a single publish call routes to multiple channels — and even multiple messaging patterns — in one operation.

<Mermaid
  chart="graph LR
    P[&#x22;Order Service&#x22;]
    K[&#x22;KubeMQ Router&#x22;]
    E{{&#x22;events:orders&#x22;}}
    ES{{&#x22;events_store:audit-log&#x22;}}
    Q[[&#x22;queues:shipping-tasks&#x22;]]

    P -- &#x22;multicast publish&#x22; --> K
    K -- &#x22;events&#x22; --> E
    K -- &#x22;events_store&#x22; --> ES
    K -- &#x22;queues&#x22; --> Q

    class P client
    class K broker
    class E events
    class ES store
    class Q queue"
/>

*One publish call routes through the KubeMQ router and fans out to Events, Events Store, and Queues channels simultaneously.*

## Prerequisites [#prerequisites]

* KubeMQ server running on `localhost:50000`
* SDK installed ([Getting Started](/learn/events/getting-started))

## Routing Syntax [#routing-syntax]

| Character | Purpose                                     | Example                                       |
| --------- | ------------------------------------------- | --------------------------------------------- |
| `;`       | Separate multiple channels of the same type | `orders;notifications` sends to both channels |
| `:`       | Specify the target pattern type             | `events:orders;events_store:audit-log`        |

### Channel Type Prefixes [#channel-type-prefixes]

| Prefix          | Pattern                      |
| --------------- | ---------------------------- |
| `events:`       | Events (fire-and-forget)     |
| `events_store:` | Events Store (persistent)    |
| `queues:`       | Queues (guaranteed delivery) |

When no prefix is provided, the channel uses the same pattern as the original publish call.

## Steps [#steps]

<Steps>
  <Step>
    ### Multicast to Same-Pattern Channels [#multicast-to-same-pattern-channels]

    Publish one event to multiple Events channels using the `;` separator.

    <Tabs groupId="language" items="['Go', 'Python', 'Node.js', 'Java', 'C#', 'Kotlin', 'C++', 'Rust', 'Ruby', 'Elixir']">
      <Tab value="Go">
        ```go title="same_pattern_multicast.go"
        package main

        import (
            "context"
            "log"

            "github.com/kubemq-io/kubemq-go/v2"
        )

        func main() {
            ctx := context.Background()
            client, err := kubemq.NewClient(ctx,
                kubemq.WithAddress("localhost", 50000),
            )
            if err != nil {
                log.Fatal(err)
            }
            defer client.Close()

            err = client.SendEvent(ctx, kubemq.NewEvent().
                SetChannel("orders;notifications").
                SetBody([]byte(`{"orderId":"ORD-500","status":"created"}`)),
            )
            if err != nil {
                log.Fatal(err)
            }
            log.Println("Multicast event sent to orders and notifications")
        }
        ```
      </Tab>

      <Tab value="Python">
        ```python title="same_pattern_multicast.py"
        from kubemq.pubsub import Client as PubSubClient
        from kubemq.pubsub import EventMessage

        client = PubSubClient(address="localhost:50000")
        client.send_event(
            EventMessage(
                channel="orders;notifications",
                body=b'{"orderId":"ORD-500","status":"created"}',
            )
        )
        print("Multicast event sent to orders and notifications")
        client.close()
        ```
      </Tab>

      <Tab value="Node.js">
        ```javascript title="same_pattern_multicast.js"
        const { KubeMQClient } = require("kubemq-js");

        const client = new KubeMQClient({ address: "localhost:50000" });

        await client.sendEvent({
          channel: "orders;notifications",
          body: Buffer.from('{"orderId":"ORD-500","status":"created"}'),
        });

        console.log("Multicast event sent to orders and notifications");
        ```
      </Tab>

      <Tab value="Java">
        ```java title="SamePatternMulticast.java"
        PubSubClient client = PubSubClient.builder()
            .address("localhost:50000")
            .clientId("multicast-publisher")
            .build();

        client.sendEventsMessage(EventMessage.builder()
            .channel("orders;notifications")
            .body("{\"orderId\":\"ORD-500\",\"status\":\"created\"}".getBytes())
            .build());

        System.out.println("Multicast event sent to orders and notifications");
        client.close();
        ```
      </Tab>

      <Tab value="C#">
        ```csharp title="SamePatternMulticast.cs"
        await using var client = new KubeMQClient(new KubeMQClientOptions());
        await client.ConnectAsync();

        await client.SendEventAsync(new EventMessage
        {
            Channel = "orders;notifications",
            Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-500\",\"status\":\"created\"}")
        });

        Console.WriteLine("Multicast event sent to orders and notifications");
        ```
      </Tab>

      <Tab value="Kotlin">
        ```kotlin title="SamePatternMulticast.kt"
        val client = PubSubClient("localhost:50000")

        client.sendEvent(EventMessage(
            channel = "orders;notifications",
            body = """{"orderId":"ORD-500","status":"created"}""".toByteArray()
        ))

        println("Multicast event sent to orders and notifications")
        client.close()
        ```
      </Tab>

      <Tab value="C++">
        ```cpp title="same_pattern_multicast.cpp"
        auto client = kubemq::PubSubClient("localhost:50000");

        kubemq::EventMessage event;
        event.channel = "orders;notifications";
        event.body = R"({"orderId":"ORD-500","status":"created"})";

        client.sendEvent(event);
        std::cout << "Multicast event sent to orders and notifications" << std::endl;
        ```
      </Tab>

      <Tab value="Rust">
        ```rust title="same_pattern_multicast.rs"
        use kubemq::prelude::*;
        use kubemq::EventBuilder;

        #[tokio::main]
        async fn main() -> kubemq::Result<()> {
            let client = KubemqClient::builder()
                .host("localhost")
                .port(50000)
                .build()
                .await?;

            let event = EventBuilder::new()
                .channel("orders;notifications")
                .body(b"{\"orderId\":\"ORD-500\",\"status\":\"created\"}".to_vec())
                .build();

            client.send_event(event).await?;
            println!("Multicast event sent to orders and notifications");

            client.close().await?;
            Ok(())
        }
        ```
      </Tab>

      <Tab value="Ruby">
        ```ruby title="same_pattern_multicast.rb"
        require 'kubemq'

        client = KubeMQ::PubSubClient.new(address: 'localhost:50000', client_id: 'multicast-publisher')

        msg = KubeMQ::PubSub::EventMessage.new(
          channel: 'orders;notifications',
          body: '{"orderId":"ORD-500","status":"created"}'
        )
        client.send_event(msg)

        puts 'Multicast event sent to orders and notifications'
        client.close
        ```
      </Tab>

      <Tab value="Elixir">
        ```elixir title="same_pattern_multicast.exs"
        {:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "multicast-publisher")

        event = KubeMQ.Event.new(
          channel: "orders;notifications",
          body: ~s({"orderId":"ORD-500","status":"created"})
        )

        :ok = KubeMQ.Client.send_event(client, event)
        IO.puts("Multicast event sent to orders and notifications")

        KubeMQ.Client.close(client)
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step>
    ### Multicast Across Different Patterns [#multicast-across-different-patterns]

    Use the `:` prefix to route one publish to Events, Events Store, and Queues simultaneously.

    <Tabs groupId="language" items="['Go', 'Python', 'Node.js', 'Java', 'C#', 'Kotlin', 'C++', 'Rust', 'Ruby', 'Elixir']">
      <Tab value="Go">
        ```go title="cross_pattern_multicast.go"
        err = client.SendEvent(ctx, kubemq.NewEvent().
            SetChannel("events:orders;events_store:audit-log;queues:shipping-tasks").
            SetBody([]byte(`{"orderId":"ORD-600","action":"ship"}`)),
        )
        if err != nil {
            log.Fatal(err)
        }
        log.Println("Cross-pattern multicast: events, events_store, queues")
        ```
      </Tab>

      <Tab value="Python">
        ```python title="cross_pattern_multicast.py"
        client.send_event(
            EventMessage(
                channel="events:orders;events_store:audit-log;queues:shipping-tasks",
                body=b'{"orderId":"ORD-600","action":"ship"}',
            )
        )
        print("Cross-pattern multicast: events, events_store, queues")
        ```
      </Tab>

      <Tab value="Node.js">
        ```javascript title="cross_pattern_multicast.js"
        await client.sendEvent({
          channel: "events:orders;events_store:audit-log;queues:shipping-tasks",
          body: Buffer.from('{"orderId":"ORD-600","action":"ship"}'),
        });

        console.log("Cross-pattern multicast: events, events_store, queues");
        ```
      </Tab>

      <Tab value="Java">
        ```java title="CrossPatternMulticast.java"
        client.sendEventsMessage(EventMessage.builder()
            .channel("events:orders;events_store:audit-log;queues:shipping-tasks")
            .body("{\"orderId\":\"ORD-600\",\"action\":\"ship\"}".getBytes())
            .build());

        System.out.println("Cross-pattern multicast: events, events_store, queues");
        ```
      </Tab>

      <Tab value="C#">
        ```csharp title="CrossPatternMulticast.cs"
        await client.SendEventAsync(new EventMessage
        {
            Channel = "events:orders;events_store:audit-log;queues:shipping-tasks",
            Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-600\",\"action\":\"ship\"}")
        });

        Console.WriteLine("Cross-pattern multicast: events, events_store, queues");
        ```
      </Tab>

      <Tab value="Kotlin">
        ```kotlin title="CrossPatternMulticast.kt"
        client.sendEvent(EventMessage(
            channel = "events:orders;events_store:audit-log;queues:shipping-tasks",
            body = """{"orderId":"ORD-600","action":"ship"}""".toByteArray()
        ))

        println("Cross-pattern multicast: events, events_store, queues")
        ```
      </Tab>

      <Tab value="C++">
        ```cpp title="cross_pattern_multicast.cpp"
        kubemq::EventMessage event;
        event.channel = "events:orders;events_store:audit-log;queues:shipping-tasks";
        event.body = R"({"orderId":"ORD-600","action":"ship"})";

        client.sendEvent(event);
        std::cout << "Cross-pattern multicast: events, events_store, queues" << std::endl;
        ```
      </Tab>

      <Tab value="Rust">
        ```rust title="cross_pattern_multicast.rs"
        let event = EventBuilder::new()
            .channel("events:orders;events_store:audit-log;queues:shipping-tasks")
            .body(b"{\"orderId\":\"ORD-600\",\"action\":\"ship\"}".to_vec())
            .build();

        client.send_event(event).await?;
        println!("Cross-pattern multicast: events, events_store, queues");
        ```
      </Tab>

      <Tab value="Ruby">
        ```ruby title="cross_pattern_multicast.rb"
        msg = KubeMQ::PubSub::EventMessage.new(
          channel: 'events:orders;events_store:audit-log;queues:shipping-tasks',
          body: '{"orderId":"ORD-600","action":"ship"}'
        )
        client.send_event(msg)

        puts 'Cross-pattern multicast: events, events_store, queues'
        ```
      </Tab>

      <Tab value="Elixir">
        ```elixir title="cross_pattern_multicast.exs"
        event = KubeMQ.Event.new(
          channel: "events:orders;events_store:audit-log;queues:shipping-tasks",
          body: ~s({"orderId":"ORD-600","action":"ship"})
        )

        :ok = KubeMQ.Client.send_event(client, event)
        IO.puts("Cross-pattern multicast: events, events_store, queues")
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step>
    ### Verify Delivery [#verify-delivery]

    Set up subscribers on each target channel. The multicast message arrives at all destinations.

    **Expected output:**

    ```text
    [Events] orders: {"orderId":"ORD-600","action":"ship"}
    [Events Store] audit-log: {"orderId":"ORD-600","action":"ship"}
    [Queue] shipping-tasks: {"orderId":"ORD-600","action":"ship"}
    ```
  </Step>
</Steps>

## How Multicast Works Internally [#how-multicast-works-internally]

1. KubeMQ **parses** the channel string into a route map keyed by pattern type
2. **Sends the first destination synchronously** and returns its result to the caller
3. **Fans out remaining destinations asynchronously** in background goroutines
4. Routed messages are tagged with `X-KUBEMQ-ROUTED=true` automatically

<Callout type="info">
  Only the **first destination's result** is returned to the publisher. Errors on other destinations are logged server-side but do not affect the publish response.
</Callout>

## Common Multicast Patterns [#common-multicast-patterns]

| Channel String                                    | Behavior                                                  |
| ------------------------------------------------- | --------------------------------------------------------- |
| `a;b;c`                                           | Send as Events to channels `a`, `b`, and `c`              |
| `events:a;events_store:b`                         | Send as Event to `a` and as persistent Event Store to `b` |
| `events:a;queues:task-queue`                      | Broadcast event and queue a task simultaneously           |
| `events_store:audit;queues:process;events:notify` | Fan out to all three patterns                             |

## Next Steps [#next-steps]

<Cards>
  <Card title="Wildcard Subscriptions" href="/learn/events/tutorials/wildcard-subscriptions" description="Receive multicast events flexibly with patterns." />

  <Card title="Stream Publishing" href="/learn/events/tutorials/stream-publishing" description="High-throughput batched event delivery." />
</Cards>
