# KubeMQ Documentation (/)
**One broker. Every protocol.** KubeMQ is a Kubernetes-native enterprise message broker. It runs as one container on Docker or Podman for development and testing, or as an operator-managed cluster of 3 or more servers on Kubernetes. Your existing Kafka, RabbitMQ, MQTT, AMQP, STOMP, AWS SQS/SNS, and Google Cloud Pub/Sub clients connect to it unchanged — and native SDKs in 10 languages give you queues, pub/sub, and request-reply over gRPC, REST, and WebSocket. No ZooKeeper, no external database, no sidecars.
## What brings you here? [#what-brings-you-here]
## Keep your clients — change one connection string [#keep-your-clients--change-one-connection-string]
KubeMQ speaks each protocol natively, on its standard port. The client that talks to Kafka or RabbitMQ today talks to KubeMQ tomorrow.
## Built on four messaging patterns [#built-on-four-messaging-patterns]
Every protocol and every SDK rides the same core patterns.
## Why teams choose KubeMQ [#why-teams-choose-kubemq]
* **Built for Kubernetes** — [Helm charts and an operator](/deploy/install/kubernetes), KEDA autoscaling, and clustering designed for safe rollouts.
* **Enterprise-grade** — [role-based access control, audit logging](/configure), FIPS builds, and replicated storage with a strict zero-loss durability mode.
* **AI-ready** — built-in [Model Context Protocol (MCP) and Agent-to-Agent (A2A) gateways](/aiway) for agentic workloads.
* **Simple to run** — one container, a [web dashboard](/operate), and the [kmq CLI](/deploy/install/kmq) for installing, messaging, administration, and observability.
## Explore the documentation [#explore-the-documentation]
***
Questions? [Open an issue on GitHub](https://github.com/kubemq-io/kubemq-community) or [Contact KubeMQ](https://kubemq.io/contact-sales/). Ready for production? [Buy a license](/licensing#buy). Building with AI agents? This site ships [llms.txt](/llms.txt) for machine consumption.
# KubeMQ Aiway (/aiway)
**KubeMQ Aiway is an AI Agents Fabric** — a switchboard that lets AI agents and AI
applications find each other, talk to each other, and stream results in real time, with
the reliability of an enterprise message broker underneath. **A2A** and **MCP** are the
two doors into the same fabric: register an agent, discover it by capability, invoke it
synchronously or as a live stream, and orchestrate the whole thing from an LLM.
## What is KubeMQ Aiway [#what-is-kubemq-aiway]
Aiway is a switchboard for AI agents. Agents register what they can do, callers find
them by capability, and the fabric routes every call — synchronous or streamed — over an
enterprise message broker. KubeMQ does the discovery, routing, protocol bridging,
streaming, security, high availability, and observability so that no caller and no agent
has to.
The agents themselves stay **plain HTTP services** — no KubeMQ SDK, no broker library, no
protobuf, no special runtime. An agent is just an HTTP server that speaks JSON-RPC 2.0
(and, optionally, Server-Sent Events). Aiway bridges the broker to that endpoint for you,
so you can wrap an existing internal microservice as a first-class AI agent in minutes.
Two doors open into the same fabric:
* **A2A (Agent-to-Agent)** — agents register their endpoint and capabilities; any caller
discovers them *by capability* and invokes them, synchronously or as a live stream.
* **MCP (Model Context Protocol)** — LLM hosts (Claude Desktop, IDEs, agent frameworks)
plug in over the open MCP standard and gain both **messaging** and **agent
orchestration** through a single endpoint.
## The big picture [#the-big-picture]
A caller — over A2A HTTP, gRPC/REST, or an MCP host — reaches the fabric, which discovers
the target agent, bridges the call to its plain-HTTP endpoint, and relays the response
(or a live SSE stream) back. The agents never touch the broker directly.
*Callers reach Aiway over A2A, gRPC/REST, or MCP; the Agent Bridge POSTs to each agent's plain-HTTP URL and the streaming relay carries live events back.*
The **Agent Bridge** is the per-agent virtual subscriber that translates broker messages
into HTTP calls to your agent (and relays responses and SSE streams back). It is why
agents need zero KubeMQ dependency: the bridge does all the broker and protocol
translation, so the agent only ever sees an HTTP `POST`.
The MCP **agent-bridge tools** (`agent_list`, `agent_info`, `agent_send`, `agent_query`,
covered under [MCP](/aiway/mcp)) invoke agents *through* this same Agent Bridge —
same concept at two layers, not two meanings. The tools are the LLM-facing door; the
Agent Bridge is the per-agent connector they (and A2A callers) route through.
## One fabric, three planes [#one-fabric-three-planes]
Aiway is not "A2A plus a separate MCP server." It is **one fabric** with three planes
that share the same core and compose freely — an LLM over MCP can enqueue durable work
*and* call an A2A agent in the same session, and a gRPC backend can invoke the same agent
an LLM just used.
| Plane | Door | What it does |
| ------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Agent plane** | A2A | Agents register, get discovered by capability, get invoked, and stream results. |
| **LLM plane** | MCP | LLM hosts discover and drive both agents and messaging through one endpoint. |
| **Messaging plane** | KubeMQ core | Durable queues, pub/sub events, a persisted/replayable event log, and RPC (commands/queries) — the same primitives the MCP messaging tools expose. |
## Two doors in [#two-doors-in]
## The enterprise envelope [#the-enterprise-envelope]
What makes Aiway production-grade rather than a demo is the envelope around both doors —
the same auth, HA, guardrails, and observability that the rest of KubeMQ runs on:
* **Security** — token-based authentication, per-agent ownership (only the registrant can
modify or remove an agent), origin validation, and TLS / mutual-TLS.
* **High availability** — the agent registry is replicated to every node, so an agent
registered on one node is reachable and discoverable cluster-wide; if a node fails, its
agents expire and re-register elsewhere and the roster self-heals.
* **Guardrails & backpressure** — TTL liveness, default and max request timeouts, a
max-agents ceiling, a per-agent concurrency cap, a max agent-response size, and
traffic gating that rejects calls when the core isn't ready instead of hanging.
* **Observability** — per-agent request, error, latency, and active-stream metrics
(Prometheus + a durable per-agent store) plus a live operations dashboard, so you can
govern an entire agent fleet.
Both doors run on the [shared HTTP server](/connectors/concepts/shared-http-server) (port
9090\) and inherit its unified middleware. The shared foundations are documented once
under Connectors:
## Start in ten minutes [#start-in-ten-minutes]
Any running KubeMQ works, including [Try KubeMQ](/deploy/quickstart). MCP and A2A are on by default on port 9090. On Kubernetes, run `kubectl --context YOUR_KUBE_CONTEXT -n kubemq port-forward svc/messaging-rest 9090:9090` first.
| You want to | Start here | Time |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------- |
| Connect Claude Desktop, Cursor or another MCP host | [Connect an MCP host](/aiway/mcp/getting-started#connect-an-mcp-host) | 5 minutes |
| Turn a plain HTTP service into an agent | [Fastest path: wrap a plain HTTP service](/aiway/a2a/getting-started#fastest-path-wrap-a-plain-http-service) | 10 minutes |
| Send to a queue and call an agent from one LLM prompt | [One prompt, two tool calls](/aiway/tutorial/orchestrate-from-an-llm#one-prompt-two-tool-calls) | 5 minutes after the first two |
With authentication off, anything that reaches port 9090 can call every MCP tool. Connect an LLM host only to a test server, or turn on [authentication](/aiway/mcp/guides/authentication) with a restricted role. To turn MCP off, see [Getting started with MCP](/aiway/mcp/getting-started#enable--disable).
## Go deeper [#go-deeper]
# Use cases (/aiway/use-cases)
New to Aiway? Start with the [overview](/aiway).
KubeMQ Aiway is an AI Agents Fabric: agents register, callers discover them by
capability, and anyone invokes them — synchronously or as a live stream — over an
enterprise message broker. The scenarios below show where that fabric is uniquely
strong, grouped by the problem they solve. Each one names the scenario, how Aiway
delivers it, and why it is hard to get this cleanly any other way.
A few terms recur:
* **Agent Bridge** — the per-agent virtual subscriber KubeMQ spawns for each
registered agent. It translates broker messages into HTTP POSTs to your agent's URL
and relays the response (or live stream) back, which is why agents need no KubeMQ
SDK. See [Building agents](/aiway/a2a/guides/building-agents).
* **Skill tags** — the capability labels (`tags[]`) an agent advertises on each skill,
used to discover agents by what they can do rather than by URL. See the
[Agent registry](/aiway/a2a/registry).
* **The transport-vs-application error split** — Aiway returns `Executed: false` when
the agent never processed the request (unreachable, timeout, oversized response), so
it is **safe to retry**; an `Executed: true` response with a JSON-RPC error means the
agent ran and returned an error, so **don't blind-retry**. See
[Error handling](/aiway/a2a/error-handling).
## Onboarding & orchestration [#onboarding--orchestration]
### Zero-SDK agent onboarding [#zero-sdk-agent-onboarding]
**Scenario:** Turn an existing internal HTTP microservice — a Python summarizer, a Go
OCR service, a Node scraper — into a first-class AI agent in minutes.
**How:** the service stays a plain HTTP server. It registers an Agent Card; the Agent
Bridge does all protocol translation.
**Why Aiway:** no KubeMQ client library, broker SDK, protobuf, or special runtime in the
agent — most frameworks force an SDK and a specific language, while Aiway onboards *any*
HTTP service in any stack. Walk it end-to-end in the
[Tutorial](/aiway/tutorial).
### LLM as orchestrator over a real agent fleet [#llm-as-orchestrator-over-a-real-agent-fleet]
**Scenario:** An LLM host (Claude Desktop, an IDE, an agent framework) plans a task,
discovers the right specialist agents, invokes them, and persists intermediate results
— all from one MCP connection.
**How:** `agent_list` / `agent_info` to discover, `agent_send` / `agent_query` to
invoke, `events_store_publish` to log, `queue_send` to hand off — same session, same
fabric.
**Why Aiway:** the LLM gets messaging **and** agent orchestration through one
open-standard endpoint, with enterprise auth and high availability — no glue code, no
custom tool server per agent. See the
[MCP agent-bridge tools](/aiway/mcp/tools/agent-bridge).
### Polyglot, mixed-protocol orchestration [#polyglot-mixed-protocol-orchestration]
**Scenario:** A gRPC backend, a REST web app, and an LLM all call the *same* agent
during one workflow.
**How:** every transport — the A2A HTTP gateway, gRPC, REST, the MCP bridge — converges
on the same Agent Bridge path.
**Why Aiway:** one agent, callable from every protocol your stack already speaks, with no
per-protocol adapters or duplicated endpoints. See
[Synchronous messaging](/aiway/a2a/sync-messaging).
## Real-time & long-running work [#real-time--long-running-work]
### Real-time long-running tasks with live progress [#real-time-long-running-tasks-with-live-progress]
**Scenario:** A caller kicks off a multi-minute job — document generation, transcode,
deep research, multi-step reasoning — and watches `task.status` and `task.artifact`
events stream in with a progress bar.
**How:** `message/stream` opens an SSE relay with keepalive, idle timeout, and
auto-cancel when the caller disconnects.
**Why Aiway:** streaming, cancellation, and backpressure (per-agent concurrency cap,
response-size limits) are built in — *production* streaming, not a fragile long-poll. See
[Streaming (SSE)](/aiway/a2a/streaming).
### Human-in-the-loop and approval flows [#human-in-the-loop-and-approval-flows]
**Scenario:** An agent streams a draft, a human reviews it, and on approval the workflow
resumes or hands off to another agent.
**How:** streaming for live drafts; durable queues or persisted events park the task
while it awaits a decision; a second agent invocation continues the work.
**Why Aiway:** real-time streaming *and* durable hand-off coexist on one fabric, so
long-lived, human-gated workflows don't need a separate workflow engine. See the
[Streaming task pipeline](/aiway/a2a/scenarios/streaming-task-pipeline).
### Ephemeral, on-demand agents [#ephemeral-on-demand-agents]
**Scenario:** Spin up specialist agents on demand — per job, per tenant — have them
register, take work, then disappear, without callers caring.
**How:** an agent registers on start, heartbeats while alive, and TTL-expires when gone;
discovery and routing always reflect the live set.
**Why Aiway:** the self-healing, capability-indexed roster makes transient agents
first-class — callers always see only what is actually available right now. See the
[Agent registry](/aiway/a2a/registry).
## Routing & multi-tenancy [#routing--multi-tenancy]
### Capability-based dynamic routing [#capability-based-dynamic-routing]
**Scenario:** "Find an agent that can `translate-legal` for `de-DE`, prefer the
lowest-latency one, call it, and fall back to another if it errors."
**How:** discover via `GET /agents?skill_tags=…` (or `agent_list`), select at runtime,
invoke, and use the transport-vs-application error split to fail over.
**Why Aiway:** agents are addressed **by capability**, not by URL — new agents appear in
discovery the moment they register, and the routing logic never changes. See the
[Multi-agent gateway](/aiway/a2a/scenarios/multi-agent-gateway).
### Multi-tenant agent directory [#multi-tenant-agent-directory]
**Scenario:** Multiple teams publish agents into one shared directory; each team can
manage only its own; everyone can discover and call them, subject to authorization.
**How:** ownership is bound to the registering identity (only the owner can modify or
deregister; a blank owner fails closed); discovery is open, invocation is authenticated.
**Why Aiway:** a built-in, fail-closed ownership model turns a shared registry into a
safe internal agent marketplace, without bespoke RBAC plumbing. See the
[Agent registry](/aiway/a2a/registry).
### Distributed, multi-region agent mesh [#distributed-multi-region-agent-mesh]
**Scenario:** Agents run close to data or users in different nodes or regions; callers
anywhere reach any agent.
**How:** the registry replicates cluster-wide; agents register on a local node; the
cluster routes calls to the owning node; on node loss, agents re-register elsewhere.
**Why Aiway:** location transparency and a self-healing registry come from the broker, so
callers never track where an agent physically runs. See the
[A2A architecture](/aiway/a2a/architecture).
## Reliability & governance [#reliability--governance]
### Resilient, retry-aware agent calls [#resilient-retry-aware-agent-calls]
**Scenario:** A flaky agent or a slow network shouldn't corrupt a workflow, and the
orchestrator needs to know *what* failed.
**How:** the `Executed: false` (transport, safe-retry) vs `Executed: true` plus error
(application, don't blind-retry) split, with specific A2A error codes and per-agent
timeouts.
**Why Aiway:** the fabric encodes retry-safe semantics at the protocol level, so
orchestration logic gets clean, correct failure signals for free. See
[Error handling](/aiway/a2a/error-handling).
### Secure enterprise agent gateway [#secure-enterprise-agent-gateway]
**Scenario:** Expose agents to partners or teams behind authentication, mutual TLS, and
origin controls, and reject traffic when the platform is degraded.
**How:** the shared security chain — auth, ownership, TLS/mTLS, trusted origins, traffic
gating — wraps every agent call.
**Why Aiway:** an enterprise security envelope is built into the fabric, so you don't
bolt a gateway in front of every agent. See
[Agent authentication](/aiway/a2a/guides/authentication).
### Governed agent fleet [#governed-agent-fleet]
**Scenario:** An ops team needs per-agent traffic, error rates, latency, active streams,
and a live roster across a large fleet, surviving restarts.
**How:** per-agent metrics (Prometheus plus a durable store) and a live dashboard;
TTL and heartbeat keep the roster honest.
**Why Aiway:** fleet-grade observability and lifecycle are native — not something you
assemble from logs after the fact. See the
[A2A configuration](/aiway/a2a/configuration) for the limits that govern a fleet.
## Hybrid pipelines & safe LLM access [#hybrid-pipelines--safe-llm-access]
### Agents plus durable messaging [#agents-plus-durable-messaging]
**Scenario:** An agent's streamed artifacts are written to a persisted, replayable event
log; downstream agents and classic consumers read from it; failed work lands in a
dead-letter queue for human review.
**How:** mix `events_store_publish` / `events_store_read` (or queues with a
`dead_letter_queue`) with agent invocation, on one fabric.
**Why Aiway:** agents and enterprise messaging are the *same* substrate, so you compose
durable, replayable, at-least-once pipelines with AI agents inside them — no integration
layer. See the [Events Store tools](/aiway/mcp/tools/events).
### MCP tool gateway for safe enterprise access [#mcp-tool-gateway-for-safe-enterprise-access]
**Scenario:** Give any MCP-speaking LLM safe, governed access to enterprise messaging —
queues, events, persisted logs, RPC — without handing it the raw broker.
**How:** the MCP messaging tools expose curated operations with input schemas,
reserved-channel protection, timeouts, and auth.
**Why Aiway:** the LLM gets a bounded, schema'd, authenticated surface onto real
enterprise messaging — a controlled blast radius, not a firehose. See the
[Queue tools](/aiway/mcp/tools/queues).
## Next steps [#next-steps]
# Configure KubeMQ (/configure)
Everything you need to configure KubeMQ for production. KubeMQ ships as a single binary with no external dependencies, so configuring it comes down to choosing how you run it and tuning the settings for your workload.
Looking for metrics, tracing, and logging? **Turning them on** is here —
[Observability settings](/configure/reference/observability) has the OpenTelemetry,
audit and notification fields for both targets. **Reading and acting on them** lives under
[Operate](/operate).
# Connectors (/connectors)
A **connector** is a built-in, server-side **protocol gateway** in kubemq-server that
bridges an external protocol to KubeMQ messaging — no KubeMQ SDK is required on the
client. Point a standard HTTP, JSON-RPC, or CloudEvents client at the server and it
speaks to the message broker for you.
## What is a connector [#what-is-a-connector]
KubeMQ ships connectors in **two classes**, all built into the server.
**Shared-HTTP gateway** — runs on the shared HTTP server (port 9090):
* **CloudEvents** — a native CNCF CloudEvents-over-HTTP interface for all five
messaging patterns — Events, Events Store, Queues, Commands, and Queries — with CESQL
routing and SSE.
KubeMQ's two AI-facing HTTP gateways — **AI Agents (A2A)** and **MCP** — also fit this
connector definition: they are built-in, server-side HTTP gateways that run on the same
shared HTTP server. They are now documented under [Aiway](/aiway), KubeMQ's AI
Agents Fabric, where the agent-to-agent story is told as a whole.
**Wire-protocol connectors** — seven connectors that speak a standard messaging
protocol on their **own dedicated ports**, so an existing client connects by changing
only its connection string, broker address, or endpoint URL:
* **AMQP 1.0** — native AMQP 1.0 clients, all five patterns (ports 5672 / 5671).
* **RabbitMQ (AMQP 0-9-1)** — RabbitMQ clients over the AMQP 0-9-1 wire dialect (5672 / 5671).
* **Kafka** — unmodified Kafka clients over the native Kafka wire protocol (ports 9092 / 9093).
* **AWS (SQS & SNS)** — unmodified AWS SDKs over the real SQS/SNS HTTP protocols (port 4566).
* **MQTT** — MQTT 3.1.1 / 5.0 clients (ports 1883 / 8883 / 8083).
* **STOMP** — native STOMP 1.0/1.1/1.2 clients (ports 61613 / 61614).
* **Google Cloud Pub/Sub** — unmodified Pub/Sub clients via `PUBSUB_EMULATOR_HOST` over the real Pub/Sub v1 gRPC protocol (port 8085).
A connector is distinct from the other ways you reach KubeMQ. A **native SDK client**
links a KubeMQ library into your application and speaks the gRPC API. A **framework
adapter** (NestJS, Spring Boot, Celery, KEDA, and the others under
[Integrations](/integrations)) wires KubeMQ into a specific framework's
programming model. A connector, by contrast, runs **inside the server** and accepts a
standard wire protocol directly — nothing KubeMQ-specific is installed on the caller.
The **HTTP gateways** listen on the **shared HTTP server (port 9090)** and are
**enabled by default** — start kubemq-server and CloudEvents (along with the Aiway
gateways, A2A and MCP) is live. The **wire-protocol connectors** listen on their own
dedicated ports. Two of them — **Kafka** (9092) and **RabbitMQ / AMQP 0-9-1** (5672) — are
**on by default**, so a stock server binds those ports out of the box. The other five
(AMQP 1.0, AWS, MQTT, STOMP, Google Cloud Pub/Sub) are **opt-in (disabled by default)** —
each opens a new network listener, so you enable only the ones you need.
*CloudEvents is the shared-HTTP gateway documented here; the AI gateways (A2A & MCP) run on the same port 9090 server but are documented under Aiway. The seven wire-protocol connectors listen on their own ports. All front the same message broker.*
## The HTTP gateway [#the-http-gateway]
AI agents (A2A) and MCP now live under **[Aiway](/aiway)** — KubeMQ's AI Agents
Fabric. They are still built-in HTTP gateways on the shared HTTP server; their docs
just moved to where the agent-to-agent story is told end to end.
## The wire-protocol connectors [#the-wire-protocol-connectors]
Speak a standard messaging protocol on a dedicated port — point an existing client at
KubeMQ by changing only its connection string, broker address, or endpoint URL.
## Shared foundations [#shared-foundations]
Every **HTTP gateway** — CloudEvents here, plus the Aiway gateways (A2A and MCP) — runs
on **one HTTP server** and shares the same auth model, middleware chain, and metrics
surface. That shared story is told once here, and each gateway links back to it instead
of repeating it (the wire-protocol connectors document their own ports and auth in their
own pages):
Every HTTP gateway also inherits the unified middleware pipeline — JWT auth, CORS, origin
validation, TLS/mTLS, a traffic gate, and OpenTelemetry tracing — and the reserved
`_AGENTS_.` channel prefix, which user channels may not use. Connector metrics roll up
into the cluster-wide observability view alongside the rest of the server.
To **disable** an HTTP gateway, set its enable env var to `false` — for example
`CONNECTORSCE_ENABLE=false` for CloudEvents. The HTTP gateways are on by default; you
never need to set `=true` for them. See [Shared HTTP server](/connectors/concepts/shared-http-server)
for their disable vars and why the names look the way they do. Among the **wire-protocol
connectors**, Kafka and RabbitMQ (AMQP 0-9-1) are on by default — turn either off with
`CONNECTORS_KAFKA_ENABLE=false` or `CONNECTORS_AMQP_ENABLE=false`. The other five are
opt-in — disabled by default. Enable each one explicitly with its enable env var:
`CONNECTORSMQTT_ENABLE=true`, `CONNECTORS_AMQP10_ENABLE=true`, `CONNECTORS_STOMP_ENABLE=true`,
`CONNECTORS_AWS_ENABLE=true`, `CONNECTORS_GCP_ENABLE=true`.
Each wire-protocol connector documents its own ports, enable var, and auth in its own pages.
## Migrating from another broker [#migrating-from-another-broker]
Already running RabbitMQ, ActiveMQ, JMS, AMQP 1.0, Kafka, AWS SQS/SNS, STOMP, GCP Pub/Sub, or
MQTT? [Migrate from another broker](/connectors/how-to/migration) maps each ecosystem to its KubeMQ
wire-protocol connector and walks through the cutover — endpoint changes, concept mapping,
a working client example, and what does not carry over — for all nine.
# Choose your path (/deploy)
KubeMQ runs as one server on Docker for development and test, or as a cluster of three or more servers on Kubernetes for production. Start by trying it on your machine in 5 minutes, then pick the page for your goal.
An air-gapped install is about 60 minutes of work in two sittings, with a wait between them while KubeMQ issues your offline license file.
## What do you want to do? [#what-do-you-want-to-do]
| You want to | Go to | Where it runs | License you need | Time |
| ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------- | ------------------------------------------- | ---------- |
| Try KubeMQ on your laptop | [Try KubeMQ](/deploy/quickstart) | One Docker server | None: a 14-day evaluation starts on its own | 5 minutes |
| Develop or test on one server | [Install with kmq](/deploy/install/kmq), or [Install with Docker](/deploy/install/docker) | One Docker or Podman server | Trial key (Docker), or a license key | 10 minutes |
| Run a production cluster | [Install on Kubernetes](/deploy/install/kubernetes) | Kubernetes, 3 or more servers | Trial key (Kubernetes), then a license key | 30 minutes |
| Install with no internet access | [Install air-gapped](/deploy/install/air-gapped) | Kubernetes, 3 or more servers | Offline license file | 60 minutes |
| Move from Kafka, RabbitMQ, SQS, MQTT, STOMP, Pub/Sub, AMQP or JMS | [Migrate from another broker](/connectors/how-to/migration) | Any | Same as the path you install with | Per guide |
| Connect AI agents or an MCP (Model Context Protocol) host | [KubeMQ Aiway](/aiway) | Any | Same as the path you install with | 10 minutes |
| Upgrade a running KubeMQ | [Upgrade KubeMQ](/deploy/upgrade) | Where it runs today | Your current license | 15 minutes |
| Leave the older `kubemq` image or chart | [Move from legacy KubeMQ](/deploy/upgrade/from-legacy) | — | Contact support | — |
Each license in the table is compared on [Plans compared](/licensing#compare-the-options).
## kmq or manual commands? [#kmq-or-manual-commands]
| Compare | kmq | Docker commands | Helm commands |
| -------------------------------------------------------------- | ------------------------------------------------- | ------------------------------ | ----------------------------------------- |
| Runs in PowerShell, no WSL (Windows Subsystem for Linux) shell | Yes | No | No |
| Adds the license for you | Yes | No | No |
| Resumes after an interruption | Yes | No | Re-run the same Helm command |
| Best when | You want one tool for install, license and checks | You manage containers yourself | You manage Kubernetes with Helm or GitOps |
All three paths install the same server and end in the same checks.
Every command on these pages installs the latest release. The artifact names and how to pin a release are on [Requirements and supported setups](/deploy/install/requirements#artifacts-and-versions).
# Production checklist (/deploy/production-checklist)
Use this list before KubeMQ takes production traffic. Each item links to the page that shows how. The last group covers your client applications.
## Cluster shape [#cluster-shape]
* [ ] An odd number of servers, at least three, chosen for the long term ([Requirements and supported setups](/deploy/install/requirements#kubernetes)).
* [ ] CPU and memory set per server, and servers spread across nodes ([Deployment & High Availability](/configure/reference/deployment#high-availability)).
* [ ] A storage class with room for every server's volume ([Requirements and supported setups](/deploy/install/requirements#sizing)).
## License [#license]
* [ ] A license key or an offline license file, not the evaluation or a trial key ([Plans compared](/licensing#which-one-fits)).
* [ ] The license check shows every server `active` ([Install on Kubernetes](/deploy/install/kubernetes#steps)).
* [ ] License expiry and license state monitored ([How licensing works](/licensing/how-it-works#check-license-status)).
* [ ] On an air-gapped cluster, a reminder to renew the offline license file ([Install air-gapped](/deploy/install/air-gapped#renew-before-it-expires)).
## Security [#security]
* [ ] A management certificate from an authority you trust ([Install on Kubernetes](/deploy/install/kubernetes#management-certificate)).
* [ ] The administrator password kept in your secrets manager ([Install on Kubernetes](/deploy/install/kubernetes#send-a-test-message)).
* [ ] Client authentication on, and a test client with no credentials refused ([Security (Auth · TLS)](/configure/reference/security#authentication)).
* [ ] Channel permissions set per client ([Security (Auth · TLS)](/configure/reference/security#authorization)).
* [ ] TLS on the interfaces your clients use ([Security (Auth · TLS)](/configure/reference/security#tls--mtls)).
* [ ] Connectors you use secured: Kafka [Authentication](/connectors/kafka/how-to/authentication) and [TLS and mTLS](/connectors/kafka/how-to/tls-and-mtls); RabbitMQ [Authentication](/connectors/rabbitmq/how-to/authentication) and [TLS and mTLS](/connectors/rabbitmq/how-to/tls-and-mtls).
* [ ] Network policies that limit which workloads reach the server ports ([Requirements and supported setups](/deploy/install/requirements#network)).
## Network [#network]
* [ ] Outbound HTTPS to `license.kubemq.io`, or an offline license file ([Requirements and supported setups](/deploy/install/requirements#network)).
* [ ] Your applications reach the interfaces they use ([Install on Kubernetes](/deploy/install/kubernetes#connect-your-applications)).
* [ ] Only the interfaces you use exposed outside the cluster ([Interfaces (gRPC · REST · API · HTTP)](/configure/reference/interfaces)).
## Data [#data]
* [ ] A backup method chosen and a restore tested ([Back up and restore](/operate/backup-and-restore#steps)). Back up the Docker volume with the container stopped. For Kubernetes, [contact support](mailto:support@kubemq.io) before relying on a restore.
## Operations [#operations]
* [ ] Metrics scraped and alerts set ([Prometheus Metrics](/operate/observability/metrics)).
* [ ] Logs collected ([Structured Logging](/operate/observability/logging)).
* [ ] An upgrade plan written ([Upgrade KubeMQ](/deploy/upgrade)).
* [ ] With GitOps, the chart version pinned (Pin a version on [Install on Kubernetes](/deploy/install/kubernetes)).
## Your applications [#your-applications]
* [ ] Clients reconnect with backoff after a server restart and handle each error category ([Error Handling Patterns](/learn/guides/error-handling)).
* [ ] A timeout on every command and query ([Configure Timeouts & Retries](/learn/rpc/how-to/timeout-configuration)).
* [ ] A dead-letter queue on every critical queue ([Dead Letter Queue](/learn/queues/tutorials/dead-letter-queue)).
* [ ] Visibility timeouts matched to processing time ([Configure Visibility Timeout](/learn/queues/how-to/visibility-timeout)).
* [ ] TLS on every client connection ([Connect with TLS & mTLS](/learn/guides/connect-with-tls)).
* [ ] Traces and metrics from every client ([OpenTelemetry Integration](/learn/guides/opentelemetry)).
* [ ] Channel names and their lifecycle managed ([Channel Management](/learn/guides/channel-management)).
* [ ] Volumes sized for channel growth: retention limits apply only on the legacy storage engine ([Storage Engines](/configure/reference/storage-engines#native-retention-scope)).
## Related [#related]
* [Install on Kubernetes](/deploy/install/kubernetes)
* [Upgrade KubeMQ](/deploy/upgrade)
* [Messaging Fundamentals](/learn/concepts)
# Try KubeMQ (/deploy/quickstart)
In about five minutes you start a KubeMQ server on your machine, create its administrator, send a message and read it back. The server runs a 14-day evaluation that needs no signup. Time: about 5 minutes.
Starting the evaluation accepts the [evaluation terms](https://onboarding.kubemq.io/evaluation-terms) and sends usage data to KubeMQ, as [Data sent to KubeMQ](/licensing/data-sent) describes.
## Before you start [#before-you-start]
* Docker Desktop or Docker Engine, running. Podman works too; see [Requirements and supported setups](/deploy/install/requirements#platforms). On Windows, use Docker Desktop; only the Docker tab's commands need WSL.
* Ports 50000, 9090, 8080 and 9092 free on this machine, and 5672 for the kmq tab.
* Outbound HTTPS to `license.kubemq.io`, directly or through a proxy; see [Requirements and supported setups](/deploy/install/requirements#network).
* On Apple silicon or another Arm machine, the Docker tab needs x86-64 emulation in Docker.
## Run KubeMQ [#run-kubemq]
### Install kmq [#get-kmq]
kmq is the KubeMQ command-line tool. On macOS and Linux, download the installer:
```bash
curl -fsSL https://raw.githubusercontent.com/kubemq-io/kmq/main/install.sh -o install-kmq.sh
```
Run it:
```bash
sh install-kmq.sh
```
Check that kmq runs:
```bash
kmq version
```
You should see:
```text title="Output"
{
"version": "..."
}
```
If the installer notes that its folder is not in your PATH, run the `export PATH` line it prints, then `kmq version` again.
On Windows, in PowerShell:
```powershell
Invoke-WebRequest -Uri https://raw.githubusercontent.com/kubemq-io/kmq/main/install.ps1 -OutFile install-kmq.ps1
```
```powershell
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
```
```powershell
& .\install-kmq.ps1
```
```powershell
kmq version
```
The second command allows the downloaded script in this window only.
### Start a server [#start-a-server]
```bash
kmq onboard --goal evaluation --name kubemq --pull --deadline 10m
```
You should see:
```text title="Output"
{
"installation_id": "...",
"state": "runtime_started_needs_management_setup",
"target": "docker",
"resource_id": "...",
"data_retained": true,
"next_action": "complete_management_authentication_then_verify"
}
```
This creates an installation named `kubemq`: a container named `kubemq` and a volume named `kubemq-data`, with every port bound to this machine only. With Podman, add `--runtime podman`.
### Create the administrator [#create-the-administrator]
```bash
kmq auth setup --installation YOUR_INSTALLATION_ID --username admin
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq onboard` printed.
When kmq asks, type a new password twice. kmq shows the minimum length.
You should see:
```text title="Output"
{
"state": "authenticated",
"credential": "...",
"account_id": "...",
"role": "read_write",
"next_action": "context_use_then_verify_installation"
}
```
If kmq reports `Management connection failed`, the server is still starting: wait a few seconds and run it again. If kmq reports `credential_storage_unavailable` on Linux, add `--credential-backend file`.
AI coding agents: a person must type this password, so hand the terminal over. See the AI coding agent section of [Install with kmq](/deploy/install/kmq#use-kmq-from-an-ai-coding-agent).
### Point kmq at the server [#point-kmq-at-the-server]
```bash
kmq context use kubemq
```
You should see:
```text title="Output"
{
"context": "kubemq",
"status": "active"
}
```
`kmq auth setup` saved a connection named `kubemq`; this command makes it the one kmq uses.
### Send a message [#send-a-message]
```bash
kmq queue send orders '{"id":1}'
```
You should see:
```text title="Output"
{
"messageId": "...",
"sentAt": "..."
}
```
On Windows, in PowerShell:
```powershell
'{"id":1}' | Set-Content message.json
```
```powershell
kmq queue send orders --file message.json
```
### Receive it [#receive-it]
```bash
kmq queue receive orders
```
You should see:
```text title="Output"
[
{
"messageId": "...",
"clientId": "...",
"metadata": "",
"body": {
"id": 1
},
"bodyBase64": "eyJpZCI6MX0=",
"timestamp": ...,
"sequence": 1,
"tags": "",
"receivedCount": 1,
"reRoutedFrom": "",
"expirationAt": 0,
"delayedTo": 0
}
]
```
Open `http://localhost:8080` and sign in as `admin` to see the `orders` channel.
These commands are for bash on macOS and Linux. On Windows, run them in WSL (Windows Subsystem for Linux), or use the kmq tab of [Try KubeMQ](/deploy/quickstart), which runs natively on Windows.
### Start a server [#start-a-server-1]
With Podman:
Check that the server is running:
```bash
docker ps --filter name=kubemq --format '{{.Names}}: {{.Status}}'
```
You should see:
```text title="Output"
kubemq: Up ...
```
[Install with Docker](/deploy/install/docker#what-this-command-does) explains each flag.
### Create the administrator [#create-the-administrator-1]
Open `http://localhost:8080` and create the administrator. If the page does not open yet, wait a few seconds and reload it. You should see the empty dashboard.
### Send a message [#send-a-message-1]
```bash
curl -X POST http://localhost:9090/queue/send \
-H "Content-Type: application/json" \
-d '{
"Channel": "orders",
"ClientID": "quickstart-curl",
"BodyString": "{\"id\":1}"
}'
```
You should see:
```text title="Output"
{"is_error":false,"message":"OK","data":{...}}
```
### Receive it [#receive-it-1]
```bash
curl -X POST http://localhost:9090/queue/receive \
-H "Content-Type: application/json" \
-d '{
"Channel": "orders",
"ClientID": "quickstart-curl",
"MaxNumberOfMessages": 1,
"WaitTimeSeconds": 5
}'
```
You should see:
```text title="Output"
{"is_error":false,"message":"OK","data":{"RequestID":"...","Messages":[{"MessageID":"...","ClientID":"quickstart-curl","Channel":"orders","Body":"eyJpZCI6MX0=","Attributes":{"Timestamp":...,"Sequence":1,"ReceiveCount":1},"Policy":{"MaxReceiveCount":1024}}],"MessagesReceived":1}}
```
`Body` is base64 for `{"id":1}`.
Both tabs create the same container and volume. Use one of them.
This server runs a 14-day evaluation. To keep it and its data, add a license to it: continue on [Install with kmq](/deploy/install/kmq) or [Install with Docker](/deploy/install/docker), matching the tab you used. [Plans compared](/licensing) lists your options.
## Clean up [#clean-up]
```bash
kmq deploy remove --installation YOUR_INSTALLATION_ID
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq onboard` printed.
You should see:
```text title="Output"
{
"installation_id": "...",
"state": "runtime_removed_data_retained",
"target": "docker",
"resource_id": "...",
"data_retained": true,
"next_action": "plan_new_installation_with_continue_volume_to_reuse_retained_data"
}
```
```bash
docker stop kubemq
```
```bash
docker rm kubemq
```
Both keep the `kubemq-data` volume, so the same server can start again later.
This deletes every message and the evaluation. A new volume does not guarantee a new evaluation.
```bash
docker volume rm kubemq-data
```
## If something goes wrong [#if-something-goes-wrong]
* **A port is already in use.** Stop the program that uses it. [Install with Docker](/deploy/install/docker#what-this-command-does) lists each port.
* **kmq reports `volume already exists`.** Run step 2 again with `--continue-volume`, then `kmq auth login --installation YOUR_INSTALLATION_ID --username admin` instead of step 3. Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that the new `kmq onboard` printed. To start fresh instead, delete the volume as in [Clean up](#clean-up).
* **kmq reports `container already exists`, or Docker reports that the name `kubemq` is in use.** Run `docker stop kubemq` and `docker rm kubemq`; the data stays in the volume. Then start the server again: with Docker, run step 1 again; with kmq, see the bullet above.
* **The server stops soon after it starts.** Run `docker logs kubemq`. `waiting for license.kubemq.io` means a network or proxy blocks the server, which retries for about two minutes. See [Troubleshooting](/licensing/troubleshooting#first-boot-unreachable). `This evaluation has finished`, `already used its evaluation` or `Signup-free evaluation is unavailable` means no evaluation is left here: start with a trial or license key on [Install with kmq](/deploy/install/kmq#if-something-goes-wrong) or [Install with Docker](/deploy/install/docker#if-something-goes-wrong).
* **Anything else.** Check `docker logs kubemq` and [Troubleshooting](/licensing/troubleshooting).
## Next steps [#next-steps]
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-p 127.0.0.1:9092:9092 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
```sh
podman run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-p 127.0.0.1:9092:9092 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Data sent to KubeMQ (/licensing/data-sent)
Everything a KubeMQ server or kmq, the KubeMQ command-line tool, sends to KubeMQ is on this page, field by field. A server with an offline license file sends nothing. Use this page to review KubeMQ's outbound traffic and data handling.
## Summary [#summary]
| Call | Sent by | When | Destination | Can it be turned off? |
| ----------------------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------- |
| Start an evaluation | Server | First start of a new single Docker server that has no license | `POST https://license.kubemq.io/v1/evaluation/start` | Yes: start with a trial key or license key instead |
| Activate a trial key or license key | Server | A start whose key has no usable saved license: the first start, a changed key, an evaluation that gets a key, or a saved license that has expired or no longer matches | `POST https://license.kubemq.io/v1/license/activate` | No, with a trial key or license key |
| Renew | Server | Regularly while an evaluation, trial key or license key is running | `POST https://license.kubemq.io/v1/license/refresh` | No, with a trial key or license key |
| Usage report | Server | At start, every 15 minutes, and at shutdown | `POST https://license.kubemq.io/v1/usage/report` | No, with a trial key or license key |
| Trial request | kmq, or the trial page | Only when you request, verify, claim or recover a trial key | `https://onboarding.kubemq.io/api/onboarding/v1/requests` and paths under it | Sent only when you run it |
| Update check | kmq | Only when you run `kmq version --check` or `kmq update` | `HEAD https://github.com/kubemq-io/kmq/releases/latest` | Yes: it is sent only when you run them |
Every server request carries `User-Agent: kubemq-server/` and standard JSON content headers. Renewals and usage reports also carry, as their credential, the latest signed license KubeMQ returned to the server. The server contacts no other KubeMQ address, and the web dashboard makes no calls to KubeMQ: it only links to KubeMQ pages.
Downloading KubeMQ images, the Helm chart or kmq is an ordinary download that carries no data about you. [Requirements and supported setups](/deploy/install/requirements#network) lists every host.
## Fields sent by the server [#fields-sent-by-the-server]
| Field | Evaluation | Activate | Renew | What it is |
| -------------- | ---------- | -------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `key` | — | Yes | — | The trial key or license key, or the key an evaluation saved at its first start. Sent only to activation. |
| `fingerprint` | Yes | Yes | Yes | The installation's identity. On Kubernetes, the ID of the `kube-system` namespace; on Docker, a random ID the server saves on its volume. |
| `source` | Yes | Yes | Yes | Where the server runs: see the next table. |
| `trusted_kids` | Yes | Yes | Yes | The IDs of the KubeMQ signing keys this server version trusts. |
| `nonce` | — | — | Yes | A random one-time value. It carries no information about you. |
## Source fields [#source-fields]
Every server call, and every usage report, carries this `source` object.
| Field | Docker | Kubernetes | What it is |
| -------------- | -------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | `docker` | `kubernetes` | How the server runs. `standalone` appears only from a server binary run directly on a host, which is not supported. |
| `host_id` | Yes | Yes | The container's hostname. On Kubernetes, the name of the node the pod runs on; some clouds put the node's private IP address in that name. |
| `cluster_id` | — | Yes | The ID of the `kube-system` namespace, or empty if the server cannot read it. |
| `namespace` | — | Yes | The pod's namespace. |
| `pod` | — | Yes | The pod's name. |
| `version` | Yes | Yes | The KubeMQ server version. |
| `image_digest` | Yes | Yes | The digest of the running image. On Kubernetes the operator fills it when the image is pinned by digest; otherwise, and on Docker, it is empty unless the container sets `KUBEMQ_IMAGE_DIGEST`. |
## Usage reports [#usage-reports]
A usage report goes out when the server starts, every 15 minutes while it runs, and when it shuts down. An example:
```json title="Usage report"
{
"license_id": "6f1c2a3e-9b4d-4c5e-8a7f-1d2e3f4a5b6c",
"fingerprint": "3f2a9c1e-7b6d-4e5f-9a8b-0c1d2e3f4a5b",
"boot_id": "0b3d5f7a-9c1e-4a2b-8d6f-1e3c5a7b9d0f",
"source": {
"type": "kubernetes",
"host_id": "node-a",
"cluster_id": "3f2a9c1e-7b6d-4e5f-9a8b-0c1d2e3f4a5b",
"namespace": "kubemq",
"pod": "messaging-0",
"version": "x.y.z",
"image_digest": "sha256:EXAMPLE_DIGEST"
},
"cursor": { "from": "2026-09-19T12:00:00Z", "to": "2026-09-19T12:15:00Z" },
"totals": { "messages": 123456789, "volume_bytes": 987654321 },
"activity": null
}
```
| Field | What it is |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `license_id` | Your license's public ID. |
| `fingerprint` | The installation's identity, as above. |
| `boot_id` | A random ID created when the server process starts. It tells a restart from a continuing run. |
| `source` | The source fields above. |
| `cursor.from`, `cursor.to` | The time window the report covers, in UTC. |
| `totals.messages` | Messages the server has handled since the last confirmed report. |
| `totals.volume_bytes` | Bytes of message traffic the server has handled since the last confirmed report. |
| `activity` | `"start"` on the first report of a run, `"stop"` when the server shuts down or a license stop ends, `null` otherwise. |
Totals are running counts for the whole run, not counts per window, so a missed report loses nothing: the next one carries the full count. Traffic that a run handled but never reported goes into the next run's reports under the same license. Reporting runs in the background and never slows or blocks message traffic.
Usage reports cannot be turned off with a trial key or license key. To send nothing, use an offline license file.
## Trial requests [#trial-requests]
kmq and the [trial page](https://onboarding.kubemq.io/trial) send the same fields to the same service. kmq's requests carry `User-Agent: kmq-onboarding/1` and, after the first one, the session token the service returned.
| Field | Sent when | What it is |
| ----------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `email` | You request or recover a trial key | Where the verification code and the key go. |
| `name`, `company` | You request a trial key | Your name and company. |
| `platform` | You request or recover a trial key | `docker` (1 server) or `kubernetes` (3 servers); a recover call always sends `docker`. |
| `server_count` | You request a trial key for Kubernetes | The number of servers. |
| `consent` | You request or recover a trial key | `true`: you accept the trial terms and the privacy notice (`"consent": true` in the kmq request file); a recover call always sends `false`. |
| `code` | You verify | The eight-digit code from the email. |
| `key_version` | You claim the key | Which key version kmq saved, so the service knows delivery succeeded. |
KubeMQ stores the issued key encrypted, so that the owner of the email address can recover the same key through the trial page or kmq. KubeMQ staff can recover keys for converted or manually issued licenses.
## What is never sent [#what-is-never-sent]
| Never sent | Detail |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Message content | No payloads, headers, metadata or tags. |
| Names | No channel, queue, client or subscription names. |
| Configuration | No configuration values or credentials of yours. A key goes only to activation; renewals and usage reports send back only the signed license KubeMQ issued. |
| Breakdowns | No per-channel or per-client counts, only the two totals. |
| IP addresses | No request adds an IP address field. On Kubernetes, `host_id` is the node name, which on some clouds contains the node's private IP address. |
KubeMQ's service sees the public address each connection comes from. For evaluations it keeps a keyed hash of that address for up to 90 days.
## If usage reports are blocked [#if-usage-reports-are-blocked]
Usage reporting is required for an evaluation, a trial key or a license key. If reports stay blocked, the server logs a warning that links to [Troubleshooting](/licensing/troubleshooting#silent-usage), KubeMQ emails the license contact, and eventually KubeMQ stops renewing the license. The server then stops at the time `kmq license` shows under `run_until`. KubeMQ pauses this whenever the cause is an outage at KubeMQ.
## Send nothing: use an offline license file [#send-nothing-use-an-offline-license-file]
A server with an offline license file makes no calls to KubeMQ. Offline license files are for Kubernetes clusters: see [Install air-gapped](/deploy/install/air-gapped), and buy one through [Plans compared](/licensing#buy). For one Docker server with no internet access, [contact support](mailto:support@kubemq.io).
## Check what your server reports [#check-what-your-server-reports]
`kmq license --detail full -o json` prints the server's full license status and needs the management sign-in. These fields show whether reports get through:
| Field | Healthy value |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled`, in the `usage` block | `true` with a trial key or license key; `false` with an offline license file. |
| `last_report_at`, in the `usage` block | Less than 20 minutes ago. |
| `last_outcome`, in the `usage` block | `accepted`, or `duplicate` right after a restart. `error` means the report was not accepted; it is retried. `rejected` means KubeMQ refused it, and `never` that none has been sent since the server started. |
| `silent` | `false`. `true` means KubeMQ has received no usage reports from this license. |
The field tables on this page are the full list: there is no other payload to inspect.
## Retention and privacy [#retention-and-privacy]
| Data | Kept for |
| ----------------------------------------- | ------------------------------------------------------------------- |
| Raw usage reports | 90 days |
| Daily totals per license and installation | Kept as the billing record |
| Evaluation address hash | Up to 90 days |
| Trial request details | As the [privacy notice](https://kubemq.io/privacy-policy-2/) states |
An evaluation runs under the [evaluation terms](https://onboarding.kubemq.io/evaluation-terms). KubeMQ handles personal data as its [privacy notice](https://kubemq.io/privacy-policy-2/) states. To ask where KubeMQ stores this data, who can recover a trial key, or to request deletion, email [support@kubemq.io](mailto:support@kubemq.io).
## Related [#related]
* [How licensing works](/licensing/how-it-works)
* [Plans compared](/licensing)
# How licensing works (/licensing/how-it-works)
Every KubeMQ server checks its own license, on Docker and Kubernetes. Without a valid license it does not start, and when a license ends it stops. Your data is never deleted. A license belongs to its installation: the Kubernetes cluster, or on Docker the data volume, so keep the volume.
## Online and offline licenses [#online-and-offline-licenses]
| Kind | Which licenses | Talks to KubeMQ | Ends |
| ------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| Online | The evaluation, trial keys and license keys | Contacts `license.kubemq.io` at first start and while running, and sends usage reports ([Data sent to KubeMQ](/licensing/data-sent)) | At the evaluation, trial or contract end. `kmq license` (kmq is the KubeMQ command-line tool) shows the time under `run_until` |
| Offline | An offline license file | Never | On the file's end date |
If both are set, the file wins ([Core & Licensing](/configure/reference/core#license)).
## When the server cannot reach KubeMQ [#when-the-server-cannot-reach-kubemq]
A server with an online license keeps running while it cannot reach KubeMQ, until the time `kmq license` shows under `run_until`. Restore the connection before then.
Meanwhile the server logs a warning ([Troubleshooting](/licensing/troubleshooting#grace-countdown)). The `kmq license` record shows the renewal result under `last_refresh` and may add an entry to `warnings`. An online license's first start must reach KubeMQ.
## When a license ends [#when-a-license-ends]
An online license stops renewing at the contract or trial end, and the server stops at `run_until`. An evaluation ends 14 days after it started.
An offline license file stops the server on its end date. Renew it first: [Install air-gapped](/deploy/install/air-gapped#renew-before-it-expires).
At a stop the server refuses new connections, lets current work finish (5 minutes by default, [Core & Licensing](/configure/reference/core#license)) and exits with code 3. Cluster servers stop at different times. Restarts fail the same way until the license is fixed (`CrashLoopBackOff` on Kubernetes).
Messages, accounts and settings stay on the volume. Add a trial key or license key with your install page's **Add your license** step and the server starts on the same data; a new evaluation cannot.
Buying before a trial key ends converts the same key; running servers pick up the new plan without a restart.
## Revocation [#revocation]
KubeMQ revokes a license only by deliberate action. Missed payments, network silence and extra installations never revoke one. Offline license files cannot be revoked. Notice periods are in the licensing policy ([Plans compared](/licensing#terms-and-policies)). A cluster larger than its license stops by itself ([Troubleshooting](/licensing/troubleshooting#cluster-over-cap)).
## Check license status [#check-license-status]
`kmq license` reads the JSON license record from the signed-in server. [Troubleshooting](/licensing/troubleshooting#check-the-license-status) shows how to sign in on each platform. `kmq license --detail full` prints the same record with all available fields for support. Neither command includes the license key or offline license contents.
The relevant fields have this shape:
```json title="Relevant fields"
{
"server_version": "...",
"adoption": {
"configured_input_sha256": "...",
"accepted_input_sha256": "...",
"state": "accepted",
"durable": true
},
"plan": "trial",
"mode": "online",
"source": "key",
"license_expires_at": "...",
"lease_expires_at": "...",
"run_until": "...",
"max_instances": 1,
"instances": 1,
"last_refresh": { "outcome": "..." },
"over_cap": false,
"warnings": [],
"stop_cause": null
}
```
The server version identifies the running release. The adoption object confirms that the configured license input was accepted and saved on persistent storage; its two hashes must match. The plan, mode, source, expiry, and instance values describe the entitlement and current use. The latest refresh result and warnings show renewal problems. A healthy licensed server has no stop cause, is not over capacity, and has applicable expiry times in the future. Restore online connectivity before `run_until` when the refresh result or warnings report a renewal problem.
The command exits with code 0 when the server returns a record. Authentication, connection, timeout, and other command failures use the [kmq CLI exit codes](/operate/kmq-cli#exit-codes). Monitoring must inspect the JSON fields as well as the command exit code, because a returned record can contain warnings or a pending stop.
## Related [#related]
* [Plans compared](/licensing)
* [Data sent to KubeMQ](/licensing/data-sent)
* [Troubleshooting](/licensing/troubleshooting)
# Plans compared (/licensing)
Every KubeMQ server needs a license. Four kinds exist. This page compares them, says which fits each situation, and links to the install step that adds each one. [How licensing works](/licensing/how-it-works) explains what the server does with them.
## Compare the options [#compare-the-options]
| Topic | Evaluation | Trial key | License key | Offline license file |
| ----------------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| Best for | Trying KubeMQ on a laptop | Developing on one server, or trying a production-shaped cluster | Production and staging | Sites with no internet access |
| Runs on | One Docker server | One Docker server, or one Kubernetes cluster of 3 servers, chosen when you request it. On Kubernetes the key stays with the first cluster it starts on, and KubeMQ issues it on request | Docker or Kubernetes, with the number of servers in your order | Kubernetes, with the number of servers in the file. For one Docker server, [contact support](mailto:support@kubemq.io) |
| Lasts | 14 days | 30 days | Your contract term | The end date in the file, up to one year |
| Signup | None | Email verification; for Kubernetes, a request to KubeMQ | An order from KubeMQ | An order plus your cluster's ID |
| Needs internet | Yes, to start and while running | Yes, to start and while running | Yes, to start and while running | Never |
| Sends usage reports ([Data sent to KubeMQ](/licensing/data-sent)) | Yes | Yes | Yes | No |
| How to get and apply it | Starts by itself: [Try KubeMQ](/deploy/quickstart) | [Install with kmq](/deploy/install/kmq#add-your-license), [Install with Docker](/deploy/install/docker#add-your-license) or [Install on Kubernetes](/deploy/install/kubernetes#add-your-license) | [Install with kmq](/deploy/install/kmq#add-your-license), [Install with Docker](/deploy/install/docker#add-your-license) or [Install on Kubernetes](/deploy/install/kubernetes#add-your-license) | [Install air-gapped](/deploy/install/air-gapped#request-your-offline-license-file) |
What happens when each one ends is on [How licensing works](/licensing/how-it-works#when-a-license-ends).
## Which one fits [#which-one-fits]
| Situation | Use |
| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Try KubeMQ on your laptop | The evaluation |
| Automated tests and continuous integration | A license key that covers the number of installations your test runs create, or any key with one persistent volume per test host. Never the evaluation, and never a trial key on fresh volumes: each fresh volume counts as a new installation, so the evaluation may be refused, and a one-server trial key warns that it is over its cap from the second run ([Troubleshooting](/licensing/troubleshooting#over-cap)) |
| Staging | A license key |
| Production | A license key on Kubernetes. Single-server Docker is for development and test only, and kmq, the KubeMQ command-line tool, refuses a production install on Docker |
| No internet access | An offline license file on Kubernetes. For one Docker server, [contact support](mailto:support@kubemq.io) |
## Buy [#buy]
See [Pricing](https://kubemq.io/product-pricing/) for plans. To buy, or to ask about anything on this page, use [Contact KubeMQ](https://kubemq.io/contact-sales/).
Send your request through the contact form with the details below. We reply within one business day. Kubernetes licenses above three servers and offline license files are issued within two business days of agreement.
* The license kind: license key or offline license file. A trial key for Kubernetes is a request here too.
* The number of servers.
* Docker or Kubernetes.
* For an offline license file, the cluster ID that [Install air-gapped](/deploy/install/air-gapped#request-your-offline-license-file) has you collect.
### Manage an existing license [#manage-an-existing-license]
Email [KubeMQ support](mailto:support@kubemq.io) to:
* renew a license key or an offline license file;
* replace a key that leaked;
* move a license to a new cluster;
* retire an installation you no longer run.
Apply the new key with the **Replace the license later** step of [Install with kmq](/deploy/install/kmq#replace-the-license-later), [Install with Docker](/deploy/install/docker#replace-the-license-later) or [Install on Kubernetes](/deploy/install/kubernetes#replace-the-license-later). Apply a new offline license file as [Install air-gapped](/deploy/install/air-gapped#renew-before-it-expires) shows.
## Terms and policies [#terms-and-policies]
* [Evaluation terms](https://onboarding.kubemq.io/evaluation-terms)
* Trial terms
* Licensing policy: KubeMQ's commitments, key recovery, data retention and hosting region
* [Privacy notice](https://kubemq.io/privacy-policy-2/)
* License agreement, for license keys and offline license files. Your order includes the license agreement; ask for it through [Contact KubeMQ](https://kubemq.io/contact-sales/).
## Related [#related]
* [How licensing works](/licensing/how-it-works)
* [Data sent to KubeMQ](/licensing/data-sent)
* [Troubleshooting](/licensing/troubleshooting)
* [Choose your path](/deploy)
# Troubleshooting (/licensing/troubleshooting)
Run `kmq license` first (it needs a signed-in kmq, below), find your symptom, then follow its fix. Refusals, stops and warnings carry `https://docs.kubemq.io/licensing/troubleshooting#`, linking to that entry.
Commands use the names from [Install on Kubernetes](/deploy/install/kubernetes). For Kubernetes, replace `kubemq` with your namespace and `messaging` with your cluster name (`kubectl --context YOUR_KUBE_CONTEXT get kubemqclusters.next.kubemq.io -A` lists them).
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context (`kubectl config current-context`).
## Check the license status [#check-the-license-status]
`kmq license` needs a signed-in kmq. Try KubeMQ signed you in; if kmq has no saved connection to this server, sign in once. If kmq installed it:
```bash title="Terminal"
kmq auth login --installation YOUR_INSTALLATION_ID --username admin
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq onboard` or `kmq deploy apply` printed.
If you started it with the Docker command:
```bash title="Terminal"
kmq auth login --api-address http://127.0.0.1:8080 --context-name kubemq --username admin
```
The login saves a context but does not select it. Select the context before asking for the license:
```bash title="Terminal"
kmq context use kubemq
```
Then:
```bash title="Terminal"
kmq license
```
`kmq license` returns one JSON record. For a licensed server, check the `adoption` object. Its `state` is `accepted`, its `durable` value is `true`, and the configured and accepted input hashes match. Confirm `plan`, `license_expires_at`, and `run_until`; `stop_cause` must be `null` and `over_cap` must be `false`.
For the full record, for support:
```bash title="Terminal"
kmq license --detail full
```
If the container is stopped, `kmq license` prints a connection error instead of a license record and exits with code 5.
Read its last log lines instead:
```bash title="Terminal"
docker logs --tail 50 kubemq
```
kmq reads one server at a time. Open the server's management port and sign in, as in [Install on Kubernetes](/deploy/install/kubernetes#open-the-management-port). Select the context saved for that server:
```bash title="Terminal"
kmq context use messaging
```
Then ask:
```bash title="Terminal"
kmq license
```
You should see one JSON record for that server. Check the acceptance, plan, expiry, capacity, warning, and stop fields described in [How licensing works](/licensing/how-it-works#check-license-status).
For the other servers, stop the port-forward, start it again with `pod/messaging-1` (then `pod/messaging-2`) in place of `pod/messaging-0`, and sign in again with a new `--context-name` (`messaging-1`, `messaging-2`). Then run `kmq license --context messaging-1` (and `--context messaging-2`). All three records must agree on `plan`, `mode`, `license_expires_at`, and `adoption.accepted_input_sha256`.
For the whole cluster at once, read the `LicenseInvalid` and `ReplicasOverLicenseCap` conditions the operator sets:
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq describe kubemqclusters.next.kubemq.io messaging
```
Replace: `YOUR_KUBE_CONTEXT` — the kubectl context of your cluster.
A server that is not running answers with a connection error instead of a license record. Read its last log lines (use its name; for a pod in `CrashLoopBackOff`, add `--previous`):
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq logs messaging-0 --tail 50
```
What the license fields mean: [How licensing works](/licensing/how-it-works#check-license-status).
## Exit codes [#exit-codes]
The server's exit codes. For `kmq license` codes, see [How licensing works](/licensing/how-it-works#check-license-status).
| Code | Meaning | Where to look |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `0` | Clean shutdown. | Nothing to do. |
| `1` | Any other failure, including a configuration error such as a `license` block left in an old configuration file. | The first error line in the log. For the `license` block, [Will not start: no license](#no-license-input). |
| `3` | A licensing refusal or stop. | The anchor at the end of the last log line. |
| `4` | Unsupported deployment: a pod the operator did not create, clustering on Docker, fewer than three servers on Kubernetes, or a server started outside a container. | [Will not start: exit code 4](#unmanaged-kubernetes) |
## Symptoms [#symptoms]
**Will not start**
| What you see | Cause | Fix |
| -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------ |
| `#no-license-input`, or a message that no evaluation can start: Kubernetes, existing data, incomplete files, unavailable, already used | No license is set, and no evaluation can start here | [Add a license](#no-license-input) |
| `#invalid-signature`, or the cluster condition `LicenseInvalid` | The license cannot be read or is not genuine | [Restore the license](#invalid-signature) |
| `#fingerprint-mismatch` | The license belongs to another installation | [Check the installation](#fingerprint-mismatch) |
| `#first-boot-bad-request` | The key is malformed | [Re-save the key](#first-boot-bad-request) |
| `#first-boot-bad-key` | KubeMQ refused the key | [Check the key](#first-boot-bad-key) |
| `#first-boot-unreachable`, or "Signup-free evaluation must reach license.kubemq.io" | The first start could not reach KubeMQ | [Open the connection](#first-boot-unreachable) |
| `#cluster-over-cap`, or the conditions `ReplicasOverLicenseCap` and `ReplicasFrozen` | More servers than the license allows | [Match the server count](#cluster-over-cap) |
| `#untrusted-kid` at first start | The server release is too old | [Use the latest image](#untrusted-kid) |
| `#clock-rollback` | The clock moved back | [Set the clock](#clock-rollback) |
| `#store-not-persistent` with exit code 3, or "Cannot save evaluation files" | The data folder cannot be written | [Fix the data folder](#store-not-persistent) |
| Exit code 4 | Unsupported deployment | [Use a supported setup](#unmanaged-kubernetes) |
| A pod in `CrashLoopBackOff` | The server exits at every start | [Read the run that stopped](#check-the-license-status) |
| `kmq license` shows the old `plan`, `license_expires_at`, or `adoption.accepted_input_sha256` after a change | The new license was not accepted | [Check the change](#license-not-accepted) |
**Stopped while running**
| What you see | Cause | Fix |
| -------------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| `#lease-and-grace-exhausted`, or a non-null `stop_cause` | The license could not be renewed in time | [Restore renewals](#lease-and-grace-exhausted) |
| `#evaluation-expired`, or "This evaluation has finished" | The evaluation ended | [Add a license](#evaluation-expired) |
| `#offline-expired` | The offline license file reached its end date | [Apply a new file](#offline-expired) |
| `#revoked` | KubeMQ revoked the license | [Contact support](#revoked) |
| `#clock-rollback` or `#cluster-over-cap` | See **Will not start** | [Set the clock](#clock-rollback) · [Match the server count](#cluster-over-cap) |
| `#clock-skew` | The clock differs from KubeMQ's and the license could not be renewed | [Synchronize the clock](#clock-skew) |
| `LicenseInvalid` on Kubernetes | A server stopped or cannot start | [Read its log](#check-the-license-status) |
**Warnings**
| What you see | Cause | Fix |
| ------------------------------------------------------ | ---------------------------------------------- | ------------------------------------------------------- |
| `#grace-countdown`, or a renewal warning in `warnings` | The server cannot reach KubeMQ | [Restore the connection](#grace-countdown) |
| an expiry warning in `warnings` | 14 days or fewer to the license end | Renew or buy through [Plans compared](/licensing#buy) |
| `#lease-refused` | KubeMQ did not renew the license | [Read the expiry](#lease-refused) |
| `#revocation-seen` | KubeMQ started to revoke the license | [Contact support](#revocation-seen) |
| `#over-cap` | More installations than licensed | [Remove the extras](#over-cap) |
| `#silent-usage` | Usage reports are not arriving | [Allow usage reports](#silent-usage) |
| `#clock-skew` | The clock differs from KubeMQ's | [Synchronize the clock](#clock-skew) |
| `#store-not-persistent` at start | The data folder is not on a volume | [Mount a volume](#store-not-persistent) |
| `#missing-kube-system-permission` | The server cannot read the cluster identity | [Grant the permission](#missing-kube-system-permission) |
| `#both-key-and-file` | A key and an offline license file are both set | [Remove one](#both-key-and-file) |
| `#untrusted-kid` on a running server | The server release is too old | [Use the latest image](#untrusted-kid) |
| `#invalid-signature` on a running server | KubeMQ could not verify the license | [Restore the license](#invalid-signature) |
| "Your KubeMQ evaluation expires in" | The evaluation is about to end | [Add a license](#evaluation-expired) |
## Will not start: no license [#no-license-input]
**What you see:** exit code 3 and one of these lines:
```text title="Server log"
license: this installation has an accepted explicit license; restore its configured license input https://docs.kubemq.io/licensing/troubleshooting#no-license-input
license: Kubernetes needs a license key. Get a free 30-day trial key (choose Kubernetes, 3 servers) at https://onboarding.kubemq.io/trial. https://docs.kubemq.io/licensing/troubleshooting#no-license-input
license: A license key was expected. Set KUBEMQ_LICENSE_KEY. Get a free 30-day trial key at https://onboarding.kubemq.io/trial. https://docs.kubemq.io/licensing/troubleshooting#no-license-input
license: The evaluation files are incomplete: the saved key has no installation identity. Set KUBEMQ_LICENSE_KEY with a free 30-day trial key from https://onboarding.kubemq.io/trial to keep your data; preserve the data volume and installation identity. https://docs.kubemq.io/licensing/troubleshooting#no-license-input
license: Signup-free evaluation is unavailable. Get a free 30-day trial key at https://onboarding.kubemq.io/trial and set KUBEMQ_LICENSE_KEY. https://docs.kubemq.io/licensing/troubleshooting#no-license-input
license: This installation has already used its evaluation. Set KUBEMQ_LICENSE_KEY with a free 30-day trial key from https://onboarding.kubemq.io/trial to keep your data; preserve the data volume and installation identity. https://docs.kubemq.io/licensing/troubleshooting#no-license-input
```
A `license` block in a configuration file exits with code 1:
```text title="Server log"
error on load config file: configuration validation error: config source carries a license block (""), which is no longer accepted: licensing is environment-only. Remove it and set KUBEMQ_LICENSE_KEY (online key), or KUBEMQ_LICENSE_FILE / KUBEMQ_LICENSE_DATA (offline file), optionally … See https://docs.kubemq.io/licensing/troubleshooting#no-license-input
```
**Why:** no license is set, and an evaluation starts only once, on a new single Docker server.
**Fix:**
1. Add a license: [Install with kmq](/deploy/install/kmq#add-your-license), [Install with Docker](/deploy/install/docker#add-your-license) or [Install on Kubernetes](/deploy/install/kubernetes#add-your-license).
2. If the line names an accepted license, put that license back; an evaluation never restarts here.
3. For a `license` block, delete it, then do step 1 ([Move from legacy KubeMQ](/deploy/upgrade/from-legacy)).
## Will not start: license not genuine or unreadable [#invalid-signature]
**What you see:** exit code 3 and one of the first four lines; on a running server, one of the last two:
```text title="Server log"
license: cannot read configured offline license file: https://docs.kubemq.io/licensing/troubleshooting#invalid-signature
license: offline license file rejected: https://docs.kubemq.io/licensing/troubleshooting#invalid-signature
license: license token rejected (expected , source ): https://docs.kubemq.io/licensing/troubleshooting#invalid-signature
license: accepted license record is malformed; restore the record from a trusted backup https://docs.kubemq.io/licensing/troubleshooting#invalid-signature
"msg":"license refresh refused with an unsigned answer; keeping the cached lease until the grace window ends", … "status":,"code":"invalid_token","run_until":"", … "doc_url":"https://docs.kubemq.io/licensing/troubleshooting#invalid-signature"
"msg":"license lease not adopted: older than the current lease (replay); keeping the current lease", … "doc_url":"https://docs.kubemq.io/licensing/troubleshooting#invalid-signature"
```
**Why:** the license cannot be read or failed verification: a file not mounted, cut or re-wrapped, or a changed licensing record on the data volume.
**Fix:**
1. On Kubernetes, check that the Secret key in `licenseFileSecretRef` holds the whole file.
2. Use the file KubeMQ sent, unchanged, from `-----BEGIN KUBEMQ LICENSE-----` to `-----END KUBEMQ LICENSE-----`.
3. If the line names the accepted license record, restore the volume from a trusted backup or contact [support](mailto:support@kubemq.io). Never edit or delete its files.
## Will not start: license issued for another installation [#fingerprint-mismatch]
**What you see:** exit code 3 and one of these lines:
```text title="Server log"
license: offline file is bound to installation(s) and this installation ("") is not one of them https://docs.kubemq.io/licensing/troubleshooting#fingerprint-mismatch
license: offline file is bound to installation(s) and this installation ("", persisted id) is not one of them; on Kubernetes grant the service account get on namespaces (resourceName kube-system) so the cluster fingerprint can be read https://docs.kubemq.io/licensing/troubleshooting#fingerprint-mismatch
license: online lease is bound to installation "" but this installation is "" https://docs.kubemq.io/licensing/troubleshooting#fingerprint-mismatch
```
**Why:** a license bound to another installation. A new cluster, a copied data volume, or a server that cannot read its cluster identity is another installation.
**Fix:**
1. If the log also shows `#missing-kube-system-permission`, [fix that first](#missing-kube-system-permission).
2. Otherwise read your cluster's ID and send its one line to KubeMQ through [Plans compared](/licensing#buy):
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT get namespace kube-system -o jsonpath='{.metadata.uid}'
```
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context.
3. On Docker, contact [support](mailto:support@kubemq.io).
A warning ending "re-activating with the license key" needs no action.
## Offline license file ended [#offline-expired]
**What you see:**
```text title="Server log"
license: offline license file expired at https://docs.kubemq.io/licensing/troubleshooting#offline-expired
```
**Why:** the offline license file reached its end date.
**Fix:** request and apply a new file: [Install air-gapped](/deploy/install/air-gapped#renew-before-it-expires).
## Will not start: license request rejected [#first-boot-bad-request]
**What you see:**
```text title="Server log"
license: first boot: the license backend rejected the activation request as malformed 3 times (HTTP 400 : ); check KUBEMQ_LICENSE_KEY, the fingerprint and the server version https://docs.kubemq.io/licensing/troubleshooting#first-boot-bad-request
license: first boot: cannot build the activation request for KUBEMQ_LICENSE_ENDPOINT="": https://docs.kubemq.io/licensing/troubleshooting#first-boot-bad-request
license: evaluation request refused (HTTP ) https://docs.kubemq.io/licensing/troubleshooting#first-boot-bad-request
```
**Why:** KubeMQ could not read the request, usually a malformed key: quotes, spaces, a line break, or a `KUBEMQ_LICENSE_KEY=` prefix in the key file.
**Fix:**
1. Save the key alone on one line, then repeat your install page's license step.
2. If the line names `KUBEMQ_LICENSE_ENDPOINT`, correct it: [Core & Licensing](/configure/reference/core#license).
3. Use the latest image. If it fails, contact [support](mailto:support@kubemq.io).
## Will not start: key refused [#first-boot-bad-key]
**What you see:**
```text title="Server log"
license: first boot: the license backend rejected the license key 3 times (HTTP 401 ); check KUBEMQ_LICENSE_KEY https://docs.kubemq.io/licensing/troubleshooting#first-boot-bad-key
```
**Why:** KubeMQ refused the key three times. It may be mistyped or replaced, or the license disabled or ended.
**Fix:**
1. Compare the server's key (the key file on Docker, the Secret on Kubernetes) with the latest key KubeMQ sent.
2. If it is correct and current, contact KubeMQ through [Plans compared](/licensing#buy).
## Will not start: cannot reach KubeMQ [#first-boot-unreachable]
**What you see:**
```text title="Server log"
license: first boot: the license backend at https://license.kubemq.io (KUBEMQ_LICENSE_ENDPOINT) stayed unreachable for (last error: ); if this installation cannot reach the endpoint request a pre-activated license file https://docs.kubemq.io/licensing/troubleshooting#first-boot-unreachable
license: Signup-free evaluation must reach license.kubemq.io. Check that outbound HTTPS to license.kubemq.io:443 is allowed, or set KUBEMQ_LICENSE_KEY with a free 30-day trial key from https://onboarding.kubemq.io/trial, or use an offline license file. https://docs.kubemq.io/licensing/troubleshooting#first-boot-unreachable
```
**Why:** a first start must reach KubeMQ. An evaluation gives up after 2 minutes and a license key after 30 minutes ([Core & Licensing](/configure/reference/core#license)).
**Fix:**
1. Check that the host answers `"status":"ok"`:
```bash title="Terminal"
curl -sS https://license.kubemq.io/api/healthz
```
On Windows, in PowerShell:
```powershell title="Terminal"
curl.exe -sS https://license.kubemq.io/api/healthz
```
2. Check from a container:
```bash title="Terminal"
docker run --rm -e HTTPS_PROXY -e NO_PROXY curlimages/curl -sS https://license.kubemq.io/api/healthz
```
Or from a pod:
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq run license-egress-check --rm -i --restart=Never --image=curlimages/curl -- -sS https://license.kubemq.io/api/healthz
```
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context.
If the image cannot be pulled, use the host check.
3. Allow HTTPS to `license.kubemq.io`, or set a proxy: [Requirements and supported setups](/deploy/install/requirements#network).
4. Otherwise, use an offline license file: [Install air-gapped](/deploy/install/air-gapped#request-your-offline-license-file).
## Warning: key and offline file both set [#both-key-and-file]
**What you see:**
```text title="Server log"
"msg":"license boot warning", … "anchor":"both-key-and-file","detail":"both KUBEMQ_LICENSE_KEY and KUBEMQ_LICENSE_FILE/KUBEMQ_LICENSE_DATA are set; the file wins and the key is ignored"
```
**Why:** the server uses the file and never contacts KubeMQ.
**Fix:** remove the file settings to run online, or the key to run offline.
## Will not start: more servers than the license allows [#cluster-over-cap]
**What you see:**
```text title="Server log"
license: cluster configuration names members but the license allows kmq.max_instances=; reduce the member list or upgrade the license https://docs.kubemq.io/licensing/troubleshooting#cluster-over-cap
license: cluster stayed over the license cap ( members > kmq.max_instances=) for consecutive minutes https://docs.kubemq.io/licensing/troubleshooting#cluster-over-cap
license: Clustering requires operator-managed Kubernetes and an approved license for at least three servers. Request approval at https://onboarding.kubemq.io/trial. https://docs.kubemq.io/licensing/troubleshooting#cluster-over-cap
```
**Why:** the cluster has more servers than the license covers. A clustered evaluation is refused too.
**Fix:** the operator never resizes a cluster. Buy a license for your server count through [Plans compared](/licensing#buy), or move traffic to a licensed-size cluster.
## Will not start: exit code 4 [#unmanaged-kubernetes]
**What you see:** exit code 4 and a line such as:
```text title="Server log"
kubemq on Kubernetes is supported only through the KubeMQ operator: this pod was not created by the operator, so the server refuses to start. Install the operator and create a KubemqCluster instead of applying a StatefulSet, Deployment or Pod directly — https://docs.kubemq.io/deploy/kubernetes-helm
unsupported KubeMQ deployment: Docker and Podman support a single non-clustered server; use single-node Docker or Podman, or an operator-managed Kubernetes cluster with at least 3 servers; migrate existing installations before upgrading — https://docs.kubemq.io/deploy/supported-deployments
```
**Why:** not a license problem. KubeMQ runs only on one Docker or Podman server, or an operator-created Kubernetes cluster of three or more servers.
**Fix:** follow [Install on Kubernetes](/deploy/install/kubernetes); see [Requirements and supported setups](/deploy/install/requirements#supported-setups).
## Stopped: could not reach KubeMQ for too long [#lease-and-grace-exhausted]
**What you see:**
```text title="Server log"
license: lease expired at and the -day grace window ended at without a refresh https://docs.kubemq.io/licensing/troubleshooting#lease-and-grace-exhausted
license: evaluation lease and grace expired; reconnect to the license backend https://docs.kubemq.io/licensing/troubleshooting#lease-and-grace-exhausted
```
**Why:** the license was not renewed before the time under `run_until` ([How licensing works](/licensing/how-it-works#when-the-server-cannot-reach-kubemq)).
**Fix:**
1. If the network was the cause (see `stop_cause.doc_url` or `warnings` in `kmq license`, or the log lines before the stop), restore it. Otherwise renew or buy through [Plans compared](/licensing#buy).
2. Start the server.
## Warning: cannot reach KubeMQ [#grace-countdown]
**What you see:**
```text title="Server log"
"msg":"license warning", … "anchor":"grace-countdown","detail":"lease expired at and the backend has not answered; running on grace, day(s) left until "
```
**Why:** the server cannot reach KubeMQ. It keeps running until the time under `run_until`.
**Fix:** restore the connection before then, using the [connection checks](#first-boot-unreachable).
## Stopped: license revoked [#revoked]
**What you see:**
```text title="Server log"
license: license revoked (); signed assertions confirmed https://docs.kubemq.io/licensing/troubleshooting#revoked
license: license remains revoked (); … https://docs.kubemq.io/licensing/troubleshooting#revoked
license: license was revoked: signed revocation assertions were confirmed before the last stop (reason: ); obtain a reinstated license with a newer token_version from the licensing authority; preserve cached state and enforcement state https://docs.kubemq.io/licensing/troubleshooting#revoked
```
**Why:** KubeMQ revoked this license. The server finishes current work, stops, and `kmq license` shows a non-null `stop_cause`. It will not start with this license.
**Fix:** contact [support](mailto:support@kubemq.io). Never delete files on the data volume.
## Warning: revocation received [#revocation-seen]
**What you see:**
```text title="Server log"
"msg":"license warning", … "anchor":"revocation-seen","detail":"a signed revocation assertion has been seen time(s) (reason: ); …"
```
**Why:** KubeMQ has started to revoke this license.
**Fix:** contact [support](mailto:support@kubemq.io) now.
## Will not start or stopped: clock moved back [#clock-rollback]
**What you see:**
```text title="Server log"
license: wall clock is more than 10m0s behind the persisted high-water mark and the license backend is unreachable; correct the clock and restore allowed connectivity; preserve the enforcement record https://docs.kubemq.io/licensing/troubleshooting#clock-rollback
license: wall clock is behind the persisted high-water mark on an offline license; correct the clock; preserve the enforcement record https://docs.kubemq.io/licensing/troubleshooting#clock-rollback
```
**Why:** the clock is earlier than a time this server already saw.
**Fix:**
1. Set the clock with NTP (Network Time Protocol), then start the server.
2. If the clock is right, contact [support](mailto:support@kubemq.io). Never delete files on the data volume.
## Warning or stop: clock differs from KubeMQ [#clock-skew]
**What you see:**
```text title="Server log"
"msg":"local clock differs from the license backend", … "skew_seconds":, … "doc_url":"https://docs.kubemq.io/licensing/troubleshooting#clock-skew"
license: lease expired and the local clock differs from the license backend by s (more than …) https://docs.kubemq.io/licensing/troubleshooting#clock-skew
"msg":"server_time disagrees with the signed lease iat; ignoring server_time", … "server_time":"","lease_iat":"","tolerance":"", … "doc_url":"https://docs.kubemq.io/licensing/troubleshooting#clock-skew"
"msg":"usage report refused as terminal; the cursor advances past this row", … "status":,"error":"", … "docs_url":"https://docs.kubemq.io/licensing/troubleshooting#clock-skew"
```
**Why:** the server's clock differs from KubeMQ's; if the license also cannot be renewed, the server stops.
**Fix:** synchronize the clock with NTP, then start the server if it stopped.
## Warning: more installations than licensed [#over-cap]
**What you see:**
```text title="Server log"
"msg":"license warning", … "anchor":"over-cap","detail":"this license exceeds kmq.max_instances= (over cap); the server keeps running, contact KubeMQ"
```
**Why:** more installations use this license than it allows; the server keeps running.
**Fix:**
1. Stop the extra installations, or get a higher limit through [Plans compared](/licensing#buy).
2. Look for containers started without their volume, and for servers missing [the cluster identity permission](#missing-kube-system-permission).
## Warning: usage reports not arriving [#silent-usage]
**What you see:**
```text title="Server log"
"msg":"license warning", … "anchor":"silent-usage","detail":"the license backend has received no usage from this license for …; leases are capped at … until usage reports resume"
"msg":"license refresh answered a server error; keeping the cached lease", … "status":,"code":"silence_suspended", … "doc_url":"https://docs.kubemq.io/licensing/troubleshooting#silent-usage"
```
**Why:** a firewall or proxy lets renewals through but not usage reports. KubeMQ eventually stops renewing.
**Fix:** let usage reports through like renewals: [Data sent to KubeMQ](/licensing/data-sent#if-usage-reports-are-blocked).
## Warning or refusal: data folder not persistent [#store-not-persistent]
**What you see:** a warning at start:
```text title="Server log"
"msg":"license boot warning", … "anchor":"store-not-persistent","detail":"store path \"\" is on the root filesystem, not a mounted volume; the license cache, instance id and usage cursor will not survive a container replacement"
```
Or exit code 3 and a refusal:
```text title="Server log"
license: cannot durably save accepted license record: https://docs.kubemq.io/licensing/troubleshooting#store-not-persistent
license: cannot persist the installation id: https://docs.kubemq.io/licensing/troubleshooting#store-not-persistent
license: Cannot save evaluation files in store folder . Make the store writable, or get a key at https://onboarding.kubemq.io/trial. https://docs.kubemq.io/licensing/troubleshooting#store-not-persistent
```
**Why:** the data folder is not on a volume (it dies with the container) or is not writable.
**Fix:**
1. On Docker, mount the `kubemq-data` volume at `/kubemq/store`.
2. On Kubernetes, set `volume.size` and `volume.storageClass` in the cluster values. Never set `volume: null`.
3. For the refusal, make the folder writable by user 1001 and free disk space. Never delete files in it.
## Warning: cannot read the cluster identity [#missing-kube-system-permission]
**What you see:**
```text title="Server log"
"msg":"license boot warning", … "anchor":"missing-kube-system-permission","detail":"could not read the kube-system namespace UID (); the service account needs a ClusterRole with get on namespaces (resourceName kube-system); falling back to the persisted instance id"
```
**Why:** without the `kube-system` namespace, each server counts as its own installation and an offline license file does not match.
**Fix:**
1. Check the permission. It must print `yes`:
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT auth can-i get namespace/kube-system --as=system:serviceaccount:kubemq:kubemq-cluster-next
```
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context.
2. If it prints `no`, reinstall the KubeMQ Helm releases; they create that ServiceAccount and its role.
3. Restart the servers one at a time:
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq delete pod messaging-0
```
Then repeat for `messaging-1` and `messaging-2`.
## Will not start: server too old for KubeMQ's signing key [#untrusted-kid]
**What you see:**
```text title="Server log"
license: first boot: the license backend signs with a key this server does not trust (trusted: ); upgrade the server https://docs.kubemq.io/licensing/troubleshooting#untrusted-kid
"msg":"license refresh refused with an unsigned answer; keeping the cached lease until the grace window ends", … "status":422,"code":"untrusted_kid", … "doc_url":"https://docs.kubemq.io/licensing/troubleshooting#untrusted-kid"
```
**Why:** this release does not trust KubeMQ's current signing key. A running server keeps running until the time under `run_until`.
**Fix:** use the latest image: [Upgrade KubeMQ](/deploy/upgrade).
## Warning: renewal refused [#lease-refused]
**What you see:**
```text title="Server log"
"msg":"license refresh refused with an unsigned answer; keeping the cached lease until the grace window ends", … "status":,"code":"","run_until":"", … "doc_url":"https://docs.kubemq.io/licensing/troubleshooting#lease-refused"
"msg":"license refresh answered HTTP 200 without a decodable lease; keeping the cached lease", … "endpoint":"", … "doc_url":"https://docs.kubemq.io/licensing/troubleshooting#lease-refused"
"msg":"license refresh answered a server error; keeping the cached lease", … "status":,"code":"", … "doc_url":"https://docs.kubemq.io/licensing/troubleshooting#lease-refused"
```
**Why:** KubeMQ did not renew the license, its service failed, or a proxy answered instead. The server keeps running until the time under `run_until`.
**Fix:**
1. For "refused", read `license_expires_at` in `kmq license`. In the past, renew through [Plans compared](/licensing#buy); in the future, the license was disabled: contact [support](mailto:support@kubemq.io).
2. For "HTTP 200", check the proxy between the server and `license.kubemq.io`.
3. For "a server error", wait; contact [support](mailto:support@kubemq.io) if it continues.
## Stopped: evaluation ended [#evaluation-expired]
**What you see:**
```text title="Server log"
license: This evaluation has finished. Set KUBEMQ_LICENSE_KEY with a free 30-day trial key from https://onboarding.kubemq.io/trial to keep your data; preserve the data volume and installation identity. https://docs.kubemq.io/licensing/troubleshooting#evaluation-expired
"msg":"evaluation expires soon", … "anchor":"evaluation-expired","detail":"Your KubeMQ evaluation expires in days. Get a free 30-day trial key at https://onboarding.kubemq.io/trial."
```
**Why:** the 14-day evaluation ended; reconnecting does not extend it.
**Fix:** add a trial key or license key on the same volume: [Install with kmq](/deploy/install/kmq#add-your-license) or [Install with Docker](/deploy/install/docker#add-your-license). Removing the volume deletes all messages.
## New license not shown after a change [#license-not-accepted]
**What you see:** after a license change, `kmq license` shows the old `plan`, `license_expires_at`, or `adoption.accepted_input_sha256`.
**Why:** the server did not accept the new license at restart.
**Fix:**
1. Check that the key file holds only the key, on one line, and that [only one license source](#both-key-and-file) is set.
2. Make sure the server can reach `license.kubemq.io`, then restart it.
3. To recover, put the previous license back. Never delete files on the data volume.
## Get help [#get-help]
Send [support](mailto:support@kubemq.io):
1. The output of `kmq license --detail full -o json` (it never includes the key).
2. The last 50 log lines of each affected server ([Check the license status](#check-the-license-status)).
3. How you installed: kmq, Docker or Helm.
# Messaging Patterns (/learn)
KubeMQ is a single message broker that supports four distinct messaging patterns — from fire-and-forget broadcasting to reliable point-to-point delivery to synchronous request-reply. This section is a learning track, not just a reference: it starts with vendor-neutral fundamentals, shows how KubeMQ implements each pattern, helps you pick and combine them, then composes them into real architectures.
One broker, four patterns, every use case.
## How to read this track [#how-to-read-this-track]
Work through it in order, or jump straight to the tier you need. Each step links to the next.
**New to messaging?** Start with the [Concepts](/learn/concepts) — six short pages that explain the ideas every pattern is built on.
## The Four Patterns [#the-four-patterns]
## The Four Patterns at a Glance [#the-four-patterns-at-a-glance]
| Feature | [Events](/learn/events) | [Events Store](/learn/events-store) | [Queues](/learn/queues) | [RPC](/learn/rpc) |
| ------------------ | ----------------------- | ----------------------------------- | ----------------------- | ----------------- |
| Direction | Pub/Sub | Pub/Sub | Point-to-Point | Request-Reply |
| Persistence | No | Yes (disk) | Yes (disk) | No |
| Delivery guarantee | At-most-once | At-least-once | Exactly-once | At-most-once |
| Replay | No | Yes (6 positions) | No | No |
| Acknowledgment | No | No | Yes (manual) | Yes (automatic) |
| Ordering | No | Yes (sequence) | Yes (FIFO) | N/A |
| Response | No | No | No | Yes |
| Dead letter queue | No | No | Yes | No |
| Delayed delivery | No | No | Yes | No |
| Caching | No | No | No | Yes (queries) |
## Which Pattern Should I Use? [#which-pattern-should-i-use]
Use the [interactive decision guide](/learn/guides/choosing-a-pattern) to find the right pattern for your use case.
| If you need... | Use |
| --------------------------------------------- | ----------------------------------- |
| Lowest latency, message loss acceptable | [Events](/learn/events) |
| Pub/sub with no message loss | [Events Store](/learn/events-store) |
| Replay historical messages | [Events Store](/learn/events-store) |
| One consumer per message, guaranteed delivery | [Queues](/learn/queues) |
| Retry, DLQ, delayed delivery | [Queues](/learn/queues) |
| Synchronous request-reply | [RPC](/learn/rpc) |
| Execute action, confirm success | [RPC Commands](/learn/rpc) |
| Request data, get result | [RPC Queries](/learn/rpc) |
## Combining Patterns [#combining-patterns]
Patterns can work together in a single application. KubeMQ's channel routing syntax lets you publish to multiple patterns simultaneously. Here are two common shapes.
*Order pipeline: a command processes the order, emits an event to the durable log, which feeds a queue for reliable fulfillment.*
*CQRS shape: commands write through the event store, the read service subscribes to build its projection, and clients query that read side.*
Channel routing syntax: use `;` to separate channels and `:` to prefix the pattern type:
```text
events:live-feed;events_store:archive;queues:process
```
## Get Started [#get-started]
# Integrations (/integrations)
KubeMQ **integrations** are framework and platform adapters that wire KubeMQ into a
specific framework's programming model — so you keep writing idiomatic NestJS, Spring,
Celery, or Ray Serve code while the adapter handles the messaging underneath. Every
integration is a native gRPC SDK client on port `50000`; there is no separate protocol to
learn and no SDK call to make by hand.
The protocol gateways are documented separately: A2A and MCP under
[**Aiway**](/aiway), and CloudEvents under [**Connectors**](/connectors).
## What an integration is [#what-an-integration-is]
An integration is a thin layer over the native KubeMQ gRPC SDK: it exposes KubeMQ through
a framework's own idioms (decorators, listeners, broker URLs, scalers) and connects to the
broker on `:50000` like any other SDK client.
There are three ways to reach KubeMQ, differing in **what you install** and **where the
bridge runs**:
| Approach | What you install | Where the bridge runs | Wire protocol | Example |
| ------------------------------- | ---------------------------------- | --------------------------------- | ------------------------------------- | -------------------------------------- |
| Native SDK client | a KubeMQ library | in your app | gRPC `:50000` | [Go](/sdks/go), [Python](/sdks/python) |
| Framework adapter (integration) | the adapter package + the gRPC SDK | in your app, inside the framework | gRPC `:50000` | this section |
| Server connector | nothing on the caller | inside kubemq-server | HTTP / JSON-RPC / CloudEvents `:9090` | [Connectors](/connectors) |
An integration **is** a native SDK client — it just sits *inside* a framework, exposing
KubeMQ through that framework's idioms rather than raw SDK calls. A **server connector**,
by contrast, runs inside kubemq-server and accepts a standard wire protocol on the shared
HTTP server, so the caller installs nothing KubeMQ-specific — see
[Connectors](/connectors) for that side of the picture.
Because integrations are gRPC clients, they connect to the **gRPC server on port 50000**,
which runs independently and is **always on**. They are **not** HTTP connectors and need
**no connector enable flag** — `CONNECTORS*_ENABLE` gates only the HTTP connectors
(A2A / MCP / CloudEvents) at `:9090`. The only prerequisite for any integration is a
running KubeMQ broker reachable on `:50000`.
## Architecture [#architecture]
Different apps load different adapters, but they all converge on the same native gRPC SDK
and the same broker on port `50000`.
*Each framework loads its own adapter, but all integrations ride the native gRPC SDK to the broker on :50000.*
## Messaging Framework Adapters [#messaging-framework-adapters]
Wire KubeMQ in as the transport for an application-messaging framework.
## Task & Inference Processing [#task--inference-processing]
Use KubeMQ as the work queue behind distributed task and ML-inference systems.
## Platform & Operations [#platform--operations]
Integrate KubeMQ with the surrounding platform — provisioning, DI, and autoscaling.
## Compare the integrations [#compare-the-integrations]
Every integration is a native gRPC SDK client on `:50000`. They differ by language,
framework, the KubeMQ patterns they expose, and what you install.
| Integration | Language / Runtime | Framework + min version | KubeMQ patterns | Primary use case | Package / install |
| ---------------------------------------- | ------------------------ | ----------------------------- | -------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------ |
| [NestJS](/integrations/nestjs) | TypeScript / Node 20.11+ | NestJS 10.x / 11.x | Events · Events Store · Queues · Commands · Queries | Decorator-driven NestJS microservices | `npm i @kubemq/nestjs-transport kubemq-js` |
| [Spring Boot](/integrations/spring-boot) | Java / Kotlin / JVM 17+ | Spring Boot 3.2.0+ | Events · Events Store · Queues · Commands · Queries | Spring services + Spring Cloud Stream | `io.kubemq:kubemq-spring-boot-starter` |
| [MassTransit](/integrations/masstransit) | C# / .NET 8.0 | MassTransit 8.5+ | Events · Events Store · Queues · Commands · Queries | KubeMQ as a MassTransit transport | NuGet `MassTransit.KubeMQ` |
| [FastStream](/integrations/faststream) | Python 3.11+ | FastStream 0.6.7+ | Events · Events Store · Queues · Commands · Queries | Async, event-driven Python apps | `pip install kubemq-faststream` |
| [Watermill](/integrations/watermill) | Go 1.25+ | Watermill | Events · Events Store · Queues · Commands · Queries | Watermill pub/sub + CQRS in Go | `go get github.com/kubemq-io/watermill-kubemq` |
| [Celery](/integrations/celery) | Python 3.10+ | Celery 5.4+ | Queues (tasks) · result backend | Distributed Python task queues | `pip install kubemq-celery` |
| [Ray Serve](/integrations/rayserve) | Python 3.10+ | Ray Serve 2.50+ | Queues · Queries · Events | Async / sync ML inference | `uv pip install kubemq-rayserve` |
| [.NET Aspire](/integrations/aspire) | C# / .NET 8.0 or 9.0 | .NET Aspire 9.0+ | Container provisioning + DI (all patterns via `IKubeMQClient`) | Provision KubeMQ + wire `IKubeMQClient` | NuGet `KubeMQ.Aspire.Hosting` + `KubeMQ.Aspire.Client` |
| [KEDA](/integrations/keda) | Go (cluster service) | KEDA 2.10+ · Kubernetes 1.27+ | Queue-depth (`Waiting`) metric | Autoscale queue consumers on Kubernetes | Helm `kubemq-keda-scaler` |
## Which integration should I use? [#which-integration-should-i-use]
Power users: the [comparison matrix](#compare-the-integrations) above lists every
integration's language, framework version, patterns, and install command side by side.
| If you need to… | Use |
| ---------------------------------------------------------- | ---------------------------------------- |
| Wire KubeMQ into a NestJS app with decorators & DI | [NestJS](/integrations/nestjs) |
| Add KubeMQ to a Spring Boot service (template + listeners) | [Spring Boot](/integrations/spring-boot) |
| Use KubeMQ as a MassTransit transport (.NET) | [MassTransit](/integrations/masstransit) |
| Build async Python apps with the FastStream framework | [FastStream](/integrations/faststream) |
| Use KubeMQ as a Watermill pub/sub in Go | [Watermill](/integrations/watermill) |
| Run distributed Python task queues (drop-in Celery broker) | [Celery](/integrations/celery) |
| Serve async/sync ML inference on Ray Serve | [Ray Serve](/integrations/rayserve) |
| Provision KubeMQ + wire `IKubeMQClient` in .NET Aspire | [.NET Aspire](/integrations/aspire) |
| Autoscale queue consumers on Kubernetes by queue depth | [KEDA](/integrations/keda) |
## Next steps [#next-steps]
# Back up and restore (/operate/backup-and-restore)
This page shows how to back up the store of a KubeMQ server running in Docker and restore it in place. The store holds your messages, accounts, license records and the installation's identity. When you finish, you have an archive, and a restored server shows the same license and messages.
This page covers one Docker server. Kubernetes has no supported backup procedure yet. Scaling a cluster to zero to copy its volumes does not work: the operator never applies a changed server count. [Contact support](mailto:support@kubemq.io) before relying on a restore.
These commands are for bash on macOS and Linux. On Windows, run them in WSL (Windows Subsystem for Linux), or use the kmq tab of [Try KubeMQ](/deploy/quickstart), which runs natively on Windows.
## Before you start [#before-you-start]
* A KubeMQ server running in Docker as container `kubemq` on volume `kubemq-data`, as [Try KubeMQ](/deploy/quickstart), [Install with kmq](/deploy/install/kmq) and [Install with Docker](/deploy/install/docker) start it.
* kmq, installed as in [Try KubeMQ](/deploy/quickstart#install-kmq), for `kmq license` only.
* A short outage: the server stops while its store is archived, because a running store cannot be copied consistently.
* Free disk space at least the size of the store.
With Podman: run every command with `podman` in place of `docker`.
Sign in to the server with an administrator account, then select the saved context:
```bash title="Terminal"
kmq auth login --api-address http://127.0.0.1:8080 --context-name kubemq --username admin
```
```bash title="Terminal"
kmq context use kubemq
```
The login saves the context; the second command makes it active for the license check after the restore.
Create a private folder for the archive and work inside it:
```bash title="Terminal"
mkdir -p -m 700 kubemq-private
```
```bash title="Terminal"
cd kubemq-private
```
## Steps [#steps]
Steps 1 to 4 back up the store. Steps 5 to 10 restore it and prove your messages came back. A public Debian container does the archiving, because the KubeMQ image has no archive tools. It keeps each file's owner, user 1001.
### Send a check message [#send-a-check-message]
Put one message on a new `backup-check` queue. Step 10 receives it after the restore.
```bash title="Terminal"
curl -s -X POST http://localhost:9090/queue/send \
-H "Content-Type: application/json" \
-d '{"Channel":"backup-check","ClientID":"backup-check","BodyString":"backup-check"}'
```
You should see:
```text title="Output"
{"is_error":false,"message":"OK","data":{"MessageID":"…","SentAt":…}}
```
### Stop the server [#stop-the-server]
```bash title="Terminal"
docker stop kubemq
```
You should see:
```text title="Output"
kubemq
```
### Archive the volume [#archive-the-volume]
```bash title="Terminal"
docker run --rm -v kubemq-data:/data:ro -v "$(pwd)":/backup \
docker.io/library/debian:stable-slim \
sh -c 'tar --numeric-owner -cpf /backup/kubemq-store.tar -C /data . && tar -tf /backup/kubemq-store.tar | head -n 1'
```
The output is the first entry of the new `kubemq-store.tar`. You should see:
```text title="Output"
./
```
On a Linux host with SELinux enforcing, add `:z` to the `$(pwd)` mount: `-v "$(pwd)":/backup:z`.
Keep the archive private and encrypted, with a copy away from this machine. It holds the installation's identity and license records.
### Start the server again [#start-the-server-again]
```bash title="Terminal"
docker start kubemq
```
You should see:
```text title="Output"
kubemq
```
### Stop the server before the restore [#stop-the-server-before-the-restore]
The restore reuses the same container and volume. Nothing is recreated, so the installation keeps its identity.
```bash title="Terminal"
docker stop kubemq
```
You should see:
```text title="Output"
kubemq
```
### Keep a safety archive [#keep-a-safety-archive]
Archive the store you are about to replace. If the restore goes wrong, repeat the next step with `kubemq-store-before-restore.tar` to put it back.
```bash title="Terminal"
docker run --rm -v kubemq-data:/data:ro -v "$(pwd)":/backup \
docker.io/library/debian:stable-slim \
sh -c 'tar --numeric-owner -cpf /backup/kubemq-store-before-restore.tar -C /data . && tar -tf /backup/kubemq-store-before-restore.tar | head -n 1'
```
You should see:
```text title="Output"
./
```
### Replace the store with the backup [#replace-the-store-with-the-backup]
**Data loss:** this command deletes everything in `kubemq-data` before it unpacks the archive. Run it only after the safety archive succeeded. Never run two servers from copies of the same store: they share one installation identity.
```bash title="Terminal"
docker run --rm -v kubemq-data:/data -v "$(pwd)":/backup:ro \
docker.io/library/debian:stable-slim \
sh -c 'find /data -mindepth 1 -delete && tar --numeric-owner -xpf /backup/kubemq-store.tar -C /data && echo restored'
```
You should see:
```text title="Output"
restored
```
### Start the server and wait until it is ready [#start-the-server-and-wait-until-it-is-ready]
```bash title="Terminal"
docker start kubemq && for i in $(seq 60); do curl -fs -o /dev/null http://localhost:8080/ready && echo ready && break; sleep 2; done
```
You should see:
```text title="Output"
kubemq
ready
```
### Check the license [#check-the-license]
```bash title="Terminal"
kmq license
```
The restored server reports the same license adoption identity recorded before the backup. In the `adoption` object, `state` is `accepted` and `durable` is `true`. `stop_cause` is `null`. You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
### Receive the check message [#receive-the-check-message]
```bash title="Terminal"
curl -s -X POST http://localhost:9090/queue/receive \
-H "Content-Type: application/json" \
-d '{"Channel":"backup-check","ClientID":"backup-check","MaxNumberOfMessages":1,"WaitTimeSeconds":5}'
```
The message from step 1 comes back, with its body base64-encoded. You should see:
```text title="Output"
{"is_error":false,"message":"OK","data":{…,"Messages":[{"MessageID":"…","ClientID":"backup-check","Channel":"backup-check","Body":"YmFja3VwLWNoZWNr",…}],"MessagesReceived":1}}
```
## If something goes wrong [#if-something-goes-wrong]
* The server does not start, or never becomes ready: check `docker logs kubemq`.
* `kmq license` reports a problem: see [Troubleshooting](/licensing/troubleshooting).
* You cannot sign in to the dashboard: the restore brought back the accounts the store held when you archived it. See [Dashboard Access and Recovery](/operate/dashboard-access#reset-a-forgotten-password).
## Next steps [#next-steps]
* [Upgrade KubeMQ](/deploy/upgrade): back up first, then upgrade.
* [Production checklist](/deploy/production-checklist): what else a server you rely on needs.
# Dashboard Access and Recovery (/operate/dashboard-access)
## Docker dashboard access [#docker-dashboard-access]
This page describes the Docker first-login behavior in the next KubeMQ image. Existing
images and existing storage retain their configured administrator behavior.
For a fresh standalone Docker volume, open
[`http://localhost:8080`](http://localhost:8080). The first visitor creates the
administrator username and a password of the minimum length the setup screen shows. KubeMQ signs that user in
immediately after the matching password confirmation. No setup token, generated password,
reverse proxy, or second password change is required for this local HTTP flow.
The default Docker and Compose commands publish port `8080` as
`127.0.0.1:8080:8080`. The dashboard and management API stay on your local machine.
Messaging traffic remains available through its configured ports and authentication.
## Returning users and seeded accounts [#returning-users-and-seeded-accounts]
Sign in with the username and password created on the first visit. The `kubemq-data`
named volume persists that account across restarts and container replacement. Keep the
volume mounted at `/kubemq/store`.
For the fresh Docker first-login flow, leave `API_AUTH_ENABLE` unset and create the
administrator in the browser. To use the older explicit seeded-account configuration, set
`API_AUTH_ENABLE=true`, `API_ALLOW_ORIGINS=https://dashboard.example.com`, and
`API_AUTH_TRUSTED_TLS_PROXY=true` behind a TLS-terminating proxy for that exact HTTPS origin.
Also set `KUBEMQ_API_ADMIN_PASSWORD` (or `KUBEMQ_API_ADMIN_PASSWORD_FILE`) and optionally
`KUBEMQ_API_ADMIN_USERNAME`; an unset username is `admin`. A seeded administrator must
change its password after the first sign-in. On later starts an existing administrator
remains authoritative; seed variables do not overwrite it unless you use recovery.
Set `API_AUTH_ENABLE=false` only when you intentionally need an unauthenticated
management API and dashboard. An explicit value is honored. Existing unconfigured storage
keeps its prior authentication mode.
## Reset a forgotten password [#reset-a-forgotten-password]
Stop the regular Compose container, then run a one-off server against the same named
volume. Set `KUBEMQ_API_ADMIN_USERNAME` to the exact username you originally chose.
```bash title="Terminal"
export KUBEMQ_API_ADMIN_USERNAME=YOUR_EXISTING_USERNAME
read -rsp 'New dashboard password: ' KUBEMQ_API_ADMIN_PASSWORD; echo
export KUBEMQ_API_ADMIN_PASSWORD
docker compose stop kubemq
```
```bash title="Terminal"
docker compose run --rm --no-deps \
-e KUBEMQ_API_ADMIN_USERNAME \
-e KUBEMQ_API_ADMIN_PASSWORD \
kubemq /kubemq/kubemq-run --reset-admin-password
```
Wait for the `admin password force-reset applied` message and for the one-off server to
become ready. It stays in the foreground because the reset flag starts a server. Press
Control+C only after that, then start the normal container.
```bash title="Terminal"
docker compose up -d
unset KUBEMQ_API_ADMIN_PASSWORD KUBEMQ_API_ADMIN_USERNAME
```
The command passes `--reset-admin-password` to the KubeMQ image and preserves the named
volume. For a mounted secret file, export `KUBEMQ_API_ADMIN_PASSWORD_FILE` with its
in-container path, then replace `KUBEMQ_API_ADMIN_PASSWORD` with
`KUBEMQ_API_ADMIN_PASSWORD_FILE` in the command and its `-e` argument. The username must
still match the existing administrator. Do not run `docker compose down -v` or delete
`/kubemq/store` to recover access.
If the authentication database is missing, restore the original `/kubemq/store` volume
or [a backup](/operate/backup-and-restore) when available. Without a backup, stop the regular container and repeat the
one-off command above with `--clean-accounts --reset-admin-password` in place of
`--reset-admin-password`. Set the administrator username and a new password first.
This rebuilds administrator access without deleting broker messages, but any previous
management accounts and service-account keys must be recreated. Stop the one-off server
after it becomes ready, then start the regular container. Never delete the volume or
onboarding state to reset access.
For a corrupt onboarding marker or database, restore a valid volume or backup. Contact
[support@kubemq.io](mailto:support@kubemq.io) if no valid backup is available.
## License, port, and access problems [#license-port-and-access-problems]
A license problem can stop the server before the dashboard starts. Check `kmq license` or
`docker logs kubemq`, then see [Troubleshooting](/licensing/troubleshooting), for example
[Evaluation finished](/licensing/troubleshooting#evaluation-expired).
The dashboard can create a `read_write` service-account key for `kmq` or other management
automation. That `kmq_...` Bearer key is separate from `KUBEMQ_LICENSE_KEY`; a license key
does not authenticate a management client.
The dashboard and management API use port `8080`. Messaging clients use ports such as
gRPC `50000` and REST `9090`; a dashboard sign-in problem does not by itself stop those
clients.
## Kubernetes dashboard access [#kubernetes-dashboard-access]
Kubernetes keeps management authentication explicit. Set `spec.api.auth.enable: true`.
Without `spec.api.auth.adminSecretRef`, the operator creates and retains a Secret named
`-api-admin`. Its password key defaults to `admin-password`.
Use the exact browser-facing HTTPS origin in `spec.api.allowOrigins`. A wildcard origin is
rejected when management authentication is enabled; with no origins, the dashboard accepts only its own origin.
```yaml title="kubemqcluster.yaml"
spec:
api:
allowOrigins:
- https://dashboard.example.com
auth:
enable: true
trustedTLSProxy: true
```
```bash title="Terminal"
kubectl get secret -n YOUR_NAMESPACE YOUR_CLUSTER-api-admin \
-o jsonpath='{.data.admin-password}' | base64 --decode; echo
```
Sign in as `spec.api.auth.adminUsername`, or `admin` when that field is unset. If you set
`spec.api.auth.adminSecretRef`, read that supplied Secret using its configured
`spec.api.auth.adminSecretKey` instead. The operator does not overwrite a supplied Secret.
Browser session sign-in requires HTTPS. Put the API behind a TLS-terminating proxy and set
`spec.api.auth.trustedTLSProxy: true`; this allows the server to issue its secure session
cookie for the browser-facing HTTPS origin. A plain `kubectl port-forward` is useful for
probes, but it does not provide a secure browser session. See
[Install on Kubernetes](/deploy/install/kubernetes) and [Security](/configure/reference/security).
Browser sessions are currently local to one pod. Route a browser consistently to the same
pod after sign-in. Log in again after that pod is replaced. If a load balancer sends the
browser to different pods and creates repeated login loops, configure its session affinity
or contact [support@kubemq.io](mailto:support@kubemq.io).
For help, email [support@kubemq.io](mailto:support@kubemq.io) or open an issue in the
[KubeMQ community repository](https://github.com/kubemq-io/kubemq-community).
# Operate KubeMQ (/operate)
Once KubeMQ is deployed and configured, this is where you keep it healthy. KubeMQ exposes metrics, distributed tracing, structured logging, and an audit trail, so you always have visibility into what the server is doing and can catch issues early. Operators interact with a running broker through the web dashboard and the kmq CLI.
# kmq CLI (/operate/kmq-cli)
`kmq` is KubeMQ's native command-line client for macOS, Linux, and Windows. It manages onboarding, protected credentials, saved deployment plans, messaging, and operations. Messaging and server inspection use the authenticated management API; deployment commands invoke your explicitly selected Docker, Podman, Helm, and Kubernetes tools.
## Overview [#overview]
`kmq` exposes every messaging pattern — Queues, Events, Events Store, and RPC
(Commands/Queries) — plus full observability (status, metrics, connections, audit,
connectors, agents) and a set of meta/discovery commands. Four properties make it
suited to automated and agent-driven use:
* **Token-efficient** — a `kmq queue send` is a few hundred tokens versus a multi-round
exchange over a protocol like MCP.
* **Deterministic** — typed exit codes and machine-readable `json`/`ndjson` output make
results easy to branch on in a script or an agent loop.
* **Self-describing** — `kmq schema` emits the whole command tree, offline, with no
network call.
* **Bounded by default** — every stream/subscribe/replay command honors
`--count`/`--duration`/`--idle`, so an agent can never loop forever waiting on it.
`kmq` does not embed the broker. To run a server, use [Install with kmq](/deploy/install/kmq) or [Install with Docker](/deploy/install/docker). A successful install command is followed by authentication, intended-license verification, and a real messaging check. `kmq mcp` inspects the server's registered tools; it does not make kmq itself a protocol server.
## Architecture [#architecture]
Messaging and server-operation commands use the management API: one-shot actions dispatch via `POST /api/request`
(`{type, data}`) or dedicated REST routes, and streaming commands use Server-Sent
Events / WebSocket subscription endpoints. Meta commands (`schema`, `cheat`, `skills`)
serve content **compiled into the binary**, so they work fully offline and never need
the server.
## Installation [#installation]
Install kmq on macOS, Linux or Windows as shown in [Try KubeMQ](/deploy/quickstart#install-kmq). `kmq version --check` tells you whether a newer release exists, and `kmq update` installs the latest release.
## Contexts & configuration [#contexts--configuration]
A **context** is a named connection profile (API address, token, TLS, defaults).
Contexts live under `$XDG_CONFIG_HOME/kmq/` (`~/.config/kmq/` by default):
```text
$XDG_CONFIG_HOME/kmq/
├── contexts/
│ ├── default.json
│ └── prod.json
└── current-context # pointer file (active context name)
```
```sh
kmq auth login --username admin --api-address https://kubemq.example.com:8080 --ca-file trusted-ca.pem --context-name prod
kmq context use prod
kmq context list
kmq context current
kmq context delete staging
```
The login command uses the supplied customer username and prompts for the password, creates a dedicated service credential, saves it through protected credential storage, and binds its reference to the endpoint. Use `kmq auth setup` when initial setup is required. Use `kmq auth import --token-stdin` to receive an existing service credential through protected input. Do not pass passwords or service tokens in command arguments.
For an installation record, add `--installation INSTALLATION_ID`. For Kubernetes bind one context per verified server endpoint. Public certificate files go in `--ca-file`; never disable verification for a non-loopback management endpoint. Local single-server loopback can use `http://127.0.0.1:8080`.
Native credential storage is the default. Where unavailable, explicitly select `--credential-backend file` and a private `--credential-dir`; protect that directory and include it in your credential backup policy. Ordinary context files store credential references, not plaintext service keys.
Configuration is resolved by precedence, highest to lowest:
| Precedence | Source |
| ----------- | ----------------------------------------------- |
| 1 (highest) | Persistent flags (`--context`, `--api-address`) |
| 2 | Environment variables |
| 3 | Active-context file |
| 4 (lowest) | Built-in defaults (`http://127.0.0.1:8080`) |
| Env var | Purpose |
| ----------------- | --------------------------------------------------------------------- |
| `KMQ_TOKEN` | Service-account Bearer key (`kmq__`) — preferred in CI |
| `KMQ_CONTEXT` | Active context name (overrides the pointer file) |
| `KMQ_API_ADDRESS` | Management API URL |
### Authentication & roles [#authentication--roles]
The onboarding recipes enable server authentication. See [Security](/configure/reference/security) for the account model and roles. Check whether it is on with `kmq doctor -o json | jq .auth`
(`on`/`off`). When auth is on, supply a service-account key through protected credential storage or a securely injected `KMQ_TOKEN` in automation. Avoid shell history and process arguments. Service-account roles gate what the CLI can do:
| Role | Grants |
| ------------ | ---------------------------------------------------------------------- |
| `read_only` | list/inspect, metrics, status, overview, schema, doctor, `license` |
| `read_write` | the above + send/receive/stream/subscribe/purge, channel create/delete |
| `admin` | the above + audit, account management |
A handful of commands and routes succeed with **no token**, even when server auth is
on: `kmq doctor`, `kmq metrics scrape` (routes `/ready`, `/health`, `/metrics`,
`/api/v1/auth/status`). Don't read the role table above as universal gating — these are the
exceptions. `kmq license` needs a signed-in context with at least the `read_only` role;
`kmq license --detail full` returns the full license record.
`config set`/`revert` and account management require the `admin` role. Service accounts
never carry `admin`, so those operations are deliberate non-goals of the CLI.
## Global flags & output discipline [#global-flags--output-discipline]
Persistent flags are inherited by every subcommand:
| Flag | Default | Purpose |
| --------------- | --------- | ----------------------------------------------------------- |
| `-o, --output` | `json` | Output format: `json` \| `ndjson` \| `yaml` \| `table` |
| `--context` | — | Use a specific context (overrides current-context) |
| `--api-address` | — | Target `:8080` endpoint (overrides context) |
| `--no-color` | `false` | Disable color in table output |
| `--verbose` | `false` | Request timing to stderr (token redacted) |
| `--yes` | `false` | Confirm destructive operations without prompting |
| `--dry-run` | `false` | Render the action without executing |
| `--fields` | — | Project output to these camelCase wire fields |
| `--detail` | `summary` | `summary` \| `full` verbosity, for commands that support it |
Output discipline:
* **Data → stdout**, warnings/errors/diagnostics → **stderr** — safe to pipe.
* One-shot commands default to compact `json`; **streaming** commands (`queue stream`,
`*subscribe`, `*replay`, `conn watch`, `command/query receive`) default to
**`ndjson`** (one record per line, flushed per record).
* `metrics scrape` emits raw Prometheus text; `cheat` and `skills get` emit raw
markdown — for those, `-o` is ignored.
```sh
kmq queue receive orders --count 10 -o ndjson | jq .body # stream, per-line
kmq estore replay telemetry --from-first --count 100 -o json # buffer then array
kmq status --fields is_healthy,channels,clients
```
## Exit codes [#exit-codes]
`kmq` returns typed exit codes so scripts and agents can branch deterministically. On
error it also writes a JSON envelope to stderr: `{"error":{"code":"...","message":"...","retryable":bool}}`.
| Code | Name | Meaning | Retry? |
| ---- | --------- | --------------------------------------- | ------------------------ |
| 0 | OK | Success | — |
| 1 | Generic | Unclassified error | No |
| 2 | Usage | Bad flags / usage | No |
| 3 | NotFound | Resource not found | No |
| 4 | Auth | Auth required / failed / forbidden | No |
| 5 | Conn | Server unreachable | Yes (server down?) |
| 6 | Timeout | Request timed out | Yes |
| 7 | Partial | Partial success | Case-by-case |
| 8 | Retryable | Server initializing / too many attempts | Yes — `kmq` auto-retries |
Server wire codes map onto this table as follows: `auth_required`, `auth_failed`,
`forbidden`, `must_change`, and `tls_required` all map to exit code **4**;
`auth_initializing` and `too_many_attempts` map to exit code **8** and are
auto-retried; `seed_read_only`, `duplicate`, and `service_admin_forbidden` map to exit
code **2**; any empty or unknown wire code maps to exit code **1**.
## Command reference [#command-reference]
Every send command reads its body from (in priority) a positional argument →
`--body-base64` → `-f/--file` → stdin, and accepts `--message-id`/`--client-id`/
`--metadata`/`-M`/`--tag k:v` (repeatable). Every stream/subscribe/replay/receive
command accepts the bounding flags `--count N`, `--duration 5m`, `--idle 30s` —
whichever fires first stops it; Ctrl-C also exits cleanly with code 0.
### Onboarding and deployment [#onboarding-and-deployment]
| Command | Purpose |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `trial request --input FILE`, `verify`, `claim`, `resume` | Request a trial key for one Docker server (a JSON file with your email, name, company, `platform` and `consent`), prove your email, and save the key as a protected credential; for Kubernetes, request a trial key through [Plans compared](/licensing#buy) |
| `license import`, `list`, `show`, `export`, `recover` | Manage protected credentials. `license` alone shows the license state of the signed-in server; see [Check license status](/licensing/how-it-works#check-license-status) |
| `license fingerprint --kube-context CONTEXT --namespace NS` | Read the Kubernetes fingerprint through the server ServiceAccount after independent operator installation |
| `deploy prepare` | Stage pinned artifacts and missing Kubernetes prerequisites |
| `deploy plan --out PRIVATE_PLAN` | Inspect the target and save its identities and artifact references |
| `deploy apply --plan PRIVATE_PLAN` | Apply or resume the same saved operation |
| `onboard` | Prepare a plan and apply a simple installation |
| `deploy status`, `restart`, `remove --installation ID` | Operate on the exact saved owned installation |
| `deploy update --installation ID --credential REF` | Replace a license while preserving data and installation identity |
| `deploy forward --installation ID --server-index N` | Hold a bounded, identity-checked forward to one Kubernetes server |
| `deploy diagnose --installation ID` | Report bounded reviewed runtime failure categories |
| `deploy connect` | Record an existing target for connection without lifecycle authority |
| `auth setup`, `login`, `import`, `use` | Bootstrap or bind protected management credentials |
| `deploy verify --installation ID` | Check intended license acceptance and authenticated messaging |
Step-by-step use: [Install with kmq](/deploy/install/kmq) and [Install on Kubernetes](/deploy/install/kubernetes). Non-interactive workflows return an actionable state when email proof, browser verification, credentials, or user input is still needed. They must not guess missing secrets or turn a partial operation into success. Reuse saved operation IDs after a lost response; do not create duplicate trials or runtimes.
### Messaging [#messaging]
| Pattern | Send | Receive / Subscribe | Notes |
| ----------------------------------- | ------------------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Queue](/learn/queues) | `kmq queue send ` | `kmq queue receive [--count N]` | persistent, at-least-once |
| Queue (peek) | — | `kmq queue peek [--count N]` | non-consuming |
| Queue (interactive) | — | `kmq queue stream [--visibility 60] [--wait 5] [--auto-ack]` | WS poll/ack/reject session |
| Queue (drain) | — | `kmq queue purge --yes` | destructive |
| [Events](/learn/events) | `kmq events send ` | `kmq events subscribe [--group g]` | fire-and-forget pub/sub |
| [Events Store](/learn/events-store) | `kmq estore send ` | `kmq estore subscribe ` | persistent + replayable |
| Events Store (replay) | — | `kmq estore replay ` | historical replay — one offset mode: `--new-only` (default), `--from-first`, `--from-last`, `--from-sequence N`, `--from-time `, `--since-seconds N`, plus `--group` |
| [Command](/learn/rpc) (RPC) | `kmq command send --timeout 30` | `kmq command receive [--respond-body '{}' \| --command 'sh']` | request/ack |
| [Query](/learn/rpc) (RPC) | `kmq query send --timeout 30` | `kmq query receive [--respond-body '{}' \| --command 'sh']` | request/data |
**Queue send** extras: `--max-receive-count`, `--dead-letter `,
`--expiration-seconds`, `--delay-seconds`.
**RPC responders**: `receive` with `--respond-body ''` echoes a static reply;
with `--command ''` the inbound body is piped to the command's stdin and its
stdout becomes the reply; with neither, requests are printed for manual handling.
`--respond-body` and `--command` are mutually exclusive.
### Channels [#channels]
```sh
kmq channel create --type queues|events|events_store|commands|queries
kmq channel delete --type queues --yes
kmq channel list [--type ]
kmq channel inspect # full detail: clients, rates, totals
# per-family shortcuts also exist: kmq queue list / kmq queue inspect
```
### Cluster [#cluster]
```sh
kmq cluster info [--node] # (alias: snapshot) cluster-merged, or --node for local
kmq cluster health # /ready — leadership role, ready/healthy
kmq cluster nodes # topology: node, type, unavailable nodes
```
### Observability [#observability]
```sh
kmq status # composite digest: /ready + snapshot, one-line health
kmq overview [--detail full] # per-pattern rollups (queues / pubsub / request-reply / totals)
kmq metrics scrape # raw Prometheus /metrics (auth-exempt)
kmq metrics history [--metric message_rate|volume_rate|error_rate|messages|bytes]
kmq conn list # active connections (first SSE snapshot)
kmq conn inspect
kmq conn watch # live SSE stream of connection events
kmq audit query [--from ..] [--to ..] [--event-type queue.send] [--limit N] ...
kmq audit stats [--group-by event_type|client_id|category|channel|transport]
kmq connector list # aws / gcp / amqp / amqp10 / stomp / mqtt / ce / kafka
kmq connector inspect [--operation ]
kmq agent list [--limit N] [--offset N] # A2A agents
kmq agent inspect
kmq mcp list # server's registered MCP tools
kmq mcp inspect
```
### Kafka [#kafka]
```sh
kmq kafka probe --bootstrap host:port[,host:port] # dial a source cluster, read-only
kmq kafka probe -b host:port --dial-timeout 30s # override the 15s default
kmq kafka probe -b host:port \
--aws-access-key --aws-secret-key --aws-session-token # MSK IAM
```
`kmq kafka probe` dials a **source** Apache Kafka / MSK / Confluent cluster over the
Kafka wire protocol and reports back the brokers plus their `ApiVersions`. It is
**read-only** — it never produces, commits, or auto-creates topics — so it's safe to
point at a production cluster. Flags: `-b/--bootstrap host:port[,host:port...]`,
`--dial-timeout` (default `15s`), and AWS MSK-IAM auth via
`--aws-access-key`/`--aws-secret-key`/`--aws-session-token`. Run it as a first
connectivity check ahead of the [Migration](#migration) family below, or see
[Migrate from Kafka](/connectors/kafka/how-to/migrate-from-kafka) for the full
workflow.
```sh
kmq kafka share-groups list # every share group the coordinator has sampled
kmq kafka share-groups describe # members + per-partition start offset, lag, in-flight
kmq kafka share-groups reset-offsets --topic --to-earliest # preview only
kmq kafka share-groups reset-offsets --topic --to-offset 42 --execute # write it
```
`kmq kafka share-groups` works with [Kafka share groups](/connectors/kafka/how-to/share-groups)
on the KubeMQ server named by the current context. `list` and `describe` read the same view
as `GET /api/kafka/share-groups`, at most about 10 seconds old. `reset-offsets` writes over the
Kafka wire (`AlterShareGroupOffsets`): pass exactly one of `--to-earliest`, `--to-latest` or
`--to-offset N` (clamped to the partition's log), one or more `--topic`, and optionally
`--partition`. Without `--execute` it only previews each partition's current and target start
offset. Where the group has no start offset yet it is created, so a group's first consumer
starts from it — the way to set share-group start positions after a migration. The bootstrap
address defaults to the context's host on port 9092; pass `--bootstrap` when that does not
apply. Exit codes: **2** for a bad flag or a group id KubeMQ does not accept (containing `/`,
`*` or `>`), **3** for an unknown topic or a group id already in use as a classic group, **8** while a consumer is attached to the group —
`kmq` does not retry that one itself; stop the consumer and run it again. If `--execute` fails
on only some partitions, the others were written: retry just the failed ones with
`--partition`.
### Migration [#migration]
| Command | Flags | Notes |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kmq assess kafka` | `--bootstrap`, `--tls`, `--sasl-mechanism` | Read-only fit assessment of an external Kafka cluster → per-topic READY/CAVEAT/UNKNOWN/BLOCKED + a T1–T4 verdict. Never writes to the source. |
| `kmq migrate assess\|replicate\|translate\|cutover` | `--bootstrap` (all four); `--target-bootstrap`, `--state` (replicate, translate, cutover); `--target-api` (required once per target node) and `--target-context` (replicate, cutover); `--dry-run` (cutover); `--check` (assess) | Four-phase migration (assess → replicate → translate → cutover) from a Kafka cluster to KubeMQ. Assess reads only the source. Replicate and a real cutover refuse a target unless every node reports strict acknowledgment. `cutover --force` is deprecated and refused. |
| `kmq migrate plan` | `--input`, `--output`, `--source-profile`, `--target-profile`, `--target-api`, `--target-context`, `--dry-run` | Author the immutable migration plan from a JSON declaration; the output file is never overwritten. |
| `kmq migrate prepare` | `--input`, `--output`, `--dry-run`, `--apply PLAN_FILE`, `--approve-hash HASH` | Preview, then apply, bounded topic preparation on the target (replicate needs every target topic created first); `--apply` takes the preview's plan file and the exact hash it printed. |
| `kmq migrate job submit` | `--plan`, `--operation`, `--state-pvc`, `--state-user-id`, `--profiles-configmap`, `--service-account`, `--cutover-service-account`, `--credential-secret`, `--target-api` | Run one migration operation as a serialized in-cluster Kubernetes Job, for a target whose Kafka listener is reachable only inside the cluster. The ConfigMap, ServiceAccounts, state volume and any credential Secret must already exist. Cutover runs as separate staged operations. |
| `kmq migrate job status` | `--plan` | Read the observed state of the plan's migration Job. |
For the full narrative (per-source auth, MirrorMaker 2 hybrid, rollback, staged dry-run) see
[Migrate from Kafka](/connectors/kafka/how-to/migrate-from-kafka).
### Meta & discovery [#meta--discovery]
```sh
kmq version # binary version
kmq version --check # compare with the latest published release
kmq update # update this binary to the latest release
kmq whoami # identity + role (auth on), or {"authenticated":false,"auth":"disabled"} (auth off)
kmq doctor # connectivity + auth check (no auth required)
kmq config get [--fields ..] # server config (read-only, server-redacted)
kmq license # license state of the signed-in server (--detail full: the full record)
kmq schema -o json # full command tree + roles + exit codes (offline)
kmq cheat [topic] # embedded recipes (offline)
kmq docs [topic] [--open] # signpost to the online docs + LLM corpus
kmq skills ... # serve/install the agent skill (see next section)
```
`kmq cheat` topics (embedded, offline): `queue`, `events`, `estore`, `rpc`, `drain`,
`subscribe`, `health`, `auth`, `context`, `output`.
`kmq schema -o json` is the machine-readable contract — the full command tree (path,
description, required role, flags), the exit-code table, the server wire error-code
catalogue, and the CLI/server versions — with no network and no auth. It is the
recommended way for an agent to introspect the CLI.
## Agent-skill distribution [#agent-skill-distribution]
The discovery skill is optional. An agent with terminal access can run
`kmq skills get core` directly. That guide is embedded in the installed binary,
so it matches the `kmq` version the agent is using. Installing the discovery skill
helps agents find the guide when a KubeMQ task begins.
```sh
kmq skills # list skills (alias: kmq skills list) → 'core'
kmq skills get core # print the core skill (raw markdown)
kmq skills get core --full # + the full command reference
kmq skills get --all # every skill
kmq skills path [name] # skills source dir, or '(embedded)'
kmq skills install [--global] [--force] # Claude Code skill + AGENTS.md pointer (no Node.js)
```
| Install path | Command | Scope |
| --------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Multi-agent installer | `npx skills add kubemq-io/kmq` | Select a supported agent and project or user scope. Requires Node.js. |
| Claude Code plugin | `claude plugin marketplace add kubemq-io/kmq` | Claude Code |
| Built-in installer | `kmq skills install` | Claude Code skill plus an `AGENTS.md` pointer in the current directory; `--global` writes to the user directory. |
The multi-agent installer [lists supported agents](https://github.com/vercel-labs/skills#supported-agents),
including Claude Code (`claude-code`), Codex (`codex`), Cursor (`cursor`),
GitHub Copilot (`github-copilot`), Gemini CLI (`gemini-cli`), and Windsurf
(`windsurf`). To target one explicitly, run
`npx skills add kubemq-io/kmq --agent codex`. Installation places the skill in
the agent's expected directory; verify that the agent actually loads it before
claiming runtime support for a particular version or configuration.
Install `kmq` first on [macOS or Linux](https://github.com/kubemq-io/kmq/blob/main/install.sh)
or on [Windows x86-64](https://github.com/kubemq-io/kmq/blob/main/install.ps1).
On Windows, download `install.ps1` and run it in PowerShell. After installation,
run `kmq version` and `kmq skills get core` in a new terminal. The skill installer
does not install the `kmq` executable.
## Server communication [#server-communication]
`kmq` speaks to the management API over HTTP. One-shot actions dispatch as
`POST /api/request` with `{type, data}` (or dedicated REST routes); the server replies
HTTP 200 with an envelope:
```json
{ "error": false, "error_string": "", "code": "", "data": {} }
```
`error: false` decodes `data` into the requested output; `error: true` maps the `code`
field to an exit code via the wire-code table above. A handful of routes are auth-exempt
(no Bearer needed) — the same ones called out in the **Auth-exempt commands** note above.
Retryable server states (`auth_initializing`, `too_many_attempts`) are auto-retried
with exponential backoff, cancellable by SIGINT/SIGTERM. Streaming uses SSE/WebSocket
subscription endpoints and stops on the first of `--count`/`--duration`/`--idle` or a
signal. SIGINT/SIGTERM cancel the root context — streaming/waiting commands close
gracefully and exit 0 on clean cancellation.
## Related [#related]
# Web Dashboard (/operate/web-dashboard)
The web dashboard is the primary visual surface for a running KubeMQ broker. It's a
single-page application served on port **8080** that shows cluster health, per-channel
throughput, connected clients, protocol connectors, AI agents, the audit trail, and live
configuration.
## Overview [#overview]
The dashboard is an embedded SPA served by the [management API](/operate/observability/api-reference).
Every number it renders comes from the same metrics collectors that feed the Prometheus
exporter and the JSON management endpoints — the dashboard is one view over that data, not
a separate source of truth.
The dashboard is **read-only for messaging data**. Producing and consuming happen through
the client SDKs, the REST/gRPC API, or a drop-in connector — never from the UI. The only
write paths in the dashboard are control-plane operations: editing or reverting
configuration, and managing accounts.
## Access [#access]
| Property | Value |
| ---------------- | ----------------------- |
| Local Docker URL | `http://localhost:8080` |
| Served by | Management API |
| Bundle | Embedded SPA |
The fresh-Docker sign-in flow described here is the target behavior for the next KubeMQ
image. Existing images and existing storage retain their configured behavior.
A fresh standalone Docker volume opens a create-administrator screen. Choose a username
and a password of the minimum length the setup screen shows, then continue directly to the dashboard. Returning
users sign in with that username. An explicitly seeded account uses
`KUBEMQ_API_ADMIN_USERNAME` and its configured password.
The management API and dashboard are protected by this sign-in flow. It does not change
messaging clients, which continue to use their existing authentication and licensing
configuration. See [dashboard access and recovery](/operate/dashboard-access) for reset
steps, and [Security](/configure/reference/security) for roles.
## The shell [#the-shell]
Common controls appear on every page:
* **Left navigation** — switches between the sections listed below.
* **Time range** — selects the window used by all rate charts on the page.
* **Refresh interval** — auto-refresh rate for live values.
* **Theme** — light / dark toggle.
* **Language** — UI localization.
## Navigation map [#navigation-map]
## Sections [#sections]
### Overview [#overview-1]
The landing page. Aggregate cluster health, total send/receive rates across all patterns,
and a connector band summarizing every active protocol connector at a glance. Use it as
the daily starting point before drilling into a specific channel or connector.
### Channels [#channels]
One page per messaging family — [Events](/learn/events),
[Events Store](/learn/events-store), [Queues](/learn/queues), and
[Commands / Queries](/learn/rpc) (RPC). Each page lists the channels of that family
with their current rates and, where applicable, depth. Clicking a channel opens a detail
view with throughput and backlog history over the selected time range, plus the clients
attached to it.
Key per-channel values:
* **Send / receive rate** — current-activity message rate (msg/s).
* **Waiting** (Queues) — messages ready and waiting for a consumer.
* **Delayed** (Queues) — messages scheduled for future delivery.
* **Clients** — connected producers/consumers on the channel.
### Clients [#clients]
Every client connected to the broker: identity, channels in use, and activity. Use it to
confirm expected consumers are attached and to spot clients that connected or dropped.
### Connectors [#connectors]
One page per drop-in protocol connector — [Kafka](/connectors/kafka), [AWS SQS/SNS](/connectors/aws),
[Google Pub/Sub](/connectors/gcp-pub-sub), [MQTT](/connectors/mqtt),
[AMQP 0-9-1](/connectors/rabbitmq), [AMQP 1.0](/connectors/amqp),
[STOMP](/connectors/stomp), and [CloudEvents](/connectors/cloudevents). Each shares the same shape: connection/link
counts, per-operation throughput, error rates, and history charts specific to that
protocol's operations. These pages are how you confirm a drop-in connector is receiving
client traffic and mapping it onto KubeMQ channels.
The **Kafka** page goes further than the others, because a Kafka estate is usually managed by
topic and consumer group rather than by connection. Besides the overview and throughput charts it
has tabs for **topics** (drill into a partition to see its offsets), **consumer groups** (members,
assignments, and lag per partition — the number to watch while repointing consumers),
**consumers**, and **connections** (each client connection, drill-down included). Kafka SASL users
are managed under **Settings → Kafka**. The page only appears when the Kafka connector is running;
if it is missing, check the server log for the ERROR that says why the connector was turned off.
### Agents [#agents]
**A2A** and **MCP** pages showing registered AI agents, their liveness, and request
throughput/latency. See [Aiway](/aiway).
### Accounts [#accounts]
Present when control-plane authentication is enabled. Manage user and service accounts,
assign roles, and issue/revoke API keys. Gated to the admin role. See
[Security](/configure/reference/security).
### Audit [#audit]
The audit trail — control, data, and system events — with filtering. The who-did-what
record for management and messaging activity. See [Audit Logging](/operate/observability/audit).
### Config [#config]
A live view of the effective server configuration, with the ability to change and revert
it. A control-plane write path, gated by role. See
[Security](/configure/reference/security) for who can write, and
[Observability settings](/configure/reference/observability) for the fields shown.
### System [#system]
Node and cluster status: per-node health, cluster membership, and liveness. In a
multi-node deployment, most metric pages present cluster-wide aggregates while System
exposes the per-node breakdown.
The dashboard home page and **Settings → License** show the license state. For scripts, run
`kmq license` or read `GET /api/v1/license` from the management API;
[Check license status](/licensing/how-it-works#check-license-status) explains what `kmq license`
shows. The Config page lists the licensing settings with the key and file data redacted.
## How to read the numbers [#how-to-read-the-numbers]
* **Rates** are current-activity deltas in messages/second — short spikes under bursty
producers are normal; a sustained slope is the signal that warrants action.
* **Depths** (waiting, delayed, backlog) are point-in-time counts, not rates.
* A rising **Waiting** count while the receive rate stays flat means consumers are not
keeping up. A non-zero **Delayed** count is intentional scheduling, not a stuck queue.
The same values are exported as Prometheus metrics and available on the JSON management
API. See [Prometheus Metrics](/operate/observability/metrics) and the
[Management API](/operate/observability/api-reference).
## Related [#related]
# Client SDKs (/sdks)
KubeMQ ships **official client libraries for ten languages**, each a thin, idiomatic wrapper over the same gRPC API. Every SDK speaks the four messaging patterns — [Events](/learn/events), [Events Store](/learn/events-store), [Queues](/learn/queues), and [RPC](/learn/rpc) — so the concepts you learn in one language carry directly to the rest.
Pick your language below, or expand it in the sidebar — the trees are structured identically, so `reference/client` in Go maps to `reference/client` in Python.
## Choose your language [#choose-your-language]
## No SDK for your language? [#no-sdk-for-your-language]
Every KubeMQ operation is also available over the **REST and WebSocket APIs**, so any language with an HTTP client can talk to KubeMQ. See the [Quick Start](/deploy/quickstart) for a language-agnostic first message.
# Release notes (/release-notes)
Release notes for the KubeMQ server, the kmq command-line tool, the operator and the Helm chart. Each release page lists the exact artifact versions, what to check before you upgrade, and what changed.
## Current release [#current-release]
The install commands on this site were last checked against **KubeMQ 3.6.18**, released 2026-10-12. Newer releases are listed below. [What changed in 3.6.18](/release-notes/v3-6-18).
| Artifact | Version | Reference | Digest |
|---|---|---|---|
| kmq | `v3.6.18` | [`kubemq-io/kmq`](https://github.com/kubemq-io/kmq/releases/tag/v3.6.18) | — |
| Server image | `v3.6.18` | `europe-docker.pkg.dev/kubemq/images/kubemq-next` | `sha256:a17818811434828b22550b2c16ab8fbff56db9bed704d8a1c97f0673bce656c5` |
| Operator image | `v3.6.0` | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next` | `sha256:fb48e31c3bebb2d99a15cb9bf5fad9b733ee0473d7aab685f81508a176f0ef25` |
| Helm chart | `3.6.0` | `kubemq-next/kubemq-next` | `sha256:b79c7641abade7300084bfb4245d8325e27f93fe0154ee349e90247aeaee6822` |
## All releases [#all-releases]
Newest first. [How KubeMQ versions work](/release-notes/versioning) explains the jump from 1.3 to 3.3 and how the legacy product differs.
| Release | Date | Highlights |
| ----------------------------------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [3.6.18](/release-notes/v3-6-18) | October 12, 2026 | Kafka failover, topic deletion and authorization fixes; storage-path latency improvements; production upgrade and rollback constraints |
| [3.6.0](/release-notes/v3-6-0) | September 28, 2026 | A clustered next engine spreads partition leadership across every node by default; a next-engine data directory needs a fresh volume; Kafka failover, share-group and correctness fixes |
| [3.5.5](/release-notes/v3-5-5) | September 28, 2026 | Published multi-arch server image no longer mislabels its `amd64` child; rebuilt-node boot identity retries; kmq commands for administering a rebuilt server |
| [3.5.4](/release-notes/v3-5-4) | September 27, 2026 | kmq's Kafka loopback advertising and Kubernetes status reads fixed; subcommands stop inheriting server flags; Kubernetes migration path closes a round of real-run failures |
| [3.5.3](/release-notes/v3-5-3) | September 27, 2026 | Kafka connections from current clients no longer drop; `OffsetFetch` v1 support; `kmq deploy` publishes Kafka and AMQP ports by default |
| [3.5.2](/release-notes/v3-5-2) | September 27, 2026 | Server images for `linux/arm64` as well as `linux/amd64`; 6-character management password minimum; kmq sign-in prompts and error reasons |
| [3.5.1](/release-notes/v3-5-1) | September 27, 2026 | Kafka share groups generally available; `kmq update` and `kmq version --check` |
| [3.5.0](/release-notes/v3-5-0) | September 25, 2026 | kmq installs and licenses KubeMQ; single-server Podman; HTTPS management API; operator and cluster as separate Helm releases |
| [3.3.0](/release-notes/v3-3-0) | September 23, 2026 | Only supported installations start; first dashboard administrator on Docker; Kubernetes clusters need 3 or more servers |
| [Releases 1.0–1.3](/release-notes/next-v1) | September 18–21, 2026 | `-next` artifact names, `next.kubemq.io/v1` API group, Kafka and RabbitMQ on by default, evaluation without signup |
| [Legacy KubeMQ (kubemq image)](/release-notes/legacy) | August 2026 | The legacy product up to v3.1.4: protocol connectors, new storage engine, rebuilt dashboard, ten SDKs |
## Staying up to date [#staying-up-to-date]
Every install command on this site installs the latest release, so you never type a version number. Each release page lists the exact versions that release contains.
* Upgrade a running install: [Upgrade KubeMQ](/deploy/upgrade).
* What `-next` means and how versions work: [Artifacts and versions](/deploy/install/requirements#artifacts-and-versions).
* On the older `kubemq` image or chart: [Move from legacy KubeMQ](/deploy/upgrade/from-legacy).
* Questions about a release? Reach us at [support@kubemq.io](mailto:support@kubemq.io).
# Legacy KubeMQ (kubemq image) (/release-notes/legacy)
**This page is about the legacy product**: the `kubemq` server image and the Helm charts in `kubemq-io/charts`. Its v3.1.4 is not an earlier release of the current `-next` product, which was renumbered at 3.3.0; see [How KubeMQ versions work](/release-notes/versioning). To move to the current product, see [Move from legacy KubeMQ](/deploy/upgrade/from-legacy).
**KubeMQ v3.1.4 · August 2026.** KubeMQ v3 is the largest release in the product's history. Since v2.10.1, KubeMQ has been rebuilt around a new replicated storage core and extended to speak the messaging protocols your teams already use — Kafka, RabbitMQ, MQTT, AMQP 1.0/JMS, STOMP, AWS SQS/SNS, Google Pub/Sub, and CloudEvents — directly, with no bridges and no code changes.
Everything your applications rely on today keeps working. The native gRPC, REST, and WebSocket APIs and all four messaging patterns — [Queues](/learn/queues), [Events](/learn/events), [Events Store](/learn/events-store), and [Commands/Queries](/learn/rpc) — are unchanged, and in-place upgrades preserve your data and configuration automatically.
## Highlights at a glance [#highlights-at-a-glance]
* **Drop-in protocol support** — your existing Kafka, RabbitMQ, MQTT, AMQP 1.0, STOMP, SQS/SNS, and Google Pub/Sub clients connect directly to KubeMQ, unmodified.
* **New storage engine** — a Raft-based replication and persistence core with a selectable durability contract, alongside the existing engine, which remains fully supported.
* **Ten client SDKs** — the five you use today (Go, Java, C#/.NET, TypeScript, Python) upgraded for v3, plus five new: C++, Kotlin, Ruby, Rust, and Elixir.
* **Framework integrations** — Spring Boot, NestJS, Celery, FastStream, MassTransit, .NET Aspire, Ray Serve, Watermill, and KEDA autoscaling.
* **Rebuilt management dashboard** — per-protocol consoles, live configuration editing, accounts with roles, audit trail, six languages.
* **New kmq CLI** — messaging, cluster administration, observability, and a guided Kafka migration workflow from one binary.
* **OpenTelemetry** — distributed traces and metrics exported over OTLP.
* **Enterprise security** — role-based access control for the management plane, API keys and service accounts, audit logging, and FIPS builds.
* **AI-ready** — a built-in Model Context Protocol (MCP) server and Agent-to-Agent (A2A) support for agentic workloads.
* **New Developer Center** — this documentation site.
## Protocol connectors — use your existing clients [#protocol-connectors--use-your-existing-clients]
In v2, connecting non-KubeMQ clients meant deploying separate connector containers next to the broker. In v3, the broker itself speaks each protocol on its native port. The same client that talks to Kafka, RabbitMQ, or SQS today talks to KubeMQ tomorrow. The wire-protocol connectors — Kafka, RabbitMQ, AMQP 1.0, MQTT, STOMP, AWS SQS/SNS, and Google Cloud Pub/Sub — are disabled by default and enabled per protocol in configuration. gRPC, REST, CloudEvents, MCP, and A2A are on by default. A [migration guide](/connectors/how-to/migration) is available for each ecosystem.
**Correction — September 22, 2026.** The preceding sentence records the v3.1.4 default. In the next line from v1.1.0, Kafka and RabbitMQ / AMQP 0-9-1 listeners are enabled by default. The other wire-protocol connectors remain opt-in.
| Protocol | Ports | In short |
| ----------------------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Kafka](/connectors/kafka) | 9092 / 9093 TLS | Full wire-protocol compatibility — producers (idempotent), consumer groups, offset management, admin operations, multi-partition topics, transactions with exactly-once semantics, log compaction and retention (enabling Kafka Connect and Kafka Streams). Share groups ("Queues for Kafka") in preview. Requires the next storage engine. |
| [RabbitMQ / AMQP 0-9-1](/connectors/rabbitmq) | 5672 / 5671 TLS | Exchanges (direct, fanout, topic, headers), queues, bindings, publisher confirms, dead-letter exchanges with RabbitMQ-exact headers, prefetch, virtual hosts. |
| [AMQP 1.0 / JMS](/connectors/amqp) | 5672 / 5671 TLS | Links, credit-based flow control, durable subscriptions, request/reply — compatible with Qpid JMS, go-amqp, and AMQP.Net Lite, including JMS message selectors. Both AMQP versions share one port with automatic detection. |
| [MQTT 3.1.1 / 5.0](/connectors/mqtt) | 1883 / 8883 TLS / 8083 WS | QoS 0/1/2, shared subscriptions, last-will messages, MQTT 5 user properties and request/response. |
| [STOMP 1.0–1.2](/connectors/stomp) | 61613 / 61614 TLS | All three acknowledgment modes, receipts, heartbeats, request/reply. |
| [AWS SQS / SNS](/connectors/aws) | 4566 | Point your AWS SDK or CLI at KubeMQ — SQS with long polling, visibility timeouts, FIFO queues; SNS topics, subscriptions, and filter policies with Signature-V4 authentication. |
| [Google Cloud Pub/Sub](/connectors/gcp-pub-sub) | 8085 | Emulator-compatible gRPC surface for the official client libraries — publish, pull, streaming pull, ordering keys, filters, dead-letter, seek/snapshots, schema validation. |
| [CloudEvents 1.0](/connectors/cloudevents) | 9090 (on by default) | Native HTTP endpoint for structured and binary CloudEvents — publish into any pattern, consume over server-sent events with resume, route by content (CESQL). |
The built-in connectors supersede the separate kubemq-targets, kubemq-sources, and kubemq-bridges deployments for the protocols above. The external connector containers remain available for other integrations — databases, caches, and third-party services.
## New storage engine [#new-storage-engine]
v3 introduces a new replicated storage engine built on Raft consensus, designed for stronger durability guarantees and safer day-2 operations. Full details: [Storage engines](/configure/reference/storage-engines).
* **Two engines, one server.** The v2 engine ("legacy", unchanged) and the new engine ("next") ship in the same binary and are selected in configuration. New deployments can adopt the next storage engine; existing ones stay on legacy until they choose to migrate.
* **Selectable durability contract** on the next storage engine. In **strict** mode, a message is acknowledged only after it is replicated to a quorum *and* written to disk — zero acknowledged-message loss, even through node crashes. In **fast** mode (the default), acknowledgment follows quorum replication, with disk sync completing in a bounded background window.
* **Engine auto-detection.** On upgrade, the server inspects the existing data directory and resolves the correct engine on its own. It never wipes or reinterprets data on a mismatch — ambiguity is a loud startup error, not a silent guess.
* **Log compaction and time-based retention** on the next storage engine — the same mechanisms that enable Kafka Connect and Kafka Streams support.
* **Engine scope.** The Kafka connector requires the next storage engine. All other connectors and all native messaging patterns run on both engines.
## Clustering and operations [#clustering-and-operations]
Clustering has been rebuilt around the new engine with one focus: predictable failure handling.
* **Safe node replacement.** A node that returns with lost or empty storage no longer rejoins silently. It stays up, reports the reason on its readiness endpoint, and is restored through an explicit, guided `kmq cluster replace` procedure that re-adds it as a learner until it has caught up.
* **Calmer elections.** Pre-vote prevents a rejoining node from disrupting a healthy cluster, and leader changes warm up connector state — Kafka coordinators included — before serving traffic.
* **Kubernetes-aware lifecycle.** Replica identity derives from the pod name, readiness is decoupled from liveness (a booting node reports live while quorum forms, avoiding restart loops), and shutdown phases are sized to the pod's termination grace period.
* **Replication security.** Optional mutual TLS on the cluster replication port.
## New kmq command-line tool [#new-kmq-command-line-tool]
One installable binary for everything that previously needed scripts, curl, or the dashboard. Full reference: [kmq CLI](/operate/kmq-cli).
* **Messaging** — send, receive, peek, stream, and purge queues; publish and subscribe to events; replay the Events Store from six starting positions; send commands and queries and run responders.
* **Cluster administration** — inspect health, members, and nodes; add, promote, remove, and replace members. Mutations are role-gated and confirmation-gated.
* **Observability** — live connection watch, metrics, audit queries, and connector and agent inspection.
* **Kafka migration workflow** — `kmq assess kafka` produces a read-only migration-fitness report of an existing Kafka cluster; `kmq migrate` replicates topics with exact offset mapping, translates configuration, and manages cutover.
* **Automation-friendly** — machine-readable output, typed exit codes, dry-run support, and a complete offline schema of every command.
## Client SDKs — ten languages [#client-sdks--ten-languages]
The SDK family has doubled from five languages to ten, all covering the four messaging patterns over the native gRPC API, each documented with working examples per pattern. Start here: [Client SDKs](/sdks).
* **Upgraded** — Go, Java, C#/.NET, TypeScript (Node.js), and Python: updated and fully compatible with v3.
* **New** — C++, Kotlin, Ruby, Rust, and Elixir.
## Framework integrations [#framework-integrations]
Adapters for the frameworks your teams already use — you keep writing idiomatic framework code; the adapter handles the messaging underneath: Spring Boot, NestJS, Celery, FastStream, MassTransit, .NET Aspire, Ray Serve, Watermill, and KEDA autoscaling on queue depth. Details: [Integrations](/integrations).
## Management dashboard — rebuilt [#management-dashboard--rebuilt]
What was a monitoring view in v2 is now a full management console, protected by login and roles. See [Web dashboard](/operate/web-dashboard).
* **Cluster overview** — health, throughput, storage-engine status, and replication posture per node.
* **Per-protocol consoles** — dedicated pages for Kafka, RabbitMQ-style queues, MQTT clients, AMQP 1.0 links, STOMP destinations, SQS/SNS, Google Pub/Sub, and CloudEvents, each modeled on the console your team already knows.
* **Live configuration** — view and change every subsystem's settings from the UI, with revert support and role gating.
* **Accounts and roles** — user accounts, service accounts, and API keys managed in the UI.
* **Audit trail** — a searchable log of who changed what, and when.
* **Channel monitor** — a live, observe-only tap on any channel.
* **Six languages** — English, Spanish, French, German, Portuguese (Brazil), and Italian, in light and dark themes.
## Observability [#observability]
* **OpenTelemetry** — distributed traces and metrics exported over OTLP (gRPC or HTTP), with W3C trace-context propagation and configurable sampling. Off by default. Setup: [OpenTelemetry guide](/learn/guides/opentelemetry).
* **Metrics that survive restarts** — counters are durable; a server restart no longer resets your Prometheus series.
* **Per-connector metrics** — dedicated metric families for every protocol connector.
* **Audit logging** — control-plane and data-plane events recorded as CloudEvents with configurable retention, queryable from the API, the CLI, and the dashboard. On by default.
## Security and access control [#security-and-access-control]
The management plane — dashboard and management API — is now protected by full authentication and role-based access control. Reference: [Security](/configure/reference/security).
* **Management-plane access control** — user accounts with session login and service accounts with API keys; three roles (read-only, read-write, admin); deny-by-default on every management endpoint; hardened credential storage, login throttling, and CSRF protection. Off by default — existing deployments are unaffected until you enable it.
* **Safer defaults** — the management port binds to localhost unless authentication is enabled or the server runs in a container or Kubernetes; secrets are redacted from configuration views.
* **Data-plane security carried forward** — TLS/mTLS, JWT and OIDC authentication, and policy-based authorization continue as in v2, extended to the new protocol connectors.
* **FIPS builds** — a dedicated FIPS image line, cryptographically verified and vulnerability-scan-gated before publication.
* **Signed supply chain** — release images are vulnerability-scanned before publication; CLI artifacts ship with signed checksums.
## AI and agentic workloads [#ai-and-agentic-workloads]
KubeMQ speaks the two emerging standards for AI-agent communication out of the box. Start here: [AI Way](/aiway).
* **Model Context Protocol (MCP) server built in** — AI assistants and agents send, receive, and inspect KubeMQ messages through standard MCP tools, with no extra infrastructure.
* **Agent-to-Agent (A2A) protocol** — agent registration and discovery, agent cards, synchronous request/reply, and streaming responses, backed by a cluster-replicated agent registry.
* Dedicated dashboard pages for agent and MCP activity.
## Kubernetes and deployment [#kubernetes-and-deployment]
* **Helm charts** — cluster, controller, CRDs, and an umbrella chart.
* **Declarative cluster resource** — a zero-configuration KubemqCluster custom resource; every connector and subsystem is configurable in the spec, with per-connector service exposure.
* **Guard rails** — the operator records the cluster's established storage engine and refuses unsafe changes (engine switches, enabling Kafka on a legacy-engine cluster) instead of applying them silently.
* **License visibility** — license type, holder, and expiry surfaced directly in `kubectl get`.
* **Escape hatches** — an environment-variable overlay and secret projection for tunables the typed spec doesn't cover, with a deny-list protecting settings the operator owns.
## Breaking changes at a glance [#breaking-changes-at-a-glance]
* **Helm installation** — the v2 stable chart line is retired. v3 charts are published on the prerelease channel and require `--devel` on install and upgrade.
* **Storage engine choice is per-deployment** — there is no in-place migration between the legacy and next storage engines. A data directory created on one engine cannot be opened by the other; the server fails loudly rather than converting.
* **Node-rebuild recovery sets a version floor** — cluster nodes rebuilt with the v3 recovery procedure cannot roll back below v3.1.0.
* **Kafka requires the next storage engine** — enabling the Kafka connector on a legacy-engine deployment is a configuration error.
* **Management API surface changes** — some management and statistics endpoints changed between v2 and v3.
* **Storage sizing on the next storage engine** — native retention limits (maximum retention, queue size, and message caps) currently apply on the legacy engine only; plan storage for channels on the next storage engine accordingly.
* **External connector containers superseded** — the separate targets/sources/bridges deployments are replaced by built-in connectors for broker protocols; they remain available for other integrations.
## Known limitations [#known-limitations]
* MQTT retained messages are not supported; the broker advertises this to connecting clients.
* AMQP 0-9-1 transactions are not supported.
* STOMP transactions and selectors are not supported.
* Kafka — replication factor is always cluster-managed; the next-generation consumer protocol (KIP-848) and Kerberos are not supported.
* Native retention limits are not yet enforced on channels on the next storage engine.
**Correction — September 22, 2026.** This limitation records the v3.1.4 behavior. In the next line from v1.2.0, Kafka topic creation accepts a replication factor from 1 through the number of cluster nodes. A requested factor above the node count is refused.
## Upgrading [#upgrading]
To move a legacy installation to the current product, see [Move from legacy KubeMQ](/deploy/upgrade/from-legacy). Adopting the next storage engine or the Kafka connector is a planned migration; see [Storage engines](/configure/reference/storage-engines) and the per-ecosystem [migration guides](/connectors/how-to/migration).
Questions? Reach us at [support@kubemq.io](mailto:support@kubemq.io).
# Releases 1.0–1.3 (before renumbering) (/release-notes/next-v1)
**v1.0.0** is the first release published as **`-next` artifacts**. These are the names every new installation uses. Newer releases are listed first; the v1.0.0 section records the behavior at that release. From 3.3.0 the same product is numbered above the legacy product; see [How KubeMQ versions work](/release-notes/versioning). To install, see [Choose your path](/deploy).
**"next" means two things in KubeMQ.** **`-next` artifacts** and the **next line** are the product line for new installations. The **next storage engine** is the server's storage engine, selected with `store.engine: next`. The storage engine setting and its values (`legacy`, `next`, `auto`) are unchanged by this release.
## v1.3.2 [#v132]
* **Evaluation wording now describes a 14-day evaluation.** The generic evaluation Docker command also exposes Kafka and RabbitMQ ports.
## v1.3.1 [#v131]
* **Standalone data survives container recreation across hostname changes.** The persisted data and evaluation identity remain available when a standalone container is recreated with a different hostname.
## v1.3.0: signup-free evaluation [#v130-signup-free-evaluation]
Fresh standalone installations can start a 14-day evaluation without
signup. Keep the named `/kubemq/store` volume across container
recreation and [continue with a trial key](/deploy/install/docker#add-your-license)
to preserve messages. Kubernetes and clustering still require a key.
**Current licensing rule.** A fresh, eligible standalone server with writable persistent storage can start without a key. Kubernetes deployments, clusters, and stores that already contain data require an explicit license key or signed license file.
## v1.2.0 [#v120]
* **Kubernetes pods must be created by the KubeMQ operator.** The server refuses a hand-written StatefulSet, Deployment, or Pod. Upgrade the operator before the server, because the operator adds the marker that lets the server start.
* **Kafka clusters recover consumer-group routing reliably.** Cluster nodes now use their per-node replication addresses for internal forwarding, and a node whose internal mesh is unavailable reports itself not ready.
* **Kafka client failures are clearer.** Oversized produce requests return `MESSAGE_TOO_LARGE`, older clients can use ListOffsets version 0, and a login sent to a server without Kafka credentials receives an authentication error instead of a disconnected socket.
* **The dashboard shows license status.** The home page and Settings show the plan, instance usage, lease status, last check-in, and expiry. Licensing warnings appear as banners.
## v1.1.0 [#v110]
* **Kafka and RabbitMQ are on by default.** A stock server listens on Kafka port `9092` and RabbitMQ / AMQP 0-9-1 port `5672`. Their TLS ports open when server TLS is configured.
* **Default-on connector failures do not stop the server.** A conflicting port or unsupported storage engine disables the default connector for that run and logs the reason. A connector enabled explicitly still stops startup when it cannot run.
## v1.0.0 historical notes [#v100-historical-notes]
### What shipped [#what-shipped]
* **New artifact names.** All images come from `europe-docker.pkg.dev/kubemq/images` and need no registry login:
| Artifact | Name |
| ------------------- | ------------------------------------------------------------ |
| Server image | `kubemq-next` |
| Server image (FIPS) | `kubemq-next-fips` |
| Operator image | `kubemq-operator-next` |
| Helm chart | `kubemq-next` from `https://kubemq-io.github.io/charts-next` |
* **New Kubernetes API group: `next.kubemq.io/v1`**, with the kinds `KubemqCluster` and `KubemqConnector`. In `kubectl`, use the full resource names `kubemqclusters.next.kubemq.io` and `kubemqconnectors.next.kubemq.io`.
* **One Helm chart.** `kubemq-next` installs the CRDs, the operator, and one cluster in a single release. **Correction — September 27, 2026.** Current charts install the operator and the cluster as two releases; see [Install on Kubernetes](/deploy/install/kubernetes).
* **Versions restart at v1.0.0.** The server, the operator, the chart, and the kmq CLI all carry v1.0.0. These numbers are not comparable with any earlier KubeMQ version number.
* **Tags.** Every image is published as an immutable release tag (`:v1.0.0`) plus the moving tag `:latest`. There is no other channel tag.
* **The kmq CLI keeps its name.** Its image stays `europe-docker.pkg.dev/kubemq/images/kmq`; its version becomes v1.0.0.
* **Licensing at v1.0.0.** Every server then needed a license to start. An online server used a **license key** (`KUBEMQ_LICENSE_KEY`), while air-gapped servers used a signed **license file** (`KUBEMQ_LICENSE_FILE` / `KUBEMQ_LICENSE_DATA`). Kubernetes gained `licenseKey`, `licenseFile`, `licenseKeySecretRef`, and `licenseFileSecretRef`. Current standalone evaluation behavior is documented above.
### Known limitations at v1.0.0 [#known-limitations-at-v100]
* **`linux/amd64` only.** Images are not yet built for other architectures.
* **Dashboard license status arrived in next v1.2.0.** The home page and Settings show licensing state; `GET /api/v1/license` and `kmq license` remain available for automation ([Check license status](/licensing/how-it-works#check-license-status)).
* **Connector images ship in next v1.1.** The Targets, Sources, and Bridges images (`kubemq-targets-next`, `kubemq-sources-next`, `kubemq-bridges-next`) are not part of v1.0.0. Until then, set `spec.image` explicitly on every `KubemqConnector`. Connectors are installed by applying a `next.kubemq.io/v1` manifest — there are no connector Helm charts. **Correction — September 27, 2026.** No default connector image is published. Set `spec.image` on every `KubemqConnector`.
## Coming from legacy KubeMQ [#coming-from-legacy-kubemq]
Moving from the older `kubemq` image or chart: [Move from legacy KubeMQ](/deploy/upgrade/from-legacy).
# Release 3.3.0 (/release-notes/v3-3-0)
**Released September 23, 2026.** This release refuses installation shapes KubeMQ does not support and makes the first minutes of an evaluation easier to follow. It is the first release numbered above the legacy product; see [How KubeMQ versions work](/release-notes/versioning).
## Artifacts [#artifacts]
| Artifact | Version |
| ------------------------ | --------------------------------------------------------------------------------------------- |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next:v3.3.0` |
| Server image (FIPS) | `europe-docker.pkg.dev/kubemq/images/kubemq-next-fips:v3.3.0` |
| Operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next:v3.3.0`, then `v3.3.1` the same day |
| Helm chart `kubemq-next` | 3.3.0 (operator `v3.3.0`, server `v3.3.0`), then 3.3.1 (operator `v3.3.1`, server `v3.3.0`) |
| kmq | No new release |
## Before you upgrade [#before-you-upgrade]
* **Only supported installations start.** The server refuses to start as a native process, under a container runtime other than Docker, as a clustered Docker server, or on Kubernetes without the operator or with fewer than 3 servers. It stops before it reads the license or changes stored data. Move such an installation to a [supported setup](/deploy/install/requirements#supported-setups) before you upgrade. Single-server Podman is supported from [3.5.0](/release-notes/v3-5-0).
* **Kubernetes clusters need at least 3 servers.** The operator refuses to reconcile a cluster with `standalone: true` or fewer than 3 servers, and leaves its running pods and volumes as they are. Move such a cluster before you upgrade. A new cluster also needs a license that covers its server count.
* **Kafka exposed outside a cluster needs per-server addresses.** On a clustered `KubemqCluster`, `spec.kafka.expose` set to `NodePort` or `LoadBalancer` now requires `spec.kafka.peers`. The operator refuses the change before it touches the running cluster.
## Changes [#changes]
* **First administrator on Docker.** On a fresh Docker server, management sign-in is on unless you turn it off, and the first person to open the dashboard chooses the administrator. Until then the dashboard and the management API stay locked; messaging keeps its own security settings. The choice survives restarts and container replacement, and recovering the administrator does not delete messages. Sign-in settings you set yourself are kept.
* **The first minutes say what is happening.** A server started without a license key that cannot reach the license service now logs what it is waiting for and how to proceed. A Kafka connector you enabled by name fails startup when its port is taken, naming the port; the default-on Kafka connector is switched off instead, and the log and the dashboard banner say why.
* **Two licensing terms.** Messages and the dashboard now say "evaluation" for the 14-day run without a key and "trial key" for the 30-day key from the trial form. When an evaluation ends, the message offers both ways forward: add a trial key, or remove the volume, which deletes its messages, and start again.
* **Dashboard.** Empty lists are told apart from failed requests, with a retry. All six dashboard languages are complete.
* **RabbitMQ (AMQP 0-9-1).** Clearing expired messages at the head of a queue no longer loses the live message behind them, and binding destinations are validated.
* **Kubernetes.** On OpenShift, chart 3.3.0 no longer grants the server's service account the `privileged` security context constraint. Operator 3.3.1 changes only the operator's own install manifest, which no longer creates a Role for that constraint; clusters behave as with 3.3.0.
## Known issues [#known-issues]
* Images are published for `linux/amd64` only. Release [3.5.2](/release-notes/v3-5-2) adds `linux/arm64`.
* No default connector image is published. Set `spec.image` on every `KubemqConnector`.
# Release 3.5.0 (/release-notes/v3-5-0)
**Released September 25, 2026.** kmq can now install, license and manage KubeMQ on Docker, Podman and Kubernetes. From this release kmq and the server share one version number. There is no server release 3.4.0.
## Artifacts [#artifacts]
| Artifact | Version |
| ------------------------ | ----------------------------------------------------------------- |
| kmq | `v3.5.0` |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next:v3.5.0` |
| Server image (FIPS) | `europe-docker.pkg.dev/kubemq/images/kubemq-next-fips:v3.5.0` |
| Operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next:v3.4.0` |
| Helm chart `kubemq-next` | 3.4.0 (operator `v3.4.0`, server `v3.5.0`) |
## Before you upgrade [#before-you-upgrade]
* **A server with a license key must reach the license service once after the upgrade.** On its first start on 3.5.0, a server started with a license key contacts the KubeMQ license service (`license.kubemq.io`), even if its last check-in is still valid. This also applies on Kubernetes. Make sure the server can reach the license service when you upgrade; later restarts behave as before. Servers on the evaluation or on an offline license file are not affected.
* **Helm: the operator and each cluster are separate releases.** Chart 3.4.0 refuses to render a release that sets both `operator.enabled` and `cluster.enabled`, and `cluster.enabled` now defaults to `false`. If one release holds both today, move it first: see [Upgrade KubeMQ](/deploy/upgrade#combined-release).
* **`helm uninstall` keeps the cluster.** The chart's pre-delete hook is gone, and setting `preDelete.enabled: true` is refused. Uninstalling a cluster release leaves the `KubemqCluster` and its volumes in place.
* **The management API is same-origin by default.** Before 3.5.0 a web page on any origin could read from the management API; changes from other sites were already refused. To let a web page on another origin call the management API, list that origin in `API_ALLOW_ORIGINS`.
## Changes [#changes]
* **kmq installs and manages KubeMQ.** `kmq onboard` starts a server from simple defaults. `kmq deploy` plans, applies, updates, restarts, diagnoses and removes an installation, and prepares pinned images, the Kubernetes namespace and protected Secrets ahead of an install. See [Install with kmq](/deploy/install/kmq).
* **kmq handles trial keys and licenses.** `kmq trial` requests, verifies and claims a trial key from the command line. `kmq license` saves, lists, shows and exports licenses in a protected local store. `kmq auth` sets up and signs in to the management API and saves the credential.
* **kmq migrates from Apache Kafka.** `kmq migrate` adds `plan`, `prepare`, `target-check`, `rehearse`, `verify`, `report`, `job` and a guarded set of `cutover-*` commands. See [Migrate from Kafka](/connectors/kafka/how-to/migrate-from-kafka).
* **Single-server Podman.** The server runs as one container on Podman as well as Docker.
* **HTTPS for the management API.** Set both `API_TLS_CERT_FILE` and `API_TLS_KEY_FILE`; see [Security](/configure/reference/security). On Kubernetes, operator 3.4.0 reads the management certificate from the TLS Secret named in `spec.api.tlsSecret`.
* **Replacing a license keeps the server.** A new license key or offline license file keeps the server's identity and stored messages. The server never falls back to a cached license that belongs to a different key.
* **Kubernetes cluster identity.** The operator identifies a cluster by its Kubernetes object, not its name: a cluster deleted and re-created under the same name is a new cluster. The operator reports a cluster ready only when the rollout it observed is complete.
## Known issues [#known-issues]
* Images are published for `linux/amd64` only. Release [3.5.2](/release-notes/v3-5-2) adds `linux/arm64`.
* No default connector image is published. Set `spec.image` on every `KubemqConnector`.
# Release 3.5.1 (/release-notes/v3-5-1)
**Released September 27, 2026.** Kafka share groups (KIP-932) are generally available, and kmq can update itself. The operator and the Helm chart are unchanged from [3.5.0](/release-notes/v3-5-0).
## Artifacts [#artifacts]
| Artifact | Version |
| ------------------------ | ----------------------------------------------------------------------------- |
| kmq | `v3.5.1` |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next:v3.5.1` |
| Server image (FIPS) | `europe-docker.pkg.dev/kubemq/images/kubemq-next-fips:v3.5.1` |
| Operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next:v3.4.0` (unchanged) |
| Helm chart `kubemq-next` | 3.4.0 (unchanged; it installs server `v3.5.0`) |
## Before you upgrade [#before-you-upgrade]
* **Kafka share groups: upgrade every server before share traffic resumes.** This release adds new cluster commands for share groups, controlled by `CONNECTORS_KAFKA_SHARE_FEATURE_VERSION` (default `2`). A server still on an older release stops when it meets one of them, and keeps stopping until it is upgraded; on a 3-server cluster this can cost the cluster its majority. Before a rolling upgrade, do one of these:
* Stop share consumers and per-group configuration changes until every server runs 3.5.1, then upgrade normally.
* Set `CONNECTORS_KAFKA_SHARE_FEATURE_VERSION=1` on each server as you upgrade it, and raise it to `2`, with a restart, once every server is upgraded. At `1`, the new share-group features are unavailable: share groups cannot be deleted, per-group configuration writes and `read_committed` share groups are refused, and lock renewal is off.
Downgrading is supported only if the setting stayed at `1` the whole time. Do not set `share.isolation.level=read_committed` until every server runs 3.5.1.
* **New share groups start at the latest offset**, as in Apache Kafka. Existing groups keep their position. To start new groups at the earliest offset, as before, set `CONNECTORS_KAFKA_SHARE_AUTO_OFFSET_RESET=earliest`.
* **Share groups count against `CONNECTORS_KAFKA_MAX_GROUPS`**, the limit that already applies to classic consumer groups. A share group counts until `DeleteGroups` removes it.
* **Rolling restarts count a delivery attempt.** Every share record in flight when a partition's leader changes counts one delivery attempt, including on each server restart of a rolling upgrade. Keep the per-group delivery limit at the default of 5 or higher.
## Changes [#changes]
* **Kafka share groups are generally available**, certified with the Java `KafkaShareConsumer` 4.3 and the Kafka 4.3 console tools on a single server and on 3-server clusters. See [Share groups](/connectors/kafka/how-to/share-groups).
* **Share-group administration:** `ListGroups` with the type filter, `DeleteGroups` once no consumer is attached, per-group settings through `kafka-configs.sh --entity-type groups`, and `read_committed` share groups.
* **Share-group monitoring:** the `kubemq_kafka_share_group_lag`, `kubemq_kafka_share_group_in_flight` and `kubemq_kafka_share_group_redelivered` metrics, `GET /api/kafka/share-groups`, share groups on the dashboard's consumer-groups tab, and `kmq kafka share-groups`.
* **Kafka fixes:** a node that became the Kafka coordinator right after it became ready now loads the committed offsets, and a clustered topic-configuration reload that fails no longer serves empty settings or loses an acknowledged change.
* **kmq updates itself.** `kmq update` installs the latest kmq release, and `kmq version --check` reports whether a newer one exists. On Windows the update is scheduled rather than applied at once.
## Known issues [#known-issues]
* Images are published for `linux/amd64` only. Release [3.5.2](/release-notes/v3-5-2) adds `linux/arm64`.
* No default connector image is published. Set `spec.image` on every `KubemqConnector`.
# Release 3.5.2 (/release-notes/v3-5-2)
**Released September 27, 2026.** Server images are published for `arm64` as well as `amd64`, the management password minimum is 6 characters, and kmq explains sign-in failures. The operator and the Helm chart are unchanged from [3.5.0](/release-notes/v3-5-0).
## Artifacts [#artifacts]
| Artifact | Version |
| ------------------------ | -------------------------------------------------------------------------------------------------- |
| kmq | `v3.5.2` |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next:v3.5.2`, for `linux/amd64` and `linux/arm64` |
| Server image (FIPS) | `europe-docker.pkg.dev/kubemq/images/kubemq-next-fips:v3.5.2`, for `linux/amd64` and `linux/arm64` |
| Operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next:v3.4.0` (unchanged) |
| Helm chart `kubemq-next` | 3.4.0 (unchanged; it installs server `v3.5.0`) |
## Before you upgrade [#before-you-upgrade]
* **Nothing new to prepare.** The operator and the Helm chart are the same as in 3.5.0, and the Helm chart still installs server 3.5.0. Coming from a release before 3.5.1, also read [Before you upgrade in 3.5.1](/release-notes/v3-5-1#before-you-upgrade); coming from 3.3.x, also read [Before you upgrade in 3.5.0](/release-notes/v3-5-0#before-you-upgrade).
## Changes [#changes]
* **Server images for `arm64`.** The server image and the FIPS image are published for `linux/arm64` as well as `linux/amd64`, under one tag, so a container runtime pulls the image for its own architecture.
* **Management password minimum is 6 characters**, down from 12, for the dashboard and the management API. Every refusal states the minimum.
* **kmq sign-in.** `kmq auth setup` states the password minimum in its prompt, checks it before sending anything, asks you to confirm the password on a terminal, and uses `admin` as the administrator name unless you give another. `kmq auth login` asks for the administrator name on a terminal when you omit `--username`.
* **kmq reports the server's reason.** When the management server refuses a request, kmq now shows the reason the server gave, such as a password below the minimum, instead of a general failure.
* **kmq runs an `amd64`-only image on an `arm64` host.** `kmq deploy` on Docker or Podman now selects `linux/amd64` emulation for such an image, and says so in its plan and result, instead of refusing.
## Known issues [#known-issues]
* No default connector image is published. Set `spec.image` on every `KubemqConnector`.
# Release 3.5.3 (/release-notes/v3-5-3)
**Released September 27, 2026.** A Kafka connection from a current client library no longer drops, `OffsetFetch` works with clients that only speak version 1, and `kmq deploy` publishes the Kafka and AMQP ports by default. The operator and the Helm chart are unchanged from [3.5.2](/release-notes/v3-5-2).
## Artifacts [#artifacts]
| Artifact | Version |
| ------------------------ | -------------------------------------------------------------------------------------------------- |
| kmq | `v3.5.3` |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next:v3.5.3`, for `linux/amd64` and `linux/arm64` |
| Server image (FIPS) | `europe-docker.pkg.dev/kubemq/images/kubemq-next-fips:v3.5.3`, for `linux/amd64` and `linux/arm64` |
| Operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next:v3.4.0` (unchanged) |
| Helm chart `kubemq-next` | 3.4.0 (unchanged; it installs server `v3.5.0`) |
## Before you upgrade [#before-you-upgrade]
* **Nothing new to prepare.** The operator and the Helm chart are the same as in 3.5.2. Coming from a release before 3.5.1, also read [Before you upgrade in 3.5.1](/release-notes/v3-5-1#before-you-upgrade).
## Changes [#changes]
* **A Kafka connection from a current client no longer drops on the first request.** `ApiVersions` requests above the server's supported version (3) were decoded with the older request layout before the version check ran, so the decode failed and the connection was torn down. The body is now left undecoded until after the check, so the client gets the existing `UNSUPPORTED_VERSION` reply and renegotiates, as real Apache Kafka 4.3.1 does. This fixed every connection failing against franz-go 1.22.0.
* **`OffsetFetch` works with clients that only request version 1**, such as segmentio/kafka-go. Version 1 has no top-level error field, so a request-wide error — no coordinator, not ready, an invalid group, authorization denied, or a proxy drop — is now repeated on every requested partition instead of the client seeing a silent success.
* **A topic is visible right after `CreateTopics` or `DeleteTopics`.** A successful call now drops the cached all-topics list, so a client that discovers topics that way no longer fails a write issued right after the topic is created.
* **`kmq deploy` publishes the Kafka and AMQP connectors by default**, on ports 9092 and 5672, and both connectors are enabled by default in the server. New `--amqp-port` flag alongside the existing `--kafka-port`; set either to `0` to leave that port unpublished.
## Known issues [#known-issues]
* No default connector image is published. Set `spec.image` on every `KubemqConnector`.
# Release 3.5.4 (/release-notes/v3-5-4)
**Released September 27, 2026.** kmq advertises the Kafka address a deployed container actually publishes, reads a Kubernetes cluster's license status the way the operator writes it, and no longer lets its subcommands inherit the server's startup flags. The Kubernetes migration path also closes a broad round of failures found running it for real. The operator and the Helm chart are unchanged from [3.5.3](/release-notes/v3-5-3).
## Artifacts [#artifacts]
| Artifact | Version |
| ------------------------ | -------------------------------------------------------------------------------------------------- |
| kmq | `v3.5.4` |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next:v3.5.4`, for `linux/amd64` and `linux/arm64` |
| Server image (FIPS) | `europe-docker.pkg.dev/kubemq/images/kubemq-next-fips:v3.5.4`, for `linux/amd64` and `linux/arm64` |
| Operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next:v3.4.0` (unchanged) |
| Helm chart `kubemq-next` | 3.4.0 (unchanged; it installs server `v3.5.0`) |
## Before you upgrade [#before-you-upgrade]
* **Nothing new to prepare.** The operator and the Helm chart are the same as in 3.5.3.
## Changes [#changes]
* **kmq advertises the Kafka loopback address a deployed container actually publishes.** A container started by `kmq deploy` publishes the Kafka port on `127.0.0.1` only, while kmq previously advertised `localhost`; kcat and other librdkafka clients resolve that to IPv6 first and were refused. kmq now sets the advertised host and port to match, so a client can connect right after deploy.
* **kmq reads a Kubernetes cluster's status and operator `Deployment` the way the operator actually writes them.** A field-name mismatch meant a fully licensed, converged cluster could still report itself `cluster_not_ready`, and an operator installed outside kmq's own release was invisible to it and risked a second install attempt.
* **kmq subcommands no longer inherit the server's startup flags.** `--config`, `--clean`, `--clean-accounts` and `--reset-admin-password` used to appear in every subcommand's `--help` and be silently accepted, doing nothing; the server's own `--help` is unchanged.
* **kmq's Kubernetes migration path closes a broad round of real-run failures.** `kmq migrate` now runs a Kafka-to-KubeMQ migration end to end from inside the cluster, provisioning the target and worker profiles and running the probe, plan, prepare and cutover stages as in-cluster Jobs. Fixes found running the trial and migration journeys for real include Podman-backed Docker identity, Helm 4 support, reviewed failure categories instead of one opaque error, retried transient Kubernetes errors, and consistent messages wherever a credential, license, lock or saved plan sits in a directory kmq will not trust.
## Known issues [#known-issues]
* No default connector image is published. Set `spec.image` on every `KubemqConnector`.
# Release 3.5.5 (/release-notes/v3-5-5)
**Released September 28, 2026.** The published server image index now labels its `amd64` child correctly, so an x86 host or a GKE node can pull it; a rebuilt node's boot identity claim retries instead of silently falling back to the wrong replica id; and kmq adds commands for administering one rebuilt server. The operator and the Helm chart are unchanged from [3.5.4](/release-notes/v3-5-4).
## Artifacts [#artifacts]
| Artifact | Version |
| ------------------------ | -------------------------------------------------------------------------------------------------- |
| kmq | `v3.5.5` |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next:v3.5.5`, for `linux/amd64` and `linux/arm64` |
| Server image (FIPS) | `europe-docker.pkg.dev/kubemq/images/kubemq-next-fips:v3.5.5`, for `linux/amd64` and `linux/arm64` |
| Operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next:v3.4.0` (unchanged) |
| Helm chart `kubemq-next` | 3.4.0 (unchanged; it installs server `v3.5.0`) |
## Before you upgrade [#before-you-upgrade]
* **Nothing new to prepare.** The operator and the Helm chart are the same as in 3.5.4.
## Changes [#changes]
* **The published multi-arch server image index no longer mislabels its `amd64` child as the `arm64` variant.** An x86 host or a GKE node could not pull `kubemq-next` or the FIPS image at all. Every child image is now added to the index with its architecture and operating system set explicitly, and a check refuses to publish an index shaped like the broken one again.
* **A rebuilt node's boot identity claim retries instead of giving up after 10 seconds.** It used to send one request before the node had route interest to its peers, then silently fall back to the configured replica id, so `kmq cluster replace` never actually took effect on Kubernetes. The claim now retries for 90 seconds with backoff, never falls back while a peer is reachable, and logs which one happened.
* **kmq adds commands for administering a rebuilt server.** Membership commands can sign in as the dashboard administrator for one operation (`--admin-username`, `--admin-password-stdin`); `kmq auth login --server-index N --bootstrap` recovers one rebuilt server; `kmq deploy verify --accept-rebuilt-server N` records that a server's volume identity was intentionally replaced. `kmq deploy prepare` now refuses an image with no entry for a node's own architecture instead of failing later, and `kmq deploy diagnose` classifies image-pull failures.
## Known issues [#known-issues]
* No default connector image is published. Set `spec.image` on every `KubemqConnector`.
# Release 3.6.0 (/release-notes/v3-6-0)
**Released September 28, 2026.** A clustered next storage engine now spreads partition leadership across every node by default, instead of pinning it to one, so Kafka produce and fetch traffic is served by the whole cluster. The layout change behind it means a next-engine data directory from 3.5.5 or earlier cannot be opened — read **Before you upgrade** first. The operator moves to `v3.5.0` and the Helm chart `kubemq-next` to `3.5.0`.
## Artifacts [#artifacts]
| Artifact | Version |
| ------------------------ | -------------------------------------------------------------------------------------------------- |
| kmq | `v3.6.0` |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next:v3.6.0`, for `linux/amd64` and `linux/arm64` |
| Server image (FIPS) | `europe-docker.pkg.dev/kubemq/images/kubemq-next-fips:v3.6.0`, for `linux/amd64` and `linux/arm64` |
| Operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next:v3.5.0` |
| Helm chart `kubemq-next` | 3.5.0 (operator `v3.5.0`, server `v3.6.0`) |
## Before you upgrade [#before-you-upgrade]
* **Breaking: every next-engine data directory needs a fresh volume.** 3.6.0 writes and opens a new on-disk layout that makes spreading partition leadership possible, and it cannot open a directory a 3.5.5-or-earlier server wrote. There is no migration and no compatibility mode: a node started on an old directory refuses to boot with *"this version needs a fresh data directory; delete the old one or start on a new volume,"* and nothing is migrated or deleted, even with `Store.CleanStore=true` (`--clean` / `STORE_CLEAN_STORE`). Drain or export any messages you still need first, then start every node on an empty directory or a new volume. Legacy-engine (`STORE_ENGINE=legacy`) data directories are not affected.
* **Two Kafka fixes stay off until every node runs 3.6.0.** `CONNECTORS_KAFKA_SHARE_FEATURE_VERSION=3` and `CONNECTORS_KAFKA_PRODUCE_CONDITIONAL_APPEND=true` each write a replicated command a node on an older release cannot apply, so both default off and a rolling upgrade with default settings is safe. Once every node runs 3.6.0, set both on every node and restart the nodes one at a time. Gate `3` stops a share consumer from losing a producer batch's unacknowledged records when it acknowledges that batch across several requests, and stops a failed read from spending a delivery attempt it should not; conditional append stops a produce batch that committed after its leader stopped waiting for it, or that a former leader forwarded after losing leadership, from taking an offset another batch already holds.
## Changes [#changes]
* **A clustered next engine spreads partition leadership across every node by default.** A cluster now runs 8 shards with the leader balancer on, so each node leads a share of the partitions and serves their produce and fetch traffic; a standalone node runs 1 shard. Both stay configurable through `STORE_NEXT_SHARDS` (1–16; every node in a cluster must agree, and changing it means creating a new cluster) and `STORE_NEXT_BALANCE_LEADERS` (`false` pins every leader to one node, as before) — see [Next storage engine settings](/configure/reference/storage-engines#next-storage-engine-settings). On Kubernetes, the operator's `spec.store.nextShards` and `spec.store.nextBalanceLeaders` fields, and the matching fields in the `kubemq-next` chart, are immutable once a cluster is created.
* **Kafka group ids and transactional ids may contain any character, as in Apache Kafka.** A route-separator character such as `;` used to split an id's durable writes across the wrong internal channels, and a space or a handful of other characters were refused outright. Such ids are now stored under escaped internal channel names; every other id is unaffected.
* **Kafka share groups (KIP-932) close out their remaining GA gaps.** A share consumer that acknowledges one producer batch across several requests (because it polls fewer records per call than the batch holds) no longer loses the records it releases or never gets to; a failed read after an acquire no longer spends a delivery attempt; and compacted topics stay consistent across replicas. Both fixes ship behind the `CONNECTORS_KAFKA_SHARE_FEATURE_VERSION=3` gate above.
* **Kafka leader failover no longer crashes Java consumers.** A partition that could not yet be served answered `Fetch` with a code Apache Kafka never sends, which the Java client (`kafka-clients` 4.3.1 and 4.4.0) treats as fatal and stops the consumer thread on. Fetch, `ListOffsets`, `OffsetForLeaderEpoch`, `Produce` and `DeleteRecords` now answer the retriable code Kafka uses in that state, and every client refreshes its metadata and retries instead of failing.
* **Kafka consumer groups can keep their members across a coordinator failover (new setting, off by default).** A moved coordinator used to force every member to rejoin with a new member id and jump the group's generation, which could turn a stale offset commit into a spurious error. `CONNECTORS_KAFKA_CLASSIC_GROUP_MEMBERSHIP_DURABLE=true` has the next coordinator reinstate each group's members, generation and assignments instead.
* **A killed next node no longer loses an acknowledged write, and a killed follower restarts instead of crash-looping.** Under the default `Store.NextAckPolicy=fast`, an acknowledged write is now always written to the operating system before the acknowledgment, with only its fsync staying in the background — see [Ack policy](/configure/reference/storage-engines#ack-policy). A follower that still lost acknowledged entries to a crash now restarts not ready and heals itself on the shard's next write, rather than panicking on every restart; a node left holding writes the rest of the cluster lost now refuses to serve them, with the cause on `/ready`, instead of stalling silently.
* **A native Events Store group subscriber on a compacted Kafka topic no longer stalls.** Once compaction removed a superseded record, every batch that included its sequence used to fail as a whole and hold up the retained records in it. The subscriber now delivers every retained record once and skips the removed sequences, the way a Kafka consumer of a compacted partition does.
* **Coordinator state survives a failover that lands mid-roll.** A Kafka consumer group's, transactional producer's or topic's replicated state log now waits for its periodic roll to finish before acknowledging a write during that roll, so a coordinator failover or restart at the wrong moment no longer rolls a committed offset, a transaction's state or a topic's configuration and partition count back to an older snapshot.
* **A round of smaller Kafka correctness fixes:** `ListOffsets` by timestamp answers from each record's own timestamp instead of when it was stored; a clustered topic reports every node holding its data as a replica, not only the leader; an idempotent producer's retry after a leader failover now reports the offset its batch was actually written at; `acks=0` records a producer sent right before closing its connection are no longer dropped; and `kubemq_kafka_produce_rejects_total` gets its own series for a fenced or unknown producer instead of folding those into generic failures.
* **`/api/cluster-snapshot` names the node raft says leads, instead of each node's own snapshot**, which could be tens of seconds stale right after a failover.
## Known issues [#known-issues]
* No default connector image is published. Set `spec.image` on every `KubemqConnector`.
# Release 3.6.18 (/release-notes/v3-6-18)
**Released October 12, 2026.** This release improves Kafka correctness under failover and storage pressure, reduces storage-path pauses, closes authorization gaps, and fixes dashboard reliability and accessibility issues. Read the upgrade guidance before changing a production cluster. The complete change list is in the [official server release](https://github.com/kubemq-io/kubemq-server/releases/tag/next/v3.6.18).
## Artifacts [#artifacts]
| Artifact | Version |
| ------------------------ | ----------------------------------------------------------------- |
| kmq | `v3.6.18` |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next:v3.6.18` |
| Operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next:v3.6.0` |
| Helm chart `kubemq-next` | 3.6.0 (operator `v3.6.0`, server `v3.6.16`) |
## Before you upgrade [#before-you-upgrade]
* Back up every data directory. This version writes a segment seal marker that older servers do not understand safely. Do not point an older server at a data directory after 3.6.18 has written it.
* Finish a rolling upgrade before deleting or recreating Kafka topics. New topic-deletion records and committed offsets use offset-log format version 2. Older servers cannot take over affected consumer groups and are no longer rollback targets for that data.
* When upgrading from 3.6.16 or earlier, Kafka topics without their own `retention.ms` now retain data for 7 days. Set `CONNECTORS_KAFKA_LOG_RETENTION_MS=-1` on every server before upgrading if those topics must retain records indefinitely. The value `0` is now rejected at boot.
* Mutual Transport Layer Security clients now use the certificate's full distinguished name as their Kafka principal. Review authorization rules that match only the common name.
* Kafka cluster administration requires a principal listed in `CONNECTORS_KAFKA_SUPER_USERS` when authorization is enabled. Review broad write grants and any settings created while running the first 3.6.18 release candidate.
* Review existing `TUNING_*`, `CONNECTORS_MQTT_*`, Model Context Protocol, and agent protocol environment variables. Variables that were previously ignored now take effect, and invalid values stop configuration loading instead of resetting it to defaults.
## Changes [#changes]
* Storage checkpoints and segment sealing leave the publish path, reducing long-tail latency. Set `STORE_NEXT_ASYNC_CHECKPOINT=false` and restart to restore the previous checkpoint locking while the new default awaits cloud acceptance testing.
* Kafka topic deletion removes committed offsets, blocks stale commits from restoring a deleted topic, and cleans up partitions recreated by producers during deletion.
* Kafka produce requests account for time spent waiting behind throttling or serialized requests. Responses now reserve 2 seconds inside the client's timeout, and expired requests store nothing.
* Storage-pressure handling retries ordered writes for up to 5 seconds. Synchronous Events Store and Queue sends now wait up to 6 seconds for persistence acknowledgement.
* Authorization now protects reserved feeds, internal channel operations, agent gateway calls, dashboard settings, and Kafka cluster administration more narrowly.
* Kafka adds stronger consumer-group reconciliation, share-group correctness, mutable access-control lists, quotas, credential administration, incremental fetch sessions, and more complete metrics.
* Compaction uses bounded memory, sealed segments no longer keep files open, and stale transaction markers are reclaimed more aggressively.
* Dashboard fixes cover session restore, sign-out, monitor reconnection, error reporting, navigation encoding, narrow layouts, keyboard access, and screen-reader semantics.
## Known limits [#known-limits]
* Cloud acceptance is still pending for asynchronous checkpoints, segment sealing outside the publish path, and byte-bounded retention. Keep the checkpoint kill switch available.
* Deleting a topic with 4,096 partitions took 60 to 100 seconds before the deletion changes. The final build has not been remeasured.
* The final build did not receive the 4-hour retention soak. A 60-minute earlier run showed stable segment file usage and much lower transaction-marker memory, but the long-run bound remains unverified.
* Recovery after an unclean node reboot took 110 to 145 seconds. Producer throughput stayed between 8% and 20% for about 85 seconds while producer state warmed.
* Rebuilding a server after disk loss reached Ready in about 29 minutes under 300,000 messages per second. Full synchronization took 924 seconds, exceeding the 900-second target.
* Under a 100-millisecond, 2% packet-loss link, an earlier build answered 16 produce requests after the client's 30-second timeout. The cause is fixed here, but the fault test was not repeated on the final build and throughput still collapses during that fault.
* With one server limited to 50 megabytes per second of disk throughput, affected partitions can take about 10 seconds to answer before leadership moves. Keep producer `delivery.timeout.ms` at 60 seconds or longer. The leadership fix was not repeated on the final build.
* After a 60-second leader isolation, one earlier run needed 68 seconds to return to full synchronization. Kafka certification and the byte-bounded replication-log acceptance run were not repeated for this release.
# How KubeMQ versions work (/release-notes/versioning)
KubeMQ has two product lines, and each has its own version numbers. This page explains how those numbers fit together. For the artifact names, what `-next` means and how to pin a release, see [Artifacts and versions](/deploy/install/requirements#artifacts-and-versions).
## The current product [#the-current-product]
The current product ships as the `-next` artifacts: the `kubemq-next` server image, the `kubemq-operator-next` operator image and the `kubemq-next` Helm chart, together with the kmq command-line tool.
* **Numbered 1.0 to 1.3 at first.** The first releases, from September 18 to 21, 2026, were numbered 1.0.0 to 1.3.2. Their notes are on [Releases 1.0–1.3](/release-notes/next-v1).
* **Renumbered at 3.3.0.** The release of September 23, 2026 was numbered 3.3.0, above every legacy release, so a current version number never matches a legacy one. No server release was numbered between 1.3.2 and 3.3.0.
* **kmq and the server share one number from 3.5.0.** There is no server release 3.4.0. The operator and the Helm chart keep their own numbers, and each release page lists the operator and chart that go with it.
## The legacy product [#the-legacy-product]
The legacy product is the `kubemq` server image, numbered v2 through v3.1.x, and the Helm charts in `kubemq-io/charts`. It is a separate product line, even where its numbers look close to current ones: legacy v3.1.4 is not an earlier release of current 3.3.0. Its history is on [Legacy KubeMQ (kubemq image)](/release-notes/legacy). To move to the current product, see [Move from legacy KubeMQ](/deploy/upgrade/from-legacy).
# Agent Cards (/aiway/a2a/agent-cards)
An **agent card** is the machine-readable description of an agent's identity and
capabilities. KubeMQ serves agent cards at the standard A2A `/.well-known/agent-card.json`
endpoints so callers can discover what an agent does before sending it a request.
## Overview [#overview]
Following the A2A protocol convention, KubeMQ exposes two kinds of card:
* **Platform card** — describes the KubeMQ gateway itself. The `name` is always
`kubemq`. It carries no agent-specific skills; it advertises the gateway and the
protocol versions it speaks.
* **Individual card** — describes one registered agent. It is the `AgentCard` you
supplied at registration, **enriched** with the server-managed `registered_at` and
`last_seen` timestamps. This is the same representation returned by
`GET /agents/{agent_id}`.
Cards are read-only discovery surfaces. You create and update them through the
[registry](/aiway/a2a/registry) (register / heartbeat); the card endpoints
just expose the current state. Both card endpoints are **public** — no JWT is required
to read them, since discovery must work before a caller authenticates.
## The two card endpoints [#the-two-card-endpoints]
| Endpoint | Returns |
| ------------------------------------------------- | --------------------------------------------- |
| `GET /.well-known/agent-card.json` | Platform card — the KubeMQ gateway's own card |
| `GET /a2a/{agent_id}/.well-known/agent-card.json` | Individual agent's enriched card |
Requesting a well-known card for a non-existent agent returns **HTTP 404**.
### Platform card [#platform-card]
The platform card represents the gateway, not any agent. Its `name` is always `kubemq`:
```json
{
"name": "kubemq",
"description": "KubeMQ A2A Gateway",
"version": "latest",
"url": "http://localhost:9090/",
"skills": [],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"]
}
```
### Individual agent card [#individual-agent-card]
An individual card returns the agent's registered fields plus the server-managed
timestamps:
```json
{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": "http://localhost:18080/",
"skills": [
{
"id": "echo",
"name": "Echo",
"description": "Echoes back the received message",
"tags": ["test", "echo"]
}
],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"],
"registered_at": "2026-04-06T10:00:00Z",
"last_seen": "2026-04-06T10:05:00Z"
}
```
## Card fields [#card-fields]
The `AgentCard` carries the agent's identity, endpoint, and capabilities. The
**required** fields are `agent_id`, `name`, and `url`.
| Field | JSON key | Required | Description |
| -------------------- | -------------------- | -------- | ----------------------------------------------------------------------------------------------------------- |
| Agent ID | `agent_id` | Yes | Unique identifier — 2–128 chars, lowercase alphanumeric with hyphens, starting and ending with alphanumeric |
| Name | `name` | Yes | Human-readable name (max 256 chars) |
| Description | `description` | No | Free-text description (max 2048 chars) |
| Version | `version` | No | Agent version, e.g. `1.0.0` (max 64 chars) |
| URL | `url` | Yes | Agent endpoint — an absolute `http://` or `https://` URL (max 2048 chars) |
| Skills | `skills` | No | List of `AgentSkill` entries (see below) |
| Capabilities | `capabilities` | No | Free-form capability map |
| Default input modes | `defaultInputModes` | No | e.g. `["text"]` |
| Default output modes | `defaultOutputModes` | No | e.g. `["text"]` |
| Protocol versions | `protocolVersions` | No | Defaults to `["1.0"]` if omitted |
| Metadata | `metadata` | No | Key-value string map |
`registered_at` and `last_seen` are **server-managed** — KubeMQ sets them on
registration and heartbeat. Do not send them when registering; they will be
overwritten.
### Skills and tags [#skills-and-tags]
Each entry in `skills` is an `AgentSkill`. Skills make agents discoverable: the
registry filters by skill **tags** when listing agents, so well-chosen tags let
callers find the right agent without knowing its ID.
| Field | JSON key | Required | Description |
| ----------- | ------------- | -------- | --------------------------------- |
| ID | `id` | Yes | Skill identifier |
| Name | `name` | Yes | Skill name |
| Description | `description` | No | What the skill does |
| Tags | `tags` | No | Tags used for discovery filtering |
To find every agent advertising a tag, pass it to the list endpoint —
`GET /agents?skill_tags=echo` — see the [registry](/aiway/a2a/registry).
## Fetch a card [#fetch-a-card]
The example below reads an individual agent's card. The curl tab hits the standard
well-known endpoint; the language tabs fetch the same card representation via the
registry API and print every field.
```bash
# Platform card (the gateway itself)
curl http://localhost:9090/.well-known/agent-card.json
# Individual agent card
curl http://localhost:9090/a2a/echo-agent-01/.well-known/agent-card.json
```
```csharp
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "full-info-agent-01";
using var client = new HttpClient();
var resp = await client.GetAsync($"{KubeMqUrl}/agents/{AgentId}");
Console.WriteLine($"Status: {(int)resp.StatusCode}");
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
Console.WriteLine("\n--- Agent Card ---");
Console.WriteLine($" agent_id: {data["agent_id"]}");
Console.WriteLine($" name: {data["name"]}");
Console.WriteLine($" description: {data["description"]}");
Console.WriteLine($" version: {data["version"]}");
Console.WriteLine($" url: {data["url"]}");
Console.WriteLine($" defaultInputModes: {data["defaultInputModes"]}");
Console.WriteLine($" defaultOutputModes: {data["defaultOutputModes"]}");
Console.WriteLine($" protocolVersions: {data["protocolVersions"]}");
Console.WriteLine($" registered_at: {data["registered_at"]}");
Console.WriteLine($" last_seen: {data["last_seen"]}");
var skills = data["skills"]?.AsArray() ?? [];
Console.WriteLine($"\n--- Skills ({skills.Count}) ---");
foreach (var skill in skills)
{
Console.WriteLine($" [{skill!["id"]}] {skill["name"]}: {skill["description"]}");
Console.WriteLine($" tags: {skill["tags"]}");
}
```
```go
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "full-info-agent-01"
)
func main() {
resp, err := http.Get(kubemqURL + "/agents/" + agentID)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Status: %d\n", resp.StatusCode)
var data map[string]interface{}
json.Unmarshal(body, &data)
fmt.Println("\n--- Agent Card ---")
fmt.Printf(" agent_id: %v\n", data["agent_id"])
fmt.Printf(" name: %v\n", data["name"])
fmt.Printf(" description: %v\n", data["description"])
fmt.Printf(" version: %v\n", data["version"])
fmt.Printf(" url: %v\n", data["url"])
fmt.Printf(" defaultInputModes: %v\n", data["defaultInputModes"])
fmt.Printf(" defaultOutputModes: %v\n", data["defaultOutputModes"])
fmt.Printf(" protocolVersions: %v\n", data["protocolVersions"])
fmt.Printf(" registered_at: %v\n", data["registered_at"])
fmt.Printf(" last_seen: %v\n", data["last_seen"])
skills, _ := data["skills"].([]interface{})
fmt.Printf("\n--- Skills (%d) ---\n", len(skills))
for _, s := range skills {
sk, _ := s.(map[string]interface{})
fmt.Printf(" [%v] %v: %v\n", sk["id"], sk["name"], sk["description"])
fmt.Printf(" tags: %v\n", sk["tags"])
}
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "full-info-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents/" + AGENT_ID))
.GET().build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + resp.statusCode());
var data = MAPPER.readTree(resp.body());
System.out.println("\n--- Agent Card ---");
System.out.println(" agent_id: " + data.path("agent_id").asText());
System.out.println(" name: " + data.path("name").asText());
System.out.println(" description: " + data.path("description").asText());
System.out.println(" version: " + data.path("version").asText());
System.out.println(" url: " + data.path("url").asText());
System.out.println(" defaultInputModes: " + data.path("defaultInputModes"));
System.out.println(" defaultOutputModes: " + data.path("defaultOutputModes"));
System.out.println(" protocolVersions: " + data.path("protocolVersions"));
System.out.println(" registered_at: " + data.path("registered_at").asText());
System.out.println(" last_seen: " + data.path("last_seen").asText());
var skills = data.path("skills");
System.out.println("\n--- Skills (" + skills.size() + ") ---");
for (var skill : skills) {
System.out.println(" [" + skill.get("id").asText() + "] "
+ skill.get("name").asText() + ": " + skill.get("description").asText());
System.out.println(" tags: " + skill.get("tags"));
}
}
}
```
```python
"""Agent-Info example — retrieves and displays all agent card fields."""
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "full-info-agent-01"
async def main() -> None:
async with httpx.AsyncClient() as client:
resp = await client.get(f"{KUBEMQ_URL}/agents/{AGENT_ID}")
print(f"Status: {resp.status_code}")
data = resp.json()
print("\n--- Agent Card ---")
print(f" agent_id: {data.get('agent_id')}")
print(f" name: {data.get('name')}")
print(f" description: {data.get('description')}")
print(f" version: {data.get('version')}")
print(f" url: {data.get('url')}")
print(f" defaultInputModes: {data.get('defaultInputModes')}")
print(f" defaultOutputModes: {data.get('defaultOutputModes')}")
print(f" protocolVersions: {data.get('protocolVersions')}")
print(f" registered_at: {data.get('registered_at')}")
print(f" last_seen: {data.get('last_seen')}")
skills = data.get("skills", [])
print(f"\n--- Skills ({len(skills)}) ---")
for skill in skills:
print(f" [{skill['id']}] {skill['name']}: {skill['description']}")
print(f" tags: {skill.get('tags', [])}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "info-agent-01";
async function main() {
const resp = await fetch(`${KUBEMQ_URL}/agents/${AGENT_ID}`);
const agent = await resp.json();
console.log("=== Agent Card Details ===");
console.log(` agent_id: ${agent.agent_id}`);
console.log(` name: ${agent.name}`);
console.log(` description: ${agent.description}`);
console.log(` version: ${agent.version}`);
console.log(` url: ${agent.url}`);
console.log(` registered_at: ${agent.registered_at}`);
console.log(` last_seen: ${agent.last_seen}`);
console.log(` protocolVersions: ${JSON.stringify(agent.protocolVersions)}`);
console.log(` defaultInputModes: ${JSON.stringify(agent.defaultInputModes)}`);
console.log(` defaultOutputModes:${JSON.stringify(agent.defaultOutputModes)}`);
console.log("\n=== Skills ===");
for (const skill of agent.skills || []) {
console.log(` - ${skill.id}: ${skill.name} (tags: ${(skill.tags || []).join(", ")})`);
console.log(` ${skill.description}`);
}
console.log("\n=== Full JSON ===");
console.log(JSON.stringify(agent, null, 2));
}
main().catch(console.error);
```
The curl tab uses the public `/.well-known/agent-card.json` endpoint; the language
tabs read the **same** card via `GET /agents/{agent_id}` (the registry API), which
returns an identical representation. Both surfaces return the enriched card.
## Related [#related]
# How It Works (/aiway/a2a/architecture)
The A2A connector is a **transparent JSON-RPC 2.0 proxy**. It never runs your agent's
logic — it routes a request to the right agent, waits for the reply, and relays it back
unchanged. The piece that makes agents plain HTTP servers (no KubeMQ SDK) is the
**virtual subscriber**: a per-agent internal bridge that turns a Query into an
outbound HTTP POST.
## Overview [#overview]
When a caller hits `POST /a2a/`, the request does **not** go straight to your
agent over HTTP. Instead it is published as a **Query** on the agent's internal
channel, picked up by that agent's virtual subscriber, and forwarded to the agent's
registered URL as an HTTP POST. The agent's response travels the same path in reverse.
This indirection is what lets agents stay simple — they are standard A2A-compliant HTTP
servers with **zero KubeMQ dependencies** (no broker client, no protobuf, no client library) — while
still benefiting from KubeMQ's routing, authorization, metrics, and persistence
infrastructure. For why agents are plain HTTP URLs, see the [overview](/aiway/a2a).
## The components [#the-components]
The gateway is one of several cooperating parts. The A2A connector handles the protocol;
the **Agent Registry** tracks who is registered; the **Subscriber Manager** owns the
lifecycle of every **virtual subscriber**; and the **Replicator** keeps registry state
in sync across a cluster.
*The A2A connector proxies via the broker; a per-agent virtual subscriber bridges the Query to an HTTP POST.*
| Component | Role |
| ---------------------- | ------------------------------------------------------------------------------------ |
| **A2A connector** | Transparent JSON-RPC 2.0 proxy; agent-management REST API; SSE relay |
| **Agent Registry** | SQLite-backed store of registered agents with TTL liveness and cluster replication |
| **Subscriber Manager** | Creates/destroys virtual subscribers on registration, deregistration, and TTL expiry |
| **Virtual Subscriber** | Per-agent broker-to-HTTP bridge; the reason agents need no KubeMQ SDK |
| **Replicator** | Propagates registry changes across cluster nodes over Events Store |
## The virtual-subscriber bridge [#the-virtual-subscriber-bridge]
Each registered agent gets its own **virtual subscriber** — an internal broker client that
subscribes to Queries on the agent's channel and forwards them to the agent over HTTP. It
is spawned by the Subscriber Manager when the agent registers and torn down when the agent
deregisters or its TTL expires.
When a Query arrives, the virtual subscriber:
Extracts the JSON-RPC body from the broker request.
Unpacks forwarded HTTP headers (the
`a2a_hdr_*`
tags) back into real headers.
Sets the
`X-KubeMQ-Caller-ID`
header to the original caller's identity.
Makes an HTTP
`POST`
to the agent's registered URL with
`Content-Type: application/json`
.
Wraps the agent's HTTP response and publishes it back on the broker reply channel.
The subscriber dispatches on the `a2a_method` tag in the incoming Query: `message/stream`
is routed to the streaming handler (which opens an SSE connection to the agent),
`stream_cancel` is routed to the cancel handler, and everything else — including
`message/send` and `tasks/send` — goes to the synchronous request handler. All broker
operations for an agent use the client ID `a2a-vsub-` (for example
`a2a-vsub-agent-b`).
Virtual subscribers use a queue subscription with the queue group set to the agent ID, so
load-balanced delivery works correctly across the cluster.
## Internal channels [#internal-channels]
All agent-platform traffic uses channels under the reserved `_AGENTS_.` prefix. User
channels that start with `_AGENTS_.` are rejected by `IsReservedChannel` — see
[Auth & security](/connectors/reference/auth-and-security).
| Channel | Purpose | Transport |
| ----------------------------- | ------------------------------------------------------------------------------- | ------------ |
| `_AGENTS_.agents/` | Request/reply to the agent via its virtual subscriber (including stream cancel) | Query |
| `_AGENTS_.stream/` | Temporary SSE stream events relayed by the virtual subscriber | Events |
| `_AGENTS_.discovery` | Registry replication events across cluster nodes | Events Store |
## Header forwarding [#header-forwarding]
Caller HTTP headers ride along to the agent through the broker request's `Tags` field using
an `a2a_hdr_` prefix: the connector packs each allowed header as
`a2a_hdr_: `, and the virtual subscriber strips the prefix and replays
it as a real HTTP header on the outbound POST.
Hop-by-hop and sensitive headers are **never** forwarded: `Connection`, `Keep-Alive`,
`Transfer-Encoding`, `Te`, `Trailer`, `Upgrade`, `Host`, `Content-Length`,
`Authorization`, `Cookie`, `Set-Cookie`, `Proxy-Authorization`, `Proxy-Authenticate`,
`X-Forwarded-For`, and `X-Real-Ip` are dropped.
Regardless of which headers the caller sent, the virtual subscriber always sets
**`X-KubeMQ-Caller-ID`** on the outbound request, carrying the original caller's KubeMQ
client identity — so your agent can always tell who called it. Any KubeMQ transport (gRPC,
REST, the A2A HTTP gateway, or the MCP bridge) can forward headers the same way by setting
`a2a_hdr_*` tags on the request.
## Concurrency control [#concurrency-control]
Each virtual subscriber enforces a **per-agent** concurrency cap using a buffered-channel
semaphore sized to `AgentMaxConcurrency` (default `100`). When a Query arrives and the
semaphore has capacity, a handler goroutine runs and releases its slot on completion. When
all slots are occupied, the overflow Query is **immediately rejected** with a transport
failure — `Executed: false`, `Error: "server busy: concurrency limit reached"` — without
spawning a goroutine.
This keeps a single hot agent from consuming unbounded goroutines under load. The cap, the
response-size limit, and the timeout/gateway-buffer behavior are covered in detail in
[Concurrency & limits](/aiway/a2a/guides/concurrency).
## Timeouts and the gateway buffer [#timeouts-and-the-gateway-buffer]
Each request carries a timeout taken from `params.configuration.timeout` in the JSON-RPC
body, falling back to `DefaultTimeoutSeconds` (`300`) and capped at `MaxTimeoutSeconds`
(`3600`). Before forwarding, the gateway adds a **`GatewayTimeoutBuffer` of 10 seconds** to
the downstream deadline so the gateway never times out before the agent does. SSE stream
endpoints skip the per-route timeout middleware entirely because they are long-lived; they
are bounded by the idle timeout instead (see [Streaming](/aiway/a2a/streaming)).
## Cluster behavior [#cluster-behavior]
Virtual subscribers are **local to the node where the agent registered** — they are not
replicated. Registry *state*, however, is shared cluster-wide.
*Only the registering node spawns the virtual subscriber; other nodes store the card and route Queries to it over the cluster mesh.*
* An agent registers on **Node A** → its virtual subscriber is spawned on **Node A only**.
* Replication events over `_AGENTS_.discovery` propagate the `AgentCard` to **Nodes B and C**; they store the card but do **not** spawn a subscriber.
* The cluster mesh routes Queries from any node to the virtual subscriber on Node A.
* If **Node A** goes down, the agent's heartbeat expires on all nodes and its subscribers are cleaned up.
* When the agent re-registers on **Node B**, a fresh virtual subscriber is spawned there.
## Transport vs. application errors [#transport-vs-application-errors]
Because the bridge is the boundary between the broker and HTTP, it cleanly separates two failure
classes via the `Executed` flag on the response:
* **Transport error** (`Executed: false`) — the agent never processed the request: it was unreachable, timed out, returned `502`/`503`/`504`, or its response exceeded the size cap. Safe to retry.
* **Application error** (`Executed: true`) — the agent *did* process the request and returned an HTTP `4xx`/`5xx` with a JSON-RPC error body. Retrying blindly usually will not help.
This distinction lets callers choose the right retry strategy — see
[Error handling](/aiway/a2a/error-handling).
## Related [#related]
# Configuration (/aiway/a2a/configuration)
The A2A connector is **enabled by default** on the [shared HTTP server](/connectors/concepts/shared-http-server) — start kubemq-server and `/a2a/*` is live with no flag to set. Configuration tunes agent liveness, request timeouts, concurrency, and response limits; you only set values that differ from the defaults below.
## Overview [#overview]
A2A settings live under `connectors.a2a` in the kubemq-server configuration (the Go `A2aConfig` struct). Every field has a working default, so a minimal deployment needs no A2A configuration at all. You can override any field through a YAML/TOML config file, an environment variable, or a Docker `-e` flag — they map one-to-one.
The connector listens on the shared HTTP server's port (`9090` by default, inherited from `Rest.Port`) and is **on unless you disable it**. There is no `=true` flag — older KubeMQ builds were off-by-default, but current builds ship all three connectors enabled.
## Config fields [#config-fields]
Defaults are taken verbatim from the `A2aConfig` struct in kubemq-server.
| Field | Type | Default | Description |
| ----------------------- | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Enable` | `bool` | `true` | Whether the A2A connector is served. Set to `false` to disable `/a2a/*` and the registry. |
| `AgentTTLSeconds` | `int` | `300` | Liveness window for a registered agent. An agent that does not heartbeat within this window is considered stale. Must be positive. |
| `DefaultTimeoutSeconds` | `int` | `300` | Timeout applied to an agent request when the caller does not set `params.configuration.timeout`. Must be positive. |
| `MaxTimeoutSeconds` | `int` | `3600` | Upper bound for caller-specified timeouts. Larger values are capped to this. Must be `>= DefaultTimeoutSeconds`. |
| `MaxAgents` | `int` | `0` | Maximum number of registered agents. `0` means unlimited. Cannot be negative. |
| `MaxSSEIdleSeconds` | `int` | `300` | Idle timeout for an SSE stream. When it fires, a `task.error` with code `-32001` is sent and the agent is asked to cancel. Must be positive. |
| `TrustedOrigins` | `[]string` | `["auto"]` | Origins allowed by Origin validation. `auto` matches localhost and the bind address; `*` allows all. See [Authentication](/aiway/a2a/guides/authentication). |
| `AgentMaxResponseBytes` | `int64` | `10485760` | Maximum agent response size in bytes (10 MB). Oversized responses are rejected with `-32603`. `0` means unlimited. Cannot be negative. |
| `AgentTLSSkipVerify` | `bool` | `false` | When agents are registered with `https://` URLs, skip TLS certificate verification. Leave `false` in production. |
| `AgentMaxConcurrency` | `int` | `100` | Maximum simultaneous in-flight requests per agent. The 101st concurrent request is rejected with `-32603`. A non-positive value resets to `100`. |
**Validation.** kubemq-server rejects the configuration at startup if `AgentTTLSeconds`, `DefaultTimeoutSeconds`, or `MaxSSEIdleSeconds` is not positive, if `MaxTimeoutSeconds < DefaultTimeoutSeconds`, or if `MaxAgents` / `AgentMaxResponseBytes` is negative.
## Enable / disable [#enable--disable]
The A2A connector is enabled by default. To **disable** it, set its enable variable to `false`:
**The enable variable name is irregular by design.** `Connectors.A2A.Enable` becomes **`CONNECTORSA2_A_ENABLE`** — the `2`-to-`A` boundary inside `A2A` splits into `A2_A`. kubemq-server derives every env var by snake-casing the dotted config path with two regexes, stripping dots, and uppercasing. Do not "fix" the name to `CONNECTORS_A2A_ENABLE`; that string is not bound and has no effect. The full algorithm and the matching MCP/CE names are documented in [Shared HTTP server](/connectors/concepts/shared-http-server#enable-model-on-by-default).
## Environment variables [#environment-variables]
Each field maps to one environment variable via the same transform. These are the A2A variables in full:
| Variable | Config field | Default |
| ----------------------------------------- | -------------------------------------- | ---------- |
| `CONNECTORSA2_A_ENABLE` | `Connectors.A2A.Enable` | `true` |
| `CONNECTORSA2_A_AGENT_TTL_SECONDS` | `Connectors.A2A.AgentTTLSeconds` | `300` |
| `CONNECTORSA2_A_DEFAULT_TIMEOUT_SECONDS` | `Connectors.A2A.DefaultTimeoutSeconds` | `300` |
| `CONNECTORSA2_A_MAX_TIMEOUT_SECONDS` | `Connectors.A2A.MaxTimeoutSeconds` | `3600` |
| `CONNECTORSA2_A_MAX_AGENTS` | `Connectors.A2A.MaxAgents` | `0` |
| `CONNECTORSA2_A_MAX_SSE_IDLE_SECONDS` | `Connectors.A2A.MaxSSEIdleSeconds` | `300` |
| `CONNECTORSA2_A_TRUSTED_ORIGINS` | `Connectors.A2A.TrustedOrigins` | `auto` |
| `CONNECTORSA2_A_AGENT_MAX_RESPONSE_BYTES` | `Connectors.A2A.AgentMaxResponseBytes` | `10485760` |
| `CONNECTORSA2_A_AGENT_TLS_SKIP_VERIFY` | `Connectors.A2A.AgentTLSSkipVerify` | `false` |
| `CONNECTORSA2_A_AGENT_MAX_CONCURRENCY` | `Connectors.A2A.AgentMaxConcurrency` | `100` |
## Configuration file [#configuration-file]
kubemq-server loads a YAML or TOML file (auto-detected) from the `--config` flag or the `CONFIG` environment variable. The A2A connector sits under `connectors.a2a`, alongside the shared `http` block. This example pins every A2A field to its default and shows the shared HTTP/CORS context:
```yaml title="config.yaml"
connectors:
rest:
enable: true
port: "9090"
http:
readtimeout: 60
bodylimit: "100M"
cors:
alloworigins: ["*"]
allowmethods: ["GET", "POST", "DELETE", "OPTIONS"]
allowheaders: ["Authorization", "Content-Type", "MCP-Protocol-Version", "MCP-Session-Id", "Last-Event-ID", "Accept"]
a2a:
enable: true
agentttlseconds: 300
defaulttimeoutseconds: 300
maxtimeoutseconds: 3600
maxagents: 0
maxsseidleseconds: 300
trustedorigins: ["auto"]
agentmaxresponsebytes: 10485760
agenttlsskipverify: false
agentmaxconcurrency: 100
```
The shared HTTP server inherits its port from `connectors.rest.port`. To run the connectors on a separate port from REST, set `connectors.http.port` explicitly. See [Shared HTTP server](/connectors/concepts/shared-http-server) for the port-inheritance and middleware details.
## Tuning the limits [#tuning-the-limits]
The concurrency and response-size caps are the two limits you are most likely to hit under load. The `.kb` examples exercise both against a live server — the curl call below shows the wire behavior, and the language tabs run the full client that fires past the limit and reports the rejection.
### Per-agent concurrency [#per-agent-concurrency]
`AgentMaxConcurrency` (default `100`) bounds in-flight requests per agent. The 101st concurrent request to a single agent is rejected with JSON-RPC error `-32603` ("internal error") while the first 100 succeed.
```bash
# Each of these is a normal request; firing more than AgentMaxConcurrency
# of them at once against one agent makes the overflow return -32603.
curl -X POST http://localhost:9090/a2a/echo-agent-01 \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": { "message": { "parts": [{ "text": "hello" }] } }
}'
```
```csharp
// .kb/integration-a2a/examples/csharp/limits/concurrency-limit/Client.cs
using System.Net.Http.Json;
var kubemqUrl = Environment.GetEnvironmentVariable("KUBEMQ_URL") ?? "http://localhost:9090";
var agentId = "concurrency-agent-01";
const int total = 101; // limit is 100; 1 request will be rejected
using var http = new HttpClient();
async Task<(bool ok, int? code)> SendOne(int i)
{
var payload = new
{
jsonrpc = "2.0",
id = i,
method = "message/send",
@params = new { message = new { parts = new[] { new { text = $"req-{i}" } } } }
};
var resp = await http.PostAsJsonAsync($"{kubemqUrl}/a2a/{agentId}", payload);
var body = await resp.Content.ReadFromJsonAsync();
if (body?.Error is not null)
return (false, body.Error.Code);
return (true, null);
}
var results = await Task.WhenAll(Enumerable.Range(0, total).Select(SendOne));
var rejected = results.Count(r => r.code == -32603);
Console.WriteLine($"Successes: {results.Count(r => r.ok)} Rejected (-32603): {rejected}");
```
```go
// .kb/integration-a2a/examples/go/limits/concurrency-limit/client.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"sync"
"sync/atomic"
)
func main() {
kubemqURL := os.Getenv("KUBEMQ_URL")
if kubemqURL == "" {
kubemqURL = "http://localhost:9090"
}
agentID := "concurrency-agent-01"
const total = 101 // limit is 100; 1 request is rejected
var success, rejected int64
var wg sync.WaitGroup
for i := 0; i < total; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
body, _ := json.Marshal(map[string]any{
"jsonrpc": "2.0", "id": i, "method": "message/send",
"params": map[string]any{"message": map[string]any{
"parts": []map[string]string{{"text": fmt.Sprintf("req-%d", i)}}}},
})
resp, err := http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(body))
if err != nil {
return
}
defer resp.Body.Close()
var out struct {
Error *struct {
Code int `json:"code"`
} `json:"error"`
}
_ = json.NewDecoder(resp.Body).Decode(&out)
if out.Error != nil && out.Error.Code == -32603 {
atomic.AddInt64(&rejected, 1)
} else {
atomic.AddInt64(&success, 1)
}
}(i)
}
wg.Wait()
fmt.Printf("Successes: %d Rejected (-32603): %d\n", success, rejected)
}
```
```java
// .kb/integration-a2a/examples/java/limits/concurrency-limit/Client.java
import java.net.URI;
import java.net.http.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class Client {
public static void main(String[] args) throws Exception {
String kubemqUrl = System.getenv().getOrDefault("KUBEMQ_URL", "http://localhost:9090");
String agentId = "concurrency-agent-01";
int total = 101; // limit is 100; 1 request is rejected
HttpClient http = HttpClient.newHttpClient();
AtomicInteger success = new AtomicInteger();
AtomicInteger rejected = new AtomicInteger();
ExecutorService pool = Executors.newFixedThreadPool(total);
var tasks = IntStream.range(0, total).>mapToObj(i -> () -> {
String payload = """
{"jsonrpc":"2.0","id":%d,"method":"message/send",
"params":{"message":{"parts":[{"text":"req-%d"}]}}}""".formatted(i, i);
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(kubemqUrl + "/a2a/" + agentId))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
String body = http.send(req, HttpResponse.BodyHandlers.ofString()).body();
if (body.contains("-32603")) rejected.incrementAndGet();
else success.incrementAndGet();
return null;
}).toList();
pool.invokeAll(tasks);
pool.shutdown();
System.out.printf("Successes: %d Rejected (-32603): %d%n", success.get(), rejected.get());
}
}
```
```python
# .kb/integration-a2a/examples/python/limits/concurrency-limit/client.py
import asyncio
import os
import httpx
KUBEMQ_URL = os.getenv("KUBEMQ_URL", "http://localhost:9090")
AGENT_ID = "concurrency-agent-01"
TOTAL = 101 # limit is 100; 1 request is rejected
async def send_one(client: httpx.AsyncClient, i: int) -> int | None:
payload = {
"jsonrpc": "2.0",
"id": i,
"method": "message/send",
"params": {"message": {"parts": [{"text": f"req-{i}"}]}},
}
resp = await client.post(f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload)
error = resp.json().get("error")
return error["code"] if error else None
async def main() -> None:
async with httpx.AsyncClient(timeout=30) as client:
codes = await asyncio.gather(*(send_one(client, i) for i in range(TOTAL)))
rejected = sum(1 for c in codes if c == -32603)
successes = sum(1 for c in codes if c is None)
print(f"Successes: {successes} Rejected (-32603): {rejected}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
// .kb/integration-a2a/examples/typescript/limits/concurrency-limit/client.ts
const kubemqUrl = process.env.KUBEMQ_URL ?? "http://localhost:9090";
const agentId = "concurrency-agent-01";
const total = 101; // limit is 100; 1 request is rejected
async function sendOne(i: number): Promise {
const resp = await fetch(`${kubemqUrl}/a2a/${agentId}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: i,
method: "message/send",
params: { message: { parts: [{ text: `req-${i}` }] } },
}),
});
const body = (await resp.json()) as { error?: { code: number } };
return body.error?.code ?? null;
}
const codes = await Promise.all(
Array.from({ length: total }, (_, i) => sendOne(i)),
);
const rejected = codes.filter((c) => c === -32603).length;
const successes = codes.filter((c) => c === null).length;
console.log(`Successes: ${successes} Rejected (-32603): ${rejected}`);
```
### Response size [#response-size]
`AgentMaxResponseBytes` (default `10485760`, 10 MB) caps the size of an agent's reply. A larger response is rejected before it reaches the caller, who receives `-32603` with the message `internal error: response too large`.
```bash
# A normal request; the cap is hit only when the agent's reply exceeds
# AgentMaxResponseBytes, in which case the response carries error -32603.
curl -X POST http://localhost:9090/a2a/oversize-agent-01 \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": { "message": { "parts": [{ "text": "return a big payload" }] } }
}'
```
```csharp
// .kb/integration-a2a/examples/csharp/limits/response-size/Client.cs
using System.Net.Http.Json;
var kubemqUrl = Environment.GetEnvironmentVariable("KUBEMQ_URL") ?? "http://localhost:9090";
var agentId = "oversize-agent-01";
using var http = new HttpClient();
var payload = new
{
jsonrpc = "2.0",
id = 1,
method = "message/send",
@params = new { message = new { parts = new[] { new { text = "return a big payload" } } } }
};
var resp = await http.PostAsJsonAsync($"{kubemqUrl}/a2a/{agentId}", payload);
var body = await resp.Content.ReadFromJsonAsync();
if (body?.Error is not null)
Console.WriteLine($"Error code: {body.Error.Code} Message: {body.Error.Message}");
else
Console.WriteLine("Response within the size limit.");
```
```go
// .kb/integration-a2a/examples/go/limits/response-size/client.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
func main() {
kubemqURL := os.Getenv("KUBEMQ_URL")
if kubemqURL == "" {
kubemqURL = "http://localhost:9090"
}
agentID := "oversize-agent-01"
body, _ := json.Marshal(map[string]any{
"jsonrpc": "2.0", "id": 1, "method": "message/send",
"params": map[string]any{"message": map[string]any{
"parts": []map[string]string{{"text": "return a big payload"}}}},
})
resp, err := http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(body))
if err != nil {
panic(err)
}
defer resp.Body.Close()
var out struct {
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
_ = json.NewDecoder(resp.Body).Decode(&out)
if out.Error != nil {
fmt.Printf("Error code: %d Message: %s\n", out.Error.Code, out.Error.Message)
} else {
fmt.Println("Response within the size limit.")
}
}
```
```java
// .kb/integration-a2a/examples/java/limits/response-size/Client.java
import java.net.URI;
import java.net.http.*;
public class Client {
public static void main(String[] args) throws Exception {
String kubemqUrl = System.getenv().getOrDefault("KUBEMQ_URL", "http://localhost:9090");
String agentId = "oversize-agent-01";
String payload = """
{"jsonrpc":"2.0","id":1,"method":"message/send",
"params":{"message":{"parts":[{"text":"return a big payload"}]}}}""";
HttpClient http = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(kubemqUrl + "/a2a/" + agentId))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
String body = http.send(req, HttpResponse.BodyHandlers.ofString()).body();
if (body.contains("-32603"))
System.out.println("Error code: -32603 (response too large)");
else
System.out.println("Response within the size limit.");
}
}
```
```python
# .kb/integration-a2a/examples/python/limits/response-size/client.py
import os
import httpx
KUBEMQ_URL = os.getenv("KUBEMQ_URL", "http://localhost:9090")
AGENT_ID = "oversize-agent-01"
def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {"message": {"parts": [{"text": "return a big payload"}]}},
}
resp = httpx.post(f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload, timeout=30)
error = resp.json().get("error")
if error:
print(f"Error code: {error['code']} Message: {error['message']}")
else:
print("Response within the size limit.")
if __name__ == "__main__":
main()
```
```typescript
// .kb/integration-a2a/examples/typescript/limits/response-size/client.ts
const kubemqUrl = process.env.KUBEMQ_URL ?? "http://localhost:9090";
const agentId = "oversize-agent-01";
const resp = await fetch(`${kubemqUrl}/a2a/${agentId}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: { message: { parts: [{ text: "return a big payload" }] } },
}),
});
const body = (await resp.json()) as {
error?: { code: number; message: string };
};
if (body.error) {
console.log(`Error code: ${body.error.code} Message: ${body.error.message}`);
} else {
console.log("Response within the size limit.");
}
```
Timeouts compound. The gateway adds `GatewayTimeoutBuffer` (10s) on top of the effective request timeout before timing out the proxied call to the agent, so the agent always has a slightly longer window than the caller-facing timeout. See [Concurrency & limits](/aiway/a2a/guides/concurrency).
## Related [#related]
## Container command examples
```sh
docker run -d --pull always --platform linux/amd64 --name kubemq --hostname kubemq -e STORE_ENGINE=next -e STORE_NEXT_ACK_POLICY=strict -e STORE_STORE_PATH=/kubemq/store -e API_BIND_ADDRESS=0.0.0.0 -e CONNECTORSA2_A_ENABLE=false -v kubemq-data:/kubemq/store europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Error Handling (/aiway/a2a/error-handling)
Every A2A response is a **JSON-RPC 2.0** envelope, so failures come back as a structured
`error` object with a numeric `code` and a `message` — never as a raw HTTP error. This
page is the field guide to those codes: which ones the gateway raises, which come from
the agent, and how to decide whether to retry.
## Overview [#overview]
The A2A gateway returns errors at HTTP `200` with a JSON-RPC `error` body for anything it
can parse as a request. A failed call looks like this:
```json
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32002,
"message": "agent not found: nonexistent-agent"
}
}
```
There are two families of codes:
* **JSON-RPC base codes** (`-32700`, `-32600`, `-32601`, `-32602`, `-32603`, `-32010`)
— shared with the [MCP connector](/aiway/mcp) and raised by the gateway for
malformed requests, bad methods, or auth failures.
* **A2A-specific codes** (`-32001` to `-32004`) — raised when the gateway routes to a
registered agent but the call to that agent fails (timeout, missing agent, rejection,
or an unparseable reply).
## JSON-RPC base codes [#json-rpc-base-codes]
These are the standard JSON-RPC 2.0 codes returned by the shared HTTP layer for requests
that never reach an agent — the body or method is wrong, or authentication failed.
| Code | Constant | Meaning | Typical cause |
| -------- | ----------------------- | ---------------------- | -------------------------------------------------------------------------- |
| `-32700` | `JSONRPCParseError` | Parse error | Invalid JSON body, or `Content-Type` is not `application/json` |
| `-32600` | `JSONRPCInvalidRequest` | Invalid request | Missing `method`, wrong `jsonrpc` version, or an invalid `agent_id` format |
| `-32601` | `JSONRPCMethodNotFound` | Method not found | Unknown `method` for the endpoint |
| `-32602` | `JSONRPCInvalidParams` | Invalid params | The `params` object failed validation |
| `-32603` | `JSONRPCInternalError` | Internal error | Unexpected gateway-side failure |
| `-32010` | `jsonrpcAuthError` | Authentication failure | Missing or invalid JWT on a protected route |
The `agent_id` in the URL path is validated before routing. An invalid format (for
example uppercase characters) is rejected with `-32600` — the request never reaches an
agent. See [Authentication](/aiway/a2a/guides/authentication) for the
`-32010` auth flow.
## A2A-specific codes [#a2a-specific-codes]
These codes are raised by the gateway when it has a registered agent to route to but the
outbound HTTP call to that agent fails.
| Code | Constant | Meaning |
| -------- | ------------------------- | -------------------------------------------------------------- |
| `-32001` | `jsonrpcAgentTimeout` | The agent did not respond within the request timeout |
| `-32002` | `jsonrpcAgentNotFound` | No agent is registered under that `agent_id` |
| `-32003` | `jsonrpcAgentUnavailable` | The agent rejected the request (unreachable or returned a 5xx) |
| `-32004` | `jsonrpcInvalidResponse` | The agent replied, but the body was not valid JSON-RPC |
The request timeout that drives `-32001` defaults to `DefaultTimeoutSeconds` (300s) and is
capped by `MaxTimeoutSeconds` (3600s); per-call, set `params.configuration.timeout`
(seconds) to lower it. The same code is also emitted as a `task.error` envelope when an
SSE stream hits its idle timeout (`MaxSSEIdleSeconds`, default 300s) — see
[SSE behavior](/aiway/a2a/guides/sse-behavior).
## Transport vs application errors [#transport-vs-application-errors]
Underneath the JSON-RPC codes, the gateway's virtual subscriber draws a sharp line
between a call the agent **never processed** and one it **processed but rejected**. This
distinction is what lets you decide whether retrying is safe.
The agent's reply carries an `Executed` flag:
* **`Executed: false`** — a **transport error**. The agent never handled the request, so
retrying (against another instance, or after a backoff) is safe. Mapped to `-32001`
(timeout), `-32002` (not found), or `-32003` (unavailable).
* **`Executed: true`** — the agent **did** process the request. A `2xx` is a success; a
`4xx`/`5xx` body is an **application error** the agent chose to return. Retrying the
same call will produce the same result, so handle it as a business outcome rather than
blindly retrying.
| Condition | Gateway result | Classification |
| ------------------------------------------------------ | ------------------------------------------------------------ | -------------- |
| Connection refused / DNS failure | `Executed: false` · "agent unreachable" | Transport |
| HTTP timeout (deadline exceeded) | `Executed: false` · "agent timeout" | Transport |
| HTTP 502 / 503 / 504 | `Executed: false` · "agent unavailable: 50x" | Transport |
| Response body exceeds `AgentMaxResponseBytes` (10 MB) | `Executed: false` · "agent response too large" | Transport |
| Concurrency limit reached (`AgentMaxConcurrency`, 100) | `Executed: false` · "server busy: concurrency limit reached" | Transport |
| HTTP 200–299 | `Executed: true` · response body | Success |
| HTTP 400 / 401 / 403 / 404 / 409 / 422 / 500 | `Executed: true` · response body | Application |
## Retry strategy [#retry-strategy]
A safe default: **retry transport errors, surface application errors.**
* **`-32002` (agent not found)** — the target is not in the registry. Do not retry the
same `agent_id`; re-resolve the agent (it may have expired its TTL) or
[register it](/aiway/a2a/registry) first.
* **`-32001` (timeout)** — retry with backoff. If it persists, the agent is overloaded or
the per-call timeout is too low for the workload; raise
`params.configuration.timeout`.
* **`-32003` (unavailable)** and `Executed: false` — the agent never ran the request;
retry with exponential backoff, optionally against a healthy instance.
* **`-32004` (invalid response)** — the agent is misbehaving (non-JSON-RPC body). Retrying
rarely helps; treat it as a bug in the agent.
* **JSON-RPC base codes** (`-32600`, `-32602`, `-32700`) — the request itself is wrong.
Fix the payload; retrying unchanged will fail identically.
* **Application errors** (`Executed: true` with a `4xx`/`5xx` body) — these are the
agent's deliberate response. Handle them as domain outcomes, not infrastructure faults.
## Examples [#examples]
The snippets below trigger each error family against a running gateway: a missing agent
(`-32002`), malformed JSON-RPC requests (base codes), and a timeout (`-32001`).
### Agent not found (-32002) [#agent-not-found--32002]
Send a `message/send` to an `agent_id` that is not registered. The gateway returns a
JSON-RPC error with code `-32002`.
```bash
curl -X POST http://localhost:9090/a2a/nonexistent-agent \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {"message": {"parts": [{"text": "Hello?"}]}}
}'
# => {"jsonrpc":"2.0","id":1,"error":{"code":-32002,"message":"agent not found: nonexistent-agent"}}
```
```csharp
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "nonexistent-agent";
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Hello?" })
}
}
};
using var client = new HttpClient();
var resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/{AgentId}",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
Console.WriteLine(JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true }));
var error = data["error"];
Console.WriteLine($"\nError code: {error?["code"]}");
Console.WriteLine($"Error message: {error?["message"]}");
var code = error?["code"]?.GetValue();
if (code == -32002)
Console.WriteLine("\nAgent-not-found error (-32002) received as expected!");
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "nonexistent-agent"
)
func main() {
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Hello?"}},
},
},
}
data, _ := json.Marshal(payload)
resp, err := http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var pretty bytes.Buffer
json.Indent(&pretty, body, "", " ")
fmt.Println(pretty.String())
var result map[string]interface{}
json.Unmarshal(body, &result)
errorObj, _ := result["error"].(map[string]interface{})
code, _ := errorObj["code"].(float64)
msg, _ := errorObj["message"].(string)
fmt.Printf("\nError code: %.0f\n", code)
fmt.Printf("Error message: %s\n", msg)
if int(code) != -32002 {
fmt.Fprintf(os.Stderr, "Expected -32002, got %.0f\n", code)
os.Exit(1)
}
fmt.Println("\nAgent-not-found error (-32002) received as expected!")
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "nonexistent-agent";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/send",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Hello?")))
)
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(data));
var error = data.path("error");
System.out.println("\nError code: " + error.path("code").asInt());
System.out.println("Error message: " + error.path("message").asText());
assert error.path("code").asInt() == -32002 : "Expected -32002, got " + error.path("code").asInt();
System.out.println("\nAgent-not-found error (-32002) received as expected!");
}
}
```
```python
import asyncio
import json
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "nonexistent-agent"
async def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "Hello?"}]},
},
}
async with httpx.AsyncClient() as client:
resp = await client.post(f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload)
data = resp.json()
print(json.dumps(data, indent=2))
error = data.get("error", {})
print(f"\nError code: {error.get('code')}")
print(f"Error message: {error.get('message')}")
assert error.get("code") == -32002, f"Expected -32002, got {error.get('code')}"
print("\nAgent-not-found error (-32002) received as expected!")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
async function main() {
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: {
message: { parts: [{ text: "Hello?" }] },
},
};
console.log("Sending to nonexistent agent...");
const resp = await fetch(`${KUBEMQ_URL}/a2a/nonexistent-agent`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const data = await resp.json();
console.log("Response:", JSON.stringify(data, null, 2));
if (data.error) {
console.log(`\nError code: ${data.error.code} (expect -32002)`);
console.log(`Error message: ${data.error.message}`);
console.log(`Match: ${data.error.code === -32002}`);
}
}
main().catch(console.error);
```
### Invalid request (JSON-RPC base codes) [#invalid-request-json-rpc-base-codes]
Malformed payloads are rejected by the gateway with base codes — invalid JSON or a wrong
`Content-Type` yields `-32700`, while a missing `method` or wrong `jsonrpc` version yields
`-32600`.
```bash
# Invalid JSON body -> -32700
curl -X POST http://localhost:9090/a2a/echo-agent-01 \
-H "Content-Type: application/json" \
-d '{invalid json!!!}'
# Missing method field -> -32600
curl -X POST http://localhost:9090/a2a/echo-agent-01 \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "id": 1, "params": {}}'
# Bad jsonrpc version -> -32600
curl -X POST http://localhost:9090/a2a/echo-agent-01 \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "1.0", "id": 1, "method": "message/send", "params": {}}'
```
```csharp
using System.Text;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "echo-agent-01";
using var client = new HttpClient();
Console.WriteLine("=== Test 1: Invalid JSON ===");
var resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/{AgentId}",
new StringContent("{invalid json!!!}", Encoding.UTF8, "application/json"));
var data = JsonNode.Parse(await resp.Content.ReadAsStringAsync())!;
var error = data["error"];
Console.WriteLine($" Code: {error?["code"]} (expected -32700)");
Console.WriteLine($" Message: {error?["message"]}");
Console.WriteLine("\n=== Test 2: Missing method field ===");
var payload2 = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["params"] = new JsonObject()
};
resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/{AgentId}",
new StringContent(payload2.ToJsonString(), Encoding.UTF8, "application/json"));
data = JsonNode.Parse(await resp.Content.ReadAsStringAsync())!;
error = data["error"];
Console.WriteLine($" Code: {error?["code"]} (expected -32600)");
Console.WriteLine($" Message: {error?["message"]}");
Console.WriteLine("\n=== Test 3: Bad jsonrpc version ===");
var payload3 = new JsonObject
{
["jsonrpc"] = "1.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject()
};
resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/{AgentId}",
new StringContent(payload3.ToJsonString(), Encoding.UTF8, "application/json"));
data = JsonNode.Parse(await resp.Content.ReadAsStringAsync())!;
error = data["error"];
Console.WriteLine($" Code: {error?["code"]} (expected -32600)");
Console.WriteLine($" Message: {error?["message"]}");
Console.WriteLine("\nAll invalid request errors demonstrated!");
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "echo-agent-01"
)
func main() {
fmt.Println("=== Test 1: Invalid JSON ===")
req, _ := http.NewRequest("POST", kubemqURL+"/a2a/"+agentID, strings.NewReader("{invalid json!!!}"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
var data map[string]interface{}
json.Unmarshal(body, &data)
errorObj, _ := data["error"].(map[string]interface{})
code, _ := errorObj["code"].(float64)
fmt.Printf(" Code: %.0f (expected -32700)\n", code)
fmt.Printf(" Message: %v\n", errorObj["message"])
fmt.Println("\n=== Test 2: Missing method field ===")
payload2, _ := json.Marshal(map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"params": map[string]interface{}{},
})
resp, _ = http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(payload2))
body, _ = io.ReadAll(resp.Body)
resp.Body.Close()
json.Unmarshal(body, &data)
errorObj, _ = data["error"].(map[string]interface{})
code, _ = errorObj["code"].(float64)
fmt.Printf(" Code: %.0f (expected -32600)\n", code)
fmt.Printf(" Message: %v\n", errorObj["message"])
fmt.Println("\n=== Test 3: Bad jsonrpc version ===")
payload3, _ := json.Marshal(map[string]interface{}{
"jsonrpc": "1.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{},
})
resp, _ = http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(payload3))
body, _ = io.ReadAll(resp.Body)
resp.Body.Close()
json.Unmarshal(body, &data)
errorObj, _ = data["error"].(map[string]interface{})
code, _ = errorObj["code"].(float64)
fmt.Printf(" Code: %.0f (expected -32600)\n", code)
fmt.Printf(" Message: %v\n", errorObj["message"])
fmt.Println("\nAll invalid request errors demonstrated!")
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "echo-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var client = HttpClient.newHttpClient();
System.out.println("=== Test 1: Invalid JSON ===");
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{invalid json!!!}"))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
var error = data.path("error");
System.out.println(" Code: " + error.path("code").asInt() + " (expected -32700)");
System.out.println(" Message: " + error.path("message").asText());
System.out.println("\n=== Test 2: Missing method field ===");
req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
MAPPER.writeValueAsString(Map.of("jsonrpc", "2.0", "id", 1, "params", Map.of()))))
.build();
resp = client.send(req, HttpResponse.BodyHandlers.ofString());
data = MAPPER.readTree(resp.body());
error = data.path("error");
System.out.println(" Code: " + error.path("code").asInt() + " (expected -32600)");
System.out.println(" Message: " + error.path("message").asText());
System.out.println("\n=== Test 3: Bad jsonrpc version ===");
req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
MAPPER.writeValueAsString(Map.of(
"jsonrpc", "1.0", "id", 1, "method", "message/send", "params", Map.of()))))
.build();
resp = client.send(req, HttpResponse.BodyHandlers.ofString());
data = MAPPER.readTree(resp.body());
error = data.path("error");
System.out.println(" Code: " + error.path("code").asInt() + " (expected -32600)");
System.out.println(" Message: " + error.path("message").asText());
System.out.println("\nAll invalid request errors demonstrated!");
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "echo-agent-01"
async def main() -> None:
async with httpx.AsyncClient() as client:
print("=== Test 1: Invalid JSON ===")
resp = await client.post(
f"{KUBEMQ_URL}/a2a/{AGENT_ID}",
content=b"{invalid json!!!}",
headers={"Content-Type": "application/json"},
)
data = resp.json()
error = data.get("error", {})
print(f" Code: {error.get('code')} (expected -32700)")
print(f" Message: {error.get('message')}")
print("\n=== Test 2: Missing method field ===")
resp = await client.post(
f"{KUBEMQ_URL}/a2a/{AGENT_ID}",
json={"jsonrpc": "2.0", "id": 1, "params": {}},
)
data = resp.json()
error = data.get("error", {})
print(f" Code: {error.get('code')} (expected -32600)")
print(f" Message: {error.get('message')}")
print("\n=== Test 3: Bad jsonrpc version ===")
resp = await client.post(
f"{KUBEMQ_URL}/a2a/{AGENT_ID}",
json={"jsonrpc": "1.0", "id": 1, "method": "message/send", "params": {}},
)
data = resp.json()
error = data.get("error", {})
print(f" Code: {error.get('code')} (expected -32600)")
print(f" Message: {error.get('message')}")
print("\nAll invalid request errors demonstrated!")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "echo-agent-01";
async function sendRaw(label: string, url: string, opts: RequestInit) {
console.log(`=== ${label} ===`);
try {
const resp = await fetch(url, opts);
const text = await resp.text();
let data: unknown;
try {
data = JSON.parse(text);
} catch {
data = text;
}
console.log(`Status: ${resp.status}`);
console.log(`Response: ${JSON.stringify(data, null, 2)}\n`);
} catch (err) {
console.log(`Error: ${err}\n`);
}
}
async function main() {
await sendRaw(
"Invalid JSON body (expect -32700)",
`${KUBEMQ_URL}/a2a/${AGENT_ID}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{invalid json!!!}",
},
);
await sendRaw(
"Missing method field (expect -32600)",
`${KUBEMQ_URL}/a2a/${AGENT_ID}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, params: {} }),
},
);
await sendRaw(
"Wrong JSON-RPC version (expect -32600)",
`${KUBEMQ_URL}/a2a/${AGENT_ID}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "1.0", id: 1, method: "message/send", params: {} }),
},
);
await sendRaw(
"Wrong Content-Type (expect -32700)",
`${KUBEMQ_URL}/a2a/${AGENT_ID}`,
{
method: "POST",
headers: { "Content-Type": "text/plain" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "message/send", params: {} }),
},
);
await sendRaw(
"Invalid agent_id format (expect -32600)",
`${KUBEMQ_URL}/a2a/UPPERCASE-BAD`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "message/send", params: {} }),
},
);
}
main().catch(console.error);
```
### Timeout (-32001) [#timeout--32001]
Set a short per-call timeout via `params.configuration.timeout` (seconds) and target an
agent that is slower than that. The gateway returns `-32001` once the deadline passes.
```bash
curl -X POST http://localhost:9090/a2a/slow-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "This will timeout"}]},
"configuration": {"timeout": 1}
}
}'
# => {"jsonrpc":"2.0","id":1,"error":{"code":-32001,"message":"agent timeout: slow-agent-01"}}
```
```csharp
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "slow-agent-01";
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "This will timeout" })
},
["configuration"] = new JsonObject { ["timeout"] = 1 }
}
};
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
Console.WriteLine("Sending request with timeout=1 to slow agent (5s delay)...");
var resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/{AgentId}",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
Console.WriteLine(JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true }));
var error = data["error"];
Console.WriteLine($"\nError code: {error?["code"]}");
Console.WriteLine($"Error message: {error?["message"]}");
var code = error?["code"]?.GetValue();
if (code == -32001)
Console.WriteLine("\nTimeout error (-32001) received as expected!");
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "slow-agent-01"
)
func main() {
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{"parts": []map[string]interface{}{{"text": "This will timeout"}}},
"configuration": map[string]interface{}{"timeout": 1},
},
}
data, _ := json.Marshal(payload)
fmt.Println("Sending request with timeout=1 to slow agent (5s delay)...")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var pretty bytes.Buffer
json.Indent(&pretty, body, "", " ")
fmt.Println(pretty.String())
var result map[string]interface{}
json.Unmarshal(body, &result)
errorObj, _ := result["error"].(map[string]interface{})
code, _ := errorObj["code"].(float64)
msg, _ := errorObj["message"].(string)
fmt.Printf("\nError code: %.0f\n", code)
fmt.Printf("Error message: %s\n", msg)
if int(code) != -32001 {
fmt.Fprintf(os.Stderr, "Expected -32001, got %.0f\n", code)
os.Exit(1)
}
fmt.Println("\nTimeout error (-32001) received as expected!")
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "slow-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/send",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "This will timeout"))),
"configuration", Map.of("timeout", 1)
)
);
var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(30))
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
System.out.println("Sending request with timeout=1 to slow agent (5s delay)...");
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(data));
var error = data.path("error");
System.out.println("\nError code: " + error.path("code").asInt());
System.out.println("Error message: " + error.path("message").asText());
assert error.path("code").asInt() == -32001 : "Expected -32001, got " + error.path("code").asInt();
System.out.println("\nTimeout error (-32001) received as expected!");
}
}
```
```python
import asyncio
import json
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "slow-agent-01"
async def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "This will timeout"}]},
"configuration": {"timeout": 1},
},
}
async with httpx.AsyncClient(timeout=30) as client:
print("Sending request with timeout=1 to slow agent (5s delay)...")
resp = await client.post(f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload)
data = resp.json()
print(json.dumps(data, indent=2))
error = data.get("error", {})
print(f"\nError code: {error.get('code')}")
print(f"Error message: {error.get('message')}")
assert error.get("code") == -32001, f"Expected -32001, got {error.get('code')}"
print("\nTimeout error (-32001) received as expected!")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "slow-agent-01";
async function main() {
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: {
message: { parts: [{ text: "This will timeout" }] },
configuration: { timeout: 1 },
},
};
console.log("Sending with timeout=1s to a 5s-delay agent...");
const resp = await fetch(`${KUBEMQ_URL}/a2a/${AGENT_ID}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const data = await resp.json();
console.log("Response:", JSON.stringify(data, null, 2));
if (data.error) {
console.log(`\nError code: ${data.error.code} (expect -32001)`);
console.log(`Error message: ${data.error.message}`);
console.log(`Match: ${data.error.code === -32001}`);
} else {
console.log("\nUnexpected: got success response instead of timeout");
}
}
main().catch(console.error);
```
## Related [#related]
# Getting started with A2A (/aiway/a2a/getting-started)
The A2A connector turns any HTTP service that accepts a JSON-RPC 2.0 POST into a callable agent. You register an agent's
URL with the gateway, then route JSON-RPC `message/send` requests to it through
`POST /a2a/` — no KubeMQ SDK on the agent. This walkthrough takes you from a
running server to a verified round-trip.
## Prerequisites [#prerequisites]
Any running KubeMQ works, including [Try KubeMQ](/deploy/quickstart). MCP and A2A are on by default on port 9090. On Kubernetes, run `kubectl --context YOUR_KUBE_CONTEXT -n kubemq port-forward svc/messaging-rest 9090:9090` first.
* Python 3, to run the throwaway agent in the fastest path.
* `curl` (or one of the language clients below) to send the message.
Confirm the gateway is live by fetching the platform agent card:
```bash
curl http://localhost:9090/.well-known/agent-card.json
```
## Enable / disable [#enable--disable]
The A2A connector is **enabled by default**. Start kubemq-server and the `/a2a/*` and
`/agents/*` routes are live immediately — there is **no `=true` flag to set**.
To **disable** A2A, set its enable variable to `false`:
The disable variable name is irregular by design — the config key `Connectors.A2A.Enable`
snake-cases to `CONNECTORSA2_A_ENABLE`, not `KUBEMQ_A2A_ENABLE`. See
[Shared HTTP server](/connectors/concepts/shared-http-server) for why, and never rely on the
older off-by-default behavior.
## How it works [#how-it-works]
A `message/send` request travels from the caller to the gateway, across the broker to the
agent's virtual subscriber, out to the agent over HTTP, and back the same way — the
gateway relays the agent's JSON-RPC response to the caller unchanged.
*The gateway proxies the request to the agent over the broker and relays the reply unchanged.*
## Fastest path: wrap a plain HTTP service [#fastest-path-wrap-a-plain-http-service]
A short Python server stands in for your own service, so you can prove the whole round trip with `python3` and `curl`. These commands are for bash on macOS and Linux; on Windows, run them in WSL (Windows Subsystem for Linux).
### Start a throwaway agent [#start-a-throwaway-agent]
Save this as `order_status_agent.py`. It answers every POST with a JSON-RPC 2.0 `result`, with no KubeMQ SDK:
```python title="order_status_agent.py"
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
# 127.0.0.1 keeps the agent off your network. Docker Engine on Linux needs 172.17.0.1 (see step 2).
BIND = os.environ.get("AGENT_BIND", "127.0.0.1")
class Agent(BaseHTTPRequestHandler):
def do_POST(self):
n = int(self.headers["Content-Length"])
req = json.loads(self.rfile.read(n))
reply = json.dumps({
"jsonrpc": "2.0",
"id": req.get("id"),
"result": {"status": "in-transit", "eta": "2 days"},
}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(reply)
HTTPServer((BIND, 8090), Agent).serve_forever()
```
Run it in a second terminal and leave it running:
```bash title="Terminal 2"
python3 order_status_agent.py
```
On Docker Engine on Linux, run it on the container bridge address instead:
```bash title="Terminal 2"
AGENT_BIND=172.17.0.1 python3 order_status_agent.py
```
At first the terminal shows nothing and stays busy while the agent runs; it prints one line for each request it answers.
### Register it [#register-it]
KubeMQ runs in a container, so it reaches your agent through your container engine's address for the host, not `localhost`:
| Container engine | Agent address |
| ------------------------------------------------------------------- | --------------------------------------- |
| Docker Desktop (macOS, Windows) | `http://host.docker.internal:8090/` |
| Docker Engine on Linux (agent started with `AGENT_BIND=172.17.0.1`) | `http://172.17.0.1:8090/` |
| Podman (macOS) | `http://host.containers.internal:8090/` |
```bash title="Terminal"
curl -X POST http://localhost:9090/agents/register \
-H "Content-Type: application/json" \
-d '{
"agent_id": "order-status-agent",
"name": "Order Status Agent",
"url": "YOUR_AGENT_URL"
}'
```
Replace:
* `YOUR_AGENT_URL` — the address from the table for your container engine.
You should see:
```text title="Output"
{"agent_id":"order-status-agent","name":"Order Status Agent","url":"http://host.docker.internal:8090/","registered_by":"anonymous","skills":null,"protocolVersions":["1.0"],"last_seen":"2026-09-27T10:00:00.123456Z","registered_at":"2026-09-27T10:00:00.123456Z"}
```
On Kubernetes, register a URL the KubeMQ pods can reach, such as a Service in the cluster.
### Confirm it is registered [#confirm-it-is-registered]
```bash title="Terminal"
curl http://localhost:9090/agents/order-status-agent
```
You should see:
```text title="Output"
{"agent_id":"order-status-agent","name":"Order Status Agent","url":"http://host.docker.internal:8090/","registered_by":"anonymous","skills":null,"protocolVersions":["1.0"],"last_seen":"2026-09-27T10:00:00.123456Z","registered_at":"2026-09-27T10:00:00.123456Z"}
```
### Invoke it [#invoke-it]
Route a JSON-RPC `message/send` request through the gateway to your agent with `POST /a2a/`:
```bash title="Terminal"
curl -X POST http://localhost:9090/a2a/order-status-agent \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"parts": [{"text": "What is the status of order 42?"}]
}
}
}'
```
You should see:
```text title="Output"
{"jsonrpc": "2.0", "id": 1, "result": {"status": "in-transit", "eta": "2 days"}}
```
The gateway relays your agent's reply unchanged.
### Keep it alive, or remove it [#keep-it-alive-or-remove-it]
A registration expires about 5 minutes after the agent's last heartbeat (`AgentTTLSeconds`, default `300`; see [Configuration](/aiway/a2a/configuration)). To keep it, send a heartbeat before then:
```bash title="Terminal"
curl -X POST http://localhost:9090/agents/heartbeat -H "Content-Type: application/json" -d '{"agent_id":"order-status-agent"}'
```
You should see:
```text title="Output"
{"ok":true}
```
To remove it now:
```bash title="Terminal"
curl -X DELETE http://localhost:9090/agents/order-status-agent
```
You should see:
```text title="Output"
{"ok":true}
```
Stop the agent with Ctrl-C in Terminal 2.
### Using your own service [#using-your-own-service]
The throwaway agent exists only to prove the round trip. To use your own service, register the address where it already listens. It must accept the gateway's JSON-RPC 2.0 `POST` and answer with a JSON-RPC 2.0 response: the request's `id` plus a `result` or an `error`. It needs no KubeMQ SDK and no new dependency. A long-running agent sends heartbeats on a timer, or registers again, so its registration never expires; see [Agent Registry](/aiway/a2a/registry#ttl-and-liveness).
## Register from code [#register-from-code]
The same registration and call in six languages.
### Register an agent [#register-an-agent]
An agent registers itself by POSTing its **agent card** — including the absolute
`url` the gateway will call — to `POST /agents/register`. The snippets below register
your agent at `http://localhost:18080/`; with KubeMQ in a container, use an address from
the table in [Register it](#register-it) instead.
```bash
curl -X POST http://localhost:9090/agents/register \
-H "Content-Type: application/json" \
-d '{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": "http://localhost:18080/",
"skills": [
{"id": "echo", "name": "Echo", "description": "Echoes back the received message", "tags": ["test", "echo"]}
],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"]
}'
```
```csharp
var card = new JsonObject
{
["agent_id"] = "echo-agent-01",
["name"] = "Echo Agent",
["description"] = "A simple echo agent for testing",
["version"] = "1.0.0",
["url"] = "http://localhost:18080/",
["skills"] = new JsonArray(new JsonObject
{
["id"] = "echo", ["name"] = "Echo",
["description"] = "Echoes back the received message",
["tags"] = new JsonArray("test", "echo")
}),
["defaultInputModes"] = new JsonArray("text"),
["defaultOutputModes"] = new JsonArray("text"),
["protocolVersions"] = new JsonArray("1.0")
};
using var client = new HttpClient();
var resp = await client.PostAsync(
"http://localhost:9090/agents/register",
new StringContent(card.ToJsonString(), System.Text.Encoding.UTF8, "application/json"));
Console.WriteLine($"Registered: {(int)resp.StatusCode}");
```
```go
card := map[string]interface{}{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": "http://localhost:18080/",
"skills": []map[string]interface{}{
{
"id": "echo",
"name": "Echo",
"description": "Echoes back the received message",
"tags": []string{"test", "echo"},
},
},
"defaultInputModes": []string{"text"},
"defaultOutputModes": []string{"text"},
"protocolVersions": []string{"1.0"},
}
data, _ := json.Marshal(card)
resp, err := http.Post("http://localhost:9090/agents/register", "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Registration failed: %v\n", err)
return
}
defer resp.Body.Close()
fmt.Printf("Registered: %d\n", resp.StatusCode)
```
```java
var card = Map.of(
"agent_id", "echo-agent-01",
"name", "Echo Agent",
"description", "A simple echo agent for testing",
"version", "1.0.0",
"url", "http://localhost:18080/",
"skills", List.of(Map.of(
"id", "echo", "name", "Echo",
"description", "Echoes back the received message",
"tags", List.of("test", "echo")
)),
"defaultInputModes", List.of("text"),
"defaultOutputModes", List.of("text"),
"protocolVersions", List.of("1.0")
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:9090/agents/register"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(card)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("Registered: " + resp.statusCode());
```
```python
card = {
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": "http://localhost:18080/",
"skills": [
{
"id": "echo",
"name": "Echo",
"description": "Echoes back the received message",
"tags": ["test", "echo"],
}
],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"],
}
async with httpx.AsyncClient() as client:
resp = await client.post("http://localhost:9090/agents/register", json=card)
print(f"Registered: {resp.status_code}")
```
```typescript
const card = {
agent_id: "echo-agent-01",
name: "Echo Agent",
description: "A simple echo agent for testing",
version: "1.0.0",
url: "http://localhost:18080/",
skills: [
{
id: "echo",
name: "Echo",
description: "Echoes back the received message",
tags: ["test", "echo"],
},
],
defaultInputModes: ["text"],
defaultOutputModes: ["text"],
protocolVersions: ["1.0"],
};
const resp = await fetch("http://localhost:9090/agents/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(card),
});
console.log("Registered:", resp.status);
```
A `200` response means the agent is registered. The gateway returns the stored card
with server-managed `registered_at` and `last_seen` fields populated.
### Send a message [#send-a-message]
Route a JSON-RPC 2.0 `message/send` request to the agent through
`POST /a2a/`. The gateway forwards it to the agent and relays the reply back.
```bash
curl -X POST http://localhost:9090/a2a/echo-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"parts": [{"text": "Hello, agent!"}]
}
}
}'
```
```csharp
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Hello, agent!" })
}
}
};
using var client = new HttpClient();
var resp = await client.PostAsync(
"http://localhost:9090/a2a/echo-agent-01",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
Console.WriteLine($"Status: {(int)resp.StatusCode}");
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
Console.WriteLine(JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true }));
```
```go
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Hello, agent!"}},
},
},
}
data, _ := json.Marshal(payload)
resp, err := http.Post("http://localhost:9090/a2a/echo-agent-01", "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Status: %d\n", resp.StatusCode)
fmt.Println(string(body))
```
```java
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/send",
"params", Map.of(
"message", Map.of(
"parts", List.of(Map.of("text", "Hello, agent!"))
)
)
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:9090/a2a/echo-agent-01"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + resp.statusCode());
var data = MAPPER.readTree(resp.body());
System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(data));
```
```python
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"parts": [{"text": "Hello, agent!"}],
},
},
}
async with httpx.AsyncClient() as client:
resp = await client.post("http://localhost:9090/a2a/echo-agent-01", json=payload)
print(f"Status: {resp.status_code}")
data = resp.json()
print(json.dumps(data, indent=2))
assert "result" in data
```
```typescript
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: {
message: {
parts: [{ text: "Hello, agent!" }],
},
},
};
const resp = await fetch("http://localhost:9090/a2a/echo-agent-01", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const data = await resp.json();
console.log("Response:", JSON.stringify(data, null, 2));
```
### Verify the reply [#verify-the-reply]
If your agent echoes the request body inside `result.echo`, the reply confirms the
round-trip through the gateway:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"echo": {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": { "parts": [{ "text": "Hello, agent!" }] }
}
}
}
}
```
A response containing `result` is a successful round-trip. A response with an `error`
object instead means the gateway or agent reported a problem — see
[Error handling](/aiway/a2a/error-handling) for the codes and how to
distinguish transport failures from application errors.
## Troubleshooting [#troubleshooting]
* Connection refused on port 9090: KubeMQ is not running, or port 9090 is not published.
* The response has an `error` object instead of `result`: read `error.message`. The gateway answers HTTP 200 with the error in the body. A message that starts `agent unreachable:` means KubeMQ cannot reach the registered `url`; recheck the address you chose in [Register it](#register-it).
* `agent not found` (code `-32002`) a few minutes after it worked: the registration expired. Register again, or send heartbeats.
## What's next [#whats-next]
## Container command examples
```sh
docker run -d --pull always --platform linux/amd64 --name kubemq --hostname kubemq -e STORE_ENGINE=next -e STORE_NEXT_ACK_POLICY=strict -e STORE_STORE_PATH=/kubemq/store -e API_BIND_ADDRESS=0.0.0.0 -e CONNECTORSA2_A_ENABLE=false -v kubemq-data:/kubemq/store europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# AI Agents (A2A) (/aiway/a2a)
The **A2A connector** turns KubeMQ into a gateway for AI agents. It implements a
subset of Google's Agent-to-Agent protocol as a transparent JSON-RPC 2.0 proxy: a
caller POSTs to `/a2a/{agent_id}`, and KubeMQ routes the request to the right agent
and relays the reply back — agents stay plain HTTP servers with **zero KubeMQ
dependencies**.
**Part of Aiway.** A2A is one of the two doors into
[KubeMQ Aiway](/aiway), the AI Agents Fabric. New here? Start with the
[Aiway overview](/aiway), or follow the end-to-end
[Aiway tutorial](/aiway/tutorial).
## What is A2A [#what-is-a2a]
A2A lets one agent call another through a single, well-known endpoint instead of
wiring point-to-point connections between every pair of agents. KubeMQ sits in the
middle as the gateway and does the work that would otherwise be repeated in each
agent: looking up where a target agent lives, enforcing timeouts and concurrency
limits, forwarding the right headers, and proxying Server-Sent Event streams.
Two pieces make this work:
* An **agent registry** — a REST API where agents announce themselves by `agent_id`
and HTTP URL. The registry tracks each agent's card (name, skills, version) with
TTL-based liveness.
* A **virtual subscriber** (also called the **Agent Bridge**) — when an agent
registers, KubeMQ spawns an internal subscriber on the internal channel
`_AGENTS_.agents/`. Incoming JSON-RPC requests arrive over the broker, and
the virtual subscriber forwards each one as an HTTP `POST` to the agent's registered
URL, then relays the response back. The MCP *agent-bridge tools*
(`agent_list`/`agent_info`/`agent_send`/`agent_query`) invoke agents *through* this
Agent Bridge — same concept, two layers, not two meanings.
Because the virtual subscriber handles all broker and protobuf translation, **an agent
is just an HTTP server that speaks JSON-RPC 2.0** — there is no KubeMQ SDK, no
protobuf, and no broker knowledge on the agent side.
This is a breaking change from older KubeMQ A2A docs, which described agents that
embedded a KubeMQ SDK. Agents are now registered by absolute `http(s)://` URL and
require no library. See [Building agents](/aiway/a2a/guides/building-agents)
for the current model.
## Why A2A on KubeMQ [#why-a2a-on-kubemq]
* **No SDK on agents** — register a URL; KubeMQ bridges the broker to your agent's HTTP
endpoint for you.
* **One gateway, many agents** — callers always POST to `/a2a/{agent_id}`; routing,
discovery, and lifecycle are centralized.
* **Sync and streaming** — `message/send` for request/reply, `message/stream` for
long-running tasks proxied as SSE.
* **Method-agnostic proxy** — standard A2A methods and any custom JSON-RPC method are
forwarded as-is; the agent decides what to handle.
* **Built-in guardrails** — per-agent concurrency caps, timeout enforcement with a
gateway buffer, response-size limits, and selective header forwarding.
## Architecture [#architecture]
A caller never connects to an agent directly. The request flows through the A2A
gateway, over the broker to the target agent's virtual subscriber, and out as an HTTP POST.
*The gateway proxies JSON-RPC over the broker; the virtual subscriber calls the agent's HTTP URL.*
## Endpoint surface [#endpoint-surface]
| Method | Path | Purpose |
| ------ | --------------------------------------------- | ---------------------------------------------------------------------------------- |
| `POST` | `/a2a/{agent_id}` | JSON-RPC 2.0 proxy to the agent (`message/send`, `message/stream`, custom methods) |
| `GET` | `/a2a/{agent_id}/stream` | SSE streaming endpoint |
| `GET` | `/a2a/{agent_id}/.well-known/agent-card.json` | Individual agent card |
| `GET` | `/.well-known/agent-card.json` | Platform-level card |
| `POST` | `/agents/register` | Register an agent |
| `POST` | `/agents/heartbeat` | Agent heartbeat (refresh liveness) |
| `POST` | `/agents/deregister` | Deregister an agent |
| `GET` | `/agents` | List registered agents (optional skill-tag filter) |
| `GET` | `/agents/{agent_id}` | Get one agent's card |
The A2A connector runs on the [shared HTTP server](/connectors/concepts/shared-http-server)
(port 9090) and is **enabled by default** — there is no flag to turn it on. To disable
it, set `CONNECTORSA2_A_ENABLE=false`.
## Send a message [#send-a-message]
A request is a JSON-RPC 2.0 envelope POSTed to `/a2a/{agent_id}`. The example below
sends `message/send` to a registered `echo-agent-01`.
```bash
curl -X POST http://localhost:9090/a2a/echo-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"parts": [{"text": "Hello, agent!"}]
}
}
}'
```
```csharp
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "echo-agent-01";
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Hello, agent!" })
}
}
};
using var client = new HttpClient();
var resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/{AgentId}",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
Console.WriteLine($"Status: {(int)resp.StatusCode}");
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
Console.WriteLine(JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true }));
if (data["result"] != null)
Console.WriteLine("\nBasic send completed successfully!");
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "echo-agent-01"
)
func main() {
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Hello, agent!"}},
},
},
}
data, _ := json.Marshal(payload)
resp, err := http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Status: %d\n", resp.StatusCode)
var pretty bytes.Buffer
json.Indent(&pretty, body, "", " ")
fmt.Println(pretty.String())
var result map[string]interface{}
json.Unmarshal(body, &result)
if _, ok := result["result"]; !ok {
fmt.Fprintf(os.Stderr, "Missing 'result' in response\n")
os.Exit(1)
}
fmt.Println("\nBasic send completed successfully!")
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "echo-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/send",
"params", Map.of(
"message", Map.of(
"parts", List.of(Map.of("text", "Hello, agent!"))
)
)
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + resp.statusCode());
var data = MAPPER.readTree(resp.body());
System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(data));
assert data.has("result");
System.out.println("\nBasic send completed successfully!");
}
}
```
```python
import asyncio
import json
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "echo-agent-01"
async def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"parts": [{"text": "Hello, agent!"}],
},
},
}
async with httpx.AsyncClient() as client:
resp = await client.post(
f"{KUBEMQ_URL}/a2a/{AGENT_ID}",
json=payload,
)
print(f"Status: {resp.status_code}")
data = resp.json()
print(json.dumps(data, indent=2))
assert "result" in data
print("\nBasic send completed successfully!")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "echo-agent-01";
async function main() {
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: {
message: {
parts: [{ text: "Hello, agent!" }],
},
},
};
const resp = await fetch(`${KUBEMQ_URL}/a2a/${AGENT_ID}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const data = await resp.json();
console.log("Response:", JSON.stringify(data, null, 2));
if (data.result) {
console.log("\nBasic send completed successfully!");
} else if (data.error) {
console.error("\nError:", data.error.message);
}
}
main().catch(console.error);
```
## Supported languages [#supported-languages]
Every A2A operation ships with a curl example plus client code in five languages,
sourced from real working examples.
| Language | Client |
| ----------- | ------------------------------------ |
| curl / HTTP | Raw JSON-RPC over HTTP |
| C# | `HttpClient` + `System.Text.Json` |
| Go | `net/http` + `encoding/json` |
| Java | `java.net.http.HttpClient` + Jackson |
| Python | `httpx` (async) |
| TypeScript | `fetch` |
## Next steps [#next-steps]
# Reference (/aiway/a2a/reference)
The complete API surface of the KubeMQ A2A connector: HTTP endpoints, the JSON-RPC 2.0 wire format, the agent card schema, internal channels, configuration fields, error codes, and Prometheus metrics. The connector is a transparent JSON-RPC proxy — agents are plain HTTP servers registered by URL, reached through a per-agent virtual subscriber over the broker.
All HTTP endpoints are served on the [shared HTTP server](/connectors/concepts/shared-http-server) (default port `9090`), which also hosts the REST, MCP, and CloudEvents connectors. Prometheus metrics are exposed separately on port `8080` (see [Observability](/connectors/concepts/observability)).
## HTTP Endpoints [#http-endpoints]
### A2A endpoints [#a2a-endpoints]
| Method | Path | Description | Request body | Success | Error |
| ------ | ------------------------ | ------------------------------------- | -------------------- | ----------------------------- | ---------------------- |
| POST | `/a2a/{agent_id}` | JSON-RPC 2.0 request (sync or stream) | JSON-RPC 2.0 payload | JSON-RPC result or SSE stream | JSON-RPC error |
| GET | `/a2a/{agent_id}` | Not supported | — | — | 405 Method Not Allowed |
| GET | `/a2a/{agent_id}/stream` | SSE stream via GET | — | `text/event-stream` | — |
`POST /a2a/{agent_id}` is the primary endpoint. Its behavior depends on the JSON-RPC `method`: `message/stream` opens an SSE proxy; every other method is forwarded synchronously to the agent. `GET /a2a/{agent_id}` always returns **405** — use POST for JSON-RPC or `GET /a2a/{agent_id}/stream` for a server-pushed stream.
```bash
# Synchronous message/send
curl -X POST http://localhost:9090/a2a/echo-agent-01 \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"message/send","params":{"message":{"parts":[{"text":"Hello, agent!"}]}}}'
# SSE stream via GET
curl -N http://localhost:9090/a2a/echo-agent-01/stream \
-H 'Accept: text/event-stream'
```
### Registry endpoints [#registry-endpoints]
Standard HTTP JSON responses (not JSON-RPC). See [Agent registry](/aiway/a2a/registry) for the full workflow.
| Method | Path | Description | Request body | Success | Error |
| ------ | -------------------- | --------------------------------------------- | ------------------ | ------------------------------------- | --------------- |
| POST | `/agents/register` | Register an agent | Agent card JSON | 200 + enriched card | 400 / 403 / 409 |
| GET | `/agents` | List agents (filter by `skill_tags`, `limit`) | — | 200 + `[, …]` (bare array) | — |
| GET | `/agents/{agent_id}` | Get one agent | — | 200 + agent card | 404 |
| POST | `/agents/deregister` | Deregister (JSON body) | `{"agent_id":"…"}` | 200 + `{"ok":true}` | 404 |
| DELETE | `/agents/{agent_id}` | Deregister (REST, backward compat) | — | 200 + `{"ok":true}` | 404 |
| POST | `/agents/heartbeat` | Refresh liveness | `{"agent_id":"…"}` | 200 + `{"ok":true}` | 400 |
`POST /agents/register` errors: **400** (card validation), **403** (ownership conflict — a different principal owns this `agent_id`), **409** (`MaxAgents` limit reached). `registered_by` is set automatically from the caller's JWT claims.
```bash
# List agents tagged "search" or "nlp", capped at 10
curl 'http://localhost:9090/agents?skill_tags=search,nlp&limit=10'
```
### Agent card endpoints [#agent-card-endpoints]
| Method | Path | Description | Success | Error |
| ------ | --------------------------------------------- | ------------------------------------- | ---------------------- | ----- |
| GET | `/.well-known/agent-card.json` | Platform agent card (KubeMQ metadata) | 200 (`name: "kubemq"`) | — |
| GET | `/a2a/{agent_id}/.well-known/agent-card.json` | Individual agent card from registry | 200 + enriched card | 404 |
Both `.well-known/agent-card.json` paths are public — they bypass authentication. See [Agent cards](/aiway/a2a/agent-cards).
```bash
# Platform card — confirms the A2A connector is reachable
curl http://localhost:9090/.well-known/agent-card.json
```
## JSON-RPC 2.0 wire format [#json-rpc-20-wire-format]
The connector uses JSON-RPC 2.0 for all client-to-agent communication. A request carries three required fields plus an optional `params` object.
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": { "parts": [{ "text": "Hello, agent!" }] },
"contextId": "optional-correlation-id",
"configuration": { "timeout": 30 }
}
}
```
### Request fields [#request-fields]
| Field | Type | Required | Description |
| ------------------------------ | ----------------- | -------- | ------------------------------------------------------------------------------------------------- |
| `jsonrpc` | string | Yes | Must be `"2.0"` |
| `id` | integer or string | Yes | Request identifier, echoed in the response |
| `method` | string | Yes | JSON-RPC method name (missing/empty → `-32600`) |
| `params` | object | No | Method parameters |
| `params.message.parts` | array | No | Message content; each part has a `text` field |
| `params.contextId` | string | No | Correlation ID, passed to the agent unmodified |
| `params.configuration.timeout` | number | No | Request timeout in seconds (falls back to `DefaultTimeoutSeconds`, capped at `MaxTimeoutSeconds`) |
### Methods [#methods]
KubeMQ is method-agnostic — it forwards any method to the agent unchanged. The five methods below are recognized for metrics labeling; all others are recorded as `method="unknown"`.
| Method | Behavior | Response |
| -------------------- | ------------------------------------------- | ------------------- |
| `message/send` | Synchronous proxy to the agent | JSON-RPC response |
| `message/stream` | SSE stream proxy via the virtual subscriber | `text/event-stream` |
| `tasks/get` | Forwarded to the agent | JSON-RPC response |
| `tasks/cancel` | Forwarded to the agent | JSON-RPC response |
| `tasks/send` | Forwarded to the agent | JSON-RPC response |
| *(any other method)* | Forwarded to the agent | JSON-RPC response |
JSON-RPC batch requests (an array of request objects) are **not supported** — send individual requests. Notifications (requests without an `id`) are forwarded to the agent but receive no response.
### Success and error responses [#success-and-error-responses]
On success, the agent's return value is placed verbatim in `result` — KubeMQ does not modify the payload. On failure, the response carries an `error` object instead.
```json
{ "jsonrpc": "2.0", "id": 1, "result": { "…": "agent output, unmodified" } }
```
```json
{ "jsonrpc": "2.0", "id": 1, "error": { "code": -32002, "message": "agent not found: nonexistent-agent" } }
```
## Agent card schema [#agent-card-schema]
The `AgentCard` is submitted on registration and returned, enriched with server-managed timestamps, from the list/get/well-known endpoints. Required fields are `agent_id`, `name`, and `url`.
| Field | JSON key | Type | Required | Description |
| --------------------- | --------------------- | --------- | -------- | -------------------------------------------------------------------------- |
| `AgentID` | `agent_id` | string | Yes | Unique ID; 2–128 chars, `^[a-z0-9][a-z0-9-]{0,126}[a-z0-9]$` |
| `Name` | `name` | string | Yes | Human-readable name (max 256 chars) |
| `Description` | `description` | string | No | Agent description (max 2048 chars) |
| `Version` | `version` | string | No | Agent version (max 64 chars) |
| `URL` | `url` | string | Yes | Absolute `http://` or `https://` URL (max 2048 chars) |
| `RegisteredBy` | `registered_by` | string | No | JWT principal that registered the agent (server-set) |
| `Capabilities` | `capabilities` | object | No | Free-form capability map |
| `Skills` | `skills` | array | No | List of `AgentSkill` (see below) |
| `DefaultInputModes` | `defaultInputModes` | string\[] | No | Default input modes |
| `DefaultOutputModes` | `defaultOutputModes` | string\[] | No | Default output modes |
| `SupportedInterfaces` | `supportedInterfaces` | JSON | No | Opaque JSON |
| `SecuritySchemes` | `securitySchemes` | JSON | No | Opaque JSON |
| `Security` | `security` | JSON | No | Opaque JSON |
| `ProtocolVersions` | `protocolVersions` | string\[] | No | Supported versions (default `["1.0"]`) |
| `Metadata` | `metadata` | object | No | Key-value metadata |
| `LastSeen` | `last_seen` | timestamp | — | Last heartbeat/registration (server-set) |
| `RegisteredAt` | `registered_at` | timestamp | — | Original registration time, preserved across re-registrations (server-set) |
### AgentSkill [#agentskill]
| Field | JSON key | Type | Required | Description |
| ------------- | ------------- | --------- | -------- | ------------------------------------------- |
| `ID` | `id` | string | Yes | Skill identifier |
| `Name` | `name` | string | Yes | Skill name |
| `Description` | `description` | string | No | Skill description |
| `Tags` | `tags` | string\[] | No | Skill tags, used by the `skill_tags` filter |
```json
{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"url": "http://localhost:18080/",
"skills": [{ "id": "echo", "name": "Echo", "tags": ["test", "echo"] }]
}
```
## Internal channel map [#internal-channel-map]
The connector and registry use the reserved `_AGENTS_.` prefix internally. User channels carrying this prefix are rejected (`IsReservedChannel`). Callers never address these channels directly — the connector and virtual subscriber own them.
| Channel pattern | Purpose | Transport |
| ----------------------------- | -------------------------------------------------------------------------------- | ------------ |
| `_AGENTS_.agents/{agent_id}` | Request/reply to an agent via its virtual subscriber (including `stream_cancel`) | Query |
| `_AGENTS_.stream/{stream_id}` | Temporary SSE stream events relayed by the virtual subscriber | Events |
| `_AGENTS_.discovery` | Registry replication across cluster nodes | Events Store |
Caller HTTP headers are forwarded to the agent as `a2a_hdr_*` tags on the broker request; the virtual subscriber always sets `X-KubeMQ-Caller-ID` to the original caller's identity. See [Architecture](/aiway/a2a/architecture).
## SSE event types [#sse-event-types]
Streaming responses (`message/stream` or `GET /a2a/{agent_id}/stream`) are delivered as Server-Sent Events. Each event has an `event:` line and a `data:` line carrying the stream envelope. A keepalive comment (`: keepalive`) is sent every 30 seconds; the idle timeout is `MaxSSEIdleSeconds` (default 300s). See [Streaming](/aiway/a2a/streaming).
| SSE event | Envelope `type` | Description | Terminal |
| --------------- | --------------- | ----------------------- | -------- |
| `task.status` | `status_update` | Progress update | No |
| `task.artifact` | `artifact` | Intermediate artifact | No |
| `task.done` | `done` | Successful completion | Yes |
| `task.error` | `error` | Failure | Yes |
| `message` | *(default)* | Any other envelope type | No |
```text
event: task.status
data: {"stream_id":"…","type":"status_update","payload":{"status":"working"}}
event: task.done
data: {"stream_id":"…","type":"done","payload":{"final_result":"completed"}}
```
## Error codes [#error-codes]
The connector returns standard JSON-RPC 2.0 base codes plus four A2A-specific codes. See [Error handling](/aiway/a2a/error-handling) for the transport-vs-application distinction and retry guidance.
| Code | Name | Trigger |
| -------- | ---------------------- | ------------------------------------------------------------------------- |
| `-32700` | Parse Error | Malformed JSON body, or `Content-Type` is not `application/json` |
| `-32600` | Invalid Request | Missing `method` field, `jsonrpc` != `"2.0"`, or empty/invalid `agent_id` |
| `-32601` | Method Not Found | Reserved — KubeMQ forwards all methods to agents and does not raise this |
| `-32602` | Invalid Params | Malformed `params` object |
| `-32603` | Internal Error | Server-side failure |
| `-32010` | Authentication Failure | JWT auth error on `/a2a/*` (REST endpoints return HTTP 401 instead) |
| `-32001` | Agent Timeout | Agent did not respond within the timeout |
| `-32002` | Agent Not Found | No agent registered with the given `agent_id` |
| `-32003` | Agent Unavailable | Agent rejected the request |
| `-32004` | Invalid Response | Invalid response from the agent |
### Transport vs application errors [#transport-vs-application-errors]
The virtual subscriber sets `Executed: false` on **transport** failures (the agent never processed the request) and `Executed: true` on **application** errors (the agent processed it and returned an error body). This lets callers choose a retry strategy.
| Agent result | `pb.Response` | Category |
| -------------------------------------------- | -------------------------------------------------------------------- | ----------- |
| Connection refused / DNS failure | `Executed: false`, `Error: "agent unreachable: …"` | Transport |
| HTTP timeout | `Executed: false`, `Error: "agent timeout"` | Transport |
| HTTP 502 / 503 / 504 | `Executed: false`, `Error: "agent unavailable: …"` | Transport |
| Response exceeds `AgentMaxResponseBytes` | `Executed: false`, `Error: "agent response too large"` | Transport |
| Concurrency limit reached | `Executed: false`, `Error: "server busy: concurrency limit reached"` | Transport |
| HTTP 200–299 | `Executed: true`, `Body: response` | Success |
| HTTP 400 / 401 / 403 / 404 / 409 / 422 / 500 | `Executed: true`, `Body: response` | Application |
## Configuration fields [#configuration-fields]
`A2aConfig` is configured in `Connectors.A2A.*`. The connector is **enabled by default** — set `CONNECTORSA2_A_ENABLE=false` to disable it. See [Configuration](/aiway/a2a/configuration) and the [shared HTTP server](/connectors/concepts/shared-http-server#enable-model-on-by-default) enable model for the irregular env-var naming.
| Field | Default | Disable/override env var | Description |
| ----------------------- | ------------------ | ----------------------------------------- | --------------------------------------------------------------------- |
| `Enable` | `true` | `CONNECTORSA2_A_ENABLE` | Enable the A2A connector (set `=false` to disable) |
| `AgentTTLSeconds` | `300` | `CONNECTORSA2_A_AGENT_TTL_SECONDS` | Agent expiry TTL (liveness check) |
| `DefaultTimeoutSeconds` | `300` | `CONNECTORSA2_A_DEFAULT_TIMEOUT_SECONDS` | Default request timeout |
| `MaxTimeoutSeconds` | `3600` | `CONNECTORSA2_A_MAX_TIMEOUT_SECONDS` | Maximum allowed request timeout (must be ≥ `DefaultTimeoutSeconds`) |
| `MaxAgents` | `0` (unlimited) | `CONNECTORSA2_A_MAX_AGENTS` | Maximum registered agents |
| `MaxSSEIdleSeconds` | `300` | `CONNECTORSA2_A_MAX_SSE_IDLE_SECONDS` | SSE stream idle timeout |
| `TrustedOrigins` | `["auto"]` | `CONNECTORSA2_A_TRUSTED_ORIGINS` | Trusted origins for browser requests |
| `AgentMaxResponseBytes` | `10485760` (10 MB) | `CONNECTORSA2_A_AGENT_MAX_RESPONSE_BYTES` | Max agent HTTP response size; larger → `Executed: false` |
| `AgentTLSSkipVerify` | `false` | `CONNECTORSA2_A_AGENT_TLS_SKIP_VERIFY` | Skip TLS verification for outbound agent calls (dev only) |
| `AgentMaxConcurrency` | `100` | `CONNECTORSA2_A_AGENT_MAX_CONCURRENCY` | Max concurrent in-flight requests per agent; overflow → "server busy" |
The gateway adds a `GatewayTimeoutBuffer` of 10 seconds on top of the caller-specified timeout so it does not time out before the downstream agent.
## Metrics [#metrics]
Prometheus metrics are exposed on port `8080` at `/metrics`. See [Observability](/connectors/concepts/observability) for the full surface and the web AI dashboard.
| Metric | Type | Labels | Description |
| -------------------------------------- | --------- | ------------------------------ | ------------------------------------------------------------- |
| `kubemq_a2a_requests_total` | Counter | `agent_id`, `method`, `status` | A2A requests forwarded to agents |
| `kubemq_a2a_request_duration_seconds` | Histogram | `agent_id` | A2A request duration |
| `kubemq_a2a_errors_total` | Counter | `agent_id`, `error_code` | A2A gateway errors |
| `kubemq_a2a_registry_operations_total` | Counter | `op`, `status` | Registry operations (register, deregister, heartbeat, expire) |
| `kubemq_a2a_sse_streams_active` | Gauge | — | Currently active SSE streams |
The `method` label is sanitized against the five standard methods; any other value is recorded as `method="unknown"` to bound Prometheus label cardinality.
```bash
curl http://localhost:8080/metrics 2>/dev/null | grep kubemq_a2a_
```
# Agent Registry (/aiway/a2a/registry)
The **agent registry** is a REST API where agents announce themselves to KubeMQ by
`agent_id` and HTTP URL. It is the source of truth for who can be reached over the A2A
gateway: registering an agent spawns its [virtual subscriber](/aiway/a2a/architecture),
and a TTL-based liveness check removes agents that stop sending heartbeats.
## Overview [#overview]
Every agent that callers can reach through `POST /a2a/{agent_id}` must first be
registered. A registration is an **agent card** — `agent_id`, human-readable `name`,
absolute `url`, and an optional list of skills. The registry persists cards in SQLite,
tracks each agent's `last_seen` time, and replicates state across a cluster so any node
can route to any agent.
The registry exposes five operations as plain HTTP+JSON (not JSON-RPC):
| Operation | Method · Path | Purpose |
| ---------- | -------------------------------------------------------- | ---------------------------------------------- |
| Register | `POST /agents/register` | Add or re-register an agent card |
| List | `GET /agents` | List agents, optionally filtered by skill tags |
| Get one | `GET /agents/{agent_id}` | Fetch a single agent's full card |
| Heartbeat | `POST /agents/heartbeat` | Refresh `last_seen` to stay alive |
| Deregister | `POST /agents/deregister` or `DELETE /agents/{agent_id}` | Remove an agent |
## How it works [#how-it-works]
The registry is a service backed by SQLite. Registering spawns a virtual subscriber and
emits a replication event; a background liveness checker sweeps expired agents.
*Registration persists the card and spawns a virtual subscriber; the liveness checker prunes agents past their TTL.*
## The agent card [#the-agent-card]
An agent card describes one agent. `agent_id`, `name`, and `url` are required; the
`url` must be an absolute `http://` or `https://` address. Server-managed fields
(`registered_at`, `last_seen`) are populated on the response.
| Field | Type | Required | Description |
| -------------------- | --------- | ---------- | -------------------------------------------------------------------- |
| `agent_id` | string | yes | Unique identifier; 2–128 chars, lowercase alphanumeric and hyphens |
| `name` | string | yes | Human-readable name (max 256 chars) |
| `url` | string | yes | Absolute `http(s)://` endpoint the gateway POSTs to (max 2048 chars) |
| `description` | string | no | Free-text description (max 2048 chars) |
| `version` | string | no | Agent version (max 64 chars) |
| `skills` | array | no | List of `AgentSkill` objects (see below) |
| `defaultInputModes` | string\[] | no | Default input modes, e.g. `["text"]` |
| `defaultOutputModes` | string\[] | no | Default output modes, e.g. `["text"]` |
| `protocolVersions` | string\[] | no | Supported protocol versions; defaults to `["1.0"]` |
| `registered_at` | string | server-set | Original registration time (preserved across re-registration) |
| `last_seen` | string | server-set | Last heartbeat or registration time |
Each entry in `skills` is an **AgentSkill**: `id` (required), `name` (required),
`description`, and `tags` (used by the [list](#list-agents) filter and skill-based
discovery).
```json
{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": "http://localhost:18080/",
"skills": [
{
"id": "echo",
"name": "Echo",
"description": "Echoes back the received message",
"tags": ["test", "echo"]
}
],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"]
}
```
## Register an agent [#register-an-agent]
`POST /agents/register` with the agent card as the JSON body. Re-registering the same
`agent_id` upserts the card and **preserves the original `registered_at`**. The response
is the stored card with `registered_at` and `last_seen` populated.
When auth is enabled, the `registered_by` field is set from the JWT principal and is
used for [ownership](#ownership) checks. Registration fails with `400` (validation),
`403` (ownership conflict), or `409` (the `MaxAgents` limit was reached).
```bash
curl -X POST http://localhost:9090/agents/register \
-H "Content-Type: application/json" \
-d '{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": "http://localhost:18080/",
"skills": [
{"id": "echo", "name": "Echo", "description": "Echoes back the received message", "tags": ["test", "echo"]}
],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"]
}'
```
```csharp
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const int AgentPort = 18080;
var card = new JsonObject
{
["agent_id"] = "echo-agent-01",
["name"] = "Echo Agent",
["description"] = "A simple echo agent for testing",
["version"] = "1.0.0",
["url"] = $"http://localhost:{AgentPort}/",
["skills"] = new JsonArray(new JsonObject
{
["id"] = "echo", ["name"] = "Echo",
["description"] = "Echoes back the received message",
["tags"] = new JsonArray("test", "echo")
}),
["defaultInputModes"] = new JsonArray("text"),
["defaultOutputModes"] = new JsonArray("text"),
["protocolVersions"] = new JsonArray("1.0")
};
using var client = new HttpClient();
var resp = await client.PostAsync(
$"{KubeMqUrl}/agents/register",
new StringContent(card.ToJsonString(), Encoding.UTF8, "application/json"));
Console.WriteLine($"Registered: {(int)resp.StatusCode}");
var body = await resp.Content.ReadAsStringAsync();
Console.WriteLine(JsonSerializer.Serialize(JsonNode.Parse(body), new JsonSerializerOptions { WriteIndented = true }));
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "echo-agent-01"
agentPort = 18080
)
func main() {
card := map[string]interface{}{
"agent_id": agentID,
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": fmt.Sprintf("http://localhost:%d/", agentPort),
"skills": []map[string]interface{}{
{
"id": "echo",
"name": "Echo",
"description": "Echoes back the received message",
"tags": []string{"test", "echo"},
},
},
"defaultInputModes": []string{"text"},
"defaultOutputModes": []string{"text"},
"protocolVersions": []string{"1.0"},
}
data, _ := json.Marshal(card)
resp, err := http.Post(kubemqURL+"/agents/register", "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Registration failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Registered: %d\n", resp.StatusCode)
var pretty bytes.Buffer
json.Indent(&pretty, body, "", " ")
fmt.Println(pretty.String())
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final int AGENT_PORT = 18080;
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var card = Map.of(
"agent_id", "echo-agent-01",
"name", "Echo Agent",
"description", "A simple echo agent for testing",
"version", "1.0.0",
"url", "http://localhost:" + AGENT_PORT + "/",
"skills", List.of(Map.of(
"id", "echo", "name", "Echo",
"description", "Echoes back the received message",
"tags", List.of("test", "echo"))),
"defaultInputModes", List.of("text"),
"defaultOutputModes", List.of("text"),
"protocolVersions", List.of("1.0")
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents/register"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(card)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("Registered: " + resp.statusCode());
var data = MAPPER.readTree(resp.body());
System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(data));
}
}
```
```python
import asyncio
import json
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_PORT = 18080
async def main() -> None:
card = {
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": f"http://localhost:{AGENT_PORT}/",
"skills": [
{
"id": "echo",
"name": "Echo",
"description": "Echoes back the received message",
"tags": ["test", "echo"],
}
],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"],
}
async with httpx.AsyncClient() as client:
resp = await client.post(f"{KUBEMQ_URL}/agents/register", json=card)
print(f"Registered: {resp.status_code}")
print(json.dumps(resp.json(), indent=2))
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_PORT = 18080;
async function main() {
const card = {
agent_id: "echo-agent-01",
name: "Echo Agent",
description: "A simple echo agent for testing",
version: "1.0.0",
url: `http://localhost:${AGENT_PORT}/`,
skills: [
{
id: "echo",
name: "Echo",
description: "Echoes back the received message",
tags: ["test", "echo"],
},
],
defaultInputModes: ["text"],
defaultOutputModes: ["text"],
protocolVersions: ["1.0"],
};
const resp = await fetch(`${KUBEMQ_URL}/agents/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(card),
});
const data = await resp.json();
console.log("Registered:", JSON.stringify(data, null, 2));
}
main().catch(console.error);
```
## List agents [#list-agents]
`GET /agents` returns a bare JSON array `[, ...]`. Add `?skill_tags=tag1,tag2`
(comma-separated) to filter by skill tags, and `?limit=N` to cap the page size. Skill-tag
filtering is applied in memory after fetching, enabling skill-based discovery.
```bash
# All agents
curl http://localhost:9090/agents
# Filter by skill tags
curl "http://localhost:9090/agents?skill_tags=echo"
```
```csharp
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
using var client = new HttpClient();
Console.WriteLine("=== All Agents ===");
var resp = await client.GetAsync($"{KubeMqUrl}/agents");
var agentsRoot = JsonNode.Parse(await resp.Content.ReadAsStringAsync())!;
var agents = agentsRoot is JsonArray arr ? arr : agentsRoot["agents"]!.AsArray();
foreach (var agent in agents)
{
var skills = agent!["skills"]?.AsArray().Select(s => s!["id"]!.GetValue()).ToList() ?? [];
Console.WriteLine($" {agent["agent_id"]}: skills=[{string.Join(", ", skills)}]");
}
Console.WriteLine($"\nTotal agents: {agents.Count}");
Console.WriteLine("\n=== Filter by skill_tags=echo ===");
resp = await client.GetAsync($"{KubeMqUrl}/agents?skill_tags=echo");
var echoRoot = JsonNode.Parse(await resp.Content.ReadAsStringAsync())!;
var filtered = echoRoot is JsonArray echoArr ? echoArr : echoRoot["agents"]!.AsArray();
foreach (var agent in filtered)
Console.WriteLine($" {agent!["agent_id"]}");
```
```go
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const kubemqURL = "http://localhost:9090"
func listAgents(url string, label string) {
resp, err := http.Get(url)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// GET /agents returns a bare JSON array: [, ...]
var agents []map[string]interface{}
if err := json.Unmarshal(body, &agents); err != nil {
// Fallback for a {"agents":[...]} wrapper, if ever present.
var wrapper map[string]interface{}
json.Unmarshal(body, &wrapper)
if raw, ok := wrapper["agents"].([]interface{}); ok {
for _, a := range raw {
if m, ok := a.(map[string]interface{}); ok {
agents = append(agents, m)
}
}
}
}
fmt.Printf("=== %s ===\n", label)
for _, agent := range agents {
fmt.Printf(" %s\n", agent["agent_id"])
}
fmt.Printf("\nTotal: %d\n\n", len(agents))
}
func main() {
listAgents(kubemqURL+"/agents", "All Agents")
listAgents(kubemqURL+"/agents?skill_tags=echo", "Filter by skill_tags=echo")
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var client = HttpClient.newHttpClient();
System.out.println("=== All Agents ===");
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents"))
.GET().build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var root = MAPPER.readTree(resp.body());
var agents = root.isArray() ? root : root.get("agents");
for (var agent : agents) {
System.out.println(" " + agent.get("agent_id").asText());
}
System.out.println("\nTotal agents: " + agents.size());
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
async def main() -> None:
async with httpx.AsyncClient() as client:
print("=== All Agents ===")
resp = await client.get(f"{KUBEMQ_URL}/agents")
data = resp.json()
agents = data.get("agents", data) if isinstance(data, dict) else data
for agent in agents:
skills = [s["id"] for s in agent.get("skills", [])]
print(f" {agent['agent_id']}: skills={skills}")
print(f"\nTotal agents: {len(agents)}")
print("\n=== Filter by skill_tags=echo ===")
resp = await client.get(f"{KUBEMQ_URL}/agents", params={"skill_tags": "echo"})
data = resp.json()
filtered = data.get("agents", data) if isinstance(data, dict) else data
for agent in filtered:
print(f" {agent['agent_id']}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
async function main() {
console.log("=== List all agents ===");
const allResp = await fetch(`${KUBEMQ_URL}/agents`);
const allData = await allResp.json();
const allAgents = Array.isArray(allData) ? allData : (allData.agents || []);
console.log(`Found ${allAgents.length} agent(s):`);
for (const agent of allAgents) {
const skillIds = (agent.skills || []).map((s: { id?: string }) => s.id).filter(Boolean);
console.log(` - ${agent.agent_id} (skills: ${skillIds.join(", ") || "none"})`);
}
console.log("\n=== Filter by skill_tags=echo ===");
const echoResp = await fetch(`${KUBEMQ_URL}/agents?skill_tags=echo`);
const echoData = await echoResp.json();
const echoAgents = Array.isArray(echoData) ? echoData : (echoData.agents || []);
for (const agent of echoAgents) {
console.log(` - ${agent.agent_id}`);
}
}
main().catch(console.error);
```
## Get one agent [#get-one-agent]
`GET /agents/{agent_id}` returns the full agent card, or `404` if the agent is not
registered. Use it to inspect server-managed fields like `registered_at` and `last_seen`.
```bash
curl http://localhost:9090/agents/echo-agent-01
```
```csharp
using System.Text.Json;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "echo-agent-01";
using var client = new HttpClient();
var resp = await client.GetAsync($"{KubeMqUrl}/agents/{AgentId}");
Console.WriteLine($"Status: {(int)resp.StatusCode}");
var data = JsonNode.Parse(await resp.Content.ReadAsStringAsync())!;
Console.WriteLine($" agent_id: {data["agent_id"]}");
Console.WriteLine($" name: {data["name"]}");
Console.WriteLine($" url: {data["url"]}");
Console.WriteLine($" registered_at: {data["registered_at"]}");
Console.WriteLine($" last_seen: {data["last_seen"]}");
```
```go
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "echo-agent-01"
)
func main() {
resp, err := http.Get(kubemqURL + "/agents/" + agentID)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Status: %d\n", resp.StatusCode)
var data map[string]interface{}
json.Unmarshal(body, &data)
fmt.Printf(" agent_id: %v\n", data["agent_id"])
fmt.Printf(" name: %v\n", data["name"])
fmt.Printf(" url: %v\n", data["url"])
fmt.Printf(" registered_at: %v\n", data["registered_at"])
fmt.Printf(" last_seen: %v\n", data["last_seen"])
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "echo-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents/" + AGENT_ID))
.GET().build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + resp.statusCode());
var data = MAPPER.readTree(resp.body());
System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(data));
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "echo-agent-01"
async def main() -> None:
async with httpx.AsyncClient() as client:
resp = await client.get(f"{KUBEMQ_URL}/agents/{AGENT_ID}")
print(f"Status: {resp.status_code}")
data = resp.json()
print(f" agent_id: {data.get('agent_id')}")
print(f" name: {data.get('name')}")
print(f" url: {data.get('url')}")
print(f" registered_at: {data.get('registered_at')}")
print(f" last_seen: {data.get('last_seen')}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "echo-agent-01";
async function main() {
const resp = await fetch(`${KUBEMQ_URL}/agents/${AGENT_ID}`);
const agent = await resp.json();
console.log(` agent_id: ${agent.agent_id}`);
console.log(` name: ${agent.name}`);
console.log(` url: ${agent.url}`);
console.log(` registered_at: ${agent.registered_at}`);
console.log(` last_seen: ${agent.last_seen}`);
}
main().catch(console.error);
```
## Heartbeat [#heartbeat]
`POST /agents/heartbeat` with `{"agent_id": "..."}` refreshes the agent's `last_seen`
time. An agent must heartbeat (or re-register) within its [TTL](#ttl-and-liveness) to
avoid being expired. When auth is enabled, the ownership check applies. The response is
`{"ok": true}`; heartbeating an unregistered agent returns an error.
```bash
curl -X POST http://localhost:9090/agents/heartbeat \
-H "Content-Type: application/json" \
-d '{"agent_id": "echo-agent-01"}'
```
```csharp
using System.Text;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "echo-agent-01";
using var client = new HttpClient();
var body = new JsonObject { ["agent_id"] = AgentId };
var resp = await client.PostAsync(
$"{KubeMqUrl}/agents/heartbeat",
new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json"));
var data = JsonNode.Parse(await resp.Content.ReadAsStringAsync())!;
Console.WriteLine($"Heartbeat: status={(int)resp.StatusCode} last_seen={data["last_seen"]}");
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "echo-agent-01"
)
func main() {
body, _ := json.Marshal(map[string]string{"agent_id": agentID})
resp, err := http.Post(kubemqURL+"/agents/heartbeat", "application/json", bytes.NewReader(body))
if err != nil {
fmt.Fprintf(os.Stderr, "Heartbeat failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
var data map[string]interface{}
json.Unmarshal(raw, &data)
fmt.Printf("Heartbeat: status=%d last_seen=%v\n", resp.StatusCode, data["last_seen"])
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "echo-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents/heartbeat"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
MAPPER.writeValueAsString(Map.of("agent_id", AGENT_ID))))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
System.out.println("Heartbeat: status=" + resp.statusCode()
+ " last_seen=" + data.path("last_seen").asText());
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "echo-agent-01"
async def main() -> None:
async with httpx.AsyncClient() as client:
resp = await client.post(
f"{KUBEMQ_URL}/agents/heartbeat",
json={"agent_id": AGENT_ID},
)
data = resp.json()
print(f"Heartbeat: status={resp.status_code} last_seen={data.get('last_seen')}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "echo-agent-01";
async function main() {
const resp = await fetch(`${KUBEMQ_URL}/agents/heartbeat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ agent_id: AGENT_ID }),
});
const data = await resp.json();
console.log(`Heartbeat: status=${resp.status}, last_seen=${data.last_seen}`);
}
main().catch(console.error);
```
## Deregister [#deregister]
Remove an agent with either `POST /agents/deregister` (body `{"agent_id": "..."}`) or
`DELETE /agents/{agent_id}`. Deregistering deletes the card, stops the agent's virtual
subscriber, and drains in-flight requests. Both methods return `{"ok": true}`; when auth
is enabled, the [ownership](#ownership) check applies.
```bash
# Deregister via POST
curl -X POST http://localhost:9090/agents/deregister \
-H "Content-Type: application/json" \
-d '{"agent_id": "echo-agent-01"}'
# Or via DELETE
curl -X DELETE http://localhost:9090/agents/echo-agent-01
```
```csharp
using System.Text;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "echo-agent-01";
using var client = new HttpClient();
// Deregister via POST
var body = new JsonObject { ["agent_id"] = AgentId };
var postResp = await client.PostAsync(
$"{KubeMqUrl}/agents/deregister",
new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json"));
Console.WriteLine($"POST deregister: {(int)postResp.StatusCode}");
// Or via DELETE
var delResp = await client.DeleteAsync($"{KubeMqUrl}/agents/{AgentId}");
Console.WriteLine($"DELETE: {(int)delResp.StatusCode}");
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "echo-agent-01"
)
func main() {
// Deregister via POST
body, _ := json.Marshal(map[string]string{"agent_id": agentID})
resp, err := http.Post(kubemqURL+"/agents/deregister", "application/json", bytes.NewReader(body))
if err != nil {
fmt.Fprintf(os.Stderr, "Deregister POST failed: %v\n", err)
os.Exit(1)
}
resp.Body.Close()
fmt.Printf("POST /agents/deregister: %d\n", resp.StatusCode)
// Or via DELETE
req, _ := http.NewRequest(http.MethodDelete, kubemqURL+"/agents/"+agentID, nil)
resp, err = http.DefaultClient.Do(req)
if err != nil {
fmt.Fprintf(os.Stderr, "DELETE failed: %v\n", err)
os.Exit(1)
}
resp.Body.Close()
fmt.Printf("DELETE /agents/%s: %d\n", agentID, resp.StatusCode)
}
```
```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "echo-agent-01";
public static void main(String[] args) throws Exception {
var client = HttpClient.newHttpClient();
// Deregister via POST
var postReq = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents/deregister"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
"{\"agent_id\": \"" + AGENT_ID + "\"}"))
.build();
var postResp = client.send(postReq, HttpResponse.BodyHandlers.ofString());
System.out.println("POST deregister: " + postResp.statusCode());
// Or via DELETE
var delReq = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents/" + AGENT_ID))
.DELETE()
.build();
var delResp = client.send(delReq, HttpResponse.BodyHandlers.ofString());
System.out.println("DELETE: " + delResp.statusCode());
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "echo-agent-01"
async def main() -> None:
async with httpx.AsyncClient() as client:
# Deregister via POST
resp = await client.post(
f"{KUBEMQ_URL}/agents/deregister",
json={"agent_id": AGENT_ID},
)
print(f"POST /agents/deregister: {resp.status_code}")
# Or via DELETE
resp = await client.delete(f"{KUBEMQ_URL}/agents/{AGENT_ID}")
print(f"DELETE /agents/{AGENT_ID}: {resp.status_code}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "echo-agent-01";
async function main() {
// Deregister via POST
const postResp = await fetch(`${KUBEMQ_URL}/agents/deregister`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ agent_id: AGENT_ID }),
});
console.log(`POST deregister status: ${postResp.status}`);
// Or via DELETE
const delResp = await fetch(`${KUBEMQ_URL}/agents/${AGENT_ID}`, {
method: "DELETE",
});
console.log(`DELETE status: ${delResp.status}`);
}
main().catch(console.error);
```
## TTL and liveness [#ttl-and-liveness]
The registry expires agents that go silent. A background **liveness checker** runs every
60 seconds and deletes any agent whose `last_seen` is older than `AgentTTLSeconds`
(default `300` — five minutes). Expiring an agent also removes its virtual subscriber and
emits a `deregister` replication event.
To stay registered, an agent must [heartbeat](#heartbeat) (or re-register) within the TTL
window. A safe interval is well under `AgentTTLSeconds` — for the default 300s TTL, a
heartbeat every 60–120 seconds gives plenty of margin.
Tune the window with `AgentTTLSeconds`. See
[Configuration](/aiway/a2a/configuration) for the full `A2aConfig` field set
and the disable env var.
## Ownership [#ownership]
When authentication is enabled, the registry records the JWT principal that registered
each agent in `registered_by`. Heartbeat and deregister then enforce an **ownership
check**: only the registering principal may refresh or remove the agent. Cross-principal
re-registration is rejected with `403` (ownership conflict).
The check **fails closed**: if auth is enabled and an agent's `registered_by` is blank,
no principal can modify or delete it. See
[Authentication](/aiway/a2a/guides/authentication) for the auth model and
`X-KubeMQ-Caller-ID` propagation.
## MaxAgents limit [#maxagents-limit]
`MaxAgents` caps the total number of registered agents. The default is `0`, meaning
**unlimited**. When a positive limit is set and reached, new registrations are rejected
with `409` (conflict) — re-registering an existing agent still succeeds, since it does not
grow the count.
## Response and status codes [#response-and-status-codes]
| Status | Operation | Meaning |
| ------ | --------------------------------- | ----------------------------------------------- |
| `200` | register / heartbeat / get / list | Success |
| `400` | register / heartbeat | Validation error (bad card, missing `agent_id`) |
| `403` | register / heartbeat / deregister | Ownership conflict (auth enabled) |
| `404` | get / deregister | Agent not found |
| `409` | register | `MaxAgents` limit reached |
## Related [#related]
# Streaming (SSE) (/aiway/a2a/streaming)
When an agent produces results incrementally — progress updates, partial artifacts, a
final answer — A2A streams them back to the caller as **Server-Sent Events (SSE)**. The
caller sends a JSON-RPC `message/stream` request and reads a sequence of typed event
frames until a terminal `task.done` or `task.error`.
## Overview [#overview]
Synchronous [`message/send`](/aiway/a2a/sync-messaging) returns a single reply.
**`message/stream`** instead opens a long-lived SSE connection and relays each event the
agent emits as it happens, so callers can show progress or consume artifacts before the
task finishes.
There are two ways to start a stream against the same agent:
| Trigger | Request | Pre-stream error format |
| -------------------------------------------------------- | ------------- | --------------------------------------------------------- |
| `POST /a2a/{agent_id}` with `"method": "message/stream"` | JSON-RPC body | JSON-RPC 2.0 error at HTTP 200 |
| `GET /a2a/{agent_id}/stream` | query/headers | HTTP status code + `{"is_error": true, "message": "..."}` |
The POST form is the common case and what the examples below use. In both cases the
response is `Content-Type: text/event-stream` and the wire protocol is identical.
## How it works [#how-it-works]
The gateway does not hold a socket open to your agent on the caller's behalf. Instead it
uses the agent's [virtual subscriber](/aiway/a2a/architecture) as an **SSE
relay**: a temporary internal channel carries the agent's events to the gateway, which
forwards them to the caller. This subscribe-first ordering guarantees no event is lost
between the query and the agent's first emission.
*The virtual subscriber relays the agent's SSE events over a temporary internal channel; the gateway forwards them to the caller until a terminal envelope closes the stream.*
## Event types [#event-types]
Each SSE frame has an `event:` name and a JSON `data:` payload. The agent's envelope
`type` maps to the SSE event name the caller sees:
| Envelope `type` | SSE event name | Meaning |
| --------------- | --------------- | ------------------------------------------ |
| `status_update` | `task.status` | Progress or status update (non-terminal) |
| `artifact` | `task.artifact` | A partial or complete result artifact |
| `done` | `task.done` | Terminal — the task completed successfully |
| `error` | `task.error` | Terminal — the task failed |
| (other) | `message` | Default event name for untyped envelopes |
Each `data:` line is a stream envelope:
```json
{
"stream_id": "f3c1...",
"type": "status_update",
"payload": { "status": "working", "progress": 3, "total": 5 }
}
```
A caller reads frames until it sees `task.done` or `task.error`, then stops — both are
terminal and the gateway closes the connection after sending them.
## Stream a task [#stream-a-task]
Send a `message/stream` request with `Accept: text/event-stream` and read the event
frames as they arrive. Stop on the terminal `task.done` / `task.error`.
```bash
curl -N -X POST http://localhost:9090/a2a/stream-agent-01 \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": {
"message": {"parts": [{"text": "Stream me some updates"}]}
}
}'
```
```csharp
using System.Text;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "stream-agent-01";
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/stream",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Stream me some updates" })
}
}
};
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };
var request = new HttpRequestMessage(HttpMethod.Post, $"{KubeMqUrl}/a2a/{AgentId}")
{
Content = new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json")
};
Console.WriteLine("Connecting to SSE stream...");
using var resp = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
using var stream = await resp.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
string? eventType = null;
int eventCount = 0;
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
if (line == null) break;
if (line.StartsWith("event: "))
eventType = line[7..];
else if (line.StartsWith("data: ") && eventType != null)
{
eventCount++;
var data = line[6..];
Console.WriteLine($"[{eventType}] {data}");
if (eventType is "task.done" or "task.error")
break;
}
else if (line.Length == 0)
eventType = null;
}
Console.WriteLine($"\nReceived {eventCount} events");
Console.WriteLine("Stream completed!");
```
```go
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "stream-agent-01"
)
func main() {
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Stream me some updates"}},
},
},
}
data, err := json.Marshal(payload)
if err != nil {
fmt.Fprintf(os.Stderr, "Marshal failed: %v\n", err)
os.Exit(1)
}
req, err := http.NewRequest(http.MethodPost, kubemqURL+"/a2a/"+agentID, bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Request build failed: %v\n", err)
os.Exit(1)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "text/event-stream")
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
fmt.Println("Connecting to SSE stream...")
eventCount := 0
eventType := ""
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "event: ") {
eventType = strings.TrimPrefix(line, "event: ")
} else if strings.HasPrefix(line, "data: ") {
eventCount++
dataStr := strings.TrimPrefix(line, "data: ")
fmt.Printf("[%s] %s\n", eventType, dataStr)
if eventType == "task.done" || eventType == "task.error" {
break
}
}
}
fmt.Printf("\nReceived %d events\n", eventCount)
fmt.Println("Stream completed!")
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "stream-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/stream",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Stream me some updates")))
)
);
var client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(60))
.build();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.header("Accept", "text/event-stream")
.timeout(Duration.ofSeconds(60))
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
System.out.println("Connecting to SSE stream...");
var resp = client.send(req, HttpResponse.BodyHandlers.ofLines());
int eventCount = 0;
String currentEvent = null;
for (var it = resp.body().iterator(); it.hasNext(); ) {
String line = it.next();
if (line.startsWith("event: ")) {
currentEvent = line.substring(7).trim();
} else if (line.startsWith("data: ")) {
eventCount++;
String data = line.substring(6);
System.out.println("[" + currentEvent + "] " + data);
if ("task.done".equals(currentEvent) || "task.error".equals(currentEvent)) {
break;
}
}
}
System.out.println("\nReceived " + eventCount + " events");
System.out.println("Stream completed!");
}
}
```
```python
import asyncio
import json
import httpx
from httpx_sse import aconnect_sse
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "stream-agent-01"
async def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": {
"message": {"parts": [{"text": "Stream me some updates"}]},
},
}
async with httpx.AsyncClient(timeout=60) as client:
print("Connecting to SSE stream...")
async with aconnect_sse(
client,
"POST",
f"{KUBEMQ_URL}/a2a/{AGENT_ID}",
json=payload,
headers={"Accept": "text/event-stream"},
) as event_source:
event_count = 0
async for event in event_source.aiter_sse():
event_count += 1
data = json.loads(event.data)
print(f"[{event.event}] {json.dumps(data)}")
if event.event in ("task.done", "task.error"):
break
print(f"\nReceived {event_count} events")
print("Stream completed!")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "stream-agent-01";
async function main() {
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/stream",
params: { message: { parts: [{ text: "Stream me some updates" }] } },
};
console.log("=== POST-based streaming ===");
const resp = await fetch(`${KUBEMQ_URL}/a2a/${AGENT_ID}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(request),
});
const reader = resp.body!.getReader();
const decoder = new TextDecoder();
let eventCount = 0;
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split("\n\n");
buffer = frames.pop() ?? "";
for (const frame of frames) {
if (!frame.trim()) continue;
let eventType = "";
let eventData = "";
for (const line of frame.split("\n")) {
if (line.startsWith("event: ")) eventType = line.slice(7).trim();
else if (line.startsWith("data: ")) eventData = line.slice(6).trim();
}
if (!eventType) continue;
eventCount++;
const payload = JSON.parse(eventData);
console.log(`[${eventType}] ${JSON.stringify(payload)}`);
if (eventType === "task.done" || eventType === "task.error") {
console.log(`\nStream complete. Total events: ${eventCount}`);
reader.cancel();
return;
}
}
}
console.log(`\nStream ended. Total events: ${eventCount}`);
}
main().catch(console.error);
```
A typical stream is a sequence of `task.status` frames followed by a terminal `task.done`:
```text
Connecting to SSE stream...
[task.status] {"type": "status_update", "payload": {"status": "working", "progress": 1, "total": 5}}
[task.status] {"type": "status_update", "payload": {"status": "working", "progress": 2, "total": 5}}
[task.status] {"type": "status_update", "payload": {"status": "working", "progress": 5, "total": 5}}
[task.done] {"type": "done", "payload": {"final_result": "completed", "event_count": 5}}
```
## Keepalive and idle timeout [#keepalive-and-idle-timeout]
To keep the connection alive through proxies during quiet periods, the gateway emits an
SSE comment line — `: keepalive` — every **30 seconds**. It is a comment, not an event,
so SSE clients ignore it; it exists only to keep the socket warm.
If the agent produces no events for `MaxSSEIdleSeconds` (default **300 seconds**), the
gateway closes the stream: it sends a terminal `task.error` with code `-32001`
(`"stream idle timeout"`) and issues a best-effort cancel to the agent. Tune the window
with `MaxSSEIdleSeconds` — see [Configuration](/aiway/a2a/configuration).
## Client disconnect [#client-disconnect]
If the caller closes the connection before a terminal event, the gateway detects the
disconnect and **cancels the work on the agent** rather than letting it run to completion.
It sends a `stream_cancel` query to the agent's virtual subscriber on
`_AGENTS_.agents/{agent_id}` (carrying `a2a_stream_id`, with a 10-second timeout), which
closes the relay's HTTP connection to the agent. This frees the
[concurrency slot](/aiway/a2a/guides/concurrency) promptly instead of waiting
for the task to finish.
The SSE stream endpoint omits the per-route timeout middleware — long-lived streams are
bounded by `MaxSSEIdleSeconds`, not the 60-second request timeout that applies to
`message/send`.
## Response size limit [#response-size-limit]
During relay, the virtual subscriber tracks the accumulated `data:` bytes of each SSE
event. If a single event exceeds `AgentMaxResponseBytes` (default **10 MB**), the relay is
aborted to protect the gateway from memory exhaustion. Keep individual artifact events
under this bound; for large results, chunk them across multiple `task.artifact` events.
## Related [#related]
# Synchronous Messaging (/aiway/a2a/sync-messaging)
Synchronous A2A messaging is a request/reply call: a caller POSTs a JSON-RPC 2.0
request to `POST /a2a/`, the gateway routes it to the target agent through
its virtual subscriber, and the agent's reply comes back on the same HTTP response —
no SSE, no polling.
## Overview [#overview]
`message/send` is the workhorse of the A2A connector. You address an agent by ID in
the URL, put a standard JSON-RPC 2.0 envelope in the body, and read the reply
synchronously. The gateway is **method-agnostic**: it forwards whatever `method` you
send — `message/send`, `tasks/get`, `tasks/cancel`, or your own `custom/action` — and
returns the agent's response as-is. Use synchronous messaging whenever you want a
single answer back in one round-trip; switch to
[streaming](/aiway/a2a/streaming) when the agent produces incremental
output over time.
## How it works [#how-it-works]
A synchronous call travels from the caller through the gateway and the agent's
virtual subscriber to the plain HTTP agent, then the reply retraces the path.
*The gateway proxies one request to one agent and relays the reply on the same HTTP response.*
The gateway validates the agent ID and `Content-Type`, reads the timeout from
`params.configuration.timeout` (falling back to `DefaultTimeoutSeconds`, capped at
`MaxTimeoutSeconds`), packs the caller's `X-*` headers, and issues a Query on
`_AGENTS_.agents/`. The agent's virtual subscriber unpacks the request,
POSTs it to the agent's registered URL, and relays the response.
## Basic message/send [#basic-messagesend]
Send a text message and read the synchronous reply. The agent receives the full
JSON-RPC envelope and returns its result.
```bash
curl -X POST http://localhost:9090/a2a/echo-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"parts": [{"text": "Hello, agent!"}]
}
}
}'
```
```csharp
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "echo-agent-01";
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Hello, agent!" })
}
}
};
using var client = new HttpClient();
var resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/{AgentId}",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
Console.WriteLine($"Status: {(int)resp.StatusCode}");
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
Console.WriteLine(JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true }));
if (data["result"] != null)
Console.WriteLine("\nBasic send completed successfully!");
```
```go
const (
kubemqURL = "http://localhost:9090"
agentID = "echo-agent-01"
)
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Hello, agent!"}},
},
},
}
data, _ := json.Marshal(payload)
resp, err := http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Status: %d\n", resp.StatusCode)
fmt.Println(string(body))
```
```java
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "echo-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/send",
"params", Map.of(
"message", Map.of(
"parts", List.of(Map.of("text", "Hello, agent!"))
)
)
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + resp.statusCode());
var data = MAPPER.readTree(resp.body());
System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(data));
```
```python
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "echo-agent-01"
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"parts": [{"text": "Hello, agent!"}],
},
},
}
async with httpx.AsyncClient() as client:
resp = await client.post(f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload)
print(f"Status: {resp.status_code}")
data = resp.json()
print(json.dumps(data, indent=2))
assert "result" in data
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "echo-agent-01";
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: {
message: {
parts: [{ text: "Hello, agent!" }],
},
},
};
const resp = await fetch(`${KUBEMQ_URL}/a2a/${AGENT_ID}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const data = await resp.json();
console.log("Response:", JSON.stringify(data, null, 2));
```
## Context IDs [#context-ids]
Set `params.contextId` to correlate a sequence of messages with the same agent — for
conversation threading or session management. The gateway forwards it to the agent,
which echoes it back so callers can confirm the correlation.
```bash
curl -X POST http://localhost:9090/a2a/context-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "Track this request"}]},
"contextId": "ctx-001"
}
}'
```
```csharp
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Track this request" })
},
["contextId"] = "ctx-001"
}
};
using var client = new HttpClient();
var resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/context-agent-01",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
var returnedCtx = data["result"]?["contextId"]?.GetValue();
Console.WriteLine($"Received contextId: {returnedCtx}");
```
```go
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{"parts": []map[string]interface{}{{"text": "Track this request"}}},
"contextId": "ctx-001",
},
}
data, _ := json.Marshal(payload)
resp, _ := http.Post("http://localhost:9090/a2a/context-agent-01", "application/json", bytes.NewReader(data))
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
if r, ok := result["result"].(map[string]interface{}); ok {
fmt.Printf("Received contextId: %v\n", r["contextId"])
}
```
```java
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/send",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Track this request"))),
"contextId", "ctx-001"
)
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/context-agent-01"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
var returnedCtx = data.path("result").path("contextId").asText(null);
System.out.println("Received contextId: " + returnedCtx);
```
```python
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "Track this request"}]},
"contextId": "ctx-001",
},
}
async with httpx.AsyncClient() as client:
resp = await client.post("http://localhost:9090/a2a/context-agent-01", json=payload)
data = resp.json()
returned_ctx = data.get("result", {}).get("contextId")
print(f"Received contextId: {returned_ctx}")
```
```typescript
const contextId = "ctx-001";
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: {
message: { parts: [{ text: "Track this request" }] },
contextId,
},
};
const resp = await fetch(`${KUBEMQ_URL}/a2a/context-agent-01`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const data = await resp.json();
const echoedCtx = data.result?.contextId;
console.log(`Echoed contextId: ${echoedCtx}`);
```
## Custom methods [#custom-methods]
The gateway forwards any JSON-RPC `method` name to the agent unchanged — standard A2A
methods like `tasks/get` and `tasks/cancel`, or your own `custom/action`. KubeMQ does
not interpret the method; the agent decides how to handle it.
```bash
curl -X POST http://localhost:9090/a2a/custom-method-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "custom/action",
"params": {"data": "custom-payload"}
}'
```
```csharp
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "custom/action",
["params"] = new JsonObject { ["data"] = "custom-payload" }
};
using var client = new HttpClient();
var resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/custom-method-agent-01",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
var handledMethod = data["result"]?["handled_method"]?.GetValue();
Console.WriteLine($"Handled method: {handledMethod}");
```
```go
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "custom/action",
"params": map[string]interface{}{"data": "custom-payload"},
}
data, _ := json.Marshal(payload)
resp, _ := http.Post("http://localhost:9090/a2a/custom-method-agent-01", "application/json", bytes.NewReader(data))
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
r, _ := result["result"].(map[string]interface{})
fmt.Printf("Handled method: %v\n", r["handled_method"])
```
```java
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "custom/action",
"params", Map.of("data", "custom-payload")
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/custom-method-agent-01"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
System.out.println("Handled method: " + data.path("result").path("handled_method").asText());
```
```python
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "custom/action",
"params": {"data": "custom-payload"},
}
async with httpx.AsyncClient() as client:
resp = await client.post("http://localhost:9090/a2a/custom-method-agent-01", json=payload)
data = resp.json()
result = data.get("result", {})
print(f"Handled method: {result.get('handled_method')}")
```
```typescript
async function sendRpc(method: string, params: unknown) {
const request = { jsonrpc: "2.0", id: Date.now(), method, params };
const resp = await fetch(`${KUBEMQ_URL}/a2a/custom-method-agent-01`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
return resp.json();
}
const custom = await sendRpc("custom/action", { data: "custom-payload" });
console.log("Response:", JSON.stringify(custom, null, 2));
```
## Header forwarding [#header-forwarding]
Caller request headers prefixed with `X-` are forwarded to the agent; hop-by-hop and
sensitive headers (`Authorization`, `Cookie`, `X-Forwarded-For`, and others) are
stripped. The gateway always injects `X-KubeMQ-Caller-ID` so the agent knows which
client originated the call.
```bash
curl -X POST http://localhost:9090/a2a/header-agent-01 \
-H "Content-Type: application/json" \
-H "X-Custom-Header: my-custom-value" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "Check my headers"}]}
}
}'
```
```csharp
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Check my headers" })
}
}
};
using var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"{KubeMqUrl}/a2a/header-agent-01")
{
Content = new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json")
};
request.Headers.Add("X-Custom-Header", "my-custom-value");
var resp = await client.SendAsync(request);
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
var received = data["result"]?["received_headers"];
Console.WriteLine($"Forwarded headers: {received?.ToJsonString()}");
```
```go
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Check my headers"}},
},
},
}
data, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", "http://localhost:9090/a2a/header-agent-01", bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Custom-Header", "my-custom-value")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
received, _ := result["result"].(map[string]interface{})["received_headers"].(map[string]interface{})
fmt.Printf("Forwarded headers: %v\n", received)
```
```java
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/send",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Check my headers")))
)
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/header-agent-01"))
.header("Content-Type", "application/json")
.header("X-Custom-Header", "my-custom-value")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
System.out.println("Forwarded headers: " + data.path("result").path("received_headers"));
```
```python
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "Check my headers"}]},
},
}
async with httpx.AsyncClient() as client:
resp = await client.post(
"http://localhost:9090/a2a/header-agent-01",
json=payload,
headers={"X-Custom-Header": "my-custom-value"},
)
data = resp.json()
received = data.get("result", {}).get("received_headers", {})
print(f"Forwarded headers: {received}")
```
```typescript
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: {
message: { parts: [{ text: "Check my headers" }] },
},
};
const resp = await fetch(`${KUBEMQ_URL}/a2a/header-agent-01`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Custom-Header": "test-value-123",
},
body: JSON.stringify(request),
});
const data = await resp.json();
const headers = data.result?.received_headers || {};
console.log(`X-Custom-Header: ${headers["x-custom-header"] || "(not forwarded)"}`);
console.log(`X-KubeMQ-Caller-ID: ${headers["x-kubemq-caller-id"] || "(not present)"}`);
```
## Concurrent requests [#concurrent-requests]
Multiple simultaneous calls to the same agent are processed in parallel up to the
per-agent concurrency cap (`AgentMaxConcurrency`, default 100). Requests beyond the
cap are rejected immediately with a "server busy" error instead of being queued — see
[Concurrency & limits](/aiway/a2a/guides/concurrency).
```bash
# Fire 20 requests in parallel against the same agent
for i in $(seq 1 20); do
curl -s -X POST http://localhost:9090/a2a/concurrent-agent-01 \
-H "Content-Type: application/json" \
-d "{\"jsonrpc\":\"2.0\",\"id\":$i,\"method\":\"message/send\",\"params\":{\"message\":{\"parts\":[{\"text\":\"Request #$i\"}]}}}" &
done
wait
```
```csharp
const int NumRequests = 20;
async Task SendRequest(HttpClient httpClient, int requestId)
{
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = requestId,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = $"Request #{requestId}" })
}
}
};
var resp = await httpClient.PostAsync(
$"{KubeMqUrl}/a2a/concurrent-agent-01",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
var body = await resp.Content.ReadAsStringAsync();
return JsonNode.Parse(body);
}
using var client = new HttpClient();
var tasks = Enumerable.Range(1, NumRequests).Select(i => SendRequest(client, i)).ToArray();
var results = await Task.WhenAll(tasks);
var successes = results.Count(r => r?["result"] != null);
Console.WriteLine($"Successes: {successes} / {NumRequests}");
```
```go
const numRequests = 20
results := make(chan map[string]interface{}, numRequests)
var wg sync.WaitGroup
for i := 1; i <= numRequests; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
payload := map[string]interface{}{
"jsonrpc": "2.0", "id": id, "method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": fmt.Sprintf("Request #%d", id)}},
},
},
}
data, _ := json.Marshal(payload)
resp, err := http.Post("http://localhost:9090/a2a/concurrent-agent-01", "application/json", bytes.NewReader(data))
if err != nil {
results <- nil
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var r map[string]interface{}
json.Unmarshal(body, &r)
results <- r
}(i)
}
wg.Wait()
close(results)
successes := 0
for r := range results {
if r != nil {
if _, ok := r["result"]; ok {
successes++
}
}
}
fmt.Printf("Successes: %d / %d\n", successes, numRequests)
```
```java
static final int NUM_REQUESTS = 20;
var client = HttpClient.newHttpClient();
List>> futures = new ArrayList<>();
for (int i = 1; i <= NUM_REQUESTS; i++) {
var payload = Map.of(
"jsonrpc", "2.0", "id", i, "method", "message/send",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Request #" + i)))
)
);
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/concurrent-agent-01"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
futures.add(client.sendAsync(req, HttpResponse.BodyHandlers.ofString()));
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
int successes = 0;
for (var future : futures) {
var data = MAPPER.readTree(future.get().body());
if (data.has("result")) successes++;
}
System.out.println("Successes: " + successes + " / " + NUM_REQUESTS);
```
```python
NUM_REQUESTS = 20
async def send_request(client: httpx.AsyncClient, request_id: int) -> dict:
payload = {
"jsonrpc": "2.0",
"id": request_id,
"method": "message/send",
"params": {
"message": {"parts": [{"text": f"Request #{request_id}"}]},
},
}
resp = await client.post("http://localhost:9090/a2a/concurrent-agent-01", json=payload)
return resp.json()
async with httpx.AsyncClient() as client:
tasks = [send_request(client, i) for i in range(1, NUM_REQUESTS + 1)]
results = await asyncio.gather(*tasks, return_exceptions=True)
successes = sum(1 for r in results if isinstance(r, dict) and "result" in r)
print(f"Successes: {successes} / {NUM_REQUESTS}")
```
```typescript
const NUM_REQUESTS = 20;
async function sendRequest(id: number): Promise {
const request = {
jsonrpc: "2.0",
id,
method: "message/send",
params: { message: { parts: [{ text: `Request ${id}` }] } },
};
try {
const resp = await fetch(`${KUBEMQ_URL}/a2a/concurrent-agent-01`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const data = await resp.json();
return !!data.result;
} catch {
return false;
}
}
const promises = Array.from({ length: NUM_REQUESTS }, (_, i) => sendRequest(i + 1));
const results = await Promise.all(promises);
const succeeded = results.filter((r) => r).length;
console.log(`Succeeded: ${succeeded} / ${NUM_REQUESTS}`);
```
## Parameters [#parameters]
The body is a standard JSON-RPC 2.0 request. Method-specific fields live under
`params`.
| Field | Type | Required | Default | Description |
| ------------------------------ | ---------------- | ------------------ | ----------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `jsonrpc` | string | yes | — | Must be `"2.0"`. |
| `id` | string \| number | yes | — | Request identifier; echoed back on the response. |
| `method` | string | yes | — | Any JSON-RPC method name, e.g. `message/send`, `tasks/get`, or a custom one. Empty method is rejected with `-32600`. |
| `params.message.parts` | array | for `message/send` | — | Message content parts, each with a `text` (or other typed) field. |
| `params.contextId` | string | no | — | Correlation ID forwarded to the agent for conversation threading. |
| `params.configuration.timeout` | number | no | `DefaultTimeoutSeconds` (300) | Per-request timeout in seconds, capped at `MaxTimeoutSeconds` (3600). |
The URL path segment `` selects the target agent and is validated against
the registry before routing.
## Response [#response]
On success the gateway returns the agent's JSON-RPC `result` verbatim (the echo agent
mirrors the request under `result.echo`):
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"echo": {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": { "parts": [{ "text": "Hello, agent!" }] }
}
}
}
}
```
A response carrying an `error` object signals a problem. KubeMQ distinguishes two
failure classes:
* **Transport errors** — the agent never processed the request (unreachable, timeout,
`502`/`503`/`504`, or an oversized response). Internally these surface as
`Executed: false`; safe to retry.
* **Application errors** — the agent processed the request and returned a JSON-RPC
error in its response body (`Executed: true`). Retrying without changing the request
usually will not help.
A timeout, for example, returns:
```json
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32001,
"message": "agent timeout: echo-agent-01"
}
}
```
See [Error handling](/aiway/a2a/error-handling) for the full code list and
retry guidance.
## Related [#related]
# Configuration (/aiway/mcp/configuration)
The MCP connector runs on KubeMQ's [shared HTTP server](/connectors/concepts/shared-http-server) and is **enabled by default**. Configuration is minimal: a tool-execution timeout and an origin-validation allow-list. This page lists every `McpConfig` field with its verified default and shows how to set each one through TOML, environment variables, and Docker.
## Configuration fields [#configuration-fields]
These are the `McpConfig` fields and their defaults, taken verbatim from `kubemq-server`. All three connectors share the HTTP server's CORS, auth, traffic-gate, and TLS settings — those live in [Shared HTTP server](/connectors/concepts/shared-http-server) and [Auth & security](/connectors/reference/auth-and-security), not here.
| Field | Type | Default | Description |
| -------------------- | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Enable` | `bool` | `true` | Whether the MCP connector is mounted. Enabled by default — set to `false` to turn it off. |
| `ToolTimeoutSeconds` | `int` | `300` | Server-side timeout applied to each tool execution. A tool that exceeds this window returns a tool error (`isError: true`). Must be positive when the connector is enabled. |
| `TrustedOrigins` | `[]string` | `["auto"]` | Origins permitted by the connector's `Origin`-header validation. `auto` allows localhost variants and the server bind address; `*` allows all; an explicit list permits only those origins. |
`ToolTimeoutSeconds` (default `300`) is the **server-side** tool-execution budget. It is independent of any client-side HTTP timeout and of the per-call `timeout_seconds` argument on tools like `command_send`, `query_send`, and `agent_send`, which is itself capped at `300`.
## Enable / disable [#enable--disable]
The MCP connector is **enabled by default**. Start `kubemq-server` and `POST /mcp` is live — no `=true` flag is required.
To **disable** it, set its enable env var to `false`:
The disable variable is `CONNECTORSMCP_ENABLE` — there is **no underscore** between `MCP` and `ENABLE`. The name is generated by snake-casing the dotted config key `Connectors.MCP.Enable`; because `MCP` has no lowercase letters, the transform inserts no separator and the segments join. This differs from older KubeMQ docs that described MCP as off-by-default and instructed enabling with `=true` — that framing is stale. See [Shared HTTP server → enable model](/connectors/concepts/shared-http-server#enable-model-on-by-default) for the full algorithm.
## TOML configuration [#toml-configuration]
Set the fields under a `[Connectors.MCP]` table in `config.toml`:
```toml title="config.toml"
[Connectors.MCP]
Enable = true
ToolTimeoutSeconds = 300
TrustedOrigins = ["auto"]
```
## Environment variables [#environment-variables]
Each config field binds to an environment variable derived from its dotted key. The dots are stripped, the remainder is snake-cased and upper-cased, so `Connectors.MCP.ToolTimeoutSeconds` becomes `CONNECTORSMCP_TOOL_TIMEOUT_SECONDS`.
| Variable | Config field | Default | Description |
| ------------------------------------ | ----------------------------------- | ------- | ---------------------------------------------------------- |
| `CONNECTORSMCP_ENABLE` | `Connectors.MCP.Enable` | `true` | Enable (default) or disable (`false`) the MCP connector. |
| `CONNECTORSMCP_TOOL_TIMEOUT_SECONDS` | `Connectors.MCP.ToolTimeoutSeconds` | `300` | Server-side per-tool execution timeout, in seconds. |
| `CONNECTORSMCP_TRUSTED_ORIGINS` | `Connectors.MCP.TrustedOrigins` | `auto` | Comma-separated origin allow-list for `Origin` validation. |
```bash title="env.sh"
export CONNECTORSMCP_ENABLE=true
export CONNECTORSMCP_TOOL_TIMEOUT_SECONDS=300
export CONNECTORSMCP_TRUSTED_ORIGINS=auto
```
The `Origin` allow-list set here is an MCP-specific check layered on top of the shared HTTP server's CORS middleware. For how `auto`, `*`, and explicit origins are evaluated — and the `-32010` error returned on a rejected origin — see [Auth & security](/connectors/reference/auth-and-security).
## Docker [#docker]
Pass the same variables to `docker run`. This example keeps MCP at its default-on state and raises the tool timeout:
The connector is served because `Enable` defaults to `true`; to turn it off, add `-e CONNECTORSMCP_ENABLE=false` as shown in [Enable / disable](#enable--disable) above.
## Client protocol settings [#client-protocol-settings]
The settings above are server-side. When a client opens a session it negotiates the protocol in the `initialize` handshake. KubeMQ expects protocol version `2025-11-25`, a `clientInfo` object, and an empty `capabilities` object — capabilities are server-driven.
| Setting | Value | Description |
| ---------------- | ------------------- | --------------------------------------------------------------------------------------------------------------- |
| Protocol version | `2025-11-25` | MCP protocol version sent in the `initialize` request and echoed in the `MCP-Protocol-Version` response header. |
| Client info | `{ name, version }` | Identifies the client to the server. |
| Capabilities | `{}` | Empty object — the server advertises its own capabilities in the response. |
```json title="initialize.json"
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {
"name": "my-agent",
"version": "1.0.0"
}
}
}
```
The server replies with its own `protocolVersion`, `capabilities`, `serverInfo`, and a `sessionId` under `result._meta`. The handshake and session reuse are covered in depth in [Session management](/aiway/mcp/guides/session-management).
## Related [#related]
## Container command examples
```sh
docker run -d --pull always --platform linux/amd64 --name kubemq --hostname kubemq -p 127.0.0.1:9090:9090 -p 127.0.0.1:50000:50000 -e STORE_ENGINE=next -e STORE_NEXT_ACK_POLICY=strict -e STORE_STORE_PATH=/kubemq/store -e API_BIND_ADDRESS=0.0.0.0 -e CONNECTORSMCP_ENABLE=false -v kubemq-data:/kubemq/store europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:50000:50000 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-e CONNECTORSMCP_TOOL_TIMEOUT_SECONDS=600 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Getting started with MCP (/aiway/mcp/getting-started)
The MCP connector is **enabled by default** on the shared HTTP server. Start KubeMQ and `POST /mcp` is live — there is no flag to turn it on. This guide takes you from a running server to your first tool call, with a Claude Desktop config, raw JSON-RPC over `curl`, and the official MCP SDK in nine languages.
## Prerequisites [#prerequisites]
Any running KubeMQ works, including [Try KubeMQ](/deploy/quickstart). MCP and A2A are on by default on port 9090. On Kubernetes, run `kubectl --context YOUR_KUBE_CONTEXT -n kubemq port-forward svc/messaging-rest 9090:9090` first.
* For Claude Desktop: a current Claude Desktop install, and Node.js, which provides `npx`.
* For the SDK examples (optional): one of the nine supported runtimes — Python 3.10+, Node.js 18+, Java 21+, .NET 8+, Go 1.21+, Rust 1.75+, Ruby 3.1+, Kotlin 1.9+, or Swift 6.0+. The `curl` path needs no SDK or runtime — it speaks the MCP JSON-RPC protocol directly over HTTP.
## Enable / disable [#enable--disable]
The MCP connector is **enabled by default** — start `kubemq-server` and `POST /mcp` is immediately available. No `=true` flag is needed.
To **disable** MCP, set its enable env var to `false`:
The enable var name `CONNECTORSMCP_ENABLE` is irregular by design, and older KubeMQ docs described MCP as off-by-default — both are explained on [Shared HTTP server](/connectors/concepts/shared-http-server#enable-model-on-by-default). Set it to `false` to disable; never to `true` to enable.
## How it works [#how-it-works]
Every MCP interaction is a JSON-RPC 2.0 call to `POST /mcp`. A client first negotiates a session with `initialize`, acknowledges it with `notifications/initialized`, then discovers tools with `tools/list` and invokes them with `tools/call`. The connector resolves each tool to a KubeMQ operation and returns the result.
*The MCP handshake establishes a session, then each `tools/call` maps to a KubeMQ operation.*
## Connect an MCP host [#connect-an-mcp-host]
KubeMQ's MCP endpoint is `http://localhost:9090/mcp`. Pick your host below.
### Claude Desktop [#claude-desktop]
Claude Desktop's configuration file lists local servers that it starts itself, so KubeMQ joins through `mcp-remote`, a small bridge that `npx` downloads and runs. Open the file from Claude Desktop → Settings → Developer → Edit Config, and add:
```json title="claude_desktop_config.json"
{
"mcpServers": {
"kubemq": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:9090/mcp"]
}
}
}
```
Quit Claude Desktop fully and start it again. Closing the window is not enough.
### Cursor [#cursor]
Add KubeMQ to `~/.cursor/mcp.json` for all projects, or to `.cursor/mcp.json` for one project:
```json title="~/.cursor/mcp.json"
{
"mcpServers": {
"kubemq": {
"url": "http://localhost:9090/mcp"
}
}
}
```
Reload the Cursor window.
### Other hosts [#other-hosts]
Add a Streamable HTTP server at `http://localhost:9090/mcp`. The `/mcp` path is required. For an authenticated server and the transport details, see [Client setup](/aiway/mcp/guides/client-setup).
### Check the connection [#check-the-connection]
#### Check the tools from the server [#check-the-tools-from-the-server]
```bash title="Terminal"
curl -s -X POST http://localhost:9090/mcp -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | grep -o '"name":"[a-z_]*"'
```
You should see:
```text title="Output"
"name":"queue_send"
"name":"queue_receive"
"name":"queue_peek"
"name":"events_publish"
"name":"events_store_publish"
"name":"events_store_read"
"name":"events_store_read_latest"
"name":"command_send"
"name":"query_send"
"name":"channel_list"
"name":"channel_info"
"name":"agent_list"
"name":"agent_info"
"name":"agent_send"
"name":"agent_query"
```
#### Check the tools from the host [#check-the-tools-from-the-host]
Start a new conversation and ask the host: *What KubeMQ tools do you have?* You should see `queue_send` among the tools.
Then ask it to send `hello` to the `mcp-check` queue. You should see a result with a `message_id`.
With authentication off, anything that reaches port 9090 can call every MCP tool. Connect an LLM host only to a test server, or turn on [authentication](/aiway/mcp/guides/authentication) with a restricted role. To turn MCP off, see [Enable / disable](#enable--disable).
## The handshake by hand [#the-handshake-by-hand]
The steps below drive the protocol directly with `curl` so you can see exactly what each MCP client does for you. These commands are for bash on macOS and Linux; on Windows, run them in WSL (Windows Subsystem for Linux).
### Initialize a session [#initialize-a-session]
Send an `initialize` request to negotiate the protocol version (`2025-11-25`) and open a session:
```bash title="terminal"
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": { "name": "test", "version": "1.0.0" }
}
}'
```
The server replies with its capabilities and a session ID under `result._meta.sessionId`. The same value is also returned in the `MCP-Session-Id` response header:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-11-25",
"capabilities": { "tools": {} },
"serverInfo": { "name": "kubemq", "version": "..." },
"_meta": { "sessionId": "" }
}
}
```
Save the `sessionId` — every subsequent request carries it in the `MCP-Session-Id` header.
### Acknowledge the handshake [#acknowledge-the-handshake]
Tell the server the handshake is complete with the `notifications/initialized` notification, passing the session ID:
```bash title="terminal"
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: ' \
-d '{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}'
```
This is a notification, so it has no `id` field. The server returns HTTP `200 OK` with body `{"jsonrpc":"2.0","result":null,"id":null}` — there is no meaningful JSON-RPC result to parse.
### List the available tools [#list-the-available-tools]
Discover what you can call with `tools/list`. KubeMQ has 11 core tools, plus 4 agent-bridge tools when the agent registry is available (15 total):
```bash title="terminal"
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: ' \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list"
}'
```
Each entry carries a `name`, `description`, and `inputSchema`. The [Tools overview](/aiway/mcp/tools) maps every tool to its KubeMQ operation.
### Call your first tool [#call-your-first-tool]
Invoke `queue_send` to put a message on a queue channel, passing the session ID:
```bash title="terminal"
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: ' \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "queue_send",
"arguments": {
"channel": "my-queue",
"body": "Hello from MCP"
}
}
}'
```
A successful call returns a `content` array whose text is the send result, including the new message's ID:
```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [{ "type": "text", "text": "{\"is_error\":false,\"message_id\":\"\",\"sent_at\":\"\"}" }]
}
}
```
A failed call returns `"isError": true` with text that starts `error:`.
## The same call from an SDK [#the-same-call-from-an-sdk]
Each official MCP SDK performs the `initialize` handshake and tracks the session ID for you over the Streamable HTTP transport — you only write the `tools/call`. All examples read `KUBEMQ_MCP_URL` (default `http://localhost:9090`) and append `/mcp`.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: ' \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "queue_send",
"arguments": {
"channel": "example-queue",
"body": "Hello from MCP",
"metadata": "example-metadata",
"tags": { "env": "dev", "source": "mcp-example" }
}
}
}'
```
```go
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "queue_send",
Arguments: map[string]any{
"channel": "example-queue",
"body": "Hello from Go MCP",
"metadata": "example-metadata",
"tags": map[string]any{"env": "dev", "source": "mcp-example"},
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Tool: queue_send")
fmt.Printf("Result: %+v\n", result)
}
```
```python
import asyncio
import os
from mcp.client.streamable_http import streamable_http_client
from mcp import ClientSession
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
async def main():
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool("queue_send", {
"channel": "example-queue",
"body": "Hello from Python MCP",
"metadata": "example-metadata",
"tags": {"env": "dev", "source": "mcp-example"},
})
print(f"Tool: queue_send")
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
async function main() {
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
const result = await client.callTool({
name: "queue_send",
arguments: {
channel: "example-queue",
body: "Hello from TypeScript MCP",
metadata: "example-metadata",
tags: { env: "dev", source: "mcp-example" },
},
});
console.log(JSON.stringify(result, null, 2));
await client.close();
}
main().catch(console.error);
```
```java
import io.modelcontextprotocol.sdk.McpClient;
import io.modelcontextprotocol.sdk.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import java.util.Map;
public class QueueSend {
public static void main(String[] args) {
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
var result = client.callTool(new CallToolRequest(
"queue_send",
Map.of(
"channel", "example-queue",
"body", "Hello from Java MCP",
"metadata", "example-metadata",
"tags", Map.of("env", "dev", "source", "mcp-example")
)
));
System.out.println(result);
client.closeGracefully();
}
}
```
```csharp
using ModelContextProtocol.Client;
class QueueSend
{
static async Task Main(string[] args)
{
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("queue_send", new Dictionary
{
["channel"] = "example-queue",
["body"] = "Hello from C# MCP",
["metadata"] = "example-metadata",
["tags"] = new Dictionary { ["env"] = "dev", ["source"] = "mcp-example" },
});
Console.WriteLine($"Tool: queue_send");
Console.WriteLine($"Result: {result}");
}
}
```
```kotlin
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport
import io.ktor.client.*
import io.ktor.client.plugins.sse.*
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("queue_send", mapOf(
"channel" to "example-queue",
"body" to "Hello from Kotlin MCP",
"metadata" to "example-metadata",
"tags" to mapOf("env" to "dev", "source" to "mcp-example")
))
println("Tool: queue_send")
println("Result: $result")
client.close()
httpClient.close()
}
```
```ruby
require "mcp"
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("queue_send", {
"channel" => "example-queue",
"body" => "Hello from Ruby MCP",
"metadata" => "example-metadata",
"tags" => { "env" => "dev", "source" => "mcp-example" },
})
puts "Tool: queue_send"
puts "Result: #{result}"
client.close
```
```rust
use rmcp::transport::streamable_http::StreamableHttpClientTransport;
use rmcp::service::RunService;
use serde_json::json;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("queue_send", json!({
"channel": "example-queue",
"body": "Hello from Rust MCP",
"metadata": "example-metadata",
"tags": {"env": "dev", "source": "mcp-example"}
})).await?;
println!("Tool: queue_send");
println!("Result: {result:#?}");
Ok(())
}
```
```swift
import Foundation
import MCP
@main
struct QueueSend {
static func main() async throws {
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("queue_send", arguments: [
"channel": "example-queue",
"body": "Hello from Swift MCP",
"metadata": "example-metadata",
"tags": ["env": "dev", "source": "mcp-example"],
])
print("Tool: queue_send")
print("Result: \(result)")
}
}
```
`queue_send` and the event-publishing tools work on their own, but `command_send` and `query_send` need an active subscriber on the target channel, and the `agent_*` bridge tools need agents registered with the server. Without them, those calls time out.
## Troubleshooting [#troubleshooting]
* No KubeMQ tools in the host: quit and restart the host fully, not a reload. Claude Desktop writes connection errors to `mcp.log` in its logs folder.
* Connection refused: confirm port 9090 is published (`docker ps`) or the port-forward is running.
* `npx` not found: install Node.js, then restart Claude Desktop.
* Calls fail with `-32010`: authentication is on; see [Authenticated servers](/aiway/mcp/guides/client-setup#authenticated-servers).
## What's next [#whats-next]
## Container command examples
```sh
docker run -d --pull always --platform linux/amd64 --name kubemq --hostname kubemq -p 127.0.0.1:9090:9090 -p 127.0.0.1:50000:50000 -e STORE_ENGINE=next -e STORE_NEXT_ACK_POLICY=strict -e STORE_STORE_PATH=/kubemq/store -e API_BIND_ADDRESS=0.0.0.0 -e CONNECTORSMCP_ENABLE=false -v kubemq-data:/kubemq/store europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# MCP (/aiway/mcp)
The **MCP connector** exposes KubeMQ messaging operations as
[Model Context Protocol](https://modelcontextprotocol.io) tools, so Claude and other AI
models can publish, subscribe, and call KubeMQ — and reach registered agents — without
a KubeMQ-specific client library. It speaks MCP protocol version `2025-11-25` over
JSON-RPC 2.0 at a single endpoint on the [shared HTTP server](/connectors/concepts/shared-http-server).
**Part of Aiway.** MCP is one of the two doors into
[KubeMQ Aiway](/aiway), the AI Agents Fabric. New here? Start with the
[Aiway overview](/aiway), or follow the end-to-end
[Aiway tutorial](/aiway/tutorial).
## What MCP is [#what-mcp-is]
The Model Context Protocol is an open standard for connecting AI models to external
tools and data over a uniform JSON-RPC 2.0 interface. A model's MCP client connects to
an MCP **server**, asks it which tools it offers (`tools/list`), and invokes them by
name (`tools/call`). KubeMQ is one such server: every KubeMQ messaging operation is
published as a named MCP tool.
Because the protocol is standard, any MCP-aware model or runtime can use KubeMQ with no
KubeMQ code on the caller. You point the official MCP SDK for your language — or a
client like Claude Desktop — at the endpoint, and the model gains messaging, persistent
events, request/reply, channel introspection, and a bridge to A2A agents as native
tools.
## Why MCP with KubeMQ [#why-mcp-with-kubemq]
* **No KubeMQ SDK on the caller** — clients use the official MCP SDK for their
language; KubeMQ is just an MCP server they connect to.
* **One endpoint** — `POST /mcp` for JSON-RPC requests (single or batch), plus
`GET /mcp` for a keepalive SSE stream, both on the shared HTTP port `9090`.
* **15 ready-to-use tools** — 11 core messaging tools plus 4 agent-bridge tools,
covering every KubeMQ pattern.
* **A bridge to agents** — the model can list, inspect, and message agents registered
with the [A2A connector](/aiway/a2a) through the same tool interface.
* **Enabled by default** — start kubemq-server and `/mcp` is live; there is no flag to
turn it on.
## How it works [#how-it-works]
An MCP client connects to the `/mcp` endpoint, completes the `initialize` handshake to
obtain a session, then calls tools. The connector translates each tool call into a
native KubeMQ operation; agent-bridge tools forward over the broker to the A2A registry.
*The MCP connector turns JSON-RPC tool calls into KubeMQ operations and bridges to A2A agents.*
The connector runs on the [shared HTTP server](/connectors/concepts/shared-http-server) and
inherits its middleware, [authentication](/aiway/mcp/guides/authentication),
and [observability](/connectors/concepts/observability). The reserved `_AGENTS_.` channel
prefix is rejected for direct messaging tools — use the agent-bridge tools to reach
agents.
## The 15 tools [#the-15-tools]
KubeMQ exposes 15 MCP tools across five categories — 11 core messaging tools that are
always available, plus 4 agent-bridge tools that appear when the agent registry is
present.
| Category | Tools | Count |
| ------------------ | ----------------------------------------------------------------------------------------- | -----: |
| Queue | `queue_send`, `queue_receive`, `queue_peek` | 3 |
| Events | `events_publish`, `events_store_publish`, `events_store_read`, `events_store_read_latest` | 4 |
| Command / Query | `command_send`, `query_send` | 2 |
| Channel management | `channel_list`, `channel_info` | 2 |
| Agent bridge | `agent_list`, `agent_info`, `agent_send`, `agent_query` | 4 |
| **Total** | | **15** |
## Endpoint surface [#endpoint-surface]
| Method | Path | Description |
| ------ | ------ | ---------------------------------------------- |
| `POST` | `/mcp` | JSON-RPC 2.0 request handler (single or batch) |
| `GET` | `/mcp` | SSE keepalive stream |
JSON-RPC methods on `POST /mcp`: `initialize`, `notifications/initialized`, `ping`,
`tools/list`, and `tools/call`. The `MCP-Protocol-Version` response header is always
`2025-11-25`, and `MCP-Session-Id` carries the session returned by `initialize`. See
the [endpoints reference](/aiway/mcp/reference/endpoints) for full signatures.
## Discover the tools [#discover-the-tools]
The `tools/list` method returns every available tool with its `name`, `description`, and
`inputSchema`. It is the first call after `initialize` — it tells the model what KubeMQ
can do.
```bash
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-H "MCP-Protocol-Version: 2025-11-25" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}'
```
```csharp
using ModelContextProtocol.Client;
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var tools = await client.ListToolsAsync();
foreach (var tool in tools)
{
Console.WriteLine($"{tool.Name}: {tool.Description}");
}
```
```go
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.ListTools(ctx, mcp.ListToolsRequest{})
if err != nil {
log.Fatal(err)
}
for _, tool := range result.Tools {
fmt.Printf("%s: %s\n", tool.Name, tool.Description)
}
}
```
```java
import io.modelcontextprotocol.sdk.McpClient;
import io.modelcontextprotocol.sdk.client.transport.HttpClientStreamableHttpTransport;
public class ToolsList {
public static void main(String[] args) {
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
var tools = client.listTools();
System.out.println(tools);
client.closeGracefully();
}
}
```
```kotlin
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport
import io.ktor.client.*
import io.ktor.client.plugins.sse.*
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val tools = client.listTools()
println(tools)
client.close()
httpClient.close()
}
```
```python
import asyncio
import os
from mcp.client.streamable_http import streamable_http_client
from mcp import ClientSession
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
async def main():
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
for tool in tools.tools:
print(f"{tool.name}: {tool.description}")
if __name__ == "__main__":
asyncio.run(main())
```
```ruby
require "mcp"
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
tools = client.list_tools
puts tools
client.close
```
```rust
use rmcp::transport::streamable_http::StreamableHttpClientTransport;
use rmcp::service::RunService;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let tools = client.list_tools(Default::default()).await?;
println!("{tools:#?}");
Ok(())
}
```
```swift
import Foundation
import MCP
@main
struct ToolsList {
static func main() async throws {
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let (tools, _) = try await client.listTools()
for tool in tools {
print("\(tool.name): \(tool.description ?? "")")
}
}
}
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
async function main() {
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
const tools = await client.listTools();
console.log(JSON.stringify(tools, null, 2));
await client.close();
}
main().catch(console.error);
```
## Supported languages [#supported-languages]
Every operation has a `curl` example plus the official MCP SDK in nine languages. The
SDK wraps the Streamable HTTP transport — session IDs, request IDs, and JSON-RPC
serialization are handled for you.
| Language | MCP SDK package | Source |
| --------------- | ------------------------------------ | --------------------- |
| C# | `ModelContextProtocol` | NuGet |
| Go | `github.com/mark3labs/mcp-go` | Go modules |
| Java | `io.modelcontextprotocol:sdk` | Maven Central |
| Kotlin | `io.modelcontextprotocol:kotlin-sdk` | Maven Central |
| Python | `mcp` | PyPI |
| Ruby | `mcp` | RubyGems |
| Rust | `rmcp` | crates.io |
| Swift | `mcp-swift-sdk` | Swift Package Manager |
| TypeScript / JS | `@modelcontextprotocol/sdk` | npm |
## Next steps [#next-steps]
# Docker (single-node) (/configure/docker)
Docker runs one KubeMQ node for development and testing. One container runs the full
server: every interface, every connector, the persistent store, and the embedded messaging
engine — the same container that runs on Docker or Podman; there is no separate native
binary install. This guide hosts the complete, runnable Docker configs; the
[reference](/configure/reference) pages show per-setting snippets and link back
here.
Install KubeMQ first with [Install with kmq](/deploy/install/kmq) or
[Install with Docker](/deploy/install/docker). This page changes the settings of a running
server.
Every command on this page recreates the container `kubemq` on the `kubemq-data` volume,
so your messages stay. Remove the running container first with `docker stop kubemq` and
`docker rm kubemq`. If kmq created the server, remove it with kmq instead, as
[Install with kmq](/deploy/install/kmq) shows; from then on you manage the container with
Docker commands. If you added a license, run each command from `kubemq-private` with
`--env-file kubemq-license.env` added, as [Install with Docker](/deploy/install/docker#add-your-license)
does: a server whose store already used its evaluation does not start without it. If kmq
saved your license, create `kubemq-license.env` first with the license step of
[Install with Docker](/deploy/install/docker#add-your-license); kmq keeps the key in its own
store, not in that file.
| Port | Interface | Purpose |
| ------- | ---------------- | -------------------------------------------------------------------------- |
| `50000` | gRPC | Primary SDK transport. |
| `9090` | REST / WebSocket | REST API, WebSocket, and the shared HTTP server (MCP · A2A · CloudEvents). |
| `8080` | API / Dashboard | Web dashboard, management API, health probes, and metrics. |
The store lives on the `kubemq-data` volume, mounted at **`/kubemq/store`** inside the
container. It is the same volume [Try KubeMQ](/deploy/quickstart) creates. Persistence is
required for the **Events Store** and **Queues** patterns.
**Two things a persistent store needs.**
**Mount at `/kubemq/store`, not `/store`.** The image's working directory is `/kubemq` and
the default `store.storepath` is the *relative* `./store`, so the server writes to
`/kubemq/store`. A volume mounted at `/store` receives nothing and the data dies with the
container — and every health check on this page still passes, because the server is
running fine, just onto container-local disk.
**Keep the hostname fixed with `--hostname`.** The store layout is
`//…`, and Docker gives every new container a random hostname unless you
set one. A single server with no `HOST` set survives a change: it adopts the one server
directory it finds in the store and logs `NOTICE: adopting existing store identity`. That
rescue does not run when `HOST` is set, and it cannot choose when the store holds more than
one server directory. The server then starts on an empty directory beside the old one.
Every command on this page sets `--hostname kubemq`.
## Three ways to supply config [#three-ways-to-supply-config]
Every setting has a documented default, so a server runs with no overrides at all. To change
a setting you have three delivery methods, in order of how much you are configuring:
### Per-field environment variables [#per-field-environment-variables]
Pass each setting as `-e GROUP_FIELD=value`. The env var is the `config.yaml` key
snake-cased, dotless, and uppercased — `store.maxretention` becomes `STORE_MAX_RETENTION`.
This is the lightest method, best for a handful of overrides:
**The connector acronym variables drop the underscore.** The CloudEvents enable variable
is **`CONNECTORSCE_ENABLE`** (no underscore between `CONNECTORS` and `CE`). The same
collapse applies to `CONNECTORSMCP_*` and `CONNECTORSMQTT_*`, while the Title-case
connectors keep the underscore (`CONNECTORS_AMQP_*`, `CONNECTORS_STOMP_*`,
`CONNECTORS_AWS_*`), and A2A splits to `CONNECTORSA2_A_*`. The full rule is in
[the reference legend](/configure/reference).
**What happens when you get it wrong depends on which form you used, and the warning is
not reliable in either direction:**
| You set | Does it work? | Does the server say anything? |
| ----------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------ |
| `CONNECTORS_MQTT_ENABLE` (wrong twin of a collapsed name) | **No** | Yes — an `IGNORED` warning, because the name is in the `CONNECTORS_` namespace |
| `CONNECTORS_CE_ENABLE` (CloudEvents only) | **Yes** — CE is the one connector that binds both forms | Yes — an `IGNORED` warning **that is wrong**; the value is applied anyway |
| A typo in a correct collapsed name (`CONNECTORSMQT_ENABLE`) | No | **Nothing at all** — collapsed names sit outside the warner's namespace list |
So: an `IGNORED` warning for a `CONNECTORS_CE_*` variable is a false alarm — do not
"fix" a working setting because of it. And the absence of a warning proves nothing about a
collapsed-form name. Check the effective value in the dashboard rather than trusting the
log either way.
### A mounted config.yaml [#a-mounted-configyaml]
Once you are setting more than a few fields, keep them in a `config.yaml` and mount it into
the container. The server auto-detects YAML or TOML; point it at the file with the
`--config` flag.
```yaml title="config.yaml"
log:
level: 1
store:
storepath: ./store
maxretention: 2880
connectors:
grpc:
enable: true
port: "50000"
rest:
enable: true
port: "9090"
ce:
enable: false
api:
port: "8080"
```
The license is not a `config.yaml` setting. It comes only from environment variables; see
[License](/configure/reference/core#license). Keep the `kubemq-data` volume when you
recreate the container.
Mount the file and select it with `--config`. **The flag goes after the image name *and*
after the binary path:**
**You must repeat `/kubemq/kubemq-run`.** The image declares no `ENTRYPOINT` — only
`CMD ["/kubemq/kubemq-run"]` — so anything you put after the image name **replaces** the
command rather than appending to it. Passing just `--config /kubemq/config.yaml` makes
Docker try to execute `--config` as the binary, and the container never starts.
**`enable` is the Docker toggle — but the default differs by family.** There are three
families. The interfaces and the HTTP-family connectors (gRPC, REST, API, MCP, A2A,
CloudEvents) ship **on by default**. The **Kafka** (`9092`/`9093`) and **RabbitMQ / AMQP 0-9-1**
(`5672`/`5671`) connectors also ship **on by default** — the image `EXPOSE`s `9092` and `5672`
alongside the core ports — and you turn them **off** with `CONNECTORS_KAFKA_ENABLE=false` /
`CONNECTORS_AMQP_ENABLE=false`. The remaining wire-protocol connectors (MQTT, AMQP 1.0, STOMP,
AWS, GCP) are **opt-in** and ship **off**; you turn them **on** with `enable: true`
(env `..._ENABLE=true`). On Docker every toggle is the same `enable: true | false` key. The
Helm/CRD surface splits them: the always-on interfaces use an opt-out `disabled: true`, while
the wire connectors use `enabled: true | false` (see [Kubernetes](/configure/kubernetes)).
Same toggles, inverted boolean.
### The CONFIG environment variable [#the-config-environment-variable]
When mounting a file is awkward — orchestrators that inject env vars, CI runners, secret
managers — supply the **whole** config inline through the `CONFIG` environment variable.
The server writes the value to a file and loads it, exactly as if you had passed
`--config`:
`CONFIG` also accepts a **base64-encoded** payload, which avoids newline and quoting
issues when the value passes through a secret store or a templating layer:
## docker-compose [#docker-compose]
To run the same single server with Docker Compose, download the Compose file from
[Install with Docker](/deploy/install/docker#use-docker-compose-instead), then add a
`docker-compose.override.yml` next to it. Compose merges the override automatically, so
the downloaded file stays as published, with its `kubemq-data` volume.
```yaml title="docker-compose.override.yml"
services:
kubemq:
command: ["/kubemq/kubemq-run", "--config", "/kubemq/config.yaml"]
environment:
LOG_LEVEL: "1"
volumes:
- ./config.yaml:/kubemq/config.yaml:ro
```
Check the merge:
```bash title="Terminal"
docker compose config
```
You should see, under `kubemq`: a `command` list ending in `--config` and
`/kubemq/config.yaml`, `LOG_LEVEL: "1"` next to the published file's variables, and two
mounts, the `kubemq-data` volume at `/kubemq/store` and `config.yaml` at
`/kubemq/config.yaml`.
If you added a license, now add `env_file: [./kubemq-license.env]` under `kubemq:` in the
override, and keep the Compose file and the override in `kubemq-private`, next to
`kubemq-license.env`; run the next commands there. Add it after the check above, because
`docker compose config` prints the values of an environment file. Leave the line out if you
have no license: Compose stops when the file is missing. With a license but without the
line, a server whose store already used its evaluation does not start.
Get the latest image:
```bash title="Terminal"
docker compose pull
```
You should see `kubemq` reported as pulled.
Start it:
```bash title="Terminal"
docker compose up -d
```
You should see the container `kubemq` created or recreated, then started. `docker compose ps`
shows it `Up`.
To supply the config inline instead of mounting a file, drop `command` and the
`config.yaml` mount from the override and set `CONFIG` (or `CONFIG` as base64) under
`environment`.
## Configure by domain [#configure-by-domain]
Every setting in the configs above is documented in the reference, grouped by domain. Each
page lists the `config.yaml` key, the environment variable, the type, the default, and the
valid values.
## Verify [#verify]
Confirm the node is up. Open the dashboard at
`http://localhost:8080`, then check the container logs:
```bash title="Terminal"
docker logs kubemq
```
A healthy start logs each interface binding to its port. The health and readiness probes
on the API port confirm the server is accepting traffic:
```bash title="Terminal"
curl http://localhost:8080/health
curl http://localhost:8080/ready
```
## Related [#related]
* [Install with Docker](/deploy/install/docker) — install a licensed single server, with Docker or Docker Compose.
* [Kubernetes (Helm)](/configure/kubernetes) — the production target with replicas and `Service` exposure.
* [Configuration overview](/configure) — the two targets and the config model.
* [Configuration reference](/configure/reference) — every setting, grouped by domain.
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-p 127.0.0.1:9092:9092 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-e LOG_LEVEL=1 \
-e STORE_MAX_RETENTION=2880 \
-e CONNECTORSCE_ENABLE=false \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-p 127.0.0.1:9092:9092 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
-v \
-v \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest /kubemq/kubemq-run --config /kubemq/config.yaml
```
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-p 127.0.0.1:9092:9092 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-e CONFIG= \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-p 127.0.0.1:9092:9092 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-e CONFIG= \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# 2. Build & register an agent (/aiway/tutorial/build-and-register-an-agent)
In [step 1](/aiway/tutorial/setup) you started KubeMQ and confirmed the Aiway
endpoints are live with an empty agent roster. Now you'll build the **research agent**
the rest of this tutorial discovers, invokes, and streams — a plain HTTP server that
speaks JSON-RPC 2.0, with **no KubeMQ SDK**. KubeMQ's per-agent
[Agent Bridge](/aiway/a2a/architecture) (a virtual subscriber) does all the broker
work; your agent only answers HTTP POSTs.
This page keeps the agent minimal so you can follow the end-to-end story. For the full
agent contract — every method, header forwarding, and the lifecycle endpoints — see
[Building agents](/aiway/a2a/guides/building-agents).
The agent listens on its own port (`18080` below). It **registers** with — and is
invoked through — the Aiway gateway on the shared HTTP port `9090`. Keep both running.
## Write the research agent [#write-the-research-agent]
The agent handles two JSON-RPC methods on a single `POST /` route:
* **`message/send`** — returns one synchronous result (used in
[step 3](/aiway/tutorial/discover-and-invoke)).
* **`message/stream`** — emits Server-Sent Events: three `task.status` updates
(`searching` → `reading` → `summarizing`), then a `task.artifact`, then a terminal
`task.done` (consumed in [step 4](/aiway/tutorial/stream-live-results)).
The `task.artifact` envelope follows the wire format in
[SSE behavior](/aiway/a2a/guides/sse-behavior) — `type: "artifact"` with a
`payload` carrying a `name` and `data`. [Building agents](/aiway/a2a/guides/building-agents)
shows only the `status` → `done` path, so the artifact shape comes from the SSE
behavior reference.
Save this as `research_agent.py`. It uses only `aiohttp` (server) and `httpx`
(registration) — install them with `pip install aiohttp httpx`.
```python
"""A plain-HTTP research agent — no KubeMQ SDK."""
import asyncio
import json
import signal
import httpx
from aiohttp import web
KUBEMQ_URL = "http://localhost:9090" # Aiway gateway (register + invoke)
AGENT_ID = "research-agent-01"
AGENT_PORT = 18080 # the agent's own HTTP port
def extract_query(body: dict) -> str:
"""Pull the caller's text out of the JSON-RPC params."""
parts = body.get("params", {}).get("message", {}).get("parts", [])
return " ".join(p.get("text", "") for p in parts).strip() or "(empty query)"
async def handle_send(body: dict) -> web.Response:
"""message/send — return one synchronous JSON-RPC result."""
query = extract_query(body)
return web.json_response({
"jsonrpc": "2.0",
"id": body.get("id"),
"result": {
"summary": f"Research summary for: {query}",
"sources": 3,
},
})
async def handle_stream(request: web.Request, body: dict) -> web.StreamResponse:
"""message/stream — emit status events, an artifact, then done over SSE."""
query = extract_query(body)
resp = web.StreamResponse(
status=200,
headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"},
)
await resp.prepare(request)
stages = ["searching", "reading", "summarizing"]
for i, status in enumerate(stages, start=1):
event = json.dumps({
"type": "status_update",
"payload": {"status": status, "progress": i, "total": len(stages)},
})
await resp.write(f"event: task.status\ndata: {event}\n\n".encode())
await asyncio.sleep(0.5)
# Intermediate artifact — envelope per the SSE behavior reference.
artifact = json.dumps({
"type": "artifact",
"payload": {
"name": "summary.json",
"data": {"summary": f"Research summary for: {query}", "sources": 3},
},
})
await resp.write(f"event: task.artifact\ndata: {artifact}\n\n".encode())
# Terminal event — stop reading after this.
done = json.dumps({"type": "done", "payload": {"final_result": "completed", "event_count": 4}})
await resp.write(f"event: task.done\ndata: {done}\n\n".encode())
await resp.write_eof()
return resp
async def handle_request(request: web.Request) -> web.StreamResponse:
body = await request.json()
if body.get("method") == "message/stream":
return await handle_stream(request, body)
return await handle_send(body)
async def register_agent() -> None:
card = {
"agent_id": AGENT_ID,
"name": "Research Agent",
"description": "Searches, reads, and summarizes — a mock LLM research agent.",
"version": "1.0.0",
"url": f"http://localhost:{AGENT_PORT}/",
"skills": [
{
"id": "research",
"name": "Research",
"description": "Searches sources and returns a summary.",
"tags": ["research", "summarize"],
}
],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"],
}
async with httpx.AsyncClient() as client:
resp = await client.post(f"{KUBEMQ_URL}/agents/register", json=card)
print(f"Registered: {resp.status_code}")
print(json.dumps(resp.json(), indent=2))
async def main() -> None:
app = web.Application()
app.router.add_post("/", handle_request)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "0.0.0.0", AGENT_PORT)
await site.start()
print(f"Research agent listening on port {AGENT_PORT}")
# Always start the server BEFORE registering — KubeMQ may route the moment
# registration succeeds.
await register_agent()
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, stop.set)
await stop.wait()
await runner.cleanup()
if __name__ == "__main__":
asyncio.run(main())
```
Run it in one terminal and leave it running:
```bash
python research_agent.py
```
It prints `Research agent listening on port 18080` and then the registration response.
## Register the Agent Card [#register-the-agent-card]
The script above self-registers on startup, but you can register (or re-register) any
agent with a plain `curl` — useful for a sidecar agent or a language not shown here. The
body is the **Agent Card**: `agent_id`, `url`, `name`, and the `skills` array, with
`protocolVersions: ["1.0"]` (this is the A2A card protocol version — not the MCP session
version you'll see in [step 5](/aiway/tutorial/orchestrate-from-an-llm)).
```bash
curl -X POST http://localhost:9090/agents/register \
-H "Content-Type: application/json" \
-d '{
"agent_id": "research-agent-01",
"name": "Research Agent",
"description": "Searches, reads, and summarizes — a mock LLM research agent.",
"version": "1.0.0",
"url": "http://localhost:18080/",
"skills": [
{"id": "research", "name": "Research", "description": "Searches sources and returns a summary.", "tags": ["research", "summarize"]}
],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"]
}'
```
A `200` response echoes the stored card, enriched with server-set `registered_at` and
`last_seen` timestamps. See the [agent registry](/aiway/a2a/registry) for the full
card schema and the [agent cards](/aiway/a2a/agent-cards) reference for every field.
## Confirm it's in the roster [#confirm-its-in-the-roster]
In step 1 `GET /agents` returned an empty list. Now it returns your agent:
```bash
curl http://localhost:9090/agents
```
```json
[
{
"agent_id": "research-agent-01",
"name": "Research Agent",
"url": "http://localhost:18080/",
"skills": [
{"id": "research", "name": "Research", "tags": ["research", "summarize"]}
],
"protocolVersions": ["1.0"],
"registered_at": "2026-06-26T10:00:00Z",
"last_seen": "2026-06-26T10:00:00Z"
}
]
```
## Keep it alive (heartbeat & TTL) [#keep-it-alive-heartbeat--ttl]
The registry expires agents that go silent. A background liveness checker removes any
agent whose `last_seen` is older than the TTL (`AgentTTLSeconds`, default **300s**). To
stay registered, an agent must heartbeat (or re-register) within that window — a beat
every 30–60s gives plenty of margin:
```bash
curl -X POST http://localhost:9090/agents/heartbeat \
-H "Content-Type: application/json" \
-d '{"agent_id": "research-agent-01"}'
```
For this tutorial the agent stays up the whole time, so you won't hit the TTL — but a
production agent should heartbeat on a timer and deregister on shutdown. The
[agent registry](/aiway/a2a/registry) covers heartbeat, TTL, deregistration, and
ownership in full.
## Next step [#next-step]
Your research agent is live in the fabric. Next, find it by capability and call it
synchronously.
# 3. Discover & invoke (/aiway/tutorial/discover-and-invoke)
In [Step 2](/aiway/tutorial/build-and-register-an-agent) you registered the
`research-agent-01` agent with a `research` skill. Now you'll act as a **caller**: first
discover the agent by its capability (no need to know its ID up front), then invoke it
synchronously and read the result back in a single round-trip.
This step assumes KubeMQ is running on port `9090` and `research-agent-01` is already
registered (Steps 1 and 2). Verify with `curl http://localhost:9090/agents` — the agent
should appear in the roster.
## Discover by capability [#discover-by-capability]
Callers don't have to hard-code agent IDs. The registry lets you find agents by **skill
tag**: `GET /agents?skill_tags=research` returns every registered agent that advertises
the `research` skill as a bare JSON array of agent cards. This is capability-based
discovery — ask for *what you need done*, get back *who can do it*.
```bash
curl "http://localhost:9090/agents?skill_tags=research"
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
async def main() -> None:
async with httpx.AsyncClient() as client:
resp = await client.get(
f"{KUBEMQ_URL}/agents",
params={"skill_tags": "research"},
)
agents = resp.json()
for agent in agents:
skills = [s["id"] for s in agent.get("skills", [])]
print(f" {agent['agent_id']}: skills={skills}, url={agent['url']}")
if __name__ == "__main__":
asyncio.run(main())
```
The response includes `research-agent-01` — its `agent_id`, `url`, and advertised
`skills`:
```json
[
{
"agent_id": "research-agent-01",
"name": "Research Agent",
"url": "http://localhost:18080/",
"skills": [
{
"id": "research",
"name": "Research",
"description": "Searches sources and returns a summary.",
"tags": ["research", "summarize"]
}
],
"protocolVersions": ["1.0"]
}
]
```
`skill_tags` accepts a comma-separated list (`?skill_tags=research,summarize`) and is
matched in memory after the roster is fetched. See the
[Agent registry](/aiway/a2a/registry) for the full list/filter API.
## Invoke synchronously [#invoke-synchronously]
Once you know the agent's ID, invoke it by POSTing a JSON-RPC 2.0 `message/send` envelope
to `POST /a2a/research-agent-01`. The gateway routes the request to the agent through its
[Agent Bridge](/aiway/a2a/architecture) (the per-agent virtual subscriber) and
relays the agent's reply on the **same HTTP response** — no SSE, no polling.
```bash
curl -X POST http://localhost:9090/a2a/research-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"parts": [{"text": "Summarize the history of message queues"}]
}
}
}'
```
```python
import asyncio
import json
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "research-agent-01"
async def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"parts": [{"text": "Summarize the history of message queues"}],
},
},
}
async with httpx.AsyncClient() as client:
resp = await client.post(f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload)
data = resp.json()
print(json.dumps(data, indent=2))
if "error" in data:
print(f"\nAgent returned an error: {data['error']['message']}")
else:
print("\nGot a synchronous result from the agent.")
if __name__ == "__main__":
asyncio.run(main())
```
The agent's JSON-RPC `result` comes back verbatim under `result`:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"summary": "Research summary for: Summarize the history of message queues",
"sources": 3
}
}
```
## Header forwarding & error handling [#header-forwarding--error-handling]
A couple of behaviors are worth knowing before you build real callers:
* **Header forwarding** — any request header you send prefixed with `X-` is forwarded to
the agent (hop-by-hop and sensitive headers like `Authorization` and `Cookie` are
stripped), and the gateway always injects `X-KubeMQ-Caller-ID` so the agent knows who
originated the call. Use this to pass tracing or tenant context through to your agent.
* **Transport vs application errors** — when a response carries an `error` object, KubeMQ
distinguishes two classes:
* **Transport errors** — the agent never processed the request (unreachable, timeout,
`502`/`503`/`504`, or an oversized reply). Internally these surface as
`Executed: false`, and they are **safe to retry**.
* **Application errors** — the agent processed the request and chose to return a
JSON-RPC error (`Executed: true`). Retrying the same request usually won't help —
fix the request instead.
Tell them apart so your retry logic only re-sends calls that never reached the agent.
For the full `message/send` envelope (context IDs, custom methods), header-forwarding
rules, and the complete error-code list, see
[Synchronous messaging](/aiway/a2a/sync-messaging) and the
[Agent registry](/aiway/a2a/registry).
## Next step [#next-step]
You've discovered and invoked your agent in one round-trip. Next, switch from a single
reply to a live stream of task events as the agent works.
# Tutorial (/aiway/tutorial)
Tutorial = the end-to-end *fabric* story (build → discover → stream → LLM orchestration); the A2A and MCP **Getting started** pages are single-gateway quickstarts. New here? This page is the guided path.
Across five steps you start KubeMQ, build and register a plain-HTTP "research" agent with **no KubeMQ SDK**, discover it by capability and invoke it synchronously, stream its live task events over SSE, and finally let an LLM discover and call that same agent over MCP — proving the "one fabric" thesis end-to-end. Every step uses Python and `curl`.
## What you'll build [#what-youll-build]
By the last step, an LLM host reaches your custom research agent through the MCP→A2A bridge — discovering it with `agent_list` and invoking it with `agent_send`, all over the message broker.
*The LLM discovers and invokes the research agent you built — through MCP, Aiway, and the message broker.*
## Prerequisites [#prerequisites]
* **Docker** (to run KubeMQ locally) — or a KubeMQ server already running with the shared HTTP server on port `9090`.
* **Python 3.11+** for the agent server and the clients.
* **`curl`** for probing the Aiway endpoints.
No KubeMQ SDK is required anywhere in this tutorial. The agent is a plain HTTP service, and every call to the fabric is JSON over HTTP.
## The steps [#the-steps]
Follow the steps in order — each one builds on the last.
# 5. Orchestrate from an LLM (MCP) (/aiway/tutorial/orchestrate-from-an-llm)
In [Step 2](/aiway/tutorial/build-and-register-an-agent) you built and registered
`research-agent-01`, and in Steps [3](/aiway/tutorial/discover-and-invoke) and
[4](/aiway/tutorial/stream-live-results) you discovered and invoked it as an A2A
caller. Now you'll put an **LLM** in the driver's seat: an MCP client connects to the
same KubeMQ server, discovers your agent, and calls it — all through the **Model Context
Protocol**, with no new glue code on your side. This is the **MCP→A2A bridge**: the LLM
reaches the exact agent you built in Step 2.
This step assumes KubeMQ is running on port `9090` and `research-agent-01` is registered
and listening (Steps 1 and 2). The MCP connector is **enabled by default** — `POST /mcp`
is already live on the shared HTTP server. For the Python path, install the MCP SDK with
`pip install mcp`. Arriving from another page? Any registered agent works; [Fastest path: wrap a plain HTTP service](/aiway/a2a/getting-started#fastest-path-wrap-a-plain-http-service) registers one in ten minutes.
## Connect and list the tools [#connect-and-list-the-tools]
An MCP client opens a session against `POST http://localhost:9090/mcp`, negotiates the
protocol version (`2025-11-25`), then calls `tools/list`. KubeMQ exposes **15 tools** —
**11 core messaging tools** plus **4 agent-bridge tools** (`agent_list`, `agent_info`,
`agent_send`, `agent_query`) that appear when the A2A agent registry is available. The
agent-bridge tools are what let the LLM reach your agent.
The MCP session version `2025-11-25` is a **different** version from the A2A Agent Card's
`protocolVersions: ["1.0"]` you registered in
[Step 2](/aiway/tutorial/build-and-register-an-agent) — one is the MCP handshake,
the other is the agent's A2A card version. They are not interchangeable.
First open a session with `initialize`, then list the tools with the returned session ID:
```bash
# 1. Initialize a session — note the protocol version is the MCP one.
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "tutorial", "version": "1.0.0"}
}
}'
# 2. List the tools (substitute the session ID from the response above).
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-H "MCP-Session-Id: " \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list"
}'
```
The `mcp` SDK runs the `initialize` handshake and tracks the session ID for you over the
Streamable HTTP transport — you only call `tools/list`:
```python
import asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
KUBEMQ_MCP_URL = "http://localhost:9090"
async def main() -> None:
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
names = [t.name for t in tools.tools]
print(f"{len(names)} tools available") # 15: 11 core + 4 agent-bridge
print("agent-bridge tools:", [n for n in names if n.startswith("agent_")])
if __name__ == "__main__":
asyncio.run(main())
```
The tool list includes the four agent-bridge tools alongside the 11 core messaging tools:
```json
["agent_list", "agent_info", "agent_send", "agent_query"]
```
## Discover the agent with agent\_list [#discover-the-agent-with-agent_list]
`agent_list` reads the same A2A registry you queried in
[Step 3](/aiway/tutorial/discover-and-invoke) — but now through an MCP tool call.
Pass `skill_tags` to filter by capability, exactly as before, and the LLM gets back
`research-agent-01` without ever hard-coding its ID.
```bash
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-H "MCP-Session-Id: " \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "agent_list",
"arguments": {"skill_tags": ["research"]}
}
}'
```
```python
result = await session.call_tool("agent_list", {"skill_tags": ["research"]})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
The result text is a JSON array of agent cards — your agent is in it:
```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [{"type": "text", "text": "[{\"agent_id\":\"research-agent-01\",\"name\":\"Research Agent\",\"skills\":[{\"id\":\"research\",\"name\":\"Research\",\"tags\":[\"research\",\"summarize\"]}]}]"}]
}
}
```
## Invoke the agent with agent\_send [#invoke-the-agent-with-agent_send]
`agent_send` wraps your message in an A2A `message/send` envelope and forwards it through
the per-agent [Agent Bridge](/aiway/a2a/architecture) — the same path the direct A2A
call took in [Step 3](/aiway/tutorial/discover-and-invoke), just initiated from MCP.
By default the call is **blocking**: it waits up to `timeout_seconds` for the agent's
reply (**default `60`, max `300`**). Pass `blocking: false` for fire-and-forget, or
`context_id` to thread the message into an existing conversation.
```bash
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-H "MCP-Session-Id: " \
-d '{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "agent_send",
"arguments": {
"agent_id": "research-agent-01",
"message": "Summarize the history of message queues",
"timeout_seconds": 60
}
}
}'
```
```python
result = await session.call_tool("agent_send", {
"agent_id": "research-agent-01",
"message": "Summarize the history of message queues",
"timeout_seconds": 60,
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
The agent's reply comes back in the `content` text: your Step 2 agent's full JSON-RPC response, with the `id` the bridge generated. The call returns:
```json
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"content": [{"type": "text", "text": "{\"jsonrpc\": \"2.0\", \"id\": \"\", \"result\": {\"summary\": \"Research summary for: Summarize the history of message queues\", \"sources\": 3}}"}]
}
}
```
An unknown `agent_id` returns `isError: true` with the text `error: agent not found` —
a tool-level error in the `content` block, not a JSON-RPC protocol error. The bridge also adds a
gateway timeout buffer on top of your `timeout_seconds`. See
[Agent-bridge tools](/aiway/mcp/tools/agent-bridge) for `agent_info`, `agent_query`,
and the full argument and error reference.
## One prompt, two tool calls [#one-prompt-two-tool-calls]
With an MCP host connected (see [Connect an MCP host](/aiway/mcp/getting-started#connect-an-mcp-host)), one prompt can drive a queue and an agent. The example uses `order-status-agent` from [Fastest path: wrap a plain HTTP service](/aiway/a2a/getting-started#fastest-path-wrap-a-plain-http-service); with `research-agent-01`, ask for a summary instead.
Ask your host:
> "Enqueue order 1042 for the fulfillment worker, then ask the order-status agent for
> an ETA."
The host turns that into two MCP tool calls on the same `/mcp` session: one to the durable queue, one to the agent bridge.
```json title="queue_send"
{ "name": "queue_send", "arguments": { "channel": "fulfillment", "body": "{\"id\":1042}" } }
```
```json title="agent_send"
{ "name": "agent_send", "arguments": { "agent_id": "order-status-agent", "message": "What is the ETA for order 1042?" } }
```
You should see two results in the conversation. `queue_send` returns the new message's ID:
```json title="queue_send result"
{
"content": [
{ "type": "text", "text": "{\"is_error\":false,\"message_id\":\"\",\"sent_at\":\"\"}" }
]
}
```
`agent_send` returns the agent's full JSON-RPC response as text:
```json title="agent_send result"
{
"content": [
{ "type": "text", "text": "{\"jsonrpc\": \"2.0\", \"id\": \"\", \"result\": {\"status\": \"in-transit\", \"eta\": \"2 days\"}}" }
]
}
```
## One fabric, no glue code [#one-fabric-no-glue-code]
Step back and notice what just happened. The LLM **discovered** your agent by capability
and **invoked** it — and you wrote no integration code to make that possible. The same
`research-agent-01` you built in Step 2 (a plain-HTTP service, no KubeMQ SDK) is now
reachable by an A2A caller *and* by any MCP-speaking LLM, over the same message broker.
That's the Aiway thesis: **one fabric, two doors** — register once, reach it from both.
To wire this into a real LLM host such as Claude Desktop, see
[Connect an MCP host](/aiway/mcp/getting-started#connect-an-mcp-host). The host then sees
all 15 tools (including the four agent-bridge tools) and can call your agent from a
conversation.
## Troubleshooting [#troubleshooting]
* The host lists no KubeMQ tools: restart it fully, then check it against [Connect an MCP host](/aiway/mcp/getting-started#connect-an-mcp-host).
* `agent_send` returns `isError: true` with `error: agent not found`: the agent is not registered. Registrations expire about 5 minutes after the last heartbeat, so register it again.
* `queue_send` returns `isError: true` with `error: reserved channel name` or `error: channel and body are required`: the channel starts with a reserved prefix such as `_AGENTS_.`, or `channel` or `body` is missing.
## Where to go next [#where-to-go-next]
You've built the full fabric end-to-end: started KubeMQ, registered a zero-SDK agent,
discovered and invoked it, streamed live task events, and orchestrated it from an LLM over
MCP. From here, go deeper:
# 1. Set up & start KubeMQ (/aiway/tutorial/setup)
This first step gets KubeMQ running locally and confirms the two Aiway doors — the **A2A** agent gateway and the **MCP** gateway — are live on the shared HTTP server (port `9090`). Both are enabled by default, so there is nothing to turn on.
Need Docker? Get it from [docker.com/get-started](https://www.docker.com/get-started/). Already ran [Try KubeMQ](/deploy/quickstart)? It publishes port `9090`; skip to Step 2.
## Setup steps [#setup-steps]
### Start KubeMQ [#start-kubemq]
Run KubeMQ locally with a single Docker command. This starts the broker with gRPC on port `50000`, the shared HTTP server (where the A2A and MCP gateways live) on port `9090`, and the dashboard on port `8080`.
This starts the free 14-day evaluation; see [Plans compared](/licensing) for longer use.
Confirm the dashboard is up at `http://localhost:8080`, then move on to verify the Aiway endpoints.
### Verify the A2A agent roster [#verify-the-a2a-agent-roster]
The A2A gateway exposes the agent registry at `GET /agents`. On a fresh server the roster is empty — that is exactly what you want to see before registering an agent in the next step.
```bash title="Terminal"
curl http://localhost:9090/agents
```
You should get back an empty roster:
```json
{
"agents": []
}
```
An empty list confirms the A2A gateway is live and ready to accept registrations. You'll register `research-agent-01` here in Step 2.
### Verify the MCP gateway [#verify-the-mcp-gateway]
The MCP gateway answers at `POST /mcp`. Open a session with a JSON-RPC `initialize` call — this negotiates the MCP protocol version (`2025-11-25`) and proves the gateway is reachable.
```bash title="Terminal"
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": { "name": "aiway-tutorial", "version": "1.0.0" }
}
}'
```
A successful handshake returns the server's protocol version and capabilities:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-11-25",
"capabilities": { "tools": {} },
"serverInfo": { "name": "kubemq-mcp", "version": "1.0.0" }
}
}
```
The MCP **session** protocol version (`2025-11-25`) is a different field from the A2A **Agent Card** `protocolVersions` (which is `["1.0"]`, used when you register an agent in Step 2). They are two distinct layers — don't conflate them.
With KubeMQ running and both Aiway gateways answering, you're ready to build an agent and register it with the fabric.
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# 4. Stream live results (/aiway/tutorial/stream-live-results)
In [step 3](/aiway/tutorial/discover-and-invoke) you called `research-agent-01` with
`message/send` and got a single reply. Real research takes time, though — and your agent
already emits progress as it works. In this step you'll switch to **`message/stream`** and
watch the task unfold live: status updates as the agent searches, reads, and summarizes,
then the result artifact, then a terminal "done" — all over a single **Server-Sent Events
(SSE)** connection.
This step assumes KubeMQ is running on port `9090` and `research-agent-01` is registered
and listening (Steps 1 and 2). All calls go to the **Aiway gateway** on `9090`, not to the
agent's own port — the gateway relays the agent's events back to you.
## How streaming works [#how-streaming-works]
`message/send` returns one reply on the same HTTP response. `message/stream` instead opens
a long-lived `text/event-stream` connection: the gateway uses the agent's
[Agent Bridge](/aiway/a2a/architecture) (its per-agent virtual subscriber) as an
**SSE relay**, forwarding each event the agent emits to you as it happens. You read frames
until a terminal event closes the stream.
Each frame has an `event:` name and a JSON `data:` envelope. The agent's envelope `type`
maps to the SSE event name you see:
| SSE event | Envelope `type` | Meaning | Terminal |
| --------------- | --------------- | ---------------------------------------------- | -------- |
| `task.status` | `status_update` | Progress update (non-terminal) | No |
| `task.artifact` | `artifact` | A partial or complete result artifact | No |
| `task.done` | `done` | The task completed successfully | Yes |
| `task.error` | `error` | The task failed (carries `code` and `message`) | Yes |
The `research-agent-01` agent from [step 2](/aiway/tutorial/build-and-register-an-agent)
emits, in order: three `task.status` updates (`searching` → `reading` → `summarizing`),
one `task.artifact`, then a terminal `task.done`. Stop reading on `task.done` (or
`task.error`). The exact wire format and envelope shapes are in
[SSE behavior](/aiway/a2a/guides/sse-behavior).
## Open a stream [#open-a-stream]
Send a `message/stream` request to `POST /a2a/research-agent-01` with
`Accept: text/event-stream`. The body is a JSON-RPC 2.0 envelope identical to `message/send`,
just with the `message/stream` method. (You can also open a stream with
`GET /a2a/research-agent-01/stream` — the POST form is the common case.)
```bash
curl -N -X POST http://localhost:9090/a2a/research-agent-01 \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": {
"message": {
"parts": [{"text": "Summarize the history of message queues"}]
}
}
}'
```
The `-N` flag disables curl's output buffering so frames print the instant they arrive.
This uses `httpx` with the `httpx-sse` helper for clean SSE parsing — install both with
`pip install httpx httpx-sse`.
```python
import asyncio
import json
import httpx
from httpx_sse import aconnect_sse
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "research-agent-01"
async def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": {
"message": {"parts": [{"text": "Summarize the history of message queues"}]},
},
}
async with httpx.AsyncClient(timeout=None) as client:
print("Connecting to SSE stream...")
async with aconnect_sse(
client,
"POST",
f"{KUBEMQ_URL}/a2a/{AGENT_ID}",
json=payload,
headers={"Accept": "text/event-stream"},
) as event_source:
async for event in event_source.aiter_sse():
data = json.loads(event.data)
print(f"[{event.event}] {json.dumps(data)}")
# task.done and task.error are terminal — stop reading.
if event.event in ("task.done", "task.error"):
break
print("Stream complete.")
if __name__ == "__main__":
asyncio.run(main())
```
The `httpx-sse` library skips keepalive comment lines for you and yields one object per
event with `.event` (the name) and `.data` (the JSON payload).
## Read the live event sequence [#read-the-live-event-sequence]
As the agent works, the frames arrive in order. You'll see the three status updates, then
the artifact, then the terminal `task.done`:
```text
Connecting to SSE stream...
[task.status] {"type": "status_update", "payload": {"status": "searching", "progress": 1, "total": 3}}
[task.status] {"type": "status_update", "payload": {"status": "reading", "progress": 2, "total": 3}}
[task.status] {"type": "status_update", "payload": {"status": "summarizing", "progress": 3, "total": 3}}
[task.artifact] {"type": "artifact", "payload": {"name": "summary.json", "data": {"summary": "Research summary for: Summarize the history of message queues", "sources": 3}}}
[task.done] {"type": "done", "payload": {"final_result": "completed", "event_count": 4}}
Stream complete.
```
Mapped to the event table above:
* **`task.status`** (`status_update`) — non-terminal progress. The agent emits one per
stage (`searching`, `reading`, `summarizing`) with `progress`/`total` so a UI can show a
bar. There can be any number of these.
* **`task.artifact`** (`artifact`) — the result payload. The envelope carries a `name`
(`summary.json`) and a `data` object with the actual result. An agent can emit several
artifacts; the [artifact envelope is defined in SSE behavior](/aiway/a2a/guides/sse-behavior).
* **`task.done`** (`done`) — **terminal**. After this the gateway closes the connection.
A failed task ends with `task.error` instead, carrying a `code` and `message`. Always
break on either.
## Keepalive, idle timeout & disconnect [#keepalive-idle-timeout--disconnect]
A few stream behaviors matter once you build real callers — all relayed by the gateway,
not the agent:
* **Keepalive** — during quiet periods the gateway emits an SSE comment line
(`: keepalive`) every **30 seconds** so proxies don't drop the idle socket. It's a
comment, not an event; SSE client libraries (including `httpx-sse`) ignore it. If you
parse the stream by hand, skip any line starting with `:`.
* **Idle timeout** — if the agent emits no events for `MaxSSEIdleSeconds` (default
**300s**), the gateway closes the stream with a terminal `task.error` (code `-32001`,
`"stream idle timeout"`). The timer measures the gap *between* events, so a long task
stays alive as long as it heartbeats with periodic `task.status` frames.
* **Auto-cancel on disconnect** — if you close the connection before a terminal event, the
gateway detects it and **cancels the work on the agent** (via a `stream_cancel` to the
Agent Bridge) rather than letting it run to completion. Closing your SSE reader is a real
cancellation signal — it frees the agent's concurrency slot promptly.
For the full streaming walkthrough, see [Streaming (SSE)](/aiway/a2a/streaming). For
the exact wire format, the artifact envelope, keepalive cadence, idle-timeout behavior, and
disconnect cancellation, see [SSE behavior](/aiway/a2a/guides/sse-behavior).
## Next step [#next-step]
You've watched a task stream live from `task.status` through `task.artifact` to a terminal
`task.done`. So far every call has been a hand-written HTTP request. In the final step, an
**LLM** does the discovering and invoking for you — over MCP, through the same fabric.
# Kubernetes (Helm) (/configure/kubernetes)
Install KubeMQ first with [Install on Kubernetes](/deploy/install/kubernetes). This page
changes the settings of a cluster you installed with Helm. For a cluster kmq installed, see
[Apply a settings change](#apply-a-settings-change).
On Kubernetes, KubeMQ runs through the **operator**. You describe the server with a
`KubemqCluster` custom resource, the operator reconciles it into a StatefulSet, Services,
and configuration, and the **`kubemq-next` Helm chart** renders that resource from your `cluster-values.yaml`.
Because the chart writes values straight into the CR, a Helm value path equals the
`KubemqCluster` `spec.*` path with the leading `spec.` removed (`spec.grpc.port` →
`grpc.port`).
This guide is the single source of truth for **complete, runnable** Helm and CRD
configurations. The [Configuration overview](/configure) and the
[reference pages](/configure/reference) show minimal single-setting snippets and
link here.
## Configure with cluster-values.yaml [#configure-with-cluster-valuesyaml]
For anything beyond the license, add settings to the `cluster-values.yaml` you created in
Install on Kubernetes. The license is set by
[Install on Kubernetes](/deploy/install/kubernetes#add-your-license); its fields are listed
in [License](/configure/reference/deployment#license). Each value maps **1:1** to a
`KubemqCluster` `spec.*` field — the chart renders your values verbatim into the CR spec, so
there is no separate Helm schema to learn.
Add each key once. Helm does not merge a repeated key: a second `api:` block replaces the
first and drops your sign-in settings. To change a key the file already has (`replicas`,
`volume`, `api`, `licenseKeySecretRef`, `env`), edit it in place instead of adding a second copy.
```yaml title="cluster-values.yaml (settings to add)"
# Example keys — add only the ones you need. Each maps to spec..
# To publish an interface outside the cluster, see Expose interfaces below.
# REST is on by default; MCP / A2A / CloudEvents ride the REST HTTP port
# (disabled: false is the default — shown here only to be explicit)
rest:
disabled: false
port: 9090
expose: ClusterIP
# Store limits and retention — enforced on the `legacy` engine only (see callout below)
store:
messagesRetentionMinutes: 1440
maxChannels: 0
# Pod resources — development-sized; size them for your load
resources:
requestsCpu: 250m
requestsMemory: 512Mi
limitsCpu: "2"
limitsMemory: 2Gi
```
Changing `resources` restarts the servers one at a time. Size them for your load with
[Resources](/configure/reference/deployment#resources).
**`store.messagesRetentionMinutes` and the other `store.max*` limits are enforced by the
`legacy` engine only — and a new cluster on a clean store comes up on `next`.** So the
`1440` above does nothing on a default install: native Events Store and Queues channels
have no age, size, or count cap and grow until the disk does. Size by `spec.volume.size`,
or use Kafka topic channels where age eviction matters. See
[Native retention scope](/configure/reference/storage-engines#native-retention-scope).
Apply the file with the commands in [Apply a settings change](#apply-a-settings-change).
The same settings as a `KubemqCluster` resource, for a cluster you manage yourself with
`kubectl apply -f` instead of Helm. Do not apply it to a cluster that Helm or kmq installed:
they overwrite the resource on their next update. It reads the license from the Secret
`messaging-license` that the Helm path of [Install on Kubernetes](/deploy/install/kubernetes#add-your-license)
creates.
```yaml title="kubemqcluster.yaml"
apiVersion: next.kubemq.io/v1
kind: KubemqCluster
metadata:
name: messaging
namespace: kubemq
spec:
licenseKeySecretRef:
name: messaging-license
key: licenseKey
replicas: 3
volume:
size: 20Gi
storageClass: YOUR_STORAGE_CLASS
rest:
disabled: false
port: 9090
expose: ClusterIP
api:
port: 8080
expose: ClusterIP
auth:
enable: true
adminUsername: admin
store:
messagesRetentionMinutes: 1440
maxChannels: 0
resources:
requestsCpu: 250m
requestsMemory: 512Mi
limitsCpu: "2"
limitsMemory: 2Gi
```
Replace:
* `YOUR_STORAGE_CLASS` — a storage class in your cluster, from `kubectl get storageclass`.
**REST is enabled by default on the chart.** The chart ships `rest.disabled: false`
(`spec.rest.disabled: false`), so REST — and the MCP, A2A, and CloudEvents connectors that
ride the **REST HTTP port** — are reachable out of the box. `disabled` is an **opt-out**
boolean: omit the key entirely to leave REST on; set `rest.disabled: true` only to turn REST
off, which also takes MCP, A2A, and CloudEvents offline.
**On Kubernetes, `.port` moves everything together.** For `grpc`, `rest`, and `api`, setting
`spec..port` makes the operator emit the matching listener env var
(`CONNECTORS_GRPC_PORT` / `CONNECTORS_REST_PORT` / `API_PORT`) **and** set the Kubernetes
`Service` `port`/`targetPort` **and** the container port — the in-pod listener and the
`Service` port move as one. This matches Docker, where the same `*_PORT` setting moves the
actual listener (which you then publish with `-p`) — see the
[Docker guide](/configure/docker).
## Apply a settings change [#apply-a-settings-change]
These commands are for clusters installed with Helm. If kmq installed your cluster, do not
run them: they replace the settings kmq applied, including the license and TLS settings, and
the servers can stop. [Contact support](mailto:support@kubemq.io) to change settings on a
cluster kmq installed.
Find the chart version the cluster runs:
```bash title="Terminal"
helm list --kube-context YOUR_KUBE_CONTEXT -n kubemq
```
Replace:
* `YOUR_KUBE_CONTEXT` — the kubectl context of your cluster, from `kubectl config get-contexts`.
You should see a row named `messaging` whose `CHART` column reads `kubemq-next-` followed by
the chart version.
Apply `cluster-values.yaml` at that same version:
```bash title="Terminal"
helm upgrade --install messaging kubemq-next/kubemq-next \
--kube-context YOUR_KUBE_CONTEXT \
-n kubemq \
--version YOUR_VERSION \
-f cluster-values.yaml \
--wait
```
Replace:
* `YOUR_VERSION` — the version after `kubemq-next-` in the `CHART` column above.
You should see `STATUS: deployed` and a `REVISION` one higher than before.
Passing the version you already run changes settings only. To move to the latest release,
follow [Upgrade KubeMQ](/deploy/upgrade) instead, which also updates the CRDs. Do not use
`--reuse-values`.
Wait for the cluster to be ready with the new settings:
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq wait --for=condition=Ready kubemqclusters.next.kubemq.io/messaging --timeout=10m
```
You should see `kubemqcluster.next.kubemq.io/messaging condition met`.
## Cluster size [#cluster-size]
A cluster runs 3 or more servers; see
[Requirements and supported setups](/deploy/install/requirements#kubernetes). Use an odd count such as 3, 5, or
7, and choose it before you install: the count cannot change once the cluster is established
(see [High availability](/configure/reference/deployment#high-availability)). For local
development and testing, use the [single-node Docker guide](/configure/docker).
## Expose interfaces [#expose-interfaces]
Set `expose` under the `grpc:` key (add the key if your file does not have it yet).
Messaging authentication is off by default, so turn it on before you publish gRPC outside
the cluster; see [Security](/configure/reference/security).
```yaml title="cluster-values.yaml (the grpc key)"
grpc:
expose: LoadBalancer # ClusterIP | NodePort | LoadBalancer
```
To publish the management API, add `expose` (and `nodePort`) under the `api:` key your file
already has, keeping its `auth` settings. Beyond the cluster, serve it over TLS; see
[Use your own management certificate](/deploy/install/kubernetes#management-certificate).
```yaml title="cluster-values.yaml (the existing api key)"
api:
expose: NodePort
nodePort: 32080 # only used with NodePort
auth:
enable: true
adminUsername: admin
```
* **`ClusterIP`** — reachable only inside the cluster (the default for internal-only
interfaces).
* **`NodePort`** — published on every node at `nodePort`; useful for direct access without a
cloud load balancer.
* **`LoadBalancer`** — provisions an external load balancer (cloud environments).
`nodePort` applies only when `expose: NodePort`. On Docker there is no `Service` — publish
ports with `-p` instead (see the [Docker guide](/configure/docker)).
## Zero-config Kafka [#zero-config-kafka]
The Kafka connector is **on by default** — a fresh cluster needs no `kafka:` block at all,
and no separate engine setting to manage.
With the store empty and `store.engine` left unset, the server auto-selects the next
storage engine (`store.engine: next`) at first boot — see
[Storage Engines → Zero-config engine selection](/configure/reference/storage-engines#zero-config-engine-selection)
for the full selection rules. To run without Kafka, turn it off explicitly:
```yaml title="cluster-values.yaml (settings to add)"
kafka:
enabled: false
```
**Every default install runs Kafka with `replicas: 3`, so Kafka producers should use
`acks>=1` for durable writes.** The next storage engine acknowledges a publish only after
it's quorum-replicated across raft peers, so an `acks=0` producer won't see a stalled or
leaderless partition.
External reachability needs `spec.kafka.expose` plus an advertised host/port pair — see
[Connectors → Kafka](/configure/reference/connectors#kafka) for the full
listener/TLS/SAN details.
## Configure by domain [#configure-by-domain]
Every server setting — with its type, default, valid values, and both per-target columns —
lives in the domain reference pages.
## Verify [#verify]
Confirm the operator has reconciled the cluster and the pods are ready.
Check the `KubemqCluster` resource and its status:
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq get kubemqclusters.next.kubemq.io
```
Replace:
* `YOUR_KUBE_CONTEXT` — the kubectl context of your cluster, from `kubectl config get-contexts`.
Inspect the full status, including the reconcile phase and any conditions:
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq describe kubemqclusters.next.kubemq.io messaging
```
Confirm the server pods are running:
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq get pods
```
You should see `messaging-0`, `messaging-1` and `messaging-2` with status `Running`.
To reach the dashboard, open a tunnel to the first server, then open
`http://127.0.0.1:18080` (`https://127.0.0.1:18080` on a cluster kmq installed):
```bash title="Terminal"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq port-forward pod/messaging-0 18080:8080
```
## Related [#related]
* [Configuration overview](/configure) — the two targets and the config model.
* [Docker (single-node)](/configure/docker) — the local / dev target.
* [Deployment & HA reference](/configure/reference/deployment) — packaging, replicas, and exposure in full.
* [Install on Kubernetes](/deploy/install/kubernetes) — the step-by-step install guide.
* [Upgrade KubeMQ](/deploy/upgrade) — move a cluster to the latest release.
# Advanced (config.yaml-only) (/configure/reference/advanced)
These are advanced, low-level knobs. The **message-broker engine** (`broker.*`), **runtime
tuning** (`tuning.*`), and **standalone clustering** (`cluster.*`) have **no Helm/CRD path**
— they are Docker / `config.yaml`-only, so their Helm/CRD column is `—` (per the
[reference legend](/configure/reference)). On Kubernetes the operator owns those
concerns. **Routing** is the exception: three of its fields (`data`, `url`, `autoReload`)
map to `spec.routing.*` on the CRD.
## Message-broker engine [#message-broker-engine]
The embedded message-broker engine's internal limits and buffers, configured through the
`broker.*` block. These are Docker / `config.yaml`-only; there is **no Helm/CRD path** (the
operator owns the engine on Kubernetes). Most fields bind to a `BROKER_*` env var — but the
two auto-assigned ports (`port`, `monitoringPort`) have **no env var** and are file-only.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------ | -------------- | ------------------------- | ------------ | ------------------------------------------------------------ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| Port | int | auto (free port) | port number | `broker.port` · *(no env var)* | — | Ephemeral — a free port is picked at every startup (`getFreePort()`). Not meant to be pinned; **no `BROKER_PORT` env var exists**. Not validated. |
| Max payload | int (bytes) | `1048576000` (\~1000 MiB) | ≥ 0 | `broker.maxpayload` · `BROKER_MAX_PAYLOAD` | — | Max message payload in **bytes**. Cast to `int32` when applied, so the effective ceiling is 2,147,483,647 bytes (\~2 GiB); larger values overflow. |
| Write deadline | int (ms) | `2000` | ≥ 0 | `broker.writedeadline` · `BROKER_WRITE_DEADLINE` | — | Per-write deadline in **milliseconds**. |
| Max connections | int | `0` (unlimited) | ≥ 0 | `broker.maxconn` · `BROKER_MAX_CONN` | — | `0` = unlimited. |
| Monitoring port | int | auto (free port) | 1–65535 | `broker.monitoringport` · *(no env var)* | — | Ephemeral — picked at every startup. **No `BROKER_MONITORING_PORT` env var exists.** This is the only broker field validated as a port. |
| Write buffer size | int (**MB**) | `2` (→ 2 MB) | ≥ 0 | `broker.writebuffersize` · `BROKER_WRITE_BUFFER_SIZE` | — | Value is in **megabytes** — the config value is multiplied by 1024×1024 (`broker.go:52`). `2` means 2 MB, **not** 2 bytes. |
| Read buffer size | int (**MB**) | `10` (→ 10 MB) | ≥ 0 | `broker.readbuffersize` · `BROKER_READ_BUFFER_SIZE` | — | Value is in **megabytes** (×1024×1024, `broker.go:53`). Read-ahead buffer. `10` = 10 MB. |
| Disk sync (s) | int | `5` | ≥ 0 | `broker.disksyncseconds` · `BROKER_DISK_SYNC_SECONDS` | — | Disk flush interval in **seconds**. Lowered from 60 s → 5 s to shrink the data-loss window. |
| Slice max messages | int | `0` (unlimited) | ≥ 0 | `broker.slicemaxmessages` · `BROKER_SLICE_MAX_MESSAGES` | — | `0` = no message-count limit per file slice. |
| Slice max bytes | int64 (**MB**) | `64` (→ 64 MB) | ≥ 0 | `broker.slicemaxbytes` · `BROKER_SLICE_MAX_BYTES` | — | Per-slice ceiling in **megabytes** (×1024×1024, `broker.go:56`). `64` = 64 MB. |
| Slice max age (s) | int | `0` (no rollover) | ≥ 0 | `broker.slicemaxageseconds` · `BROKER_SLICE_MAX_AGE_SECONDS` | — | `0` = no age-based slice rollover. Value in **seconds**. |
| Parallel recovery | int | `4` | **≥ 1** | `broker.parallelrecovery` · `BROKER_PARALLEL_RECOVERY` | — | Recovery worker count. Must be **≥ 1** (`0` or negative is rejected). |
`broker.writeBufferSize`, `broker.readBufferSize`, and `broker.sliceMaxBytes` are expressed
in **megabytes**, not bytes — the raw config value is multiplied by 1024×1024 internally. Set
`readBufferSize: 10` for a 10 MB buffer. `broker.maxPayload`, by contrast, is in **bytes**.
## Runtime tuning [#runtime-tuning]
Optional Go-runtime tuning through the `tuning.*` block. Every zero value means
"auto-detect from the environment." **`TuningConfig` is the one config domain with no env-var
bindings at all** — there are **no `TUNING_*` environment variables** (verified: `tuning.go`'s
`defaultTuningConfig()` makes no `bindViperEnv` call). These keys are therefore **only settable
through a mounted `config.yaml`/TOML file**. There is no Helm/CRD path. For the three fields
that wrap standard Go knobs, the Go runtime independently honors the native `GOGC`,
`GOMEMLIMIT`, and `GOMAXPROCS` env vars.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| --------------------- | ---- | ---------- | ------------ | ---------------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------- |
| GC percent | int | `0` (auto) | ≥ 0 | `tuning.gc_percent` · *(no env var)* | — | Config-file-only. Wraps Go GC frequency; use the native `GOGC` env var instead for env-based tuning. |
| Memory limit (MB) | int | `0` (auto) | ≥ 0 | `tuning.memory_limit_mb` · *(no env var)* | — | Config-file-only. Wraps `GOMEMLIMIT`; use the native `GOMEMLIMIT` env var for env-based tuning. |
| Max procs | int | `0` (auto) | ≥ 0 | `tuning.max_procs` · *(no env var)* | — | Config-file-only. Wraps `GOMAXPROCS`; use the native `GOMAXPROCS` env var for env-based tuning. |
| Pipe init buffer (KB) | int | `0` (auto) | ≥ 0 | `tuning.pipe_init_buf_kb` · *(no env var)* | — | Config-file-only. Internal memory-pipe initial buffer size. |
| Pipe max buffer (KB) | int | `0` (auto) | ≥ 0 | `tuning.pipe_max_buf_kb` · *(no env var)* | — | Config-file-only. Internal memory-pipe maximum buffer size. |
| Allow TLS SHA-1 | bool | `false` | true / false | `tuning.tls_allow_sha1` · *(no env var)* | — | Config-file-only. Permits SHA-1 in TLS cipher suites (legacy interop). |
`tuning.*` keys use `snake_case` in `config.yaml` (they carry explicit `mapstructure` tags —
`gc_percent`, `memory_limit_mb`, etc.), unlike the dotted-camel keys elsewhere. Because there
are **no `TUNING_*` env vars**, a K8s CRD/Helm chart cannot set these today without a custom
mounted config file — prefer the native `GOGC` / `GOMEMLIMIT` / `GOMAXPROCS` container env
vars for GC/memory/CPU tuning.
## Cluster configuration [#cluster-configuration]
Manual `cluster.*` configuration creates an unsupported Docker cluster. Do not use it for a
deployment. Kubernetes clustering is supported only through `spec.replicas` and the KubeMQ
operator; see [Requirements and supported setups](/deploy/install/requirements#supported-setups).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| -------------- | ------ | -------- | ------------ | ------------------------------------ | ------------- | -------------------------------------------------------------------------------------------------- |
| Enable | bool | `false` | true / false | `cluster.enable` · `CLUSTER_ENABLE` | — | Master toggle. When `false`, all other `cluster.*` fields are ignored (validation short-circuits). |
| Cluster name | string | `kubemq` | name string | `cluster.name` · `CLUSTER_NAME` | — | Shared cluster identifier across peers. |
| Cluster port | int | `5228` | 1–65535 | `cluster.port` · `CLUSTER_PORT` | — | Peer-to-peer cluster port. Validated only when `enable: true`. |
| Cluster routes | string | `""` | route list | `cluster.routes` · `CLUSTER_ROUTES` | — | Addresses of peer nodes to connect to. |
| Is seed | bool | `false` | true / false | `cluster.isseed` · `CLUSTER_IS_SEED` | — | Whether this node is a seed node. Struct field is `IsSeed`; config.yaml key is `cluster.isseed`. |
The `next` storage engine uses an additional replication membership plane managed by Dragonboat. Its dedicated `Cluster.Replication.*` configuration fields and `POD_NAME`→`ReplicaID` auto-derivation are documented in the [Storage Engines](/configure/reference/storage-engines) reference page.
## Routing [#routing]
Channel-routing rules, configured through the `routing.*` block. The server uses the standard
**`enable: true/false`** toggle. On the CRD, routing has **no explicit toggle** — the operator
auto-emits `ROUTING_ENABLE=true` whenever `spec.routing.data` **or** `spec.routing.url` is set.
Three fields map to `spec.routing.*`; `enable` and `filePath` are Docker-only (`—`).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ---------------- | ------ | --------- | -------------------- | -------------------------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable | bool | `false` | true / false | `routing.enable` · `ROUTING_ENABLE` | — | Master toggle (server side). On the CRD it is implicit — set automatically when `data` or `url` is provided. When `false`, the rest of the block is ignored. |
| Routing data | string | `""` | inline routing rules | `routing.data` · `ROUTING_DATA` | `spec.routing.data` | Inline routing table. Consumed **raw** (not base64-decoded), so the operator emits it as a plain ConfigMap variable. Takes precedence over `filePath` and `url`. |
| Routing URL | string | `""` | URL | `routing.url` · `ROUTING_URL` | `spec.routing.url` | Fetch the routing table from a URL. Validated as a URL when set. Struct field is `URL`; config.yaml key is `routing.url`. Emitted raw. |
| Auto-reload (ms) | int | `0` (off) | ≥ 0 | `routing.autoreload` · `ROUTING_AUTO_RELOAD` | `spec.routing.autoReload` | Reload interval in **milliseconds**. `0` disables periodic reload. CRD field is `int32`, `omitempty` — the operator only emits `ROUTING_AUTO_RELOAD` when non-zero (no CRD-side default). |
| Routing file | string | `""` | file path | `routing.filepath` · `ROUTING_FILE_PATH` | — | Load rules from a file path. Docker / config.yaml-only — **not** exposed on the CRD (superseded by inline `data`). Validated as a filename when set. |
When routing is enabled you must provide **exactly one** source: `data`, `filePath`, or `url`
(enabling routing with none set is a configuration error). Precedence when more than one is
present: `data` → `filePath` → `url`. `autoReload` must be ≥ 0.
## Example [#example]
Set a message-broker buffer. On Docker this is a `config.yaml` key (in **MB**) or a `BROKER_*`
env var; on Kubernetes the broker engine has **no Helm/CRD path**, so the operator owns it.
This is a single-setting snippet — see the [Docker guide](/configure/docker) for complete,
runnable configurations.
```yaml title="config.yaml"
broker:
readBufferSize: 10 # megabytes → 10 MB
```
```yaml title="cluster-values.yaml"
# Not available on Helm/CRD — the message-broker engine is config.yaml-only.
# On Kubernetes the operator manages the broker engine.
```
For the full Docker delivery methods (env vars, mounted `config.yaml`, the `CONFIG`
variable) see the [Docker guide](/configure/docker).
# Connectors (/configure/reference/connectors)
KubeMQ ships ten connectors — the **MCP** and **A2A (agents)** agent platforms,
**CloudEvents**, and seven wire-protocol connectors: **MQTT**, **AMQP 0.9.1**, **AMQP 1.0**,
**STOMP**, **Kafka**, **AWS** (SQS/SNS), and **GCP Pub/Sub**. The three HTTP-server connectors
(MCP, A2A, CloudEvents) are **on by default**, and so are **Kafka** (ports 9092/9093) and
**AMQP 0.9.1 / RabbitMQ** (ports 5672/5671) — a stock server binds 9092 and 5672 out of the
box. The **other five wire-protocol connectors are opt-in (disabled by default)** — each opens
a new network port and must be explicitly enabled.
Each setting is shown for both targets — Docker single-node (`config.yaml` key · env var)
and Kubernetes/Helm (`spec.*` path). A dash (`—`) in the Helm/CRD column means the setting
is not available on that surface (it is `config.yaml`/env-var-only — supply it through a
mounted config file or a raw pod env var, never a typed CRD field).
Connector environment-variable prefixes follow the acronym rule: all-caps acronym
segments **drop** the underscore (`CONNECTORSMCP_*`, `CONNECTORSCE_*`, `CONNECTORSMQTT_*`,
`CONNECTORSA2_A_*`), while Title-case segments **keep** it (`CONNECTORS_AMQP_*`,
`CONNECTORS_AMQP10_*`, `CONNECTORS_STOMP_*`, `CONNECTORS_KAFKA_*`, `CONNECTORS_AWS_*`,
`CONNECTORS_GCP_*`). See [the reference legend](/configure/reference) for the full rule
and the silently-ignored wrong twin.
## Enabling and disabling a connector [#enabling-and-disabling-a-connector]
The toggle shape differs by connector type and by target:
* **HTTP-server connectors (MCP, A2A, CloudEvents):** always on by default. Docker turns
them **off** with `enable: false`; Kubernetes/Helm turns them off with `disabled: true`
(omit the key while the connector is on).
* **Default-on wire connectors (Kafka, AMQP 0.9.1):** **enabled by default**. Docker turns
them **off** with `enable: false` (`CONNECTORS_KAFKA_ENABLE=false`,
`CONNECTORS_AMQP_ENABLE=false`); Kubernetes/Helm turns them off with `enabled: false`
(`spec.kafka.enabled: false`, `spec.amqp.enabled: false`). Omitting the block or the field
means **on**.
* **Opt-in wire connectors (MQTT, AMQP 1.0, STOMP, AWS, GCP Pub/Sub):**
**disabled by default**. Docker turns them **on** with `enable: true`; Kubernetes/Helm
turns them on with `enabled: true` (a positive-sense field — omitting it leaves the connector
off).
**A default-on connector never blocks boot.** If Kafka or AMQP 0.9.1 is on only by default
and the configuration cannot run it — Kafka on the `legacy` storage engine, port 9092/9093
clashing with another enabled listener, a clustered Kafka whose raft members all sit on one
host (per-broker addresses cannot be derived), `Broker.MaxPayload` too small, or AMQP
batch/receive limits above the queue limits — the server prints one stderr warning and
continues without that connector:
```text
WARNING: the Kafka connector is on by default but cannot run with this configuration, so it is DISABLED for this run: ... — set Connectors.Kafka.Enable=false to silence this, or =true to make it a startup error
```
(The AMQP twin says `the AMQP 0-9-1 (RabbitMQ) connector` and `Connectors.Amqp.Enable`.)
Setting the connector to `true` explicitly keeps those errors fatal, as before.
The snippets below show turning CloudEvents off (HTTP-server connector, uses `disabled:`) and
enabling MQTT (opt-in wire-protocol connector, uses `enabled:`). See the
[Docker guide](/configure/docker) and the
[Kubernetes guide](/configure/kubernetes) for complete, runnable configurations; on Kubernetes, apply a change with [Apply a settings change](/configure/kubernetes#apply-a-settings-change).
```yaml title="config.yaml"
connectors:
ce:
enable: false
```
```yaml title="cluster-values.yaml"
ce:
disabled: true
```
```bash title="docker run"
docker run -e CONNECTORSMQTT_ENABLE=true ...
```
```yaml title="cluster-values.yaml"
mqtt:
enabled: true
```
## Service exposure & session affinity [#service-exposure--session-affinity]
Every wire connector carries the same Kubernetes exposure surface on the CRD, alongside
its protocol settings. These are Kubernetes-only — on Docker you publish a port with
`docker run -p`.
| Field | Type | Default | Valid values | Helm/CRD path | Notes |
| ------------------- | ------------- | ----------- | ----------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Service exposure | string (enum) | `ClusterIP` | `ClusterIP` / `NodePort` / `LoadBalancer` | `spec..expose` | Type of the connector's `Service`. |
| Session affinity | string (enum) | `None` | `None` / `ClientIP` | `spec..sessionAffinity` | Pins a client to one replica. **Required for AWS and GCP** — see the callout below. |
| Node port | int32 | *unset* | 30000–32767 | `spec..nodePort` | Honored **only** when `expose: NodePort`. Unset ⇒ the kernel assigns one, which you cannot configure into a client ahead of the install. |
| TLS node port | int32 | *unset* | 30000–32767 | `spec..tlsNodePort` | Same, for the connector's TLS listener. |
| WebSocket node port | int32 | *unset* | 30000–32767 | `spec.mqtt.wsNodePort` | MQTT only — its WebSocket listener. |
Which connector has which:
| Connector | `expose` | `sessionAffinity` | `nodePort` | `tlsNodePort` | `wsNodePort` |
| ----------- | -------------- | ----------------- | ---------- | ------------- | ------------ |
| MQTT | ✅ | ✅ | ✅ | ✅ | ✅ |
| AMQP 0.9.1 | ✅ | ✅ | ✅ | ✅ | — |
| AMQP 1.0 | ✅ | ✅ | ✅ | ✅ | — |
| STOMP | ✅ | ✅ | ✅ | ✅ | — |
| Kafka | ✅ | ✅ | ✅ | ✅ | — |
| AWS | ✅ | ✅ | ✅ | — | — |
| GCP Pub/Sub | ✅ | ✅ | ✅ | — | — |
| CloudEvents | — (rides REST) | — | — | — | — |
**Session affinity is not optional for the AWS and GCP connectors on a multi-replica
cluster.** Both protocols hand the client a token that only the replica that minted it can
honor:
* **AWS** — an SQS **receipt handle** is bound to the replica that issued it, and it is the
only way to delete a message. A delete that lands on another replica is refused, the
message reappears at the visibility timeout, **and the queue never drains**. A client
holding a single keep-alive connection is pinned by accident and never sees this; it
bites when the connection breaks, or when the client does not pool connections.
* **GCP Pub/Sub** — an **ack id** minted by one replica and acked on another is refused,
with no disruption required to trigger it. Ordered subscriptions additionally need
stickiness to preserve per-key ordering.
Set `sessionAffinity: ClientIP` on both:
```yaml title="cluster-values.yaml"
aws:
enabled: true
expose: NodePort
sessionAffinity: ClientIP
nodePort: 30171
gcp:
enabled: true
expose: NodePort
sessionAffinity: ClientIP
nodePort: 32439
```
**`ClientIP` affinity is unreliable when clients share a NAT or egress IP** — every client
behind it looks like one address and lands on one replica. Where an ingress exists, prefer
**cookie-based affinity on the ingress** instead.
**AMQP 0.9.1 and AMQP 1.0 share one listener, and one Service.** Both ride `5672`/`5671`;
enabling both is supported and both are served through the **`-amqp`** Service.
Enabling `amqp10` additionally creates a **`-amqp10`** Service as a
discoverability alias onto that same listener. `expose` and `sessionAffinity` are
**shared** between the two blocks — last one wins — so set them consistently. The operator
raises an `AmqpSessionAffinityConflict` warning event if the two disagree.
**Kafka exposure on a multi-replica cluster needs one address per broker.** Kafka hands
every client an address **per broker** in its Metadata response, so a single Service —
`ClusterIP`, `NodePort`, or `LoadBalancer` alike — is one address that round-robins across
all replicas and cannot address a 3-broker cluster. Setting `kafka.expose: LoadBalancer`
on a multi-replica cluster does **not** give you working external Kafka.
* **In-cluster, any replica count:** leave `spec.kafka.advertisedHost` unset. The operator
derives per-broker addresses from the pods' stable DNS names and gives each pod its own
advertised host. Nothing to configure.
* **External, single replica:** `expose` + `advertisedHost` works.
* **External, multi-replica:** you must provision one client-reachable address per broker
— a Service or LoadBalancer per pod, or a per-pod NodePort — and list them in
`spec.kafka.peers`. The operator does not create per-broker addressing for you. Leave
`advertisedHost` unset in this case: with a peer map each broker advertises itself from
its own entry, and one `advertisedHost` could only ever be right for one of them.
**CloudEvents has no port or Service of its own.** It rides the server's shared HTTP
listener alongside REST, and is reached and exposed through **`spec.rest.expose` /
`spec.rest.nodePort`**. There is deliberately no `spec.ce.expose`.
## MCP [#mcp]
The Model Context Protocol agent platform, served on the shared HTTP server. Env prefix
`CONNECTORSMCP_*` (all-caps `MCP` collapses the underscore after `CONNECTORS`); CRD group
`spec.mcp.*`. This is an **HTTP-family connector — on by default** (opt-out): Docker turns it
off with `enable: false`, Kubernetes/Helm with `spec.mcp.disabled: true`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ---------------- | --------- | ----------- | ---------------------- | -------------------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------ |
| Enable / disable | bool | `true` (on) | true / false | `connectors.mcp.enable` · `CONNECTORSMCP_ENABLE` | `spec.mcp.disabled` | Inverted boolean: Docker `enable: false` turns it off; Helm `disabled: true` turns it off. |
| Tool timeout (s) | int | `300` | `> 0` | `connectors.mcp.tooltimeoutseconds` · `CONNECTORSMCP_TOOL_TIMEOUT_SECONDS` | `spec.mcp.toolTimeoutSeconds` | Must be positive (rejected if ≤ 0). CRD minimum 1. |
| Trusted origins | string\[] | `["auto"]` | origin list / `"auto"` | `connectors.mcp.trustedorigins` · `CONNECTORSMCP_TRUSTED_ORIGINS` | `spec.mcp.trustedOrigins` | `auto` derives allowed origins from the request host. |
**The MCP env prefix is `CONNECTORSMCP_` — no underscore between `CONNECTORS` and `MCP`.** The
natural `CONNECTORS_MCP_*` form does **not** bind — the server starts, accepts the variable
without error, and silently ignores it. Unlike CloudEvents, MCP has no natural-name alias, so
`CONNECTORSMCP_ENABLE` / `CONNECTORSMCP_TOOL_TIMEOUT_SECONDS` / `CONNECTORSMCP_TRUSTED_ORIGINS`
are the only working names.
## A2A (Agents) [#a2a-agents]
The agent-to-agent platform, served on the shared HTTP server. Env prefix `CONNECTORSA2_A_*`;
the CRD group is `spec.agents.*` (note the group name differs from the connector name). This is
an **HTTP-family connector — on by default** (opt-out): Docker turns it off with `enable: false`,
Kubernetes/Helm with `spec.agents.disabled: true`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| -------------------------- | --------- | ------------------ | ------------------------ | ---------------------------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| Enable / disable | bool | `true` (on) | true / false | `connectors.a2a.enable` · `CONNECTORSA2_A_ENABLE` | `spec.agents.disabled` | Inverted boolean. |
| Agent TTL (s) | int | `300` | `> 0` | `connectors.a2a.agentttlseconds` · `CONNECTORSA2_A_AGENT_TTL_SECONDS` | `spec.agents.agentTtlSeconds` | Must be positive. CRD json tag is `agentTtlSeconds` (lowercase `tl`). |
| Default timeout (s) | int | `300` | `> 0` | `connectors.a2a.defaulttimeoutseconds` · `CONNECTORSA2_A_DEFAULT_TIMEOUT_SECONDS` | `spec.agents.defaultTimeoutSeconds` | Must be positive. |
| Max timeout (s) | int | `3600` | `≥ default timeout` | `connectors.a2a.maxtimeoutseconds` · `CONNECTORSA2_A_MAX_TIMEOUT_SECONDS` | `spec.agents.maxTimeoutSeconds` | Cross-field: must be ≥ Default timeout (enforced server-side, not by the CRD schema). |
| Max agents | int | `0` | `≥ 0` (`0` = unlimited) | `connectors.a2a.maxagents` · `CONNECTORSA2_A_MAX_AGENTS` | `spec.agents.maxAgents` | `0` = unlimited. |
| Max SSE idle (s) | int | `300` | `> 0` | `connectors.a2a.maxsseidleseconds` · `CONNECTORSA2_A_MAX_SSE_IDLE_SECONDS` | `spec.agents.maxSseIdleSeconds` | Must be positive. CRD json tag is `maxSseIdleSeconds`. |
| Trusted origins | string\[] | `["auto"]` | origin list / `"auto"` | `connectors.a2a.trustedorigins` · `CONNECTORSA2_A_TRUSTED_ORIGINS` | `spec.agents.trustedOrigins` | |
| Agent max response (bytes) | int64 | `10485760` (10 MB) | `≥ 0` | `connectors.a2a.agentmaxresponsebytes` · `CONNECTORSA2_A_AGENT_MAX_RESPONSE_BYTES` | `spec.agents.agentMaxResponseBytes` | Caps a downstream agent's response body. |
| Agent TLS skip verify | bool | `false` | true / false | `connectors.a2a.agenttlsskipverify` · `CONNECTORSA2_A_AGENT_TLS_SKIP_VERIFY` | `spec.agents.agentTlsSkipVerify` | CRD json tag is `agentTlsSkipVerify`. |
| Agent max concurrency | int | `100` | any int (`≤ 0` accepted) | `connectors.a2a.agentmaxconcurrency` · `CONNECTORSA2_A_AGENT_MAX_CONCURRENCY` | `spec.agents.agentMaxConcurrency` | `≤ 0` is **accepted** and silently clamped back to `100` — it does not error, and there is no output saying it was rewritten. |
| Metrics retention (h) | int | `168` (7 days) | `> 0` | `connectors.a2a.metricsretentionhours` · `CONNECTORSA2_A_METRICS_RETENTION_HOURS` | `spec.agents.metricsRetentionHours` | Must be positive. Retention window for per-agent metrics. |
**The A2A env prefix is `CONNECTORSA2_A_` — not `CONNECTORS_A2A_`.** The `convertEnvFormat`
rule splits `A2A` into `A2_A` (the regex breaks between the digit and the trailing `A`), so the
agent variables read `CONNECTORSA2_A_MAX_AGENTS`, `CONNECTORSA2_A_AGENT_TTL_SECONDS`, and so on.
Neither `CONNECTORS_A2A_*` nor `CONNECTORSA2A_*` binds — both are silently ignored. Note also
that the CRD group is `spec.agents.*`, not `spec.a2a.*`.
## CloudEvents [#cloudevents]
The CloudEvents connector, served on the shared HTTP server. Env prefix `CONNECTORSCE_*`;
CRD group `spec.ce.*`. This is an **HTTP-family connector — on by default** (opt-out): Docker
turns it off with `enable: false`, Kubernetes/Helm with `spec.ce.disabled: true`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------- | ---- | ----------- | ----------------------- | ----------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------ |
| Enable / disable | bool | `true` (on) | true / false | `connectors.ce.enable` · `CONNECTORSCE_ENABLE` | `spec.ce.disabled` | Inverted boolean. |
| Timeout (s) | int | `60` | `> 0` | `connectors.ce.timeoutseconds` · `CONNECTORSCE_TIMEOUT_SECONDS` | `spec.ce.timeoutSeconds` | Must be positive. |
| Sub buffer size | int | `100` | `1`–`10000` | `connectors.ce.subbuffsize` · `CONNECTORSCE_SUB_BUFF_SIZE` | `spec.ce.subBuffSize` | Rejected if ≤ 0 or > 10000. |
| Max SSE idle (s) | int | `300` | `> 0` | `connectors.ce.maxsseidleseconds` · `CONNECTORSCE_MAX_SSE_IDLE_SECONDS` | `spec.ce.maxSseIdleSeconds` | Must be positive. CRD json tag is `maxSseIdleSeconds`. |
| Max SSE connections | int | `0` | `≥ 0` (`0` = unlimited) | `connectors.ce.maxsseconnections` · `CONNECTORSCE_MAX_SSE_CONNECTIONS` | `spec.ce.maxSseConnections` | `0` = unlimited. CRD json tag is `maxSseConnections`. |
**CloudEvents accepts both env forms.** The primary name is the collapsed `CONNECTORSCE_*`
(e.g. `CONNECTORSCE_ENABLE`), but CE is the one connector that also binds the natural
`CONNECTORS_CE_*` alias (`CONNECTORS_CE_ENABLE`, `CONNECTORS_CE_TIMEOUT_SECONDS`, …). Both
resolve to the same setting — this compensating alias exists only for CloudEvents; MCP, A2A,
and MQTT do **not** have it.
**But the server warns that the alias is IGNORED, and that warning is wrong.** The
unknown-variable warner does not track the alias binding, so a `CONNECTORS_CE_*` variable is
reported as ignored while its value is being applied. Meanwhile a typo in the *collapsed*
form (`CONNECTORSC_ENABLE`) produces no warning at all, because collapsed names sit outside
the warner's namespace list. See [the reference legend](/configure/reference) for the
full picture.
## MQTT [#mqtt]
The MQTT 3.1.1 / 5.0 wire protocol. Env prefix `CONNECTORSMQTT_*` (no underscore after
`CONNECTORS`); CRD group `spec.mqtt.*`. This is a **wire-protocol connector — opt-in (disabled
by default)**: Docker turns it on with `enable: true`, Kubernetes/Helm with `spec.mqtt.enabled:
true` (a positive-sense `*bool` — omitting it leaves MQTT off). Ports are `string` server-side
(`""` disables a listener) and `int32` on the CRD.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------------------------------- | ------ | -------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| Enable / disable | bool | **`false` (opt-in)** | true / false | `connectors.mqtt.enable` · `CONNECTORSMQTT_ENABLE` | `spec.mqtt.enabled` | Opt-in: set `true` to open ports 1883/8883/8083. Helm uses positive-sense `enabled: true`. |
| Port | string | `1883` | port / `""` | `connectors.mqtt.port` · `CONNECTORSMQTT_PORT` | `spec.mqtt.port` | Plaintext TCP listener; `""` disables it. CRD type int32 (1–65535). |
| TLS port | string | `8883` | port / `""` | `connectors.mqtt.tlsport` · `CONNECTORSMQTT_TLS_PORT` | `spec.mqtt.tlsPort` | TLS listener; **active only when Security mode ≠ None**. `""` disables. CRD int32 (1–65535). |
| WebSocket port | string | `8083` | port / `""` | `connectors.mqtt.wsport` · `CONNECTORSMQTT_WS_PORT` | `spec.mqtt.wsPort` | WebSocket listener; `""` disables. CRD int32 (1–65535). |
| Default pattern | enum | `events` | `events` / `store` / `none` | `connectors.mqtt.defaultpattern` · `CONNECTORSMQTT_DEFAULT_PATTERN` | `spec.mqtt.defaultPattern` | KubeMQ pattern for prefixless topics. |
| Sub buffer size | int | `100` | `1`–`10000` | `connectors.mqtt.subbuffsize` · `CONNECTORSMQTT_SUB_BUFF_SIZE` | `spec.mqtt.subBuffSize` | Rejected if ≤ 0 or > 10000. |
| Queue ACK timeout (s) | int | `30` | `> 0` | `connectors.mqtt.queueacktimeoutseconds` · `CONNECTORSMQTT_QUEUE_ACK_TIMEOUT_SECONDS` | `spec.mqtt.queueAckTimeoutSeconds` | Must be positive. |
| RPC timeout (s) | int | `30` | `> 0` | `connectors.mqtt.rpctimeoutseconds` · `CONNECTORSMQTT_RPC_TIMEOUT_SECONDS` | `spec.mqtt.rpcTimeoutSeconds` | Must be positive. |
| RPC max pending | int | `1024` | `> 0` | `connectors.mqtt.rpcmaxpending` · `CONNECTORSMQTT_RPC_MAX_PENDING` | `spec.mqtt.rpcMaxPending` | Must be positive. |
| Detail history enabled | bool | `true` | true / false | `connectors.mqtt.detailhistoryenabled` · `CONNECTORSMQTT_DETAIL_HISTORY_ENABLED` | `spec.mqtt.detailHistoryEnabled` | Master switch for per-entity (client/subscription) detail-page history recording. |
| Detail history max entities | int | `5000` | `≥ 0` (`0` = unbounded) | `connectors.mqtt.detailhistorymaxentities` · `CONNECTORSMQTT_DETAIL_HISTORY_MAX_ENTITIES` | `spec.mqtt.detailHistoryMaxEntities` | Caps tracked per-entity history keys; new keys refused beyond it. Validated even when history is off. |
| Capabilities · max clients | int64 | `0` | `≥ 0` (`0` = unlimited) | `connectors.mqtt.capabilities.maxclients` · `CONNECTORSMQTT_CAPABILITIES_MAX_CLIENTS` | `spec.mqtt.capabilities.maxClients` | `0` = unlimited (explicit opt-in; startup logs a WARN). Never clamped. |
| Capabilities · max packet size (bytes) | uint32 | `4194304` (4 MB) | `0` or `1`–`4294967295` | `connectors.mqtt.capabilities.maxpacketsizebytes` · `CONNECTORSMQTT_CAPABILITIES_MAX_PACKET_SIZE_BYTES` | `spec.mqtt.capabilities.maxPacketSizeBytes` | A `0` is clamped back to 4 MB (0 = "unlimited" is a DoS footgun); effective value logged at startup. |
| Capabilities · receive maximum | uint16 | `1024` | `0` or `1`–`65535` | `connectors.mqtt.capabilities.receivemaximum` · `CONNECTORSMQTT_CAPABILITIES_RECEIVE_MAXIMUM` | `spec.mqtt.capabilities.receiveMaximum` | A `0` is clamped back to 1024. |
| Capabilities · max inflight | uint16 | `8192` | `0`–`65535` | `connectors.mqtt.capabilities.maxinflight` · `CONNECTORSMQTT_CAPABILITIES_MAX_INFLIGHT` | `spec.mqtt.capabilities.maxInflight` | Not clamped. |
| Capabilities · max session expiry (s) | uint32 | `3600` | `0` or `1`–`4294967295` | `connectors.mqtt.capabilities.maxsessionexpiryseconds` · `CONNECTORSMQTT_CAPABILITIES_MAX_SESSION_EXPIRY_SECONDS` | `spec.mqtt.capabilities.maxSessionExpirySeconds` | A `0` is clamped back to 3600. |
| Capabilities · max message expiry (s) | int64 | `86400` | `≥ 0` | `connectors.mqtt.capabilities.maxmessageexpiryseconds` · `CONNECTORSMQTT_CAPABILITIES_MAX_MESSAGE_EXPIRY_SECONDS` | `spec.mqtt.capabilities.maxMessageExpirySeconds` | Rejected if negative. |
| Capabilities · max QoS | byte | `2` | `0`–`2` | `connectors.mqtt.capabilities.maxqos` · `CONNECTORSMQTT_CAPABILITIES_MAX_QOS` | `spec.mqtt.capabilities.maxQos` | Rejected if > 2. |
| Capabilities · min protocol version | byte | `4` | `4` / `5` | `connectors.mqtt.capabilities.minprotocolversion` · `CONNECTORSMQTT_CAPABILITIES_MIN_PROTOCOL_VERSION` | `spec.mqtt.capabilities.minProtocolVersion` | `4` = MQTT 3.1.1, `5` = MQTT 5.0. |
| Capabilities · max subscriptions per client | int | `1000` | `≥ 0` (`0` = unlimited) | `connectors.mqtt.capabilities.maxsubscriptionsperclient` · `CONNECTORSMQTT_CAPABILITIES_MAX_SUBSCRIPTIONS_PER_CLIENT` | `spec.mqtt.capabilities.maxSubscriptionsPerClient` | Caps distinct subscription filters per client; excess SUBSCRIBEs get SUBACK 0x97 (DoS cap). `0` = unlimited. |
**The MQTT env prefix is `CONNECTORSMQTT_` — no underscore between `CONNECTORS` and `MQTT`.**
The natural `CONNECTORS_MQTT_*` form does **not** bind and is silently ignored. This applies to
every MQTT variable, including the nested `CONNECTORSMQTT_CAPABILITIES_*` keys. Unlike
CloudEvents, MQTT has no natural-name alias.
**Some MQTT capabilities are forced, not configurable.** At server construction the connector
pins `RetainAvailable = 0` (retained messages rejected), `SharedSubAvailable = 1`, and
`WildcardSubAvailable = 1` regardless of config. A partially-specified `capabilities` block
leaves unset safety caps (`maxPacketSizeBytes`, `receiveMaximum`, `maxSessionExpirySeconds`) at
`0`, which the server clamps back to their safe defaults rather than treating as "unlimited" —
the effective caps are logged at startup. At least one listener port (`port`, `tlsPort`, or
`wsPort`) must be non-empty, and no two may share the same value.
## AMQP 0.9.1 [#amqp-091]
The AMQP 0.9.1 / RabbitMQ wire protocol. Env prefix `CONNECTORS_AMQP_*`; CRD group
`spec.amqp.*`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| --------------------- | ------ | -------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Enable | bool | **`true` (on by default)** | true / false | `connectors.amqp.enable` · `CONNECTORS_AMQP_ENABLE` | `spec.amqp.enabled` | On by default: Docker `enable: false`, Helm `enabled: false` to turn it off (omitting the field means on). Opens ports 5672/5671 (shared mux with AMQP 1.0). With authentication off, 5672 accepts any username/password — the same trust model as unauthenticated gRPC/REST. |
| Port | int | `5672` | `0`–`65535` (`0` disables) | `connectors.amqp.port` · `CONNECTORS_AMQP_PORT` | `spec.amqp.port` | Plaintext listener, shared with AMQP 1.0. `Port` and `TlsPort` cannot both be `0` when enabled. CRD accepts `1`–`65535`. |
| TLS port | int | `5671` | `0`–`65535` (`0` disables) | `connectors.amqp.tlsport` · `CONNECTORS_AMQP_TLS_PORT` | `spec.amqp.tlsPort` | TLS listener. |
| Heartbeat (s) | int | `60` | ≥ `0` | `connectors.amqp.heartbeatseconds` · `CONNECTORS_AMQP_HEARTBEAT_SECONDS` | `spec.amqp.heartbeatSeconds` | |
| Frame max (bytes) | int | `131072` | ≥ `4096` (accepted; > 512 MiB is clamped down) | `connectors.amqp.framemax` · `CONNECTORS_AMQP_FRAME_MAX` | `spec.amqp.frameMax` | Silently **clamped down to 536870912 (512 MiB)** if set higher (a stderr warning is emitted); a value ≥ 2³² would otherwise narrow to `0` and disable the codec frame-size cap. |
| Channel max | int | `2047` | `1`–`65535` | `connectors.amqp.channelmax` · `CONNECTORS_AMQP_CHANNEL_MAX` | `spec.amqp.channelMax` | |
| Max connections | int | `1000` | ≥ `0` (`0` = unlimited) | `connectors.amqp.maxconnections` · `CONNECTORS_AMQP_MAX_CONNECTIONS` | `spec.amqp.maxConnections` | `0` = unlimited. |
| Max body size (bytes) | int | `104857600` | > `0` | `connectors.amqp.maxbodysize` · `CONNECTORS_AMQP_MAX_BODY_SIZE` | `spec.amqp.maxBodySize` | |
| Default vhost | string | `default` | non-empty; no whitespace or `;:*>`; no trailing `.`; **no `.` anywhere** | `connectors.amqp.defaultvhost` · `CONNECTORS_AMQP_DEFAULT_VHOST` | `spec.amqp.defaultVhost` | Becomes a channel segment, so it must pass the channel-charset rules. A dotted vhost would make two distinct queues collide onto one channel (`amqp.{vhost}.{queue}` is joined with a bare dot), so it fails validation at startup. |
| Get batch size | int | `32` | `1`–`1024` | `connectors.amqp.getbatchsize` · `CONNECTORS_AMQP_GET_BATCH_SIZE` | `spec.amqp.getBatchSize` | Must also be ≤ `queue.maxNumberOfMessages` (cross-checked in top-level config validation). |
| Dead-letter max hops | int | `16` | ≥ `1` | `connectors.amqp.deadlettermaxhops` · `CONNECTORS_AMQP_DEAD_LETTER_MAX_HOPS` | `spec.amqp.deadLetterMaxHops` | |
| Max receive count | int | `0` | ≥ `0` (`0` = unlimited) | `connectors.amqp.maxreceivecount` · `CONNECTORS_AMQP_MAX_RECEIVE_COUNT` | `spec.amqp.maxReceiveCount` | `0` = unlimited. Must also be ≤ `queue.maxReceiveCount` (cross-checked in top-level config validation). |
| SSL cert login | bool | `false` | true / false | `connectors.amqp.sslcertlogin` · `CONNECTORS_AMQP_SSL_CERT_LOGIN` | `spec.env` | The opt-in that turns on certificate login over SASL `EXTERNAL`. Deliberately not inferred from the TLS settings. Requires a non-zero TLS port, and mutual TLS (`Security.Cert`, `Security.Key` **and** `Security.Ca`) for the mechanism to ever be offered. |
| SSL cert login from | string | `distinguished_name` | `distinguished_name` / `common_name` | `connectors.amqp.sslcertloginfrom` · `CONNECTORS_AMQP_SSL_CERT_LOGIN_FROM` | `spec.env` | Which certificate field becomes the `EXTERNAL` identity — RabbitMQ's own setting name and values. `subject_alternative_name` is not supported; any other value is a startup error. |
| Credentials | list | `[]` | `{Username, Password, Permissions, Tags}` entries | `connectors.amqp.credentials` · **no env var** | **none** | Connector-local RabbitMQ-style users with per-vhost configure/write/read permissions and tags. File or structured config only — there is no environment variable, so on an operator-managed cluster there is no shipped way to set it today. Non-empty, both username and password are checked and the authorization subject becomes the encoded username. See [Users and permissions](/connectors/rabbitmq/how-to/users-and-permissions). |
| Management enable | bool | `false` | true / false | `connectors.amqp.management.enable` · `CONNECTORS_AMQP_MANAGEMENT_ENABLE` | `spec.env` | The RabbitMQ-compatible [management HTTP API](/connectors/rabbitmq/reference/management-api) on a second listener. Starts only beside a running AMQP 0-9-1 connector; TLS follows the server-wide `Security` mode on the same port. |
| Management port | int | `15672` | `1`–`65535` | `connectors.amqp.management.port` · `CONNECTORS_AMQP_MANAGEMENT_PORT` | `spec.env` | Must differ from every other enabled listener port; checked whenever management is enabled, independent of the AMQP enable flag. |
**Two cross-checks against the queue limits.** The server rejects the config unless
`amqp.maxReceiveCount ≤ queue.maxReceiveCount` and `amqp.getBatchSize ≤
queue.maxNumberOfMessages`. Keep the AMQP values within the queue ceilings (see
[Storage & Queues](/configure/reference/storage-queues)).
## AMQP 1.0 [#amqp-10]
The AMQP 1.0 wire protocol (also the JMS / Qpid path). Env prefix `CONNECTORS_AMQP10_*`;
CRD group `spec.amqp10.*`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------------ | ----- | -------------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable | bool | **`false` (opt-in)** | true / false | `connectors.amqp10.enable` · `CONNECTORS_AMQP10_ENABLE` | `spec.amqp10.enabled` | Opt-in wire connector. Ports 5672/5671 are already open on a stock server through the listener shared with AMQP 0.9.1; enabling this turns on AMQP 1.0 dispatch on them. Until then an AMQP 1.0 client connects but fails protocol negotiation. |
| Port | int | `5672` | `0`–`65535` (`0` disables) | `connectors.amqp10.port` · `CONNECTORS_AMQP10_PORT` | `spec.amqp10.port` | Shared with AMQP 0.9.1 — a `Port == Amqp.Port` collision is intentionally allowed (the mux dedupes the bind). `Port` and `TlsPort` cannot both be `0`. |
| TLS port | int | `5671` | `0`–`65535` (`0` disables) | `connectors.amqp10.tlsport` · `CONNECTORS_AMQP10_TLS_PORT` | `spec.amqp10.tlsPort` | |
| Max frame size (bytes) | int | `131072` | ≥ `512` | `connectors.amqp10.maxframesize` · `CONNECTORS_AMQP10_MAX_FRAME_SIZE` | `spec.amqp10.maxFrameSize` | Spec floor 512. |
| Max message size (bytes) | int64 | `104857600` | > `0` | `connectors.amqp10.maxmessagesize` · `CONNECTORS_AMQP10_MAX_MESSAGE_SIZE` | `spec.amqp10.maxMessageSize` | `int64`; matches the AMQP 0.9.1 `maxBodySize` default (100 MB). |
| Session max | int | `256` | `1`–`65535` | `connectors.amqp10.sessionmax` · `CONNECTORS_AMQP10_SESSION_MAX` | `spec.amqp10.sessionMax` | |
| Max links per session | int | `256` | ≥ `1` | `connectors.amqp10.maxlinkspersession` · `CONNECTORS_AMQP10_MAX_LINKS_PER_SESSION` | `spec.amqp10.maxLinksPerSession` | |
| Max connections | int | `1000` | ≥ `0` (`0` = unlimited) | `connectors.amqp10.maxconnections` · `CONNECTORS_AMQP10_MAX_CONNECTIONS` | `spec.amqp10.maxConnections` | `0` = unlimited. |
| Idle timeout (s) | int | `120` | ≥ `0` (`0` = disabled) | `connectors.amqp10.idletimeoutseconds` · `CONNECTORS_AMQP10_IDLE_TIMEOUT_SECONDS` | `spec.amqp10.idleTimeoutSeconds` | `0` = disabled. |
| Default pattern | enum | `queues` | `queues` / `events` / `events-store` / `commands` / `queries` | `connectors.amqp10.defaultpattern` · `CONNECTORS_AMQP10_DEFAULT_PATTERN` | `spec.amqp10.defaultPattern` | KubeMQ pattern mapped from AMQP addresses. |
| Get batch size | int | `32` | `1`–`1024` | `connectors.amqp10.getbatchsize` · `CONNECTORS_AMQP10_GET_BATCH_SIZE` | `spec.amqp10.getBatchSize` | |
| Max unsettled per link | int | `1024` | ≥ `1` | `connectors.amqp10.maxunsettledperlink` · `CONNECTORS_AMQP10_MAX_UNSETTLED_PER_LINK` | `spec.amqp10.maxUnsettledPerLink` | |
| Default RPC timeout (s) | int | `30` | ≥ `1` | `connectors.amqp10.defaultrpctimeoutseconds` · `CONNECTORS_AMQP10_DEFAULT_RPC_TIMEOUT_SECONDS` | `spec.amqp10.defaultRpcTimeoutSeconds` | |
| RPC max pending | int | `512` | ≥ `1` | `connectors.amqp10.rpcmaxpending` · `CONNECTORS_AMQP10_RPC_MAX_PENDING` | `spec.amqp10.rpcMaxPending` | |
**AMQP 1.0 shares port `5672` (and TLS `5671`) with AMQP 0.9.1.** The two protocols are
demultiplexed on a single shared listener, so running both on the default ports is fine.
If you set a **different** port for one, keep the pair consistent so clients reach the
listener you intend.
## STOMP [#stomp]
The STOMP 1.0 / 1.1 / 1.2 wire protocol. Env prefix `CONNECTORS_STOMP_*`; CRD group
`spec.stomp.*`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| --------------------- | ------ | -------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable | bool | **`false` (opt-in)** | true / false | `connectors.stomp.enable` · `CONNECTORS_STOMP_ENABLE` | `spec.stomp.enabled` | Opt-in wire connector. Opens ports 61613/61614. |
| Port | string | `61613` | `""` (disabled) or `1`–`65535` | `connectors.stomp.port` · `CONNECTORS_STOMP_PORT` | `spec.stomp.port` | Plaintext listener. String on the server (`""` disables); the CRD takes an `int32` (`1`–`65535`). `Port` must differ from `TlsPort`. |
| TLS port | string | `61614` | `""` (disabled) or `1`–`65535` | `connectors.stomp.tlsport` · `CONNECTORS_STOMP_TLS_PORT` | `spec.stomp.tlsPort` | TLS listener. At least one of `Port`/`TlsPort` must be set. |
| Default pattern | enum | `events` | `events` / `queues` / `store` / `none` | `connectors.stomp.defaultpattern` · `CONNECTORS_STOMP_DEFAULT_PATTERN` | `spec.stomp.defaultPattern` | KubeMQ pattern for bare (prefixless) destinations. |
| Sub buffer size | int | `100` | `1`–`10000` | `connectors.stomp.subbuffsize` · `CONNECTORS_STOMP_SUB_BUFF_SIZE` | `spec.stomp.subBuffSize` | Events deliver-channel buffer. |
| Max connections | int | `1000` | ≥ `0` (`0` = unlimited) | `connectors.stomp.maxconnections` · `CONNECTORS_STOMP_MAX_CONNECTIONS` | `spec.stomp.maxConnections` | `0` = unlimited. |
| Max body size (bytes) | int | `104857600` | > `0` | `connectors.stomp.maxbodysize` · `CONNECTORS_STOMP_MAX_BODY_SIZE` | `spec.stomp.maxBodySize` | |
| Heartbeat (ms) | int | `10000` | ≥ `0` (`0` = disabled) | `connectors.stomp.heartbeatms` · `CONNECTORS_STOMP_HEARTBEAT_MS` | `spec.stomp.heartbeatMs` | Advertised sx,sy; `0` disables the server side. |
| Queue ACK timeout (s) | int | `30` | > `0` | `connectors.stomp.queueacktimeoutseconds` · `CONNECTORS_STOMP_QUEUE_ACK_TIMEOUT_SECONDS` | `spec.stomp.queueAckTimeoutSeconds` | |
| RPC timeout (s) | int | `30` | > `0` (accepted; > `2147483` is clamped down) | `connectors.stomp.rpctimeoutseconds` · `CONNECTORS_STOMP_RPC_TIMEOUT_SECONDS` | `spec.stomp.rpcTimeoutSeconds` | Silently **clamped down to `2147483`** (\~24.8 days) if set higher, so `timeout × 1000` cannot overflow the `int32` RPC-bridge deadline. |
| RPC max pending | int | `1024` | > `0` | `connectors.stomp.rpcmaxpending` · `CONNECTORS_STOMP_RPC_MAX_PENDING` | `spec.stomp.rpcMaxPending` | In-flight RPC cap. |
## Kafka [#kafka]
The embedded **Kafka drop-in connector** — KubeMQ speaks the native Kafka wire protocol,
so real `librdkafka`/`kcat`/Java clients connect unchanged. Env prefix `CONNECTORS_KAFKA_*`;
CRD group `spec.kafka.*`. The connector is compiled into the **default build**
(no build tag) and gated purely at runtime by `Enable`.
Eight fields are exposed as typed CRD fields (`spec.kafka.*`) — including the Service-exposure
type; the remaining advanced knobs — fourteen scalars, the eighteen
[share-group settings](#share-group-settings), **and the six-field OAUTHBEARER block** — are
**`config.yaml`/env-var-only** (Helm/CRD path `—`) and have no CRD field — set them via a
mounted config file or a raw pod env var. The
SASL credential store is **secret/file-only** (no env var, no CRD field).
See the [Kafka connector overview](/connectors/kafka) and the
[migration guide](/connectors/kafka/how-to/migrate-from-kafka) for adoption
planning, fitness assessment, and cutover tooling beyond this config reference.
**Kafka requires the `next` storage engine — but it's zero-config.** On a **fresh** store
with Kafka enabled and `Store.Engine` unset, the server **auto-selects `next`** (a `NOTICE`
is logged) — no manual `store.engine=next` step needed. It fails closed only when the store
directory already holds `legacy` data (a config error naming the conflicting directory) or
`Store.Engine=legacy` is set explicitly alongside Kafka. Pinning `STORE_ENGINE=next` skips
the probe entirely and always wins. See
[Storage Engines](/configure/reference/storage-engines#zero-config-engine-selection).
### Core (CRD-exposed) settings [#core-crd-exposed-settings]
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------------- | ------------- | -------------------------- | ----------------------------------------- | ------------------------------------------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable | bool | **`true` (on by default)** | true / false | `connectors.kafka.enable` · `CONNECTORS_KAFKA_ENABLE` | `spec.kafka.enabled` | On by default: Docker `enable: false`, Helm `enabled: false` to turn it off (omitting the field means on). Opens ports 9092/9093. A single node with no `Host` set advertises `localhost:9092`; set `advertisedHost` for remote clients. |
| Port | string | `9092` | `""` (disabled) or `1`–`65535` | `connectors.kafka.port` · `CONNECTORS_KAFKA_PORT` | `spec.kafka.port` | Plaintext listener. Set it to `""` for a TLS-only listener. `Port` must differ from `TlsPort`. |
| TLS port | string | `9093` | `""` (disabled) or `1`–`65535` | `connectors.kafka.tlsport` · `CONNECTORS_KAFKA_TLS_PORT` | `spec.kafka.tlsPort` | TLS listener. It opens only when the server-wide Security configuration provides certificate material. A TLS-only setup needs `Port: ""`, a TLS port, and valid certificate material; otherwise startup fails. |
| Advertised host | string | `""` | hostname / IP | `connectors.kafka.advertisedhost` · `CONNECTORS_KAFKA_ADVERTISED_HOST` | `spec.kafka.advertisedHost` | The single broker address handed to every client in Metadata/FindCoordinator. **Set it** to the external LoadBalancer DNS / NodePort IP (or the in-cluster Service DNS) — leaving it `""` falls back to the server `Host`, then the pod hostname, which is unreachable off-pod (connect-then-hang). The TLS cert SAN must include this value. |
| Advertised port | int | `0` | `0`–`65535` (`0` = use `Port`) | `connectors.kafka.advertisedport` · `CONNECTORS_KAFKA_ADVERTISED_PORT` | `spec.kafka.advertisedPort` | The external LB/NodePort port. `0` = fall back to `Port` on the config.yaml/env path. **The CRD schema is stricter than the server**: `spec.kafka.advertisedPort` enforces `minimum: 1`, so `0` is rejected on the typed CRD field even though the server itself accepts it. |
| Max connections | int | `1000` | ≥ `0` (`0` = unlimited) | `connectors.kafka.maxconnections` · `CONNECTORS_KAFKA_MAX_CONNECTIONS` | `spec.kafka.maxConnections` | `0` = unlimited. |
| Max request bytes | int | `104857600` (100 MiB) | ≤ `1073741824` (1 GiB); `0` = default | `connectors.kafka.maxrequestbytes` · `CONNECTORS_KAFKA_MAX_REQUEST_BYTES` | — (set through `spec.env`) | Largest request frame accepted — Kafka's `socket.request.max.bytes`, same default. Never lower than one batch under `Max message bytes`. |
| Max message bytes | int | `1048576` | `1`–`1073741824` (1 GiB) | `connectors.kafka.maxmessagebytes` · `CONNECTORS_KAFKA_MAX_MESSAGE_BYTES` | `spec.kafka.maxMessageBytes` | Per-message cap (1 MiB default). Hard ceiling 1 GiB — Kafka frames are `int32`-length-prefixed, so a larger value would truncate. |
| Service exposure | string (enum) | `ClusterIP` | `ClusterIP` / `NodePort` / `LoadBalancer` | — (Docker: `-p` host port mapping) | `spec.kafka.expose` | Kubernetes Service type for the Kafka listener. Kafka also takes `sessionAffinity`, `nodePort`, and `tlsNodePort` — see [Service exposure & session affinity](#service-exposure--session-affinity), including the **multi-replica addressing** limit. |
### Advanced settings (config.yaml / env-var only — no CRD field) [#advanced-settings-configyaml--env-var-only--no-crd-field]
These are on the `configData` allowlist and have no CRD field. Every one has a
working env var but **no `spec.kafka.*` path** — mount them via config file or a raw pod env var.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| -------------------------------- | --------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Max fetch wait (ms) | int | `1000` | ≤ `300000` (5 min) | `connectors.kafka.maxfetchwaitms` · `CONNECTORS_KAFKA_MAX_FETCH_WAIT_MS` | — | Ceiling a client's `fetch.max.wait.ms` is clamped to. `≤ 0` falls back to the 1 s default; an over-ceiling value is rejected. |
| Timestamp type | string | `CreateTime` | `""` / `CreateTime` | `connectors.kafka.timestamptype` · `CONNECTORS_KAFKA_TIMESTAMP_TYPE` | — | `LogAppendTime` is **rejected** (deferred); any other value is rejected. |
| Offsets retention (min) | int | `10080` (7 days) | ≤ `52560000` (100 yr) | `connectors.kafka.offsetsretentionminutes` · `CONNECTORS_KAFKA_OFFSETS_RETENTION_MINUTES` | — | Committed-offset expiry. `≤ 0` is floored to the default (no "retain forever"); over-ceiling rejected. |
| Max groups | int | `10000` | ≤ `10000000` | `connectors.kafka.maxgroups` · `CONNECTORS_KAFKA_MAX_GROUPS` | — | Coordinator-wide consumer-group registry cap. The same value separately caps share groups (a share group counts until it is deleted) and the share groups that can hold stored per-group configuration. `≤ 0` floored to default; over-ceiling rejected. |
| Max topics per request | int | `10000` | ≤ `1000000` | `connectors.kafka.maxtopicsperrequest` · `CONNECTORS_KAFKA_MAX_TOPICS_PER_REQUEST` | — | Per-request distinct-topic cap (DoS fan-out guard). `≤ 0` floored; over-ceiling rejected. |
| Max partitions per request | int | `100000` | ≤ `10000000` | `connectors.kafka.maxpartitionsperrequest` · `CONNECTORS_KAFKA_MAX_PARTITIONS_PER_REQUEST` | — | Per-request distinct-partition cap. `≤ 0` floored; over-ceiling rejected. |
| SCRAM iterations | int | `4096` | ≤ `1000000` | `connectors.kafka.scramiterations` · `CONNECTORS_KAFKA_SCRAM_ITERATIONS` | — | PBKDF2 iteration count for the SCRAM verifier. `≤ 0` floored to 4096 (RFC-7677 minimum); over-ceiling rejected. |
| SASL mechanisms | string\[] | `[]` (offer `PLAIN`, `SCRAM-SHA-256`, `SCRAM-SHA-512`) | subset of `PLAIN`, `SCRAM-SHA-256`, `SCRAM-SHA-512`, `OAUTHBEARER` (empty = offer the first three only) | `connectors.kafka.saslmechanisms` · `CONNECTORS_KAFKA_SASL_MECHANISMS` | — | Empty = offer the first three (`PLAIN`, `SCRAM-SHA-256`, `SCRAM-SHA-512`). `OAUTHBEARER` is **never** part of the implicit default — it must be listed explicitly, and doing so requires `OAuthBearer.Issuer` set (see OAUTHBEARER authentication below). A non-empty allow-list restricts what `SaslHandshake` offers (e.g. SCRAM-only, dropping cleartext PLAIN); an unknown entry is rejected. |
| Produce byte rate | int | `0` (unlimited) | ≤ `1099511627776` (1 TiB/s) | `connectors.kafka.producebyterate` · `CONNECTORS_KAFKA_PRODUCE_BYTE_RATE` | — | Per-principal produce quota (bytes/s). `0` = unlimited (`ThrottleMillis=0`). `< 0` floored to 0; over-ceiling rejected. |
| Fetch byte rate | int | `0` (unlimited) | ≤ `1099511627776` (1 TiB/s) | `connectors.kafka.fetchbyterate` · `CONNECTORS_KAFKA_FETCH_BYTE_RATE` | — | Fetch-direction twin of the produce quota. |
| Max transaction timeout (ms) | int | `900000` (15 min) | ≤ `86400000` (24 h) | `connectors.kafka.maxtransactiontimeoutms` · `CONNECTORS_KAFKA_MAX_TRANSACTION_TIMEOUT_MS` | — | Ceiling on the `transaction.timeout.ms` a client negotiates. `≤ 0` floored; over-ceiling rejected. |
| Transactional ID expiration (ms) | int64 | `604800000` (7 days) | ≤ `3153600000000` (100 yr) | `connectors.kafka.transactionalidexpirationms` · `CONNECTORS_KAFKA_TRANSACTIONAL_ID_EXPIRATION_MS` | — | Idle-`transactional.id` reaper deadline. `int64`. `≤ 0` floored; over-ceiling rejected. |
| Max transactional IDs | int | `10000` | ≤ `10000000` | `connectors.kafka.maxtransactionalids` · `CONNECTORS_KAFKA_MAX_TRANSACTIONAL_I_DS` | — | Txn-coordinator registry cap. **Env-name trap** (see callout). `≤ 0` floored; over-ceiling rejected. |
| Producer ID block size | int | `1000` | ≤ `1000000` | `connectors.kafka.produceridblocksize` · `CONNECTORS_KAFKA_PRODUCER_ID_BLOCK_SIZE` | — | Producer-ID allocation block. `≤ 0` floored; over-ceiling rejected. |
| Produce pipeline depth | int | `5` | `1`–`5` | `connectors.kafka.producepipelinedepth` · `CONNECTORS_KAFKA_PRODUCE_PIPELINE_DEPTH` | — | Per-partition in-flight produce batches. `5` matches Kafka's idempotent in-flight cap, and is the hard ceiling — above it the broker cannot de-duplicate on replay, so it is rejected. `1` is serial behavior, the emergency rollback. `< 1` is floored to `1` (the safe side), **not** to the default. Worst-case memory is `depth × maxMessageBytes` held per hot partition. |
| Per-broker peer map | string | `""` | `id@host:port,…` | `connectors.kafka.peers` · `CONNECTORS_KAFKA_PEERS` | — | The clustered per-broker **client-reachable** advertised addresses, same grammar as the replication peer map. The id is the peer's raft replica id (= its Kafka broker node id). Meaningful **only** when Kafka is enabled on a cluster running the next storage engine — setting it while the connector is on but the cluster is not is **rejected**. A peer's Kafka address must never equal that same id's raft address; that paste mistake is rejected, since clients would otherwise hammer the replication listener. See the [multi-replica exposure callout](#service-exposure--session-affinity). |
| SASL credentials | struct\[] | — | list of `{username, password}` | `connectors.kafka.credentials` (config file / secret only) | — | **Secret — no env var, no CRD field.** SASL/PLAIN + SCRAM user store; when non-empty, SASL auth is enforced on every listener. `Validate()` rejects empty or duplicate usernames, empty passwords, and a username matching the reserved internal dashboard identity. Passwords are redacted in logs. |
**Kafka env-var trap: `CONNECTORS_KAFKA_MAX_TRANSACTIONAL_I_DS`.** The `MaxTransactionalIDs`
field renders to `..._MAX_TRANSACTIONAL_I_DS` (an extra underscore before `DS`), **not** the
intuitive `..._MAX_TRANSACTIONAL_IDS`. The wrong form does not bind and is silently ignored.
All other Kafka names follow the normal `CONNECTORS_KAFKA_*` rule.
### Share-group settings [#share-group-settings]
Server-wide settings for [Kafka share groups](/connectors/kafka/how-to/share-groups)
(KIP-932). Like the advanced settings above, each has a working env var but **no
`spec.kafka.*` path** — set them via a mounted config file or a raw pod env var. Each
`GroupShare*` default applies to a group with no value of its own; its `Min`/`Max` pair bounds
what a per-group `kafka-configs.sh --entity-type groups` write may set. For the `GroupShare*`
settings, `0` falls back to the default, a negative value is rejected, and each `Min` ≤ default
≤ `Max` triple must hold, or the server refuses to start and names all three fields.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------------------ | ------ | -------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Share feature version | int | `2` | `1` / `2` | `connectors.kafka.sharefeatureversion` · `CONNECTORS_KAFKA_SHARE_FEATURE_VERSION` | — | **Rolling-upgrade setting.** Leave at `2`. Set `1` on each node while upgrading a cluster from a release before share groups became [generally available](/release-notes/v3-5-1), then raise it back to `2` once every node is upgraded; restart required either way. At `1` the in-flight limit, share-group delete, per-group config writes, renew, `record_limit` and `read_committed` groups are unavailable. Downgrading is supported only if it stayed at `1` the whole time. `0` falls back to `2`; any other value is rejected at startup. See [Upgrading a cluster](/connectors/kafka/how-to/share-groups#upgrading-a-cluster). |
| Share start position | string | `latest` | `latest` / `earliest` / `by_duration:` | `connectors.kafka.shareautooffsetreset` · `CONNECTORS_KAFKA_SHARE_AUTO_OFFSET_RESET` | — | Where a new share group starts on a partition; existing groups keep their position. `latest` matches Apache Kafka; `earliest` restores the behavior of earlier releases. `by_duration` compares KubeMQ's ingest time. Empty falls back to `latest`; any other value is rejected at startup. |
| Share metrics groups per tick | int | `200` | ≤ `10000` | `connectors.kafka.sharemetricsmaxgroupspertick` · `CONNECTORS_KAFKA_SHARE_METRICS_MAX_GROUPS_PER_TICK` | — | How many share groups the coordinator samples every 5 seconds for the share-group metrics and `/api/kafka/share-groups`, taken in turn; groups not sampled keep their last figures. `≤ 0` falls back to the default; over the ceiling is rejected. |
| Record lock duration (ms) | int | `30000` | `1000`–`3600000` | `connectors.kafka.groupsharerecordlockdurationms` · `CONNECTORS_KAFKA_GROUP_SHARE_RECORD_LOCK_DURATION_MS` | — | Default `share.record.lock.duration.ms`: how long an acquired record stays locked before it is handed out again. |
| Min record lock duration (ms) | int | `15000` | `1000`–`3600000` | `connectors.kafka.groupshareminrecordlockdurationms` · `CONNECTORS_KAFKA_GROUP_SHARE_MIN_RECORD_LOCK_DURATION_MS` | — | Lowest per-group value; a lower write is refused `INVALID_CONFIG`. |
| Max record lock duration (ms) | int | `60000` | `1000`–`3600000` | `connectors.kafka.groupsharemaxrecordlockdurationms` · `CONNECTORS_KAFKA_GROUP_SHARE_MAX_RECORD_LOCK_DURATION_MS` | — | Highest per-group value; a higher write is refused `INVALID_CONFIG`. |
| Session timeout (ms) | int | `45000` | `1000`–`3600000` | `connectors.kafka.groupsharesessiontimeoutms` · `CONNECTORS_KAFKA_GROUP_SHARE_SESSION_TIMEOUT_MS` | — | Default `share.session.timeout.ms`: how long a member may go without a heartbeat before it is evicted. |
| Min session timeout (ms) | int | `45000` | `1000`–`3600000` | `connectors.kafka.groupshareminsessiontimeoutms` · `CONNECTORS_KAFKA_GROUP_SHARE_MIN_SESSION_TIMEOUT_MS` | — | Lowest per-group value; a lower write is refused. Must be greater than the max heartbeat interval. |
| Max session timeout (ms) | int | `60000` | `1000`–`3600000` | `connectors.kafka.groupsharemaxsessiontimeoutms` · `CONNECTORS_KAFKA_GROUP_SHARE_MAX_SESSION_TIMEOUT_MS` | — | Highest per-group value; a higher write is refused. |
| Heartbeat interval (ms) | int | `5000` | `1000`–`3600000` | `connectors.kafka.groupshareheartbeatintervalms` · `CONNECTORS_KAFKA_GROUP_SHARE_HEARTBEAT_INTERVAL_MS` | — | Default `share.heartbeat.interval.ms`. |
| Min heartbeat interval (ms) | int | `5000` | `1000`–`3600000` | `connectors.kafka.groupshareminheartbeatintervalms` · `CONNECTORS_KAFKA_GROUP_SHARE_MIN_HEARTBEAT_INTERVAL_MS` | — | Lowest per-group value; a lower write is refused. |
| Max heartbeat interval (ms) | int | `15000` | `1000`–`3600000` | `connectors.kafka.groupsharemaxheartbeatintervalms` · `CONNECTORS_KAFKA_GROUP_SHARE_MAX_HEARTBEAT_INTERVAL_MS` | — | Highest per-group value; a higher write is refused. Must be less than the min session timeout, or the server refuses to start. |
| Delivery count limit | int | `5` | `2`–`10` | `connectors.kafka.groupsharedeliverycountlimit` · `CONNECTORS_KAFKA_GROUP_SHARE_DELIVERY_COUNT_LIMIT` | — | Default `share.delivery.count.limit`: failed deliveries before a record is archived. |
| Min delivery count limit | int | `2` | `2`–`10` | `connectors.kafka.groupsharemindeliverycountlimit` · `CONNECTORS_KAFKA_GROUP_SHARE_MIN_DELIVERY_COUNT_LIMIT` | — | A lower per-group write is clamped up to this value, never refused. |
| Max delivery count limit | int | `10` | `2`–`10` | `connectors.kafka.groupsharemaxdeliverycountlimit` · `CONNECTORS_KAFKA_GROUP_SHARE_MAX_DELIVERY_COUNT_LIMIT` | — | A higher per-group write is clamped down to this value, never refused. |
| Partition max record locks | int | `2000` | `100`–`10000` | `connectors.kafka.groupsharepartitionmaxrecordlocks` · `CONNECTORS_KAFKA_GROUP_SHARE_PARTITION_MAX_RECORD_LOCKS` | — | Default `share.partition.max.record.locks`: the in-flight limit per share partition, counted in stored batches, not records. |
| Min partition max record locks | int | `100` | `100`–`10000` | `connectors.kafka.groupshareminpartitionmaxrecordlocks` · `CONNECTORS_KAFKA_GROUP_SHARE_MIN_PARTITION_MAX_RECORD_LOCKS` | — | A lower per-group write is clamped up to this value, never refused. |
| Max partition max record locks | int | `4000` | `100`–`10000` | `connectors.kafka.groupsharemaxpartitionmaxrecordlocks` · `CONNECTORS_KAFKA_GROUP_SHARE_MAX_PARTITION_MAX_RECORD_LOCKS` | — | A higher per-group write is clamped down to this value, never refused. |
A clamped per-group value is stored as clamped and never re-clamped: tightening these bounds
later leaves existing groups' values as they were written.
### Kafka SASL credentials [#kafka-sasl-credentials]
**Kafka SASL credentials are secret/file-only.** Unlike AWS, there is **no `CredentialsData`
env-var escape hatch and no CRD field** — supply the `credentials` list through a mounted
`config.yaml` (or Secret-mounted file). On Kubernetes the delivery mechanism is
[`spec.envFromSecrets`](/configure/reference/deployment#advanced--other-top-level-spec-fields),
which projects an existing Secret into the pod without the values transiting the operator.
Plan the credential delivery path before enabling SASL on Kubernetes.
### OAUTHBEARER authentication [#oauthbearer-authentication]
OAUTHBEARER activates when `OAuthBearer.Issuer` is non-empty — there is no separate enable
flag. It is enforced only on the TLS/SASL\_SSL listener (`TlsPort`); like the advanced knobs
above, it is `config.yaml`/env-var-only (Helm/CRD path `—`, not a CRD field).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------------------------- | ------ | ------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------- |
| Issuer | string | `""` | non-empty to activate; else OAUTHBEARER stays off | `connectors.kafka.oauthbearer.issuer` · `CONNECTORS_KAFKA_OAUTH_BEARER_ISSUER` (alias of `CONNECTORS_KAFKAO_AUTH_BEARER_ISSUER`) | — | Non-empty **requires** a non-empty `TlsPort` — a bearer token must not cross a plaintext transport. |
| Client ID | string | `""` | required unless Skip client-ID check is `true` | `connectors.kafka.oauthbearer.clientid` (by convention) · `CONNECTORS_KAFKA_OAUTH_BEARER_CLIENT_ID` | — | The OIDC audience. Enforced only when `Issuer` is set. |
| Skip client-ID check | bool | `false` | true / false | `connectors.kafka.oauthbearer.skipclientidcheck` (by convention) · `CONNECTORS_KAFKA_OAUTH_BEARER_SKIP_CLIENT_ID_CHECK` | — | The one skip-flag Kafka **permits** as `true` — some IdPs legitimately omit or vary the audience claim. |
| Skip expiry check | bool | `false` | must stay `false` | `connectors.kafka.oauthbearer.skipexpirycheck` (by convention) · `CONNECTORS_KAFKA_OAUTH_BEARER_SKIP_EXPIRY_CHECK` | — | `true` is **hard-rejected** on the Kafka listener — stricter than the generic OIDC authentication path, which only warns. |
| Skip issuer check | bool | `false` | must stay `false` | `connectors.kafka.oauthbearer.skipissuercheck` (by convention) · `CONNECTORS_KAFKA_OAUTH_BEARER_SKIP_ISSUER_CHECK` | — | `true` is **hard-rejected** — it would accept tokens from any issuer. |
| Insecure skip signature check | bool | `false` | must stay `false` | `connectors.kafka.oauthbearer.insecureskipsignaturecheck` (by convention) · `CONNECTORS_KAFKA_OAUTH_BEARER_INSECURE_SKIP_SIGNATURE_CHECK` | — | `true` is **hard-rejected** — it would accept forged/unsigned tokens. |
**Both OAUTHBEARER env forms work — use the readable one.** The generic snake-caser fuses
`Kafka` and `OAuthBearer` into one word and produces the unguessable
`CONNECTORS_KAFKAO_AUTH_BEARER_*`. Because nobody can guess that, the server **also** binds
the natural **`CONNECTORS_KAFKA_OAUTH_BEARER_*`** form deliberately, and both resolve to the
same setting. Prefer the natural form:
```bash
CONNECTORS_KAFKA_OAUTH_BEARER_ISSUER=https://idp.example.com
CONNECTORS_KAFKA_OAUTH_BEARER_CLIENT_ID=kubemq
```
**One caveat: the server's unknown-variable warner does not know about the alias**, so
setting the natural form prints an `IGNORED` warning even though the value is applied. The
warning is wrong. Do not "fix" a working issuer because of it — confirm the effective value
in the dashboard instead.
**Skip-flags are hard-rejected on Kafka, not just warned.** Setting `Insecure skip signature
check`, `Skip issuer check`, or `Skip expiry check` to `true` on the Kafka listener is
**rejected outright** by `Validate()` — stricter than the generic OIDC authentication path,
which only warns. `Skip client-ID check` is the one permitted skip. (`OAuthBearer.Issuer` also
requires a non-empty `TlsPort` — see the Issuer row above.)
## AWS [#aws]
The AWS SQS/SNS-compatible connector. Env prefix `CONNECTORS_AWS_*`; CRD group `spec.aws.*`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------------ | --------- | -------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable | bool | **`false` (opt-in)** | true / false | `connectors.aws.enable` · `CONNECTORS_AWS_ENABLE` | `spec.aws.enabled` | Opt-in wire connector. Opens port 4566. |
| Port | string | `4566` | `1`–`65535` | `connectors.aws.port` · `CONNECTORS_AWS_PORT` | `spec.aws.port` | Rejected if it collides with the gRPC/REST/HTTP or GCP listener port. |
| Region | string | `kubemq` | non-empty | `connectors.aws.region` · `CONNECTORS_AWS_REGION` | `spec.aws.region` | |
| Account ID | string | `000000000000` | `^[0-9]{12}$` | `connectors.aws.accountid` · `CONNECTORS_AWS_ACCOUNT_ID` | `spec.aws.accountId` | Exactly 12 digits. |
| Advertised URL | string | `""` | `""` or `scheme://host[:port]` | `connectors.aws.advertisedurl` · `CONNECTORS_AWS_ADVERTISED_URL` | `spec.aws.advertisedUrl` | Rejected unless it parses with a scheme and host. |
| Max inflight per queue | int | `20000` | `1`–`10000000` | `connectors.aws.maxinflightperqueue` · `CONNECTORS_AWS_MAX_INFLIGHT_PER_QUEUE` | `spec.aws.maxInflightPerQueue` | Over-ceiling rejected (OOM guard). |
| Max concurrent polls | int | `1024` | `1`–`1000000` | `connectors.aws.maxconcurrentpolls` · `CONNECTORS_AWS_MAX_CONCURRENT_POLLS` | `spec.aws.maxConcurrentPolls` | Over-ceiling rejected. |
| Read timeout (s) | int | `60` | `1`–`3600` | `connectors.aws.readtimeout` · `CONNECTORS_AWS_READ_TIMEOUT` | `spec.aws.readTimeout` | Per-action sync deadline; over-ceiling rejected. |
| Body limit | string | `2M` | size string | `connectors.aws.bodylimit` · `CONNECTORS_AWS_BODY_LIMIT` | `spec.aws.bodyLimit` | |
| Message signing | bool | `false` | true / false | `connectors.aws.messagesigning` · `CONNECTORS_AWS_MESSAGE_SIGNING` | `spec.aws.messageSigning` | Sign SNS Notification / SubscriptionConfirmation envelopes (SigV2). |
| Signing cert TTL (h) | int | `8760` | ≥ `1` | `connectors.aws.signingcertttlhours` · `CONNECTORS_AWS_SIGNING_CERT_TTL_HOURS` | `spec.aws.signingCertTtlHours` | Self-signed signing-cert validity (default 365 days). Applies when message signing is on. |
| Credentials (data blob) | string | `""` | JSON or base64-of-JSON credential array | `connectors.aws.credentialsdata` · `CONNECTORS_AWS_CREDENTIALS_DATA` | `spec.aws.credentialsData` | SigV4 credential array. On Helm/CRD this is rendered into a **Kubernetes Secret** (not a plain ConfigMap). |
| Credentials (structured) | struct\[] | — | list of `{accessKeyId, secretAccessKey, clientID}` | `connectors.aws.credentials` (config file only) | — | **No env var, no CRD field.** File/structured-only credential list; the env/CRD path is `credentialsData`. Empty or duplicate `accessKeyId` is rejected; `clientID` defaults to `accessKeyId`. |
**AWS credentials go through a Secret, not a plain CRD value.** The `spec.aws.credentialsData`
field exists but the operator writes it into a Kubernetes **Secret** (`CONNECTORS_AWS_CREDENTIALS_DATA`),
never a ConfigMap. On Docker, set `connectors.aws.credentialsdata` (JSON or base64-of-JSON) or
the `CONNECTORS_AWS_CREDENTIALS_DATA` env var. The fully-structured `connectors.aws.credentials`
list is config-file-only and has no env/CRD route.
## GCP Pub/Sub [#gcp-pubsub]
The Google Cloud Pub/Sub emulator connector (gRPC). Env prefix `CONNECTORS_GCP_*`; CRD group
`spec.gcp.*`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------------------------- | ------ | -------------------- | ----------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| Enable | bool | **`false` (opt-in)** | true / false | `connectors.gcp.enable` · `CONNECTORS_GCP_ENABLE` | `spec.gcp.enabled` | Opt-in wire connector. Opens port 8085. |
| Port | string | `8085` | `1`–`65535` | `connectors.gcp.port` · `CONNECTORS_GCP_PORT` | `spec.gcp.port` | gRPC listener (Pub/Sub emulator convention). Rejected if it collides with the gRPC/REST/HTTP or AWS listener port. |
| Advertised endpoint | string | `""` | endpoint | `connectors.gcp.advertisedendpoint` · `CONNECTORS_GCP_ADVERTISED_ENDPOINT` | `spec.gcp.advertisedEndpoint` | Endpoint advertised to clients. |
| Max message bytes | int | `10485760` (10 MiB) | `1`–`1073741824` (1 GiB) | `connectors.gcp.maxmessagebytes` · `CONNECTORS_GCP_MAX_MESSAGE_BYTES` | `spec.gcp.maxMessageBytes` | Feeds the gRPC frame ceiling (value + 1 MiB); hard cap 1 GiB. |
| Default ack deadline (s) | int | `10` | `10`–`600` | `connectors.gcp.defaultackdeadlineseconds` · `CONNECTORS_GCP_DEFAULT_ACK_DEADLINE_SECONDS` | `spec.gcp.defaultAckDeadlineSeconds` | |
| Max outstanding messages | int | `1000` | > `0` | `connectors.gcp.maxoutstandingmessages` · `CONNECTORS_GCP_MAX_OUTSTANDING_MESSAGES` | `spec.gcp.maxOutstandingMessages` | |
| Max inflight per subscription | int | `20000` | > `0` | `connectors.gcp.maxinflightpersubscription` · `CONNECTORS_GCP_MAX_INFLIGHT_PER_SUBSCRIPTION` | `spec.gcp.maxInflightPerSubscription` | |
| Max concurrent polls | int | `1024` | > `0` | `connectors.gcp.maxconcurrentpolls` · `CONNECTORS_GCP_MAX_CONCURRENT_POLLS` | `spec.gcp.maxConcurrentPolls` | |
| Max concurrent streams | int | `1024` | `0` (default) or `1`–`65536` | `connectors.gcp.maxconcurrentstreams` · `CONNECTORS_GCP_MAX_CONCURRENT_STREAMS` | `spec.gcp.maxConcurrentStreams` | Per-server cap on concurrent StreamingPull streams. `0` = use the built-in default (1024). |
| Delivery shards | int | `16` | `1`–`256` | `connectors.gcp.deliveryshards` · `CONNECTORS_GCP_DELIVERY_SHARDS` | `spec.gcp.deliveryShards` | Striped delivery-pool shards. |
| Max ack extension (s) | int | `600` | `0` (disabled) or `10`–`3600` | `connectors.gcp.maxackextensionseconds` · `CONNECTORS_GCP_MAX_ACK_EXTENSION_SECONDS` | `spec.gcp.maxAckExtensionSeconds` | `0` disables the ordered-head ack-deadline keep-alive. |
| Stream close (s) | int | `1800` | > `0` | `connectors.gcp.streamcloseseconds` · `CONNECTORS_GCP_STREAM_CLOSE_SECONDS` | `spec.gcp.streamCloseSeconds` | |
| Max seek replay | int | `1000000` | > `0` | `connectors.gcp.maxseekreplay` · `CONNECTORS_GCP_MAX_SEEK_REPLAY` | `spec.gcp.maxSeekReplay` | |
| Enable reflection | bool | `false` | true / false | `connectors.gcp.enablereflection` · `CONNECTORS_GCP_ENABLE_REFLECTION` | `spec.gcp.enableReflection` | gRPC server reflection. |
**Enable GCP Pub/Sub explicitly.** A stock kubemq-server does **not** bind port 8085 until you set
`CONNECTORS_GCP_ENABLE=true` (Docker) or `spec.gcp.enabled: true` (Kubernetes). Point clients at
the connector with `PUBSUB_EMULATOR_HOST=localhost:8085` — no auth, no TLS (emulator mode).
# Core & Licensing (/configure/reference/core)
These are the foundational settings every KubeMQ server needs: the **license** (a key or
a file) that lets the server start, the **log level** that controls how much it writes,
and the **host identity** it reports itself under. Each setting is shown for both deployment targets —
Docker single-node (`config.yaml` key · env var) and Kubernetes/Helm (`spec.*` path). A
dash (`—`) in the Helm/CRD column means the setting is not available on that surface.
## License [#license]
License input is **environment-only**: there is no `config.yaml` key and no command-line
flag, and a `license:` block inside `config.yaml` or the base64 `CONFIG` variable is rejected
by the loader. On Kubernetes the operator renders the `spec.license*` fields into the pod
environment for you ([License fields](/configure/reference/deployment#license)). Which
license you need is on [Plans compared](/licensing); what the server does at start, offline
and at expiry is on [How licensing works](/licensing/how-it-works). This section lists the
settings.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------ | ------------- | ------------------------------------------------------- | ------------------------------------------------- | --------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| License key | string | unset | 43-character key | — · `KUBEMQ_LICENSE_KEY` | `spec.licenseKey` · `spec.licenseKeySecretRef{name,key}` | Online license. To apply it, follow the license step of [Install with kmq](/deploy/install/kmq#add-your-license), [Install with Docker](/deploy/install/docker#add-your-license) or [Install on Kubernetes](/deploy/install/kubernetes#add-your-license). |
| License file | string | unset | path to an armored license file | — · `KUBEMQ_LICENSE_FILE` | — | Offline license file. Wins over the key. See [Install air-gapped](/deploy/install/air-gapped). |
| License data | string | unset | armored file contents, or the bare token | — · `KUBEMQ_LICENSE_DATA` | `spec.licenseFile` · `spec.licenseFileSecretRef{name,key}` | Offline license file contents. Wins over the key; if both `FILE` and `DATA` are set, `FILE` wins and a warning is logged. |
| Licensing endpoint | string | `https://license.kubemq.io` | `https://` base URL (a trailing slash is trimmed) | — · `KUBEMQ_LICENSE_ENDPOINT` | — | Where an online server activates, refreshes and reports usage. Change only when told to by KubeMQ. Any value that is not an `https://` base URL is a configuration error (exit code 1). |
| Drain window | int (seconds) | `300` | `0`–`3600` | — · `KUBEMQ_LICENSE_DRAIN_SECONDS` | — | How long the server drains connections before a licensing exit (exit code 3). A value outside the range is a configuration error (exit code 1). |
| First-boot retry | int (minutes) | `2` for an automatic evaluation; `30` when a key is set | `1`–`1440` | — · `KUBEMQ_LICENSE_FIRST_BOOT_RETRY_MINUTES` | — | How long a first start keeps retrying when it cannot reach the licensing endpoint, before it exits with `#first-boot-unreachable`. Setting the variable applies the value to both cases. A value outside the range is a configuration error (exit code 1). |
| Cached lease | string | unset | set by the operator | — · `KUBEMQ_LICENSE_CACHED_LEASE` | set by the operator | Set by the operator. Do not set it yourself. |
| Operator token | string | unset | set by the operator | — · `KUBEMQ_API_OPERATOR_TOKEN` | set by the operator | Set by the operator. Do not set it yourself. |
Precedence: `KUBEMQ_LICENSE_FILE` > `KUBEMQ_LICENSE_DATA` > `KUBEMQ_LICENSE_KEY`. With none
set, a fresh single Docker or Podman server starts the 14-day evaluation ([Plans compared](/licensing)).
The credential values — `KUBEMQ_LICENSE_KEY`, `KUBEMQ_LICENSE_DATA`,
`KUBEMQ_LICENSE_CACHED_LEASE` and `KUBEMQ_API_OPERATOR_TOKEN` — are redacted on
`GET /config` and in the dashboard; the file path, endpoint, drain and retry values are
shown as set.
Kubernetes always needs a trial key (choose Kubernetes when you request it), a license key
or an offline license file ([Plans compared](/licensing)).
## Host identity [#host-identity]
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------- | ------ | ---------------- | --------------- | ---------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Host identity | string | derived hostname | any host string | `host` · `HOST` | — | `Config.Host`. Auto-derived from the OS hostname when empty; explicit `viper.BindEnv("Host","HOST")`. No CRD field. Part of the store path — see the warning below. |
**A changed host can orphan the store.** The store layout is `//…`, so the
host identity is part of the data path, not just a label. On a cluster, or when `HOST` is set
explicitly, a changed host boots clean and healthy onto an empty directory, with the previous
store intact beside it and unread. Nothing fails and every health check passes.
A single Docker server keeps its data across a hostname change. With `HOST` unset and one
server directory in the store, it adopts that directory and logs
`NOTICE: adopting existing store identity`. Keep `--hostname` fixed anyway, as the
[Docker guide](/configure/docker) does.
If you must change `HOST`, treat it as a **migration**: stop the server, move
`/` to `/`, then start it. To recover from an
accidental change, set `HOST` back to the original value — the old directory is still
there.
## Logging [#logging]
`Log level` controls verbosity — the same value on both targets, passed through to the
server unchanged. `Log to file` / `Log file path` enable and locate an on-disk log; both
are Docker / `config.yaml`-only (no Helm/CRD path).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------- | -------------------- | ---------- | --------------------------------------------------------- | ------------------------------------ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Log level | int (`LogLevelType`) | `2` (Info) | `0`=Trace `1`=Debug `2`=Info `3`=Warn `4`=Error `5`=Fatal | `log.level` · `LOG_LEVEL` | `spec.log.level` | Higher = less. Validate rejects only negatives; a value >5 silently maps to the verbose default (Trace/Debug), not silent. CRD constrains 0–5. |
| Log to file | bool | `false` | `true` \| `false` | `log.fileenable` · `LOG_FILE_ENABLE` | — | When `true`, **Log file path** must be non-empty. |
| Log file path | string | `""` | filesystem path | `log.filepath` · `LOG_FILE_PATH` | — | Required when file logging is enabled. |
The **0–5 scale above is authoritative** (`0`=Trace … `5`=Fatal, default `2`=Info). The
operator passes the value through to the server **verbatim**. An older CRD annotation
describes a different scale (`0`=silent / `1`=info / `2`=debug) — that annotation does
**not** match the running server, so do not rely on it. Use the 0–5 enum above.
## Example [#example]
Set the log level on each target. This is a single-setting snippet — see the
[Docker guide](/configure/docker) and the
[Kubernetes guide](/configure/kubernetes) for complete, runnable configurations.
```yaml title="config.yaml"
log:
level: 2
```
```yaml title="cluster-values.yaml"
log:
level: 2
```
For the full Docker delivery methods (env vars, mounted `config.yaml`, the `CONFIG`
variable) see the [Docker guide](/configure/docker); for `cluster-values.yaml` mapped to
the `KubemqCluster` spec see the [Kubernetes guide](/configure/kubernetes).
# Deployment & High Availability (/configure/reference/deployment)
These settings cover how KubeMQ is **packaged and run on Kubernetes** — the container
image, persistent storage, resource requests/limits, health probes, node scheduling, and
`Service` exposure — plus the **high-availability** replica controls.
Unlike the rest of this reference, these fields do **not** exist in the server's
`config.yaml`: they are typed on the `KubemqCluster` **CRD** and consumed by the operator,
which renders the StatefulSet, Services, and PersistentVolumeClaim. The pattern is therefore
**inverted** — the **Helm/CRD path is the real one**, and the Docker column is `—`
(Kubernetes-only) except where the operator translates a CRD field into a pod env var (shown
as `· env VAR`). On Docker single-node, the equivalent concerns are `docker run` flags
(`-p`, `-v`, `--cpus` / `--memory`) covered in the [Docker guide](/configure/docker).
## Kubernetes packaging [#kubernetes-packaging]
### Container image [#container-image]
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------ | ------------- | -------------------------------------------------- | ----------------------------------- | ---------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Image | string | The server image of the installed operator release | image reference | — (K8s-only) | `spec.image.image` | Leave it unset: the cluster then runs the server image its operator release sets ([Artifacts and versions](/deploy/install/requirements#artifacts-and-versions); each release's image is in the [release notes](/release-notes)). Resolution order: `spec.image.image` → operator env `RELATED_IMAGE_KUBEMQ_CLUSTER` → built-in fallback (`config/image.go:8,18-30`). No server env binding. |
| Pull policy | string (enum) | `Always` | `IfNotPresent` / `Always` / `Never` | — | `spec.image.pullPolicy` | CRD pattern `(IfNotPresent\|Always\|Never)`; empty is coerced to `Always` (`config/image.go:14,34-37`). |
| Image pull secrets | string\[] | `[]` | Secret names | — | — (chart value `imagePullSecrets[]`) | The chart value `imagePullSecrets` applies to the operator pod only; it never reaches the cluster resource. For server pods pulling from a private mirror, see [Install air-gapped](/deploy/install/air-gapped). |
### Storage (volume) [#storage-volume]
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------- | ------ | ---------------------------- | -------------------------- | ---------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Volume size | string | *unset → ephemeral (no PVC)* | k8s quantity (e.g. `50Gi`) | — | `spec.volume.size` | When set, the operator renders a `volumeClaimTemplates` PVC (`ReadWriteOnce`) mounted at `./kubemq/store`. When **unset/empty, the pod has no persistent volume** and the store is ephemeral (`deployment.go:78-81`, `deployment/statefulset.go:108-124`). There is **no built-in `10Gi` default** in code. **Required for durable data on the next storage engine** — such a cluster with no `spec.volume.size` set raises the `EphemeralNextStore` warning (its durable data would otherwise live on ephemeral container storage). |
| Storage class | string | `""` → cluster default | StorageClass name | — | `spec.volume.storageClass` | Only consulted when `size` is set; empty renders a blank `storageClassName:` → the cluster's default StorageClass (`config/volume.go:8`). |
**`spec.store.path` on the `next` storage engine: the operator rejects a leading `/`.** The
operator itself supplies the mount-rooted absolute path for the PVC, so a
`spec.store.path` value starting with `/` is rejected outright — the operator, not
the server, owns that absolute path. This is the **inverse** of the server-layer
behavior documented on [Storage & Queues](/configure/reference/storage-queues):
the `next` storage engine's **server process** honors an absolute `StorePath` verbatim (it's
the `legacy` engine that rewrites a leading `/` to `./`). Keep the two facts distinct —
"the operator rejects a leading `/` in the CR field" and "the server on the next storage engine
process honors an absolute `StorePath`" are both true, at different layers.
### Resources [#resources]
Each field is rendered into the pod's `resources:` block only when non-empty; there are no
defaults (`config/resources.go:32-47`).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------------- | ------ | ------- | ----------------------------------- | ---------------------------------- | ----------------------------------------- | ------------------------------------------- |
| CPU limit | string | unset | k8s CPU quantity (e.g. `2`, `500m`) | — | `spec.resources.limitsCpu` | Pod `resources.limits.cpu`. |
| Memory limit | string | unset | k8s memory quantity (e.g. `2Gi`) | — | `spec.resources.limitsMemory` | Pod `resources.limits.memory`. |
| Ephemeral-storage limit | string | unset | k8s quantity | — | `spec.resources.limitsEphemeralStorage` | Pod `resources.limits.ephemeral-storage`. |
| CPU request | string | unset | k8s CPU quantity | — | `spec.resources.requestsCpu` | Pod `resources.requests.cpu`. |
| Memory request | string | unset | k8s memory quantity | — | `spec.resources.requestsMemory` | Pod `resources.requests.memory`. |
| Ephemeral-storage request | string | unset | k8s quantity | — | `spec.resources.requestsEphemeralStorage` | Pod `resources.requests.ephemeral-storage`. |
### Health probe [#health-probe]
The liveness probe is **off by default** and only injected when `enabled: true`
(`config/health.go:46-60`).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------------- | ----- | ------- | ---------------- | -------------------------------------------------------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enabled | bool | `false` | true / false | · env `API_BIND_ADDRESS=0.0.0.0` (side-effect when true) | `spec.health.enabled` | When true, the operator adds a `livenessProbe` httpGet `/health` on the API port **and** sets `API_BIND_ADDRESS=0.0.0.0` so the kubelet (pod IP) can reach the probe — the API binds `127.0.0.1` otherwise (`config/health.go:48-60`). |
| Initial delay (s) | int32 | `5` | any; `≤0` → `5` | — | `spec.health.initialDelaySeconds` | `config/health.go:38-40`. |
| Period (s) | int32 | `10` | any; `≤0` → `10` | — | `spec.health.periodSeconds` | `config/health.go:35-37`. |
| Timeout (s) | int32 | `5` | any; `≤0` → `5` | — | `spec.health.timeoutSeconds` | `config/health.go:32-34`. |
| Success threshold | int32 | `1` | any; `≤0` → `1` | — | `spec.health.successThreshold` | `config/health.go:29-31`. |
| Failure threshold | int32 | `12` | any; `≤0` → `12` | — | `spec.health.failureThreshold` | `config/health.go:41-43`. |
**`/health` (liveness) vs `/ready` (readiness).** The table above covers the **optional**
`/health` liveness probe (`spec.health.enabled`, off by default). Readiness is separate: for a
**clustered `next`-engine deployment**, the operator wires
a **readinessProbe** against a `/ready` endpoint on the API port — it holds the pod not-`Ready`
until cluster quorum forms, so traffic only reaches pods that can actually serve. The response
code varies by mode, so it isn't listed here.
### Node scheduling [#node-scheduling]
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| -------------- | ------------------ | ------- | -------------------------- | ---------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------- |
| Node selectors | map\[string]string | `{}` | node label key/value pairs | — | `spec.nodeSelectors.keys` | Rendered as the pod `nodeSelector`; an empty map applies no constraint (`config/node_selectors.go:9-24`). |
### Service exposure & interface toggles [#service-exposure--interface-toggles]
The three built-in interface Services — **gRPC** (`50000`), **REST/WebSocket** (`9090`), and
**API/dashboard** (`8080`) — each expose a Service type, optional NodePort, custom port, and a
disable toggle. These HTTP/interface Services are **opt-out** via `disabled: true`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------------- | ------------- | ------------------- | ----------------------------------------- | ------------------------------------ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| gRPC disabled | bool | `false` | true / false | · env `CONNECTORS_GRPC_ENABLE=false` | `spec.grpc.disabled` | Deletes the `-grpc` Service and disables the listener (`config/grpc.go:64-66`, `deployment.go:203-206`). |
| gRPC Service type | string (enum) | `ClusterIP` | `ClusterIP` / `NodePort` / `LoadBalancer` | — | `spec.grpc.expose` | Empty → `ClusterIP` (`config/grpc.go:56`); CRD pattern-validated. |
| gRPC NodePort | int32 | `0` (auto-assigned) | 30000–32767 | — | `spec.grpc.nodePort` | Applied only when `expose: NodePort` **and** value > 0 (`config/grpc.go:77-81`). |
| gRPC port | int32 | `50000` | port | · `CONNECTORS_GRPC_PORT` | `spec.grpc.port` | Moves the container/Service/target port and emits the env (`config/grpc.go:71-75`). |
| REST disabled | bool | `false` | true / false | · env `CONNECTORS_REST_ENABLE=false` | `spec.rest.disabled` | The `-rest` Service (9090) is **shared** by REST/MCP/Agents/CE — the operator removes it only when **all four** are disabled (`deployment.go:99-120`). |
| REST Service type | string (enum) | `ClusterIP` | `ClusterIP` / `NodePort` / `LoadBalancer` | — | `spec.rest.expose` | Empty → `ClusterIP` (`config/rest.go:71`). |
| REST NodePort | int32 | `0` (auto) | 30000–32767 | — | `spec.rest.nodePort` | Applied only when `expose: NodePort` and > 0 (`config/rest.go:91-95`). |
| REST port | int32 | `9090` | port | · `CONNECTORS_REST_PORT` | `spec.rest.port` | `config/rest.go:85-88`. |
| API disabled | bool | `false` | true / false | · env `API_ENABLE=false` | `spec.api.disabled` | Deletes the `-api` Service (`config/api.go:65-66`, `deployment.go:89-92`). |
| API Service type | string (enum) | `ClusterIP` | `ClusterIP` / `NodePort` / `LoadBalancer` | — | `spec.api.expose` | Empty → `ClusterIP` (`config/api.go:58`). |
| API NodePort | int32 | `0` (auto) | 30000–32767 | — | `spec.api.nodePort` | Applied only when `expose: NodePort` and > 0 (`config/api.go:79-83`). |
| API port | int32 | `8080` | port | · `API_PORT` | `spec.api.port` | `config/api.go:73-76`. |
**`spec.statefulsetConfigData` is a one-way door for every other packaging field.** It does
not merge with, patch, or extend the StatefulSet the operator builds — it **replaces the
body outright**. The moment it is set, `spec.image`, `spec.volume`, `spec.resources`,
`spec.health`, `spec.nodeSelectors`, `spec.podAntiAffinity` and
`spec.terminationGracePeriodSeconds` stop having any effect on the pod, silently: they stay
in the CR, they still validate, and they change nothing. You now own the whole pod spec,
including the parts the operator was maintaining for you across upgrades. Use it only when
a field you need genuinely has no typed equivalent, and expect to re-check it on every
operator upgrade.
Only the **exposure** subset of `spec.grpc` / `spec.rest` / `spec.api` lives here. Their
tuning fields (buffer/body limits, gRPC reflection, REST read/write timeouts, CORS, API
allow-origins, and the API-auth block) are documented on the
[Interfaces](/configure/reference/interfaces) and
[Security](/configure/reference/security) pages.
### License [#license]
Set exactly one of the four fields: the chart and the CRD refuse none or more than one.
Which license you need is on [Plans compared](/licensing).
On the Helm path, [Install on Kubernetes](/deploy/install/kubernetes#add-your-license) creates the Secret
`messaging-license` that `spec.licenseKeySecretRef` reads; kmq names its Secret `messaging-license-` plus eight hexadecimal characters.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------------ | ------------- | ------- | ------------------------------- | ---------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| License key | string | unset | 43-character license key | — · env `KUBEMQ_LICENSE_KEY` | `spec.licenseKey` | Literal key, stored in the custom resource and in Helm values; prefer `spec.licenseKeySecretRef`. Rendered into the pod environment. The CRD rejects an object without exactly one `license*` field (`exactly one license source is required`). See [Install on Kubernetes](/deploy/install/kubernetes#add-your-license). |
| License key from Secret | `{name, key}` | unset | existing Secret name + data key | — · env `KUBEMQ_LICENSE_KEY` | `spec.licenseKeySecretRef` | **Recommended.** The operator reads the Secret's data key (default `licenseKey`) at each reconcile and copies the value into the pod-environment Secret it owns; your Secret is only ever read, and the value never appears on the CR or in Helm values. |
| License file | string | unset | armored license file contents | — · env `KUBEMQ_LICENSE_DATA` | `spec.licenseFile` | Offline license file as a literal. The operator verifies it (signature, key id, not revoked, offline kind) before creating or updating the StatefulSet; a file that fails sets condition `LicenseInvalid` and the operator keeps checking until a valid file is supplied. See [Install air-gapped](/deploy/install/air-gapped). |
| License file from Secret | `{name, key}` | unset | existing Secret name + data key | — · env `KUBEMQ_LICENSE_DATA` | `spec.licenseFileSecretRef` | Offline license file from a Secret (data key defaults to `licenseFile`); read and copied like the key, and verified like `spec.licenseFile`. The operator watches the referenced Secret, so a corrected file is reconciled at once. |
### Advanced / other top-level spec fields [#advanced--other-top-level-spec-fields]
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| -------------------- | ------------------ | ------- | ------------------------- | ---------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| StatefulSet override | string (YAML) | unset | StatefulSet YAML fragment | — | `spec.statefulsetConfigData` | ⚠️ Escape hatch — when set, **replaces the operator-generated StatefulSet body** with your fragment (`deployment/statefulset.go:126-135,268-271`). All other packaging fields above are ignored for the STS. See the warning below. |
| Config data (OIDC) | string | unset | OIDC block | — | `spec.configData` | OIDC-only passthrough — **not** a generic `config.yaml`. See [Security](/configure/reference/security). |
| Env overlay | map\[string]string | `{}` | env key/value pairs | — | `spec.env` | Last-wins overlay onto the pod ConfigMap — the general escape hatch for any server env key the CRD doesn't type. Operator-computed identity keys are **rejected**: `STORE_ENGINE`, `CLUSTER_ENABLE`, `CLUSTER_NAME`, `CLUSTER_ROUTES`, `API_BIND_ADDRESS`, `CHECKSUM`, `POD_NAME`, and any `CLUSTER_REPLICATION_*` key — **not** a `CLUSTER_*` wildcard (e.g. `CLUSTER_PORT` is still allowed) — plus the licensing variables (`KUBEMQ_LICENSE_KEY`, `KUBEMQ_LICENSE_FILE`, `KUBEMQ_LICENSE_DATA`, `KUBEMQ_LICENSE_CACHED_LEASE`) and `KUBEMQ_API_OPERATOR_TOKEN`, which reach the pods only from operator-owned Secrets (rejected with a `ReconcileError` condition, nothing silently stripped). Not for secrets. |
| Env from Secrets | string\[] | `[]` | existing Secret names | — | `spec.envFromSecrets` | Projects existing Secret(s) as pod env (`envFrom`) — the general Secret-envFrom escape hatch; Secret values never transit the operator. This is the mechanism behind [Kafka SASL credentials](/configure/reference/connectors#kafka-sasl-credentials). |
## High availability [#high-availability]
High availability on Kubernetes is **multiple replicas** managed by the operator — not the
Docker `cluster.*` block.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------- | -------- | ------- | ------------- | ---------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Replica count | `*int32` | `3` | **3 or more** | — | `spec.replicas` | Supported Kubernetes clusters require at least three replicas. Nil or `0` defaults to `3`; a request below `3` is refused before workload creation. Backs the `scale` subresource (`specpath=.spec.replicas`). The operator wires `CLUSTER_*` and the 5228 cluster port. **Once the engine is established as `next`, `spec.replicas` is immutable** — a CEL rule plus an operator fail-closed guard reject any change (see the engine-establishment guard below). |
**`spec.replicas` becomes immutable once the engine is `next` — and `next` is what a new
cluster gets.** This is a one-way door, armed at creation on a default install, not an
edge case for people who opted into `next`. Once the engine is established as `next`, a
CEL rule on the CRD and an operator fail-closed guard both reject **any** change to the
replica count — up or down. `helm upgrade --set replicas=5` fails; so does editing the CR.
**Choose the replica count before you create the cluster.** 3 is the minimum supported count, and `standalone: true` is rejected. See [Requirements and supported setups](/deploy/install/requirements#kubernetes) for what the cluster network must provide. Three is also the smallest count that
gets a disruption budget; see [Disruption budget & pod
spread](#disruption-budget--pod-spread). Changing it afterwards means creating a new
cluster and migrating, so decide with the ceiling in mind rather than the starting load.
### Disruption budget & pod spread [#disruption-budget--pod-spread]
Both default to **on** for a multi-replica cluster — the operator creates them without
being asked, and these fields exist to tune or disable them.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------------- | ----- | -------------------------------- | ------------ | ---------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------- |
| Disruption budget enabled | bool | `true` | true / false | — | `spec.podDisruptionBudget.enabled` | Set `false` to create no `PodDisruptionBudget`. |
| Minimum available | int32 | raft majority (`replicas/2 + 1`) | ≥ `1` | — | `spec.podDisruptionBudget.minAvailable` | Defaults to **2 of 3, 3 of 5**. Overriding it downward trades quorum safety for drainability. |
| Anti-affinity enabled | bool | `true` | true / false | — | `spec.podAntiAffinity.enabled` | Spreads replicas across nodes. |
| Anti-affinity required | bool | `false` | true / false | — | `spec.podAntiAffinity.required` | `false` (default) = *preferred* spread; `true` = *required*. See the trade below. |
**Use an odd replica count, 3 or more.** A request below three replicas is refused before
workload creation. A budget is created from **3 replicas up**.
An **even** replica count gets an **`EvenReplicaCount`** Warning event: the majority of 4
is 3, the same single-failure tolerance as 3, at the cost of an extra replica and another
copy of the data.
These two events are your only signal — nothing else reports that no budget was created:
```bash
kubectl get events -n --field-selector reason=UnsupportedReplicaCount
```
**The anti-affinity trade is real — choose it deliberately.**
`required: false` (the default) means pods **always schedule**, but two replicas **may**
share a node, so a single node loss can still cost quorum. `required: true` **guarantees**
the spread, but a replica stays `Pending` while there are fewer schedulable nodes than
replicas.
### Shutdown grace period [#shutdown-grace-period]
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ---------------------------- | ----- | -------------------------- | ------------ | ---------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| Termination grace period (s) | int32 | *unset* → Kubernetes' `30` | ≥ `1` | — (`docker stop -t`) | `spec.terminationGracePeriodSeconds` · env `KUBEMQ_TERMINATION_GRACE_PERIOD_SECONDS` | The pod's shutdown budget. The operator sets the **pod spec** and passes the **same number to the server** — they always move together. |
**This setting governs message durability on shutdown, not just tidiness.** The server
splits the grace period between **connector teardown** — which requeues in-flight messages
that would otherwise be **lost** — and **store shutdown**.
Kubernetes does not expose `terminationGracePeriodSeconds` to the container, so the
operator both sets the pod spec **and** passes the same value as
`KUBEMQ_TERMINATION_GRACE_PERIOD_SECONDS`. Left unset, Kubernetes uses **30s** and the
server assumes 30s.
**The concrete numbers:** at the default 30-second grace the requeue backstop is **1
second**. **45 seconds funds the full 12-second backstop.** Set at least `45` on any
cluster where losing in-flight messages on a pod roll matters, and higher still if your
connectors hold long in-flight batches.
```yaml title="cluster-values.yaml"
terminationGracePeriodSeconds: 45
```
**Connector Services & ports (operator-exposed).** The pod always publishes container ports
for every wire connector — MQTT `1883/8883/8083`, AMQP `5672/5671`, STOMP `61613/61614`,
AWS `4566`, GCP `8085`, **Kafka `9092/9093`** (`deployment/statefulset.go:70-102`,
`deployment/service.go:192-256`). The matching ClusterIP `Service` is created **only when
that connector is enabled** — otherwise the operator prunes it (`deployment.go:122-199`).
Kafka and AMQP 0.9.1 are **on by default**, so their Services (`9092/9093`, `5672/5671`) are
created by default and removed only with `spec.kafka.enabled: false` /
`spec.amqp.enabled: false`. The other five wire connectors (MQTT, AMQP 1.0, STOMP, AWS, GCP)
are **opt-in** (`enabled: true`, default off) and get a Service only once enabled; the HTTP
interfaces above (gRPC/REST/API) remain **opt-out** (`disabled: true`).
**`status.engine`.** The `KubemqCluster` status subresource exposes `status.engine`
(`legacy` / `next` / `auto`) — the engine established for this cluster by the guard below.
Read it alongside `status.replicas` when auditing the replicas-freeze caveat above: once
`status.engine` reports `next`, `spec.replicas` can no longer change.
**`auto` is not an engine.** It means the cluster **delegated** the choice to the server,
which resolves it at boot from the store directory. On such a cluster `status.engine` and
the `established-engine` annotation both read `auto`, and the engine actually running is
reported **only** in the server's boot NOTICE in the pod log — see
[Which engine am I actually on?](/configure/reference/storage-engines#which-engine-am-i-actually-on).
### Engine-establishment guard [#engine-establishment-guard]
The operator records the **live** persistence engine in the
`next.kubemq.io/established-engine` annotation (`legacy` / `next` / `auto`) — once
present, this annotation is **authoritative** on an established cluster, **outranking
`spec.store.engine`** for every guard decision. A mismatch between the two is **refused,
not silently applied**. Derivation runs in order: (1) the annotation, if present; (2) else
the explicit `spec.store.engine`; (3) else the pod ConfigMap's `STORE_ENGINE` key; (4)
else, if a StatefulSet or retained PVC already exists, the engine is **unknown** and the
operator refuses to guess — set `spec.store.engine` explicitly or delete the retained PVCs;
(5) else the cluster has **no engine on record** and the operator delegates: it writes
`STORE_ENGINE=auto` and the server resolves the engine at boot from the store directory
(clean ⇒ `next`).
**A fresh cluster gets `auto`, not a pinned engine** — the operator does not
override the server's clean-store default. An established cluster keeps its named
engine and nothing rolls. **Setting `spec.store.engine` later on an `auto` cluster is
allowed**, because `auto` records a delegation rather than an established engine — pin the
engine the server actually resolved; a pin that disagrees with the data on disk is refused
by the server at boot, and the server never deletes a datadir.
The operator **never changes a live cluster's engine.** Two advisory CEL rules on the CRD
back this: `spec.store.engine` is immutable once set (born-one-mode), and `spec.replicas`
is immutable once the engine is established as `next`.
This operator-side derivation runs **before** the server-side probe documented on
[Storage Engines](/configure/reference/storage-engines#zero-config-engine-selection)
and the Kafka callout on [Connectors](/configure/reference/connectors#kafka) — two
layers of one decision: the operator decides what the pod's env will say before the pod
ever boots, and when that env says `auto`, the server-side probe is what actually decides
once it does.
## Example [#example]
Publish the gRPC port on each target. On Kubernetes you set the `Service` exposure and node
port; on Docker you publish the port with `-p`. This is a single-setting snippet — see the
[Kubernetes guide](/configure/kubernetes) for complete, runnable configurations.
```yaml title="cluster-values.yaml"
grpc:
expose: NodePort
nodePort: 32000
```
For the full install flow (custom resource definitions → operator → cluster) and
`cluster-values.yaml` mapped to the `KubemqCluster` specification, see
[Install on Kubernetes](/deploy/install/kubernetes).
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Configuration Reference (/configure/reference)
The reference documents the KubeMQ server settings an operator configures, grouped by
domain. Every option is rendered in a table with the same seven columns — most pages carry
several, one per settings group — so the same field reads identically whether you run
KubeMQ with Docker or on Kubernetes via Helm. This page is the legend — read it once, then
every table downstream is unambiguous.
**Not every field in the server's config struct appears here.** Internal, test-only, and
derived fields are deliberately out of scope, and a handful of newer knobs are documented
on the page that owns their behavior rather than in a settings table. If a variable you
found in a log or a struct dump isn't here, that is not proof it does nothing — check the
domain page for the feature it belongs to first.
## How to read the tables [#how-to-read-the-tables]
Every settings table on every domain page uses the same **7 columns**:
| Column | What it tells you |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **Setting** | The human-readable name of the option. |
| **Type** | The value type — `int`, `bool`, `string`, size string, enum, etc. |
| **Default** | The value the server uses when the setting is omitted. |
| **Valid values** | The accepted range or enum, where one applies. |
| **Docker (config.yaml key · env var)** | Both Docker forms: the `config.yaml` key **and** its environment variable. |
| **Helm/CRD path** | The `KubemqCluster` `spec.*` path. The **Helm value** is that path with the leading `spec.` removed (`spec.grpc.port` → `grpc.port`). |
| **Notes** | Name divergences, validation rules, and cross-field constraints. |
The Docker column always shows **two** forms of the same setting. The `config.yaml` key is
viper-lowercased with no per-segment separators (for example `store.maxretention`); the
environment variable is that key in `UPPER_SNAKE` (`STORE_MAX_RETENTION`).
The Helm/CRD column shows the CRD `spec.*` path. Because the chart renders your `cluster-values.yaml`
straight into the CR `spec`, a Helm value is just that path minus `spec.` — there is no
separate Helm schema to learn.
## The "—" convention [#the--convention]
A dash (`—`) in the **Helm/CRD path** column means the setting is **not available on that
surface** — it is a Docker / `config.yaml`-only knob with no Helm route. It does **not**
mean "to be filled in later."
Whole domains are Docker-only by design: the message-broker engine (`broker.*`), runtime
tuning (`tuning.*`), and standalone clustering (`cluster.*`) are advanced settings exposed
through `config.yaml`/env only. On Kubernetes the operator owns those concerns. See the
[Advanced](/configure/reference/advanced) page.
## The env-var acronym rule [#the-env-var-acronym-rule]
Docker derives each environment variable from the `config.yaml` key with `convertEnvFormat`:
snake-case the key, drop the dots, uppercase. The trap is in the **connector prefixes** —
how `CONNECTORS` joins the next segment depends on whether that segment is a Title-case word
or an all-caps acronym:
| Connector segment | Form | Env-var prefix |
| ------------------ | ------------------------------------------- | --------------------- |
| `Amqp` (0.9.1) | Title-case → **keeps** the underscore | `CONNECTORS_AMQP_*` |
| `Amqp10` (1.0) | Title-case → keeps the underscore | `CONNECTORS_AMQP10_*` |
| `Stomp` | Title-case → keeps the underscore | `CONNECTORS_STOMP_*` |
| `Aws` | Title-case → keeps the underscore | `CONNECTORS_AWS_*` |
| `Kafka` | Title-case → keeps the underscore | `CONNECTORS_KAFKA_*` |
| `Gcp` | Title-case → keeps the underscore | `CONNECTORS_GCP_*` |
| `MCP` | all-caps acronym → **drops** the underscore | `CONNECTORSMCP_*` |
| `CE` (CloudEvents) | all-caps acronym → drops the underscore | `CONNECTORSCE_*` |
| `MQTT` | all-caps acronym → drops the underscore | `CONNECTORSMQTT_*` |
| `A2A` (agents) | splits to `A2_A` | `CONNECTORSA2_A_*` |
**The wrong twin is silently ignored — except for CloudEvents.** CloudEvents is the one
connector that binds **both** forms: the collapsed `CONNECTORSCE_*` (primary) and the
underscored `CONNECTORS_CE_*` (a compensating alias) resolve to the same setting — either
`CONNECTORSCE_ENABLE` or `CONNECTORS_CE_ENABLE` works. **MCP, A2A, and MQTT have no such
alias.** For those, only the collapsed form binds — `CONNECTORSMCP_*`, `CONNECTORSA2_A_*`,
and `CONNECTORSMQTT_*`. The underscored twin (`CONNECTORS_MCP_*`, `CONNECTORS_A2_A_*`,
`CONNECTORS_MQTT_*`) does **not** bind — the server starts and accepts the variable
without error.
**Kafka's OAUTHBEARER block has the same kind of alias as CloudEvents:** the generic rule
produces the unguessable `CONNECTORS_KAFKAO_AUTH_BEARER_*`, so the natural
`CONNECTORS_KAFKA_OAUTH_BEARER_*` is bound deliberately alongside it. Both work.
**The server's "IGNORED" warning is unreliable in both directions — do not use it as
proof.** It reports variables that sit in a KubeMQ namespace prefix but bind to no config
key, and that heuristic has two holes:
* **False alarms.** The two deliberate aliases above — `CONNECTORS_CE_*` and
`CONNECTORS_KAFKA_OAUTH_BEARER_*` — are bound by a path the warner doesn't track, so it
reports them as IGNORED **while they are being applied**. Do not "fix" a working setting
because of this warning.
* **Silence that means nothing.** The warner's namespace list contains only prefixes ending
in `_` (`STORE_`, `CLUSTER_`, `API_`, `CONNECTORS_`, `BROKER_`, `QUEUE_`, `ROUTING_`,
`AUTHORIZATION_`, `AUTHENTICATION_`, `LOG_`, `METRICS_`, `AUDIT_`). Every collapsed-acronym
form is structurally outside it, so a typo in `CONNECTORSMQTT_*`, `CONNECTORSMCP_*`,
`CONNECTORSCE_*` or `CONNECTORSA2_A_*` produces **no output at all**. So are the
`KUBEMQ_LICENSE_`, `NOTIFICATION_`, `SECURITY_`, `TELEMETRY_` and `TUNING_` namespaces —
a typo in `KUBEMQ_LICENSE_KEY` is silent here, but the server then refuses to start
with `#no-license-input` (see [Troubleshooting](/licensing/troubleshooting#no-license-input)).
Confirm the **effective** value in the dashboard rather than trusting the log either way.
## `enable` ↔ `disabled` inversion [#enable--disabled-inversion]
The enable model is **not uniform** — it splits into two families, and each family's
default and CRD field name are different:
* **HTTP-family** interfaces/connectors (gRPC, REST, API, MCP, A2A, CloudEvents) are
**opt-out** — **on by default**. Docker turns one off with `enable: false` — for
example `connectors.ce.enable: false` (env `CONNECTORSCE_ENABLE=false`). Helm/CRD turns
one off with `spec..disabled: true`; omit the key while the connector stays on.
* **Wire-protocol** connectors (MQTT, AMQP 0.9.1, AMQP 1.0, STOMP, Kafka, AWS, GCP) are
**opt-in** — **off by default**. Docker turns one on with
`enable: true`. Helm/CRD turns one on with `spec..enabled: true`; omit the key and
the connector stays off.
**Docker always uses `enable: true | false`** regardless of family — only the default and
the Helm/CRD field name (`disabled` vs `enabled`) differ. Each domain page shows the form
that applies on each target.
## Configuration domains [#configuration-domains]
The settings are grouped across these nine domain pages.
# Interfaces (gRPC · REST · API · HTTP) (/configure/reference/interfaces)
KubeMQ fronts its server core with four interfaces: the **gRPC** transport, the
**REST/WebSocket** transport, the management/dashboard **API** (with opt-in API
authentication), and the **shared HTTP server** that hosts MCP, A2A, and CloudEvents on
the REST port. Each setting is shown for both targets — Docker single-node (`config.yaml`
key · env var) and Kubernetes/Helm (`spec.*` path). A dash (`—`) in the Helm/CRD column
means the setting is not a typed CRD field; on Kubernetes it is reachable only through
`spec.configData` (raw config) or a directly-set pod env var.
**All four interfaces are opt-out (always-on).** gRPC, REST, and API are enabled by
default on both targets. On Docker they use the `enable: true/false` model; on the chart
they use the inverted `disabled: true/false` framing (`spec.grpc.disabled`,
`spec.rest.disabled`, `spec.api.disabled`) — all shipped as `disabled: false`. Set
`disabled: true` to turn one off. The shared HTTP server has no toggle of its own — it
rides the REST port and is emitted only when you set one of its `spec.http.*` fields.
**The shared HTTP listener does not belong to REST.** It starts if **any** of REST, MCP,
A2A, or CloudEvents is enabled, and stops only when all four are off. Disabling REST alone
retires the REST routes and leaves the other three serving on the same port.
**`.port` on Kubernetes moves everything together.** Setting `spec.grpc.port` /
`spec.rest.port` / `spec.api.port` makes the operator emit the matching listener env var
(`CONNECTORS_GRPC_PORT` / `CONNECTORS_REST_PORT` / `API_PORT`) **and** set the Kubernetes
`Service` `port`/`targetPort` **and** the container port — the in-pod listener and the
Service port move as one. On Docker the same env var moves the actual listener, which you
then publish with `docker run -p`.
**A default install publishes nothing outside the cluster.** The shipped
`values.yaml` sets no `expose` and no `nodePort` for any interface, and a `KubemqCluster`
with `expose` unset gets a **`ClusterIP`** Service. gRPC is *not* reachable on every node
out of the box — to reach it from outside you set `expose` yourself (`NodePort` or
`LoadBalancer`), and if you need a **predictable** port you must also set `nodePort`,
because an unset one is assigned by the kernel and cannot be configured into a client
ahead of the install.
## gRPC [#grpc]
The primary client transport. Enabled by default on both targets.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ---------------- | ------------ | --------------------- | ----------------------------------------- | ------------------------------------------------------------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable / disable | bool | enabled (`true`) | true / false | `connectors.grpc.enable` · `CONNECTORS_GRPC_ENABLE` | `spec.grpc.disabled` | Inverted boolean: Docker `enable: true`, Helm `disabled: false`. When disabled, no listener starts and the rest of the section is skipped. |
| Port | int (string) | `50000` | 1–65535 | `connectors.grpc.port` · `CONNECTORS_GRPC_PORT` | `spec.grpc.port` | Server field is a string port; rejected if non-numeric or out of range. |
| Sub buffer size | int | `100` | ≥ 0 | `connectors.grpc.subbuffsize` · `CONNECTORS_GRPC_SUB_BUFF_SIZE` | `spec.grpc.bufferSize` | Per-subscription channel buffer. Negative rejected. **Name divergence:** server `subBuffSize` ↔ CRD `bufferSize`. |
| Body limit | int (bytes) | `104857600` (100 MB) | ≥ 0 bytes | `connectors.grpc.bodylimit` · `CONNECTORS_GRPC_BODY_LIMIT` | `spec.grpc.bodyLimit` | Server `int` bytes; CRD `int32` bytes, emitted only when non-zero (no CRD type default). Chart example sets `10000000`. |
| gRPC reflection | bool | `false` | true / false | `connectors.grpc.enablereflection` · `CONNECTORS_GRPC_ENABLE_REFLECTION` | `spec.grpc.enableReflection` | Enables server reflection for grpcurl/tooling. |
| Service exposure | enum | `ClusterIP` | `ClusterIP` / `NodePort` / `LoadBalancer` | (`-p` host port) | `spec.grpc.expose` | Kubernetes `Service` type; empty ⇒ `ClusterIP`. The chart ships **no** `expose` value. On Docker use `-p`. |
| NodePort | int | `0` (kernel-assigned) | 30000–32767 | (`-p`) | `spec.grpc.nodePort` | Applied only when `expose: NodePort` **and** the value is > 0. The chart ships no default — leave it unset and the kernel picks a port you cannot configure into a client ahead of the install. |
## REST · WebSocket [#rest--websocket]
The HTTP/WebSocket transport, which also hosts the shared HTTP server (MCP, A2A,
CloudEvents). Enabled by default on both targets.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ---------------- | ------------ | --------------------- | ----------------------------------------- | ---------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Enable / disable | bool | enabled (`true`) | true / false | `connectors.rest.enable` · `CONNECTORS_REST_ENABLE` | `spec.rest.disabled` | Inverted boolean. Disabling REST removes the REST routes (they return `404`) but **leaves MCP, A2A and CloudEvents serving** — the shared HTTP server starts if *any* of the four is enabled. To take the whole listener down, disable all four. |
| Port | int (string) | `9090` | 1–65535 | `connectors.rest.port` · `CONNECTORS_REST_PORT` | `spec.rest.port` | String port; rejected if non-numeric or out of range. |
| Body limit | string / int | server `"100M"` | Echo size string or bytes | `connectors.rest.bodylimit` · `CONNECTORS_REST_BODY_LIMIT` | `spec.rest.bodyLimit` | Server size-string (`"100M"`); CRD `int32` bytes, emitted only when non-zero. Chart example sets `1000000`. |
| Sub buffer size | int | `100` | ≥ 0 | `connectors.rest.subbuffsize` · `CONNECTORS_REST_SUB_BUFF_SIZE` | `spec.rest.bufferSize` | Negative rejected. **Name divergence:** `subBuffSize` ↔ `bufferSize`. |
| Read timeout | int (s) | `60` | ≥ 0 (CRD ≥ 1) | `connectors.rest.readtimeout` · `CONNECTORS_REST_READ_TIMEOUT` | `spec.rest.readTimeout` | Seconds. Server rejects negative; CRD enforces `Minimum=1`. |
| Write timeout | int (s) | `60` | ≥ 0 (CRD ≥ 1) | `connectors.rest.writetimeout` · `CONNECTORS_REST_WRITE_TIMEOUT` | `spec.rest.writeTimeout` | Seconds. Server rejects negative; CRD enforces `Minimum=1`. |
| Service exposure | enum | `ClusterIP` | `ClusterIP` / `NodePort` / `LoadBalancer` | (`-p` host port) | `spec.rest.expose` | Kubernetes `Service` type; empty ⇒ `ClusterIP`. The chart ships **no** `expose` value. On Docker use `-p`. |
| NodePort | int | `0` (kernel-assigned) | 30000–32767 | (`-p`) | `spec.rest.nodePort` | Applied only when `expose: NodePort` **and** the value is > 0. The chart ships no default. |
### REST CORS [#rest-cors]
CORS policy for the REST transport. On the CRD it is a first-class `spec.rest.cors.*`
sub-object; on Docker/env the keys ride the `CONNECTORS_REST_CORS_*` prefix.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------------- | --------- | ---------------- | ------------ | ---------------------------------------------------------------------------------- | --------------------------------- | --------------------------------------------------------- |
| Allow origins | string\[] | `["*"]` | origin list | `connectors.rest.cors.alloworigins` · `CONNECTORS_REST_CORS_ALLOW_ORIGINS` | `spec.rest.cors.allowOrigins` | **Must be non-empty** — validation rejects an empty list. |
| Allow methods | string\[] | `["GET","POST"]` | method list | `connectors.rest.cors.allowmethods` · `CONNECTORS_REST_CORS_ALLOW_METHODS` | `spec.rest.cors.allowMethods` | **Must be non-empty.** |
| Allow headers | string\[] | `[]` | header list | `connectors.rest.cors.allowheaders` · `CONNECTORS_REST_CORS_ALLOW_HEADERS` | `spec.rest.cors.allowHeaders` | Empty list allowed. |
| Allow credentials | bool | `false` | true / false | `connectors.rest.cors.allowcredentials` · `CONNECTORS_REST_CORS_ALLOW_CREDENTIALS` | `spec.rest.cors.allowCredentials` | |
| Expose headers | string\[] | `[]` | header list | `connectors.rest.cors.exposeheaders` · `CONNECTORS_REST_CORS_EXPOSE_HEADERS` | `spec.rest.cors.exposeHeaders` | |
| Max age | int (s) | `0` | ≥ 0 | `connectors.rest.cors.maxage` · `CONNECTORS_REST_CORS_MAX_AGE` | `spec.rest.cors.maxAge` | Negative rejected. |
**REST → shared-HTTP inheritance.** When you explicitly set `Rest.ReadTimeout`,
`Rest.BodyLimit`, `Rest.Cors.AllowOrigins`, or `Rest.Cors.AllowMethods` (and don't set the
matching `Http.*` key), the value propagates to the shared HTTP server. `Http.Port` always
inherits `Rest.Port` when `Http.Port` is unset. The shared server's distinct CORS defaults
(the `MCP-*`/`OPTIONS`/`DELETE` headers below) are preserved whenever you did **not**
override the REST side, so MCP and A2A keep working.
## Management API [#management-api]
The management/dashboard API. Enabled by default on both targets.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| -------------------- | --------- | ------------------------------- | ----------------------------------------- | ---------------------------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable / disable | bool | enabled (`true`) | true / false | `api.enable` · `API_ENABLE` | `spec.api.disabled` | Inverted boolean. |
| Port | int | `8080` | 1–65535 | `api.port` · `API_PORT` | `spec.api.port` | Validated only when the API is enabled. |
| Bind address | string | `127.0.0.1` (empty → `0.0.0.0`) | IP address | `api.bindaddress` · `API_BIND_ADDRESS` | — | Config/env only; no typed CRD field. An empty value is normalized to `0.0.0.0`. |
| Allow origins (CORS) | string\[] | none (same origin only) | origin list | `api.alloworigins` · `API_ALLOW_ORIGINS` | `spec.api.allowOrigins` | An empty list, the default, lets only the dashboard's own origin call the API. CRD joins the list with commas into the env var. **When API auth is enabled, `"*"` is rejected** (see below). |
| Service exposure | enum | `ClusterIP` | `ClusterIP` / `NodePort` / `LoadBalancer` | (`-p` host port) | `spec.api.expose` | Kubernetes `Service` type; empty ⇒ `ClusterIP`. The chart ships **no** `expose` value. On Docker use `-p`. |
| NodePort | int | `0` (kernel-assigned) | 30000–32767 | (`-p`) | `spec.api.nodePort` | Applied only when `expose: NodePort` **and** the value is > 0. The chart ships no default. |
### Management API authentication [#management-api-authentication]
Opt-in authentication for the management API + web dashboard (`[Api.Auth]`). **Disabled by
default.** The data plane (gRPC/REST messaging) is unaffected. On the CRD it lives under
`spec.api.auth.*`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ---------------------- | ------ | --------------------- | ---------------- | ----------------------------------------------------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable | bool | `false` | true / false | `api.auth.enable` · `API_AUTH_ENABLE` | `spec.api.auth.enable` | Gates the whole section. |
| Session idle minutes | int | `30` | > 0 when enabled | `api.auth.sessionidleminutes` · `API_AUTH_SESSION_IDLE_MINUTES` | `spec.api.auth.sessionIdleMinutes` | Idle-session timeout. Must be positive. |
| Session absolute hours | int | `8` | > 0 when enabled | `api.auth.sessionabsolutehours` · `API_AUTH_SESSION_ABSOLUTE_HOURS` | `spec.api.auth.sessionAbsoluteHours` | Absolute session lifetime. Must be positive. |
| Store path | string | `""` → main store dir | filesystem path | `api.auth.storepath` · `API_AUTH_STORE_PATH` | `spec.api.auth.storePath` | When empty and auth enabled, defaults to `Store.StorePath` (the main store directory). |
| Trusted TLS proxy | bool | `false` | true / false | `api.auth.trustedtlsproxy` · `API_AUTH_TRUSTED_TLS_PROXY` | `spec.api.auth.trustedTLSProxy` | Set `true` when a TLS-terminating reverse proxy fronts the API port; otherwise cookie/session login is refused on plain HTTP. |
| Admin username | string | `admin` | username | `KUBEMQ_API_ADMIN_USERNAME` (os env) | `spec.api.auth.adminUsername` | **Env/secret only — not a viper config-file field.** Read directly from the environment. |
| Admin password | string | — | password | `KUBEMQ_API_ADMIN_PASSWORD` / `KUBEMQ_API_ADMIN_PASSWORD_FILE` (os env) | `spec.api.auth.adminSecretRef` · `adminSecretKey` | **Secret only** — never a config field. The operator injects the password into the pod from a Secret; on Docker set the env var (or `_FILE`) yourself. Cluster mode requires it when auth is enabled. |
#### The account model [#the-account-model]
The two settings above (`adminUsername` / `adminPassword`) bootstrap the **first** account.
They are not the whole model — once auth is on, the control plane has three roles and two
account types, and only the first admin is configured through the server config at all.
Every other account is created through the API or dashboard.
**Three roles**, each a superset of the one below it:
| Role | Can do |
| ------------ | ------------------------------------------------------------------------- |
| `read_only` | Read dashboards, stats, snapshots, audit logs |
| `read_write` | Everything in `read_only`, plus send/receive messages and subscribe |
| `admin` | Everything in `read_write`, plus manage accounts and revert configuration |
**Two account types:**
| Type | Authenticates with | Notes |
| --------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `user` | Username + password, cookie session | Subject to the idle and absolute session limits above. |
| `service` | A bearer API key, `kmq__` | Sent as `Authorization: Bearer …`. For scripts, agents, and CI. **A service account cannot hold the `admin` role** — that combination is rejected at creation. |
Two behaviors worth knowing before you turn auth on:
* **The bootstrap admin must rotate its password on first login.** The login response
carries `must_change_password`, and the account stays in that state until the password
is changed — an automation that logs in with the bootstrap credentials and ignores the
flag will not get far.
* **Cookie-authenticated mutations require an `X-KubeMQ-CSRF` header.** Bearer-authenticated
service accounts are exempt: there is no ambient credential for a malicious site to
replay, so the guard applies to session cookies only.
**A `read_only` account is a real account, and it can read configuration.** If you are
handing out dashboard access, `read_only` is the right default — but treat it as a
principal with visibility into server settings, not as a view of nothing sensitive.
**Wildcard CORS is refused when API auth is enabled.** With `api.auth.enable: true`, the
server rejects boot if `api.alloworigins` contains `"*"`. An empty list, the default, allows
only the dashboard's own origin; list any other browser origin explicitly (e.g.
`["https://app.example.com"]`). The `sessionIdleMinutes`/`sessionAbsoluteHours` values must both be positive.
## Shared HTTP server [#shared-http-server]
The shared HTTP server hosts MCP, A2A, and CloudEvents on the REST port. On Kubernetes it
is a first-class `spec.http.*` group; its CORS lives under `spec.http.cors.*`. It has no
enable/disable toggle — it is active whenever REST is, and the CRD emits its env vars only
for the `spec.http.*` fields you set.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ---------------------- | --------- | ------------------------------------------------------------------------------------------ | ---------------- | ---------------------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| Port | string | inherits `Rest.Port` (`9090`) | 1–65535 | `connectors.http.port` · `CONNECTORS_HTTP_PORT` | `spec.http.port` | Empty ⇒ inherits the REST port. A differing explicit value logs a warning; the HTTP server uses `Http.Port`. |
| Read timeout | int (s) | `60` | ≥ 0 (CRD ≥ 1) | `connectors.http.readtimeout` · `CONNECTORS_HTTP_READ_TIMEOUT` | `spec.http.readTimeout` | Negative rejected. |
| Body limit | string | `"100M"` | Echo size string | `connectors.http.bodylimit` · `CONNECTORS_HTTP_BODY_LIMIT` | `spec.http.bodyLimit` | CRD field is a string. |
| Base URL | string | `""` | URL | `connectors.http.baseurl` · `CONNECTORS_HTTP_BASE_URL` | `spec.http.baseUrl` | Server field is `BaseURL`; env `..._BASE_URL`. |
| CORS allow origins | string\[] | `["*"]` | origin list | `connectors.http.cors.alloworigins` · `CONNECTORS_HTTP_CORS_ALLOW_ORIGINS` | `spec.http.cors.allowOrigins` | |
| CORS allow methods | string\[] | `GET, POST, DELETE, OPTIONS` | method list | `connectors.http.cors.allowmethods` · `CONNECTORS_HTTP_CORS_ALLOW_METHODS` | `spec.http.cors.allowMethods` | Wider than REST — MCP/A2A need `DELETE`/`OPTIONS`. |
| CORS allow headers | string\[] | `Authorization, Content-Type, MCP-Protocol-Version, MCP-Session-Id, Last-Event-ID, Accept` | header list | `connectors.http.cors.allowheaders` · `CONNECTORS_HTTP_CORS_ALLOW_HEADERS` | `spec.http.cors.allowHeaders` | Includes the `MCP-*` headers. |
| CORS allow credentials | bool | `false` | true / false | `connectors.http.cors.allowcredentials` · `CONNECTORS_HTTP_CORS_ALLOW_CREDENTIALS` | `spec.http.cors.allowCredentials` | |
| CORS expose headers | string\[] | `MCP-Session-Id, MCP-Protocol-Version` | header list | `connectors.http.cors.exposeheaders` · `CONNECTORS_HTTP_CORS_EXPOSE_HEADERS` | `spec.http.cors.exposeHeaders` | |
| CORS max age | int (s) | `86400` | ≥ 0 | `connectors.http.cors.maxage` · `CONNECTORS_HTTP_CORS_MAX_AGE` | `spec.http.cors.maxAge` | Negative rejected. |
## Example [#example]
Set the gRPC port on each target. On Kubernetes `spec.grpc.port` moves the in-pod listener,
the `Service` port/`targetPort`, and the container port together; on Docker it moves the
listener and you publish it with `-p`. This is a
single-setting snippet — see the [Docker guide](/configure/docker) and the
[Kubernetes guide](/configure/kubernetes) for complete, runnable configurations.
```yaml title="config.yaml"
connectors:
grpc:
port: "50000"
```
```yaml title="cluster-values.yaml"
grpc:
port: 50000
```
For the full Docker delivery methods and `docker run` port publishing see the
[Docker guide](/configure/docker); for `cluster-values.yaml` mapped to the
`KubemqCluster` spec and `Service` exposure see the
[Kubernetes guide](/configure/kubernetes).
# Observability (/configure/reference/observability)
KubeMQ reports on itself through three domains: **OpenTelemetry** traces and metrics, an
**audit** log of operations, and **notifications** about server events. Each setting is
shown for both deployment targets — Docker single-node (`config.yaml` key · env var) and
Kubernetes/Helm (`spec.*` path). A dash (`—`) in the Helm/CRD column means the setting is
not available on that surface; a dash in the env-var slot means the field has **no
environment binding at all** (config-file/secret-only).
This page is the **settings reference** for telemetry, audit, and notifications. For
concepts, how-to guides, the full metric series, the audit event catalog, and the
management API, see **[Observability](/operate/observability)**.
## Telemetry (OpenTelemetry) [#telemetry-opentelemetry]
KubeMQ exports traces and metrics over OTLP. The scalar fields are a first-class
`spec.telemetry.*` group on Kubernetes. The master `enable` flag is **off by default**;
turn it on, then optionally tune the traces, metrics, and exporter sub-blocks. Every
sub-block only takes effect while the master switch is on.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------------------- | ------------------ | ---------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Enable (master) | bool | `false` | true / false | `telemetry.enable` · `TELEMETRY_ENABLE` | `spec.telemetry.enable` | Master switch — off disables all telemetry (`Validate` returns early). |
| Service name | string | `kubemq` | non-empty service name | `telemetry.servicename` · `TELEMETRY_SERVICE_NAME` | `spec.telemetry.serviceName` | Reported as the OTLP `service.name`. Empty is coerced back to `kubemq` at load. |
| Traces enable | bool | `true` | true / false | `telemetry.traces.enable` · `TELEMETRY_TRACES_ENABLE` | `spec.telemetry.traces.enable` | Applies only when the master switch is on. |
| Traces sampling ratio | float64 | `1.0` | `0`–`1` | `telemetry.traces.samplingratio` · `TELEMETRY_TRACES_SAMPLING_RATIO` | `spec.telemetry.traces.samplingRatio` | Fraction of traces sampled. Out-of-range values are coerced back to `1.0`. |
| Traces sampler | enum | `parent_based` | `always_on` / `always_off` / `trace_id_ratio` / `parent_based` | `telemetry.traces.sampler` · `TELEMETRY_TRACES_SAMPLER` | `spec.telemetry.traces.sampler` | Sampling strategy. Any other value is coerced to `parent_based`. |
| Metrics enable | bool | `true` | true / false | `telemetry.metrics.enable` · `TELEMETRY_METRICS_ENABLE` | `spec.telemetry.metrics.enable` | Applies only when the master switch is on. |
| Metrics export interval | duration | `30s` | Go duration string | `telemetry.metrics.exportinterval` · `TELEMETRY_METRICS_EXPORT_INTERVAL` | `spec.telemetry.metrics.exportInterval` | How often metrics are pushed. Unparseable values are coerced to `30s`. |
| Exporter protocol | enum | `grpc` | `grpc` / `http` | `telemetry.exporter.protocol` · `TELEMETRY_EXPORTER_PROTOCOL` | `spec.telemetry.exporter.protocol` | OTLP wire protocol. Any other value is coerced to `grpc`. |
| Exporter endpoint | string | `localhost:4317` | host:port | `telemetry.exporter.endpoint` · `TELEMETRY_EXPORTER_ENDPOINT` | `spec.telemetry.exporter.endpoint` | OTLP collector endpoint. Empty is coerced to `localhost:4317`. |
| Exporter insecure | bool | `true` | true / false | `telemetry.exporter.insecure` · `TELEMETRY_EXPORTER_INSECURE` | `spec.telemetry.exporter.insecure` | Disable TLS to the collector. |
| Exporter compression | enum | `gzip` | `gzip` / `none` | `telemetry.exporter.compression` · `TELEMETRY_EXPORTER_COMPRESSION` | `spec.telemetry.exporter.compression` | Payload compression. Any other value is coerced to `gzip`. |
| Exporter timeout | duration | `10s` | Go duration string | `telemetry.exporter.timeout` · `TELEMETRY_EXPORTER_TIMEOUT` | `spec.telemetry.exporter.timeout` | Export request timeout. Unparseable values are coerced to `10s`. |
| Exporter headers | map\[string]string | `{}` | key/value map | `telemetry.exporter.headers` · ⚠️ `TELEMETRY_EXPORTER_HEADERS` (**do not use — see callout**) | — | **Config-file-only in practice.** A `TELEMETRY_EXPORTER_HEADERS` env binding exists but is a landmine (below). Not exposed on the CRD. |
| Resource attributes | map\[string]string | `{}` | key/value map | `telemetry.resource` · — (no env binding) | — | **Config-file-only.** No `bindViperEnv` call and no CRD field — set only in the mounted `config.yaml`. |
**Do not set `TELEMETRY_EXPORTER_HEADERS` — it corrupts the entire running config.**
`Telemetry.Exporter.Headers` is a `map[string]string`, and viper/mapstructure has no
default string→map decode hook. Setting the env var makes `viper.Unmarshal` fail, and the
loader's error path **discards the whole config and falls back to pure defaults** — every
other file setting and env var is silently lost, with only a stderr line as evidence. The
env name appears in the golden key list, but treat it as unusable: configure exporter
headers only via the `telemetry.exporter.headers` map in the mounted `config.yaml`. The
sibling `telemetry.resource` map is safer — it has **no** env binding at all, so it is
cleanly config-file-only. Neither map has a CRD path.
## Audit [#audit]
The audit log records server operations and retains them for a configurable window. It is a
first-class `spec.audit.*` group on Kubernetes and is **enabled by default**. The CRD models
`enable` as `*bool` deliberately — because audit defaults on server-side, a plain bool could
never emit `false` to turn it off.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ---------------------- | ---- | ------- | ------------ | ----------------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| Enable | bool | `true` | true / false | `audit.enable` · `AUDIT_ENABLE` | `spec.audit.enable` | Audit is on by default. CRD field is `*bool` so it can emit `false`. |
| Retention hours | int | `720` | ≥ 1 | `audit.retentionhours` · `AUDIT_RETENTION_HOURS` | `spec.audit.retentionHours` | How long audit records are kept (720h = 30 days). Values \< 1 are coerced to `720`. CRD type is `int32` with `Minimum=1`. |
| Cleanup interval (min) | int | `60` | ≥ 1 | `audit.cleanupintervalminutes` · `AUDIT_CLEANUP_INTERVAL_MINUTES` | `spec.audit.cleanupIntervalMinutes` | How often expired records are purged. Values \< 1 are coerced to `60`. CRD type is `int32` with `Minimum=1`. |
## Notifications [#notifications]
Server-event notifications are published to an internal channel. The toggle and prefix have
**name divergences** between the two targets — read the Notes column carefully. The server
struct has no `mapstructure` tags; viper binds these by field path (case-insensitive).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------------- | ------ | --------------- | ---------------- | ------------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------ |
| Enable | bool | `false` | true / false | `notification.enable` · `NOTIFICATION_ENABLE` | `spec.notification.enabled` | **Name divergence:** Docker `enable` ↔ Helm `enabled`. |
| Channel prefix | string | `notifications` | non-empty prefix | `notification.reportchannelprefix` · `NOTIFICATION_REPORT_CHANNEL_PREFIX` | `spec.notification.prefix` | **Name divergence:** `reportchannelprefix` ↔ `prefix`. |
| Log notifications | bool | `false` | true / false | `notification.log` · `NOTIFICATION_LOG` | `spec.notification.log` | Also write notifications to the server log. |
**Cross-field rule:** when notifications are enabled, if `log` is `false` **and** the
channel prefix is empty, the server fails validation with
`bad notification configuration: missing parameters`. Either keep a non-empty prefix
(the default `notifications` satisfies this) or set `log: true`.
## Example [#example]
Enable telemetry on each target. This is a single-setting snippet — see the
[Docker guide](/configure/docker) and the
[Kubernetes guide](/configure/kubernetes) for complete, runnable configurations.
```yaml title="config.yaml"
telemetry:
enable: true
```
```yaml title="cluster-values.yaml"
telemetry:
enable: true
```
For the full Docker delivery methods (env vars, mounted `config.yaml`, the `CONFIG`
variable) see the [Docker guide](/configure/docker); for `cluster-values.yaml` mapped to
the `KubemqCluster` spec see the [Kubernetes guide](/configure/kubernetes).
# Security (Auth · TLS) (/configure/reference/security)
KubeMQ secures the server with three independent layers: **authentication** (verify who
is connecting, via JWT or OIDC), **authorization** (policy-based access control), and
**TLS/mTLS** (transport encryption). Each setting is shown for both deployment targets —
Docker single-node (`config.yaml` key · env var) and Kubernetes/Helm (`spec.*` path). A
dash (`—`) in the Helm/CRD column means the setting is not available on that surface
(it is `config.yaml`/env-only).
## Authentication [#authentication]
Authentication is **off by default** and opt-in (`enable: true`). The `type` field is the
**mode selector**: the literal value `oidc` delegates verification to an OIDC provider;
**any other value (including empty or `jwt`) selects JWT mode**, which validates a signed
token with a configured key and signature algorithm. There is no wire-connector
opt-in/opt-out toggle here — authentication uses the plain `enable` flag on both surfaces.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| -------------------- | -------------------- | ------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable | bool | `false` | true / false | `authentication.enable` · `AUTHENTICATION_ENABLE` | `spec.authentication.enable` | Off by default. When `false` the server ignores every other auth field (`authentication.go:100`). Operator emits from the `Enable` pointer. |
| Type (mode selector) | string | `""` | `oidc`, or empty ⇒ JWT | `authentication.type` · `AUTHENTICATION_TYPE` | `spec.authentication.type` | Only the exact value `oidc` triggers OIDC; empty or any other value ⇒ JWT (`authentication.go:103`). |
| JWT signature type | string | `""` | `HS256`·`HS384`·`HS512`·`RS256`·`RS384`·`RS512`·`ES256`·`ES384`·`ES512` | `authentication.jwtconfig.signaturetype` · `AUTHENTICATION_JWT_CONFIG_SIGNATURE_TYPE` | `spec.authentication.signatureType` | Required when JWT is enabled (`authentication.go:19`). The 9 algorithms come from `pkg/authentication/jwt.go:10-20`. Name divergence `jwtconfig.signaturetype` ↔ `signatureType`. Operator stores it in a **Secret**. |
| JWT key | string | `""` | HMAC secret / PEM public key | `authentication.jwtconfig.key` · `AUTHENTICATION_JWT_CONFIG_KEY` | `spec.authentication.key` | Verification key, read verbatim. Either `key` or `filePath` is required (`authentication.go:22`). Name divergence `jwtconfig.key` ↔ `key`. Operator stores it in a **Secret**. |
| JWT key file | string | `""` | file path | `authentication.jwtconfig.filepath` · `AUTHENTICATION_JWT_CONFIG_FILE_PATH` | — | Alternative to the inline key; validated as a filename (`authentication.go:25`). **`config.yaml`/env-only** — superseded by the inline `key` on the CRD (allowlist). |
| OIDC config | string (base64 JSON) | `""` | base64-encoded OIDC JSON | `authentication.config` · `AUTHENTICATION_CONFIG` | `spec.authentication.oidc` | Docker takes **base64-encoded** OIDC JSON, which the server base64-decodes (`authentication.go:74`). Helm takes a first-class `oidc` block that the operator encodes for you. Required when `type: oidc` (`authentication.go:104`). |
### OIDC block fields [#oidc-block-fields]
These live inside the OIDC config: on Docker they are keys of the base64-encoded JSON in
`AUTHENTICATION_CONFIG`; on Helm they are typed fields under `spec.authentication.oidc`.
They have **no individual env bindings** — the whole block travels as the single
`AUTHENTICATION_CONFIG` value (config-file/secret-only per field).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------------------------- | ------ | ------- | ---------------- | -------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Issuer | string | `""` | issuer URL | *(part of `authentication.config` JSON)* · — | `spec.authentication.oidc.issuer` | **Required** (`authentication.go:51`). |
| Client ID | string | `""` | OAuth2 client id | *(part of `authentication.config` JSON)* · — | `spec.authentication.oidc.clientID` | Required unless `skipClientIDCheck` is set (`authentication.go:54`). |
| Skip client-ID check | bool | `false` | true / false | *(part of `authentication.config` JSON)* · — | `spec.authentication.oidc.skipClientIDCheck` | Disables audience validation. |
| Skip expiry check | bool | `false` | true / false | *(part of `authentication.config` JSON)* · — | `spec.authentication.oidc.skipExpiryCheck` | **Insecure** — accepts expired tokens; logs a warning (`authentication.go:64`). |
| Skip issuer check | bool | `false` | true / false | *(part of `authentication.config` JSON)* · — | `spec.authentication.oidc.skipIssuerCheck` | **Insecure** — accepts any issuer; logs a warning (`authentication.go:67`). |
| Insecure skip signature check | bool | `false` | true / false | *(part of `authentication.config` JSON)* · — | `spec.authentication.oidc.insecureSkipSignatureCheck` | **Insecure** — token signatures are NOT verified; logs a warning (`authentication.go:61`). |
**OIDC hard rejection:** a config that disables **all four** checks at once
(`insecureSkipSignatureCheck` + `skipExpiryCheck` + `skipIssuerCheck` + `skipClientIDCheck`)
is **rejected** — at least one check must remain enabled (`authentication.go:58`).
**`spec.authentication.oidc` supersedes the legacy `spec.configData` OIDC block.** A CR
that sets **both** JWT fields (`key` / `signatureType`) **and** `oidc` is **rejected** —
pick one authentication mode (k8s `config/authentication.go:100`). Note that
`spec.configData` is a raw string carrying **only** an OIDC block (k8s
`config/config_data.go`); it is **not** a generic `config.yaml` passthrough.
The rejection happens twice and is loud: **at admission**, by a CEL rule on the
`KubemqCluster` CRD shipped in the `kubemq-next` chart, and again **at reconcile** by the
operator, which raises a `ReconcileError` condition and a `Warning` event and
**leaves running pods untouched**.
**`ReconcileError` clears on its own once you fix the CR.** The
condition flips to `False` with reason `LastReconcileCycleSucceeded` on the next reconcile
that completes — it is not deleted, so alerts keyed on the condition's *presence* keep working
and the recovery carries its own transition time.
Moving from a legacy cluster? Its authentication settings do not carry over; see
[Move from legacy KubeMQ](/deploy/upgrade/from-legacy).
## Authorization [#authorization]
Policy-based access control, **off by default**. Supply the policy inline (`policy`) or by
URL (`url`), with optional periodic auto-reload. When enabled, **exactly one** of policy
data, policy file, or URL must be present (`authorization.go:34`).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| --------------------- | --------------- | ------- | ------------------------------ | -------------------------------------------------------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enable | bool | `false` | true / false | `authorization.enable` · `AUTHORIZATION_ENABLE` | — (auto-derived) | Docker opt-in. On the CRD **there is no enable field** — the operator sets `AUTHORIZATION_ENABLE=true` automatically whenever `policy` or `url` is set (k8s `config/authorization.go:20-25`). |
| Policy data | string (base64) | `""` | base64-encoded policy document | `authorization.policydata` · `AUTHORIZATION_POLICY_DATA` | `spec.authorization.policy` | **Base64-encoded** — the server base64-decodes the policy content. Name divergence `policydata` ↔ `policy`. Operator emits it base64 (k8s `config/authorization.go:27`). |
| Policy URL | string | `""` | http(s) URL | `authorization.url` · `AUTHORIZATION_URL` | `spec.authorization.url` | **Raw, NOT base64** — the server hands it verbatim to `http.Get`; `validateURL` rejects a base64 blob (`authorization.go:51`, k8s `config/authorization.go:32`). `config.yaml` key is `authorization.url` (server field `Authorization.Url`). |
| Auto-reload (seconds) | int | `0` | ≥ 0 (`0` = disabled) | `authorization.autoreload` · `AUTHORIZATION_AUTO_RELOAD` | `spec.authorization.autoReload` | Reload interval in **seconds** (`services/authorization/authorization.go:50`). Negative is rejected (`authorization.go:37`). Name divergence `autoreload` ↔ `autoReload`. Omitted from CRD env when `0`. |
| Policy file | string | `""` | file path | `authorization.filepath` · `AUTHORIZATION_FILE_PATH` | — | Validated as a filename (`authorization.go:44`). **`config.yaml`/env-only** — superseded by the inline `policy` on the CRD (allowlist). |
## TLS / mTLS [#tls--mtls]
Transport encryption for the interfaces. There is **no enable flag** — the mode is
**auto-derived** from which artifacts are present (`security.go:76`): **none** (omit all),
**TLS** (server `cert` + `key`), and **mTLS** (additionally a client `ca`, so both peers
authenticate). The Docker `config.yaml` group is `security.*`; the Helm/CRD group is
`spec.tls.*` — a **name divergence**. On Docker each artifact accepts inline `data` or a
`filename`, and inline `data` takes precedence over `filename` (`resource.go:19`).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ----------- | ------ | ------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| Server cert | string | `""` | PEM block (`data`) / file path (`filename`) | `security.cert.data` / `security.cert.filename` · `SECURITY_CERT_DATA` / `SECURITY_CERT_FILENAME` | `spec.tls.cert` | **Name divergence:** `security` ↔ `tls`. Required for TLS and mTLS (`security.go:48`). `*_DATA` is a raw PEM; the operator stores it in a **Secret**. |
| Server key | string | `""` | PEM block (`data`) / file path (`filename`) | `security.key.data` / `security.key.filename` · `SECURITY_KEY_DATA` / `SECURITY_KEY_FILENAME` | `spec.tls.key` | Required for TLS and mTLS (`security.go:52`). Secret on the CRD. |
| CA (mTLS) | string | `""` | PEM block (`data`) / file path (`filename`) | `security.ca.data` / `security.ca.filename` · `SECURITY_CA_DATA` / `SECURITY_CA_FILENAME` | `spec.tls.ca` | Presence promotes the mode to **mTLS** (client-certificate verification, `security.go:79`). Secret on the CRD. |
On the CRD only the inline **data** fields (`spec.tls.cert` / `.key` / `.ca`) are exposed.
The `SECURITY_*_FILENAME` keys are **`config.yaml`/env-only** and are superseded by the
inline data on the CRD (allowlist). The same holds for `AUTHENTICATION_JWT_CONFIG_FILE_PATH`
and `AUTHORIZATION_FILE_PATH`.
## Example [#example]
Supply a TLS server certificate on each target. This is a single-setting snippet — see the
[Docker guide](/configure/docker) and the
[Kubernetes guide](/configure/kubernetes) for complete, runnable configurations.
```yaml title="config.yaml"
security:
cert:
filename: /certs/server.crt
key:
filename: /certs/server.key
```
```yaml title="cluster-values.yaml"
tls:
cert: |
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
key: |
-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
```
For the full Docker delivery methods (env vars, mounted `config.yaml`, the `CONFIG`
variable) see the [Docker guide](/configure/docker); for `cluster-values.yaml` mapped to
the `KubemqCluster` spec see the [Kubernetes guide](/configure/kubernetes).
## Management API transport [#management-api-transport]
The management listener has its own certificate settings. Set **both** `API_TLS_CERT_FILE` and `API_TLS_KEY_FILE` to readable PEM files to serve HTTPS. A partial pair or unreadable/invalid pair fails startup. These settings do not configure client messaging transport; configure that separately above.
On Kubernetes use `spec.api.tlsSecret`, referencing a same-namespace Secret with `tls.crt` and `tls.key`. The operator mounts both files read-only, configures HTTPS probes, and verifies the certificate for its management calls. The certificate must cover `-api..svc` plus the names or IP addresses clients use. Keep authentication enabled and management private. Supply the public chain through `kmq auth login --ca-file` when using a private authority; do not disable certificate verification.
# Storage Engines (/configure/reference/storage-engines)
KubeMQ ships **two persistence engines**: `next` and `legacy`. The engine
governs **only the persistence plane** — the Events Store and Queues. Ephemeral patterns
(Events pub/sub, Commands/Queries RPC) ride the same internal messaging core in both modes
and behave **identically** regardless of which engine a cluster runs.
## The two engines [#the-two-engines]
| | `legacy` | `next` (resolved on a clean store) |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Persistence | the legacy persistence engine (file store) | owned segment log + Dragonboat raft |
| Durability on ack | accepted into the legacy file store; fsync on a timer (`Broker.DiskSyncSeconds`, default 5s) | **selectable.** `fast` (**the default**): ack after quorum-replication, fsync follows in a bounded background window. `strict`: ack only after quorum-replication **and** fsync (zero acked-loss). See [Ack policy](#ack-policy) |
| Cluster consensus | file-store raft over the cluster mesh | Dragonboat raft over a dedicated replication listener (optional mTLS, default off) |
| Kafka compaction | not supported (Kafka is `next`-only) | supported — unlocks Kafka Connect and Kafka Streams |
| Native store limits & retention (`store.max*`) | enforced | **not consumed** — native channels have no age/size/count cap ([details](#native-retention-scope)) |
| Status | **feature-frozen** (maintenance/security/bug fixes only); opt-in — name it explicitly at creation | what a clean store resolves to; receives all new durability and compaction features |
## Choosing an engine [#choosing-an-engine]
* **A new deployment on a clean store comes up on `next`.** There is nothing to set — see
[Zero-config engine selection](#zero-config-engine-selection) below.
* **`next` is also required for Kafka** compacted topics, and it is the only engine that
can give you quorum-fsynced durability — **but not by default**: that needs
`store.nextackpolicy: strict`. See [Ack policy](#ack-policy).
* **To run `legacy`, name it explicitly at creation** — `store.engine: legacy` (Docker) or
`spec.store.engine: legacy` (Kubernetes). It is no longer what you get by omission.
* **An existing cluster keeps the engine it was born with.** There is no migration path
between engines, and nothing about the change above rolls or reinterprets a running
cluster.
**If you have a page, script, or values file that assumes `legacy` is what you get by
default, it is now wrong.** A fresh cluster with a clean store resolves to `next`. This
holds on Kubernetes and on Docker alike: the server resolves a clean store to `next`
when the engine is left unset.
## Zero-config engine selection [#zero-config-engine-selection]
An explicit engine always wins and skips every probe below: `store.engine` (Docker
`config.yaml`), `STORE_ENGINE` (env), or `spec.store.engine` (Kubernetes).
Otherwise **the server resolves the engine itself at boot**, by probing the store
directory:
* **The directory already holds a store** → the engine that wrote it.
* **The directory is clean** → `next`.
The resolved engine is named in a **boot NOTICE** in the server log, along with the
deciding signal and the directory that was probed. When the choice was delegated rather
than pinned, **that log line is the only place the running engine is reported** — see
[Which engine am I actually on?](#which-engine-am-i-actually-on) below.
### On Kubernetes the operator delegates, with `STORE_ENGINE=auto` [#on-kubernetes-the-operator-delegates-with-store_engineauto]
A cluster with **no engine on record** is created with
`STORE_ENGINE=auto` and the server resolves it as above. Established clusters are
untouched — their engine stays named explicitly and nothing rolls.
Three consequences worth holding onto:
* **`status.engine` and the `next.kubemq.io/established-engine` annotation both read
`auto`** on such a cluster. That value records *the delegation*, not the engine running.
* **Setting `spec.store.engine` later on an `auto` cluster is allowed.** `auto` records
that the cluster delegated the choice, not an established engine, so pinning afterwards
is a first choice rather than an engine change. **Pin the engine the server actually
resolved** — a pin that disagrees with the data on disk is refused by the server at
boot, and the server never deletes a datadir.
* **On an established cluster the annotation is authoritative and outranks
`spec.store.engine`.** A mismatch is refused, not silently applied. See the
[engine-establishment guard](/configure/reference/deployment#engine-establishment-guard).
### Which engine am I actually on? [#which-engine-am-i-actually-on]
| Cluster | Where to read the engine |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Engine named explicitly | `spec.store.engine`, `status.engine`, or the annotation — all agree |
| Engine delegated (`auto`) | **the server's boot NOTICE in the pod log**, or the two API fields below. `status.engine` and the annotation both say `auto`, which is the delegation, not the answer |
```bash
kubectl logs -n | grep -i 'store engine'
```
The management API's config view carries the same answer in two read-only fields — they
exist precisely because this question was previously unanswerable on a delegating
deployment. Neither is an operator input, and neither is ever written back into a saved
config file:
| Field | What it holds |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `engineResolved` | The engine this node is **actually running** — always a concrete `legacy` or `next`, never `auto`. |
| `engineResolvedSignal` | **Why** it holds that, in plain words: `clean store (auto default)`, `explicitly configured (detection did not run)`, `clean store (CleanStore=true)`, or the on-disk evidence the probe matched. |
The signal matters as much as the engine. A node reporting `legacy` may have been pinned by
an operator, or may have detected legacy data on disk — and the remedy differs.
### Kafka [#kafka]
Kafka runs on `next` only, and needs no manual engine step:
* **Clean store + Kafka enabled + engine unset** → resolves to `next` (NOTICE logged) —
the same clean-store outcome as without Kafka.
* **Existing `legacy` store data, Kafka left at its default (on)** → the server **starts
without Kafka**. Kafka is on by default, so a legacy deployment that never asked for it
must not be stopped by it: the connector is turned off for that run, port 9092 does not
open, and the server logs an ERROR naming the port and the reason. Everything else runs.
* **Existing `legacy` store data, Kafka enabled explicitly** (`Connectors.Kafka.Enable=true`
or `CONNECTORS_KAFKA_ENABLE=true`) → fails closed at boot with a config error naming the
conflicting store directory. Kafka never ran on `legacy`, so the server refuses to mix
engines rather than silently reinterpreting existing data.
* **Explicit `store.engine: legacy` + Kafka** → the same two cases: Kafka off for the run
if it was only on by default, a boot refusal if you enabled it explicitly.
* **Naming `next` explicitly** skips the probe entirely and always wins — the predictable
choice for IaC/GitOps that shouldn't depend on probe-time filesystem state.
## Mode isolation [#mode-isolation]
A cluster is **born one mode and stays there**. The data directory records a mode marker
at first boot. Every later boot compares that marker against the configured engine — a
**mismatch is a fatal boot error**: the server refuses to start, and it **never wipes the
directory**. There is no in-place engine migration and no cross-format compatibility
between `legacy` and `next` data.
## Durability guarantees [#durability-guarantees]
Three distinct dimensions govern durability, and they should not be conflated:
1. **Ack meaning.** On `legacy`, a publish is acknowledged after the write lands in the
file store; the store is fsynced on a timer (`Broker.DiskSyncSeconds`, default 5s) —
so an ack can precede the fsync. On `next`, **it depends on the ack policy** below:
under `strict` a publish is acknowledged only after the write is quorum-replicated
**and** fsynced; under `fast` — the shipped default — it is acknowledged once
quorum-replicated, with the fsync following in a bounded background window.
2. **Loss window.** "Zero acked-loss" describes **`next` with `strict` only**. It means an
acknowledgement follows quorum disk synchronization. Survival still depends on
retaining the required replicas and their storage. Under the default `fast`, an ack does
**not** imply the record is on disk: writes acknowledged inside the flush window can be
lost to power loss on a whole-quorum failure. And on any engine or policy, "zero
acked-loss" never means zero loss overall — unacked, in-flight work can still be lost
if the client never receives the ack.
3. **Consistency under failover.** On `next`, per-channel sequence numbers are assigned
from the committed raft apply order — they are **gap-free, monotonic, and
restart-stable**, even across a leader election.
## Next storage engine settings [#next-storage-engine-settings]
Six `next`-engine settings live on the store config. All are `config.yaml` / env-only —
none has a typed CRD field, so on Kubernetes they travel through `spec.env` or a mounted
config. Every one of them parses and validates on **both** engines; they are simply inert
under `legacy`, so a config that would be wrong after an engine switch fails when it is
written rather than when it becomes load-bearing.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| --------------------- | ------------- | -------------------------------------- | ------------------ | --------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Ack policy | string (enum) | `fast` | `fast` \| `strict` | `store.nextackpolicy` · `STORE_NEXT_ACK_POLICY` | — | The ack durability contract — see [Ack policy](#ack-policy) below. **Exact match only**: `Fast`, `STRICT` and `true` are all rejected. |
| Raft address | string | `""` → `127.0.0.1:` | `host:port` | `store.nextraftaddress` · `STORE_NEXT_RAFT_ADDRESS` | — | The engine's Dragonboat replication-listener bind address. Empty computes a single-node loopback default. A standalone node pins the listener to loopback regardless — it must not be routable. |
| Segment size (bytes) | int64 | `0` → engine default (64 MiB) | ≥ `0` | `store.nextsegmentsize` · `STORE_NEXT_SEGMENT_SIZE` | — | Per-channel segment-log size, the analog of Kafka's `segment.bytes`. A smaller value rolls segments sooner, which is what lets compaction reclaim space promptly on low-volume topics. |
| Shard-pool size | int | `8` on a fresh cluster; `1` standalone | `1`–`16` | `store.nextshards` · `STORE_NEXT_SHARDS` | — | KubeMQ 3.6.21 defaults an unset value to eight independent raft groups on a clustered next node and one otherwise. Channels are hash-mapped onto them. The count is fixed at data-directory creation; existing stores retain their layout. Above `16` is rejected. |
| Balance shard leaders | bool | `true` | true / false | `store.nextbalanceleaders` · `STORE_NEXT_BALANCE_LEADERS` | — | KubeMQ 3.6.21 enables balancing by default, spreading shard leaders across cluster nodes. It has no effect on a standalone node or a one-shard layout. `false` pins leaders rather than balancing them. |
### Ack policy [#ack-policy]
**The shipped default is `fast`, and under `fast` an ack does NOT mean the record is on
disk.** A fresh `next` cluster does not give you the quorum-fsynced ack unless you ask for
it.
| | `fast` (**default**) | `strict` |
| ----------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| Ack means | the entry is **quorum-replicated**; the raft log fsync follows in the background, within a bounded window | the entry is quorum-replicated **and fsynced on a quorum** of raft logs |
| Loss window | writes acked inside the flush window can be lost to a whole-quorum power loss | no unsynchronized acknowledgement window; replica or storage destruction and retention remain separate concerns |
| Cost | lower publish latency | fsync on the publish path |
If a compliance requirement or an audit answer depends on *"an ack means it is on disk"*,
set it explicitly:
```yaml title="config.yaml"
store:
nextackpolicy: strict
```
On Kubernetes, via `spec.env`:
```yaml title="cluster-values.yaml"
env:
STORE_NEXT_ACK_POLICY: "strict"
```
## Native retention scope [#native-retention-scope]
The store-level limit and retention settings — **Max channels**, **Max channel size**,
**Max messages**, **Message retention**, and **Purge inactive** (see
[Storage & Queues](/configure/reference/storage-queues)) — are enforced by the
**`legacy` engine only**. The `next` storage engine does not consume them: a native Events Store
or Queues channel on `next` has **no age, size, or count cap** and grows unbounded under
a slow or absent consumer. The queue ack-wait timeout governs redelivery of in-flight
messages — it is not a backlog-eviction bound.
On `next`, the only age-evicted channels are **Kafka topic channels**, via the Kafka
connector's `retention.ms` (see
[Durability & Retention](/connectors/kafka/concepts/durability-and-retention#retention-time-and-size)).
Size native Events Store / Queues workloads on `next` by disk capacity, or use Kafka
topic channels where age eviction matters.
**This now applies to new clusters by default.** Because a clean store resolves to `next`,
a freshly installed cluster has **no age, size, or count cap** on native Events Store and
Queues channels unless you set one — the `store.max*` limits are `legacy`-only. Size by
disk, and set a `spec.volume.size` you can live with.
## Support & deprecation [#support--deprecation]
Both engines are **fully supported today**. `legacy` is **feature-frozen** — it receives
maintenance, security, and bug fixes only. `next` receives all new durability and
compaction features going forward. The deprecation policy for `legacy` is **explicitly
TBD** — no sunset date has been set, and both engines are supported until one is.
## Compaction [#compaction]
Kafka log compaction is **`next`-only**. The Kafka connector's `cleanup.policy` accepts
`delete` (default), `compact`, or `compact,delete`. Compaction keeps only the latest
record per key and reaps tombstones after `delete.retention.ms` (default 24h) — it never
renumbers surviving offsets. Compaction is scoped to Kafka topic channels only; native
Queues and Events Store channels never compact. This is the feature that unlocks Kafka
Connect (its internal topics require compaction) and Kafka Streams changelogs.
## Clustered replication on the next storage engine [#clustered-replication-on-the-next-storage-engine]
The `Cluster.Replication.*` block configures the `next` storage engine's Dragonboat replication
listener — a second membership plane a `next`-mode cluster runs alongside the cluster
mesh. It is meaningful **only** when `Store.Engine` is `next` **and** `Cluster.Enable` is
`true`. This block is Docker / `config.yaml` and env-only — there is **no Helm/CRD path**.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| -------------------- | ------ | ------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Replica ID | uint64 | `0` | ≥ 0 | `cluster.replication.replicaid` · `CLUSTER_REPLICATION_REPLICA_ID` | — | This node's Dragonboat replica id (1..N); must be a key in `Peers`. May be left `0` when `POD_NAME` is present — see [ReplicaID auto-derive](#replicaid-auto-derive). |
| Raft address | string | `""` | `host:port` | `cluster.replication.raftaddress` · `CLUSTER_REPLICATION_RAFT_ADDRESS` | — | This node's **advertised** raft address. When set it wins over the address derived from `Peers` for what this node announces to its peers — set it when the address peers must dial differs from the one this node binds. |
| Peers | string | `""` | `id@host:port,...` | `cluster.replication.peers` · `CLUSTER_REPLICATION_PEERS` | — | Full initial-members map — every initial member, including self. Byte-identical on every pod. |
| Join | bool | `false` | true / false | `cluster.replication.join` · `CLUSTER_REPLICATION_JOIN` | — | Boot as a later-added replica, with an empty members map. |
| RTT (ms) | uint64 | `200` | ≥ 0 | `cluster.replication.rttmillisecond` · `CLUSTER_REPLICATION_RTT_MILLISECOND` | — | Dragonboat logical-clock tick, in milliseconds. |
| Election RTT | uint64 | `10` | ≥ 0 | `cluster.replication.electionrtt` · `CLUSTER_REPLICATION_ELECTION_RTT` | — | Must be greater than `2 × HeartbeatRTT`. |
| Heartbeat RTT | uint64 | `1` | ≥ 0 | `cluster.replication.heartbeatrtt` · `CLUSTER_REPLICATION_HEARTBEAT_RTT` | — | |
| Snapshot entries | uint64 | `10000` | ≥ 0 | `cluster.replication.snapshotentries` · `CLUSTER_REPLICATION_SNAPSHOT_ENTRIES` | — | Committed entries between automatic snapshots. |
| Compaction overhead | uint64 | `2000` | ≥ 0 | `cluster.replication.compactionoverhead` · `CLUSTER_REPLICATION_COMPACTION_OVERHEAD` | — | Log entries retained past a snapshot. |
| Boot timeout (s) | int | `60` | ≥ 0 | `cluster.replication.boottimeoutseconds` · `CLUSTER_REPLICATION_BOOT_TIMEOUT_SECONDS` | — | Clustered-boot readiness-probe budget, in seconds. |
| Mutual TLS | bool | `false` | true / false | `cluster.replication.mutualtls` · `CLUSTER_REPLICATION_MUTUAL_TLS` | — | Optional mTLS trust domain. Default **off** (plaintext) — see the security callout below. |
| CA / Cert / Key file | string | `""` | file path | `cluster.replication.cafile` / `cluster.replication.certfile` / `cluster.replication.keyfile` · `CLUSTER_REPLICATION_CA_FILE` / `CLUSTER_REPLICATION_CERT_FILE` / `CLUSTER_REPLICATION_KEY_FILE` | — | A **dedicated** trust domain — not reused from `Security`. Required (fail-closed) when `Mutual TLS` is `true`. |
When **Mutual TLS** is left at its default `false`, a clustered `next` node's Dragonboat
replication listener runs an **unauthenticated, FSM-writing raft port**. This is
acceptable only on a trusted pod network, bounded by a `NetworkPolicy` — never expose this
listener beyond the cluster's own pod network.
## ReplicaID auto-derive [#replicaid-auto-derive]
On a `next`-engine cluster with clustering enabled, `Peers` set, `Replica ID` left at `0`,
and `POD_NAME` present in the environment, the server derives
`ReplicaID = ordinal(POD_NAME) + 1` — the integer after the last `-` in the pod name, plus
one (StatefulSet ordinals are 0-based, so replica ids run `1..N`).
* An **explicit non-zero** `Replica ID` always wins — the derive path is skipped.
* An **unparseable** `POD_NAME` (no `-` suffix) fails closed.
* The operator obligation: the host at id `ordinal + 1` in `Peers` must be the DNS name
of the pod at that ordinal — a mismatch is a DNS-time failure (the cluster boots but
never forms quorum), not a config-validation error.
This lets `Peers` be byte-identical across every pod in a StatefulSet, with no per-pod
templating required.
## Kubernetes [#kubernetes]
On Kubernetes, the persistence engine is established once, at cluster creation, by the
operator's engine-establishment guard — it is never changed for a live cluster. See
[Deployment & High Availability](/configure/reference/deployment) for the operator-side
behavior.
## Example [#example]
Set the persistence engine on each target. This is a single-setting snippet — see the
[Docker guide](/configure/docker) and the
[Kubernetes guide](/configure/kubernetes) for complete, runnable configurations.
```yaml title="config.yaml"
store:
engine: next
```
```yaml title="cluster-values.yaml"
store:
engine: next
```
## See Also [#see-also]
# Storage & Queues (/configure/reference/storage-queues)
KubeMQ persists messages through an embedded **persistent store** and serves pull-based
delivery through its **queues**. The store controls how much is retained and for how long;
the queue settings control visibility, wait, delay, expiration, and retry behavior. Each
setting is shown for both deployment targets — Docker single-node (`config.yaml` key · env
var) and Kubernetes/Helm (`spec.*` path). A dash (`—`) in the Helm/CRD column means the
setting is not available on that surface.
Store and queue tuning is **opt-out**: the `store` and `queue` blocks are internal
server sections (not wire connectors), so they are always active with the defaults below —
there is no `enable`/`disabled` toggle. Override only the fields you need.
## Persistent store [#persistent-store]
Limits and retention for the persistent store. The **persistence engine** is chosen once
at cluster creation — see [Storage Engines](/configure/reference/storage-engines) for
the full engine model, durability guarantees, and clustering. Several store fields carry
**name divergences** between the Docker `config.yaml` key and the Helm/CRD field — the
Notes column flags each one. The ten fields below are all CRD-settable under
`spec.store.*`; the store config carries **five more** — the `next`-engine settings
(`nextackpolicy`, `nextraftaddress`, `nextsegmentsize`, `nextshards`,
`nextbalanceleaders`), which are `config.yaml`/env-only and documented on
[Storage Engines](/configure/reference/storage-engines#next-storage-engine-settings).
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| ------------------------ | ------ | ------------------------------------------------------------ | ---------------------------- | -------------------------------------------------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Persistence engine | string | *unset* → resolved from the store directory (clean ⇒ `next`) | `legacy` \| `next` \| `auto` | `store.engine` · `STORE_ENGINE` | `spec.store.engine` (typed CRD enum) | Chosen **once, at cluster creation** — a cluster is born one mode and stays there; no in-place migration. **Unset (or the explicit `auto`) does not mean `legacy`:** the server probes the store directory and resolves the engine that wrote it, or `next` for a clean one. To get `legacy` you must name it. See [Zero-config engine selection](/configure/reference/storage-engines#zero-config-engine-selection). |
| Clean store on start | bool | `false` | true / false | `store.cleanstore` · `STORE_CLEAN_STORE` | `spec.store.clean` | ⚠️ **Destructive — wipes the store on every boot.** See the warning below. Name divergence: `cleanstore` ↔ `clean`. CRD emits `STORE_CLEAN_STORE=true` only when `clean: true`; otherwise unset. |
| Store path | string | `./store` | non-empty file path | `store.storepath` · `STORE_STORE_PATH` | `spec.store.path` | Name divergence: `storepath` ↔ `path`. Empty string is rejected. **On the `legacy` engine, absolute paths are rewritten to relative:** a leading `/` is prefixed with `.` (so `/data` becomes `./data`). **On the `next` storage engine, an absolute `StorePath` is honored verbatim** (e.g. a mounted PVC path like `/store`) — no rewrite. This is server-process behavior; on Kubernetes the operator supplies the mount and rejects a leading `/` in `spec.store.path` outright (see [Deployment](/configure/reference/deployment)) — the two layers aren't in conflict. |
| Max channels | int | `0` (∞) | ≥ 0; `0` = unlimited | `store.maxqueues` · `STORE_MAX_QUEUES` | `spec.store.maxChannels` | **Name divergence:** `store.maxqueues` ↔ `spec.store.maxChannels`. Negative rejected. `0` logs a stderr WARNING (unbounded). |
| Max channel size (bytes) | int64 | `0` (∞) | ≥ 0; `0` = unlimited | `store.maxqueuesize` · `STORE_MAX_QUEUE_SIZE` | `spec.store.maxChannelSize` | **Name divergence:** `store.maxqueuesize` ↔ `spec.store.maxChannelSize`. **Type divergence:** server field is `int64`; the CRD field is `*int32`, so via Helm the max is \~2.1 GB — set larger caps through `config.yaml`/env. `0` logs a stderr WARNING. |
| Max messages / channel | int | `0` (∞) | ≥ 0; `0` = unlimited | `store.maxmessages` · `STORE_MAX_MESSAGES` | `spec.store.maxMessages` | Negative rejected. `0` logs a stderr WARNING. |
| Max subscribers | int | `0` (∞) | ≥ 0; `0` = unlimited | `store.maxsubscribers` · `STORE_MAX_SUBSCRIBERS` | `spec.store.maxSubscribers` | Negative rejected. `0` logs a stderr WARNING. |
| Message retention (min) | int | `1440` | ≥ 0 (minutes) | `store.maxretention` · `STORE_MAX_RETENTION` | `spec.store.messagesRetentionMinutes` | **Name divergence:** `store.maxretention` ↔ `spec.store.messagesRetentionMinutes`. Negative rejected. |
| Purge inactive (min) | int | `1440` | ≥ 0 (minutes) | `store.maxpurgeinactive` · `STORE_MAX_PURGE_INACTIVE` | `spec.store.purgeInactiveMinutes` | **Name divergence:** `store.maxpurgeinactive` ↔ `spec.store.purgeInactiveMinutes`. Negative rejected. |
| Idle prune cutoff (hrs) | int | `24` | ≥ 1 | `store.idleprunecutoffhours` · `STORE_IDLE_PRUNE_CUTOFF_HOURS` | `spec.store.idlePruneCutoffHours` | Must be **at least 1** (server rejects `0`; CRD schema enforces `minimum: 1`). |
**`store.cleanstore: true` deletes the persistent store on every single boot — not once.**
It is not a one-shot reset. Left in a `cluster-values.yaml` or a `config.yaml`, every pod roll,
node drain, crash-restart, and routine upgrade wipes production data — **and every restart
looks completely healthy**, because deleting the store is exactly what you asked for.
Use it for a deliberate, supervised reset and **take it back out immediately**. There is
no confirmation, no dry-run, and no undo.
Two things bound the damage, neither of which is a safety net you should rely on: the
engine-mode guard runs **before** the wipe, so a mode-mismatched or unrecognized directory
fails fast and is never deleted; and on a clustered `next` cluster the server **refuses**
to wipe a member's datadir outright, telling you to remove the member from the cluster
first. A standalone node has neither protection.
Leaving any of **Max channels / Max channel size / Max messages / Max subscribers** at
its default of `0` means *unlimited* and prints a startup WARNING to stderr — the store
places no bound on that dimension, which can drive unbounded memory/disk use in
production. Set explicit ceilings for production workloads.
**These limits are enforced by the `legacy` engine only — and `next` is what a new
cluster gets.** A fresh install on a clean store resolves to `next`, so **the default
deployment enforces no retention at all**, including the `1440`-minute Message retention
and Purge inactive values printed in the table above. Those two rows describe `legacy`.
On the `next` storage engine, **Max channels / Max channel size / Max messages / Message retention
/ Purge inactive** are not consumed — a native Events Store or Queues channel has no age, size, or
count cap and grows unbounded under a slow or absent consumer. Size `next` deployments by
disk capacity, or use Kafka topic channels (whose `retention.ms` *is* age-enforced on
`next`) where eviction matters. See
[Storage Engines](/configure/reference/storage-engines#native-retention-scope).
## Queues [#queues]
Delivery defaults and ceilings for pull-based queues. Two Docker keys diverge from the
Helm/CRD field names — `queue.maxreceivecount` ↔ `spec.queue.maxReQueues` (the retry
ceiling) and `queue.maxnumberofmessages` ↔ `spec.queue.maxReceiveMessagesRequest` (the
per-request batch). All ten queue fields are fully CRD-settable under `spec.queue.*`.
| Setting | Type | Default | Valid values | Docker (config.yaml key · env var) | Helm/CRD path | Notes |
| -------------------------- | ----- | ------- | ------------ | ------------------------------------------------------------------------ | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Default visibility (s) | int32 | `60` | > 0 | `queue.defaultvisibilityseconds` · `QUEUE_DEFAULT_VISIBILITY_SECONDS` | `spec.queue.defaultVisibilitySeconds` | |
| Default wait timeout (s) | int32 | `1` | > 0 | `queue.defaultwaittimeoutseconds` · `QUEUE_DEFAULT_WAIT_TIMEOUT_SECONDS` | `spec.queue.defaultWaitTimeoutSeconds` | |
| Max visibility (s) | int32 | `43200` | > 0 | `queue.maxvisibilityseconds` · `QUEUE_MAX_VISIBILITY_SECONDS` | `spec.queue.maxVisibilitySeconds` | 43200 s = 12 h. |
| Max wait timeout (s) | int32 | `3600` | > 0 | `queue.maxwaittimeoutseconds` · `QUEUE_MAX_WAIT_TIMEOUT_SECONDS` | `spec.queue.maxWaitTimeoutSeconds` | |
| Max delay (s) | int32 | `43200` | > 0 | `queue.maxdelayseconds` · `QUEUE_MAX_DELAY_SECONDS` | `spec.queue.maxDelaySeconds` | 43200 s = 12 h. |
| Max expiration (s) | int32 | `43200` | > 0 | `queue.maxexpirationseconds` · `QUEUE_MAX_EXPIRATION_SECONDS` | `spec.queue.maxExpirationSeconds` | 43200 s = 12 h. |
| Retry ceiling (→ DLQ) | int32 | `1024` | > 0 | `queue.maxreceivecount` · `QUEUE_MAX_RECEIVE_COUNT` | `spec.queue.maxReQueues` | **Name divergence:** `queue.maxreceivecount` ↔ `spec.queue.maxReQueues`. Max redeliveries before dead-lettering. |
| Max messages / receive req | int32 | `1024` | > 0 | `queue.maxnumberofmessages` · `QUEUE_MAX_NUMBER_OF_MESSAGES` | `spec.queue.maxReceiveMessagesRequest` | **Name divergence:** `queue.maxnumberofmessages` ↔ `spec.queue.maxReceiveMessagesRequest`. Per-request batch ceiling. |
| Max inflight | int32 | `2048` | > 0 | `queue.maxinflight` · `QUEUE_MAX_INFLIGHT` | `spec.queue.maxInflight` | Max unacked in-flight messages per queue. |
| Pub-ack wait (s) | int32 | `60` | > 0 | `queue.pubackwaitseconds` · `QUEUE_PUB_ACK_WAIT_SECONDS` | `spec.queue.pubAckWaitSeconds` | Publish-ack wait before the send is considered failed. |
**Every queue field must be greater than `0` — the server rejects `0` at startup.** The
CRD schema already enforces this with `minimum: 1` on all ten queue fields, so a Helm
value of `0` is rejected by the API server *and* would fail server validation. Treat the
effective minimum for every queue setting as **`1`**.
## Example [#example]
Set message retention on each target. This is a single-setting snippet — see the
[Docker guide](/configure/docker) and the
[Kubernetes guide](/configure/kubernetes) for complete, runnable configurations.
```yaml title="config.yaml"
store:
maxretention: 1440
```
```yaml title="cluster-values.yaml"
store:
messagesRetentionMinutes: 1440
```
For the full Docker delivery methods (env vars, mounted `config.yaml`, the `CONFIG`
variable) see the [Docker guide](/configure/docker); for `cluster-values.yaml` mapped to
the `KubemqCluster` spec see the [Kubernetes guide](/configure/kubernetes).
# AMQP 1.0 (/connectors/amqp)
Point your AMQP 1.0 application at KubeMQ by changing only the connection string and
node address. The **AMQP 1.0 connector** is a built-in, wire-protocol bridge inside
kubemq-server that speaks the OASIS AMQP 1.0 dialect natively — any standard AMQP 1.0
client (Qpid, go-amqp, AMQPNetLite, rhea) talks to KubeMQ's Queues, Events,
Events-Store, Commands, and Queries with no KubeMQ SDK, no library swap, and no code
rewrite.
## What is the AMQP 1.0 connector [#what-is-the-amqp-10-connector]
The AMQP 1.0 connector exposes [AMQP 1.0](https://www.amqp.org/) (OASIS / ISO-IEC 19464)
natively over a dedicated port for **all five KubeMQ messaging patterns**. The leading
segment of the address a client attaches to selects the pattern: attaching to
`queues/orders` binds to a KubeMQ Queue, `events/telemetry` to Events, and so on. The
connector is a *gateway*, not a client library — your application only needs a stock
AMQP 1.0 client.
AMQP 1.0 is a peer-to-peer [link](/connectors/amqp/concepts/architecture#connection--session--link)
protocol, distinct from the AMQP 0-9-1 dialect the [RabbitMQ connector](/connectors/rabbitmq)
speaks: a link attaches to a *node* (an address), flow is governed by *credit*, and
delivery is resolved by a *delivery state* (accepted / released / modified / rejected) —
there are no exchanges, bindings, routing keys, or publisher-confirms. See
[Architecture](/connectors/amqp/concepts/architecture) for the full model, or
[Migrating from ActiveMQ](/connectors/how-to/migration/from-activemq) if you're
coming from 0-9-1.
Key capabilities:
* **All five patterns over one wire** — Queues, Events, Events-Store, Commands, and
Queries, selected by the address prefix.
* **Address-driven pattern routing** — `queues/`, `events/`, `events-store/`,
`commands/`, `queries/` prefixes map a link to a KubeMQ pattern by longest-prefix
match.
* **Native settlement and credit** — at-least-once (unsettled) or at-most-once
(pre-settled) delivery, credit-driven flow control, and the standard AMQP dispositions.
* **Cross-protocol interop** — a message sent over AMQP 1.0 to `queues/orders` is
consumable by a gRPC or REST KubeMQ client on the same channel, and vice-versa.
**Opt-in — disabled by default.** A stock kubemq-server already binds port `5672` (and `5671`
under TLS) for the RabbitMQ / AMQP 0-9-1 connector, which is on by default — but AMQP 1.0
dispatch on that port stays off until you turn this connector on with
`CONNECTORS_AMQP10_ENABLE=true` (Docker) or `spec.amqp10.enabled: true` (Kubernetes). Until
then an AMQP 1.0 client connects at the TCP level and is then closed during protocol
negotiation. See
[Getting started](/connectors/amqp/tutorials/getting-started).
## How it works [#how-it-works]
An AMQP 1.0 client connects to the connector and attaches a link to a node address. The
connector resolves the address to a KubeMQ `(pattern, channel)` pair, hands the message to
the message broker, and consumers on the same channel — over AMQP 1.0 or any other KubeMQ
transport — receive it.
*The shared `amqpmux` front door classifies the connection by its 8-byte protocol header and dispatches it to the AMQP 1.0 engine, which maps the node address onto a KubeMQ pattern and channel.*
## Ports & protocol surface [#ports--protocol-surface]
| Port | Transport | Protocol | Notes |
| ------ | ---------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `5672` | Plain TCP (SASL ANONYMOUS / PLAIN) | AMQP 1.0 (OASIS / ISO-IEC 19464) | Default plain listener. **Shared with the RabbitMQ (AMQP 0-9-1) connector** via the internal `amqpmux`; bound out of the box because 0-9-1 is on by default. |
| `5671` | TLS over TCP | AMQP 1.0 | Binds only when the server-global `Security` block is configured. Shared TLS listener with AMQP 0-9-1. |
A single `amqpmux` listener accepts every connection on `5672`/`5671`, reads the 8-byte
AMQP protocol header, and routes it to the matching dialect engine — so AMQP 1.0 and
AMQP 0-9-1 coexist on the same ports. Because the 0-9-1 connector is on by default, the port
is open on a stock server even when AMQP 1.0 is not enabled; an AMQP 1.0 header then has no
engine to route to and the mux closes the connection. There is **no vhost**: the OPEN `hostname` field is
accepted and ignored. See [Architecture](/connectors/amqp/concepts/architecture) for the
dispatch detail.
## Send a message [#send-a-message]
The example below produces one message to `queues/` over a stock AMQP 1.0 client.
Each send is unsettled (at-least-once): it blocks until the connector returns an `accepted`
disposition, confirming the broker stored the message. Every client reads the broker
endpoint from `KUBEMQ_AMQP_URL` (default `amqp://localhost:5672`).
```go
package main
import (
"context"
"fmt"
"log"
"os"
"time"
amqp "github.com/Azure/go-amqp"
)
func amqpURL() string {
if v := os.Getenv("KUBEMQ_AMQP_URL"); v != "" {
return v
}
return "amqp://localhost:5672"
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
addr := "queues/amqp10.examples.basic"
// OPEN: SASL ANONYMOUS by default (no userinfo in the URL).
conn, err := amqp.Dial(ctx, amqpURL(), nil)
if err != nil {
log.Fatalf("dial: %v", err)
}
defer func() { _ = conn.Close() }()
session, err := conn.NewSession(ctx, nil)
if err != nil {
log.Fatalf("new session: %v", err)
}
// ATTACH a sender (server-receiver link) and send one unsettled message.
sender, err := session.NewSender(ctx, addr, nil)
if err != nil {
log.Fatalf("new sender: %v", err)
}
if err := sender.Send(ctx, amqp.NewMessage([]byte("hello from AMQP 1.0")), nil); err != nil {
log.Fatalf("send: %v", err)
}
_ = sender.Close(ctx)
fmt.Printf("sent 1 message to %s (accepted)\n", addr)
}
```
```python
import os
from proton import Message
from proton.utils import BlockingConnection
def amqp_url() -> str:
return os.environ.get("KUBEMQ_AMQP_URL", "amqp://localhost:5672")
def main() -> None:
addr = "queues/amqp10.examples.basic"
# OPEN: SASL ANONYMOUS by default (no userinfo in the URL).
conn = BlockingConnection(amqp_url())
try:
# ATTACH a sender; each send blocks for the accepted disposition.
sender = conn.create_sender(addr)
sender.send(Message(body="hello from AMQP 1.0"))
sender.close()
print(f"sent 1 message to {addr} (accepted)")
finally:
conn.close()
if __name__ == "__main__":
main()
```
```java
import javax.jms.Connection;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.qpid.jms.JmsConnectionFactory;
public final class Main {
public static void main(String[] args) throws Exception {
String url = System.getenv().getOrDefault("KUBEMQ_AMQP_URL", "amqp://localhost:5672");
String address = "queues/amqp10.examples.basic";
// OPEN: SASL ANONYMOUS by default. The JMS destination name IS the
// connector node address.
JmsConnectionFactory factory = new JmsConnectionFactory(url);
try (Connection connection = factory.createConnection()) {
connection.start();
try (Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE)) {
Queue queue = session.createQueue(address);
try (MessageProducer producer = session.createProducer(queue)) {
TextMessage msg = session.createTextMessage("hello from AMQP 1.0");
producer.send(msg); // blocks until the accepted DISPOSITION
}
System.out.printf("sent 1 message to %s (accepted)%n", address);
}
}
}
}
```
```csharp
using System.Text;
using Amqp;
using Amqp.Framing;
static string AmqpUrl() =>
Environment.GetEnvironmentVariable("KUBEMQ_AMQP_URL") is { Length: > 0 } v
? v
: "amqp://localhost:5672";
var addr = "queues/amqp10.examples.basic";
// OPEN: SASL ANONYMOUS by default (no userinfo in the URL).
var connection = await Connection.Factory.CreateAsync(new Address(AmqpUrl()));
try
{
var session = new Session(connection);
// ATTACH a sender (server-receiver link) and send one unsettled message.
var sender = new SenderLink(session, "basic-sender", addr);
var message = new Message
{
BodySection = new Data { Binary = Encoding.UTF8.GetBytes("hello from AMQP 1.0") },
};
sender.Send(message, TimeSpan.FromSeconds(15)); // blocks for the accepted DISPOSITION
await sender.CloseAsync();
await session.CloseAsync();
Console.WriteLine($"sent 1 message to {addr} (accepted)");
}
finally
{
await connection.CloseAsync();
}
```
```typescript
import { Connection, type ConnectionOptions } from "rhea-promise";
function connectionOptions(): ConnectionOptions {
const url = new URL(process.env["KUBEMQ_AMQP_URL"] ?? "amqp://localhost:5672");
return {
host: url.hostname,
port: url.port ? Number(url.port) : 5672,
// The connector requires a non-empty container-id; rhea sends one by default.
container_id: `kubemq-amqp10-js-${process.pid}`,
reconnect: false,
};
}
async function main(): Promise {
const address = "queues/amqp10.examples.basic";
// OPEN: SASL ANONYMOUS by default (no username/password).
const connection = new Connection(connectionOptions());
await connection.open();
try {
// Attach an AwaitableSender; send() resolves on the accepted disposition.
const sender = await connection.createAwaitableSender({ target: { address } });
await sender.send({ body: "hello from AMQP 1.0" }, { timeoutInSeconds: 15 });
await sender.close();
console.log(`sent 1 message to ${address} (accepted)`);
} finally {
await connection.close();
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
```
```rust
use fe2o3_amqp::{Connection, Sender, Session};
use fe2o3_amqp_types::definitions::SenderSettleMode;
fn amqp_url() -> String {
std::env::var("KUBEMQ_AMQP_URL").unwrap_or_else(|_| "amqp://localhost:5672".to_string())
}
#[tokio::main]
async fn main() -> Result<(), Box> {
let addr = "queues/amqp10.examples.basic";
// OPEN: SASL ANONYMOUS by default; a non-empty container-id is required.
let mut connection = Connection::open("kubemq-amqp10-rust", amqp_url().as_str()).await?;
let mut session = Session::begin(&mut connection).await?;
// ATTACH a sender pinned to Unsettled (at-least-once); the connector
// rejects the AMQP default `mixed`.
let mut sender = Sender::builder()
.name("basic-sender")
.target(addr)
.sender_settle_mode(SenderSettleMode::Unsettled)
.attach(&mut session)
.await?;
let outcome = sender.send("hello from AMQP 1.0").await?;
if !outcome.is_accepted() {
return Err(format!("unexpected outcome {outcome:?}").into());
}
sender.close().await?;
println!("sent 1 message to {addr} (accepted)");
session.end().await?;
connection.close().await?;
Ok(())
}
```
## Supported languages [#supported-languages]
The connector speaks standard AMQP 1.0, so any conformant client works. The examples
pin one native AMQP 1.0 client per language — there is no KubeMQ SDK, no proto bindings,
and no published package.
| Language | Client library | Notes |
| ----------------------- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| Go | [`github.com/Azure/go-amqp`](https://github.com/Azure/go-amqp) | The connector's reference client. |
| Python | [`python-qpid-proton`](https://qpid.apache.org/proton/) | Sync `BlockingConnection`. |
| Java | [`org.apache.qpid:qpid-jms-client`](https://qpid.apache.org/components/jms/) | Qpid JMS 2.x (`jakarta.jms`) or 1.x (`javax.jms`). |
| C# / .NET | [`AMQPNetLite.Core`](https://github.com/Azure/amqpnetlite) | Task-based async. |
| JavaScript / TypeScript | [`rhea`](https://github.com/amqp/rhea) + [`rhea-promise`](https://github.com/amqp/rhea-promise) | Event-driven, promise-wrapped. |
| Rust | [`fe2o3-amqp`](https://github.com/minghuaw/fe2o3-amqp) | async/await on Tokio. |
Apache Qpid JMS (Java) cannot drive the anonymous-terminus link — it has no API to force
a raw null-target link, and the connector advertises no `ANONYMOUS-RELAY` capability. Use
per-pattern senders instead. See [Address mapping](/connectors/amqp/reference/address-mapping).
## Next steps [#next-steps]
# AWS (SQS & SNS) (/connectors/aws)
Point your AWS SQS / SNS application at KubeMQ by changing only the endpoint URL. The
**AWS connector** is a built-in, wire-protocol bridge inside kubemq-server that speaks the
genuine AWS SQS and SNS HTTP protocols on a dedicated second listener — any standard,
unmodified AWS SDK (boto3, `aws-sdk-go-v2`, the AWS SDK for Java/JS/.NET/Ruby/Rust) talks
to KubeMQ with no LocalStack, no library swap, and no KubeMQ SDK.
## What is the AWS connector [#what-is-the-aws-connector]
The connector is **one binary with two service surfaces** that map onto two distinct
KubeMQ models:
* **SQS → KubeMQ Queue.** Every SQS queue maps onto a native KubeMQ **Queue** channel
`sqs.{name}`. AWS producers and native gRPC/REST consumers share the same messages on
that channel. A FIFO group fans onto its own channel `sqs.{name}.fifo.g.{enc(group)}`.
* **SNS → virtual fan-out.** SNS topics are **virtual** — a registry replicated across
cluster nodes, with no native channel. At publish time a topic fans out to every
confirmed subscription: subscribed SQS queues (a batch send) and HTTP/HTTPS webhooks (a
delivery engine).
Because SQS is point-to-point and SNS is publish/subscribe — neither is request/reply —
there is **no RPC**: no Commands, no Queries, no gRPC responder anywhere. The connector
exposes the queue and fan-out surfaces only.
The AWS connector is **opt-in (disabled by default)** — enabling it opens a **new HTTP
listener on port 4566** that is not bound until you set `CONNECTORS_AWS_ENABLE=true`. Unlike
the other wire-protocol connectors, a stock server does **not** serve AWS until you turn it
on. See [Getting started](/connectors/aws/tutorials/getting-started).
## How it works [#how-it-works]
An AWS SDK client sends a signed SQS or SNS request to the connector's endpoint. The
connector detects the protocol, verifies the SigV4 signature shape, and dispatches: SQS
operations land on the KubeMQ Queue channel `sqs.{name}` through the message broker; SNS
publishes resolve the virtual topic registry and fan out to the subscribed targets.
*SQS requests map onto the KubeMQ Queue channel `sqs.{name}` through the message broker; SNS publishes resolve the virtual topic registry and fan out to subscribed SQS queues and HTTP/HTTPS webhooks.*
## Ports & protocol surface [#ports--protocol-surface]
| Port | Transport | Protocol | Notes |
| ------ | ------------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `4566` | Plain HTTP (SigV4) | AWS SQS JSON + SNS Query | A dedicated second listener (the LocalStack convention). **Bound only when the connector is enabled** (`CONNECTORS_AWS_ENABLE=true`), and must differ from the gRPC/REST/HTTP ports. |
| — | HTTPS | AWS SQS JSON + SNS Query | TLS is provided by the server-wide `Security` block — there is **no AWS-specific TLS option**. SigV4 over plain HTTP is unencrypted on the wire; production deployments should use the HTTPS listener. |
The listener accepts both `POST /` and `GET /` on a single AWS-style endpoint — there are
no per-route REST paths. SQS uses the AWS **JSON protocol** (`X-Amz-Target: AmazonSQS.{Op}`)
with a Query-protocol fallback; SNS uses the AWS **Query protocol** (form body / GET query →
XML). See [Architecture](/connectors/aws/concepts/architecture) for the dispatch detail.
## Send a message [#send-a-message]
The example below runs the full SQS round-trip — `CreateQueue` → `GetQueueUrl` →
`SendMessage` → `ReceiveMessage` → `DeleteMessage` — over a stock AWS SDK. The only change
versus a real-AWS app is the **endpoint override**: each client points at `KUBEMQ_AWS_URL`
(default `http://localhost:4566`). **Dummy credentials are still required** so the SDK forms
a valid SigV4 signature; the connector's default accept-any mode checks the signature shape,
not its value.
```go
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/sqs"
)
func awsURL() string {
if v := os.Getenv("KUBEMQ_AWS_URL"); v != "" {
return v
}
return "http://localhost:4566"
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// Dummy static credentials are required so the SDK forms a valid SigV4
// request; the connector's accept-any mode does not verify their value.
cfg, err := config.LoadDefaultConfig(ctx,
config.WithRegion("us-east-1"),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("test", "test", "")),
)
if err != nil {
log.Fatalf("load config: %v", err)
}
// Override ONLY the endpoint URL — everything else is a normal AWS SDK app.
client := sqs.NewFromConfig(cfg, func(o *sqs.Options) {
o.BaseEndpoint = aws.String(awsURL())
})
// CreateQueue "orders" maps to KubeMQ Queue channel "sqs.orders".
created, err := client.CreateQueue(ctx, &sqs.CreateQueueInput{QueueName: aws.String("orders")})
if err != nil {
log.Fatalf("CreateQueue: %v", err)
}
queueURL := aws.ToString(created.QueueUrl)
if _, err := client.SendMessage(ctx, &sqs.SendMessageInput{
QueueUrl: aws.String(queueURL),
MessageBody: aws.String("hello from the AWS SDK"),
}); err != nil {
log.Fatalf("SendMessage: %v", err)
}
recv, err := client.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
QueueUrl: aws.String(queueURL),
MaxNumberOfMessages: 1,
WaitTimeSeconds: 5,
})
if err != nil || len(recv.Messages) != 1 {
log.Fatalf("ReceiveMessage: %v (got %d)", err, len(recv.Messages))
}
msg := recv.Messages[0]
fmt.Printf("received: %q\n", aws.ToString(msg.Body))
// DeleteMessage acks the message off the queue by its receipt handle.
if _, err := client.DeleteMessage(ctx, &sqs.DeleteMessageInput{
QueueUrl: aws.String(queueURL),
ReceiptHandle: msg.ReceiptHandle,
}); err != nil {
log.Fatalf("DeleteMessage: %v", err)
}
}
```
```python
import os
import boto3
QUEUE = "orders"
def make_sqs():
# Override ONLY the endpoint URL; dummy credentials are still required so
# boto3 forms a valid SigV4 request (accept-any mode checks shape only).
return boto3.client(
"sqs",
endpoint_url=os.environ.get("KUBEMQ_AWS_URL", "http://localhost:4566"),
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)
def main() -> None:
sqs = make_sqs()
# CreateQueue "orders" maps to KubeMQ Queue channel "sqs.orders".
queue_url = sqs.create_queue(QueueName=QUEUE)["QueueUrl"]
sqs.send_message(QueueUrl=queue_url, MessageBody="hello from boto3")
recv = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1, WaitTimeSeconds=5)
msg = recv["Messages"][0]
print(f"received: {msg['Body']!r}")
# DeleteMessage acks the message off the queue by its receipt handle.
sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=msg["ReceiptHandle"])
if __name__ == "__main__":
main()
```
```java
import java.net.URI;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.Message;
public final class Main {
public static void main(String[] args) {
String url = System.getenv().getOrDefault("KUBEMQ_AWS_URL", "http://localhost:4566");
// endpointOverride is the only change versus a real-AWS app; dummy
// credentials are still required to form a valid SigV4 request.
try (SqsClient sqs = SqsClient.builder()
.endpointOverride(URI.create(url))
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test")))
.build()) {
// CreateQueue "orders" maps to KubeMQ Queue channel "sqs.orders".
String queueUrl = sqs.createQueue(b -> b.queueName("orders")).queueUrl();
sqs.sendMessage(b -> b.queueUrl(queueUrl).messageBody("hello from the AWS SDK for Java"));
Message msg = sqs.receiveMessage(b -> b
.queueUrl(queueUrl)
.maxNumberOfMessages(1)
.waitTimeSeconds(5))
.messages().get(0);
System.out.printf("received: %s%n", msg.body());
// DeleteMessage acks the message off the queue by its receipt handle.
sqs.deleteMessage(b -> b.queueUrl(queueUrl).receiptHandle(msg.receiptHandle()));
}
}
}
```
```typescript
import {
SQSClient,
CreateQueueCommand,
SendMessageCommand,
ReceiveMessageCommand,
DeleteMessageCommand,
} from "@aws-sdk/client-sqs";
const QUEUE = "orders";
// Override ONLY the endpoint; dummy credentials are still required so the SDK
// forms a valid SigV4 request (accept-any mode checks the signature shape).
const sqs = new SQSClient({
endpoint: process.env["KUBEMQ_AWS_URL"] ?? "http://localhost:4566",
region: "us-east-1",
credentials: { accessKeyId: "test", secretAccessKey: "test" },
});
async function main(): Promise {
// CreateQueue "orders" maps to KubeMQ Queue channel "sqs.orders".
const created = await sqs.send(new CreateQueueCommand({ QueueName: QUEUE }));
const queueUrl = created.QueueUrl!;
await sqs.send(new SendMessageCommand({ QueueUrl: queueUrl, MessageBody: "hello from the AWS SDK v3" }));
const recv = await sqs.send(
new ReceiveMessageCommand({ QueueUrl: queueUrl, MaxNumberOfMessages: 1, WaitTimeSeconds: 5 }),
);
const msg = recv.Messages![0];
console.log(`received: ${msg.Body}`);
// DeleteMessage acks the message off the queue by its receipt handle.
await sqs.send(new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: msg.ReceiptHandle! }));
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
```
```csharp
using Amazon.Runtime;
using Amazon.SQS;
using Amazon.SQS.Model;
var url = Environment.GetEnvironmentVariable("KUBEMQ_AWS_URL") ?? "http://localhost:4566";
// ServiceURL carries the full http://host:port; dummy credentials are still
// required to form a valid SigV4 request (accept-any mode checks shape only).
var config = new AmazonSQSConfig { ServiceURL = url, AuthenticationRegion = "us-east-1" };
using var sqs = new AmazonSQSClient(new BasicAWSCredentials("test", "test"), config);
const string queueName = "orders";
// CreateQueue "orders" maps to KubeMQ Queue channel "sqs.orders".
var created = await sqs.CreateQueueAsync(new CreateQueueRequest { QueueName = queueName });
var queueUrl = created.QueueUrl;
await sqs.SendMessageAsync(new SendMessageRequest
{
QueueUrl = queueUrl,
MessageBody = "hello from AWSSDK.NET",
});
var recv = await sqs.ReceiveMessageAsync(new ReceiveMessageRequest
{
QueueUrl = queueUrl,
MaxNumberOfMessages = 1,
WaitTimeSeconds = 5,
});
var msg = recv.Messages[0];
Console.WriteLine($"received: {msg.Body}");
// DeleteMessage acks the message off the queue by its receipt handle.
await sqs.DeleteMessageAsync(new DeleteMessageRequest
{
QueueUrl = queueUrl,
ReceiptHandle = msg.ReceiptHandle,
});
```
```ruby
# frozen_string_literal: true
require "aws-sdk-sqs"
# The Ruby SQS plugin rewrites the request endpoint to the full QueueUrl path,
# which the single-endpoint connector rejects — remove it so requests stay on
# the configured base endpoint (as boto3 and aws-sdk-go-v2 do).
Aws::SQS::Client.remove_plugin(Aws::SQS::Plugins::QueueUrls)
url = ENV.fetch("KUBEMQ_AWS_URL", "http://localhost:4566")
# Override ONLY the endpoint; dummy credentials are still required so the SDK
# forms a valid SigV4 request (accept-any mode checks the signature shape).
sqs = Aws::SQS::Client.new(
endpoint: url,
region: "us-east-1",
credentials: Aws::Credentials.new("test", "test")
)
# CreateQueue "orders" maps to KubeMQ Queue channel "sqs.orders".
queue_url = sqs.create_queue(queue_name: "orders").queue_url
sqs.send_message(queue_url: queue_url, message_body: "hello from aws-sdk-ruby")
recv = sqs.receive_message(queue_url: queue_url, max_number_of_messages: 1, wait_time_seconds: 5)
msg = recv.messages.first
puts "received: #{msg.body.inspect}"
# DeleteMessage acks the message off the queue by its receipt handle.
sqs.delete_message(queue_url: queue_url, receipt_handle: msg.receipt_handle)
```
```rust
use aws_config::BehaviorVersion;
use aws_sdk_sqs::config::Credentials;
use aws_sdk_sqs::config::Region;
use std::error::Error;
fn aws_url() -> String {
std::env::var("KUBEMQ_AWS_URL").unwrap_or_else(|_| "http://localhost:4566".to_string())
}
#[tokio::main]
async fn main() -> Result<(), Box> {
// Override ONLY the endpoint; dummy credentials are still required so the
// SDK forms a valid SigV4 request (accept-any mode checks shape only).
let creds = Credentials::new("test", "test", None, None, "kubemq-aws");
let conf = aws_config::defaults(BehaviorVersion::latest())
.region(Region::new("us-east-1"))
.credentials_provider(creds)
.endpoint_url(aws_url())
.load()
.await;
let sqs = aws_sdk_sqs::Client::new(&conf);
// CreateQueue "orders" maps to KubeMQ Queue channel "sqs.orders".
sqs.create_queue().queue_name("orders").send().await?;
let url = sqs
.get_queue_url()
.queue_name("orders")
.send()
.await?
.queue_url
.ok_or("GetQueueUrl returned no URL")?;
sqs.send_message()
.queue_url(&url)
.message_body("hello from aws-sdk-rust")
.send()
.await?;
let received = sqs
.receive_message()
.queue_url(&url)
.max_number_of_messages(1)
.wait_time_seconds(5)
.send()
.await?;
let msg = &received.messages()[0];
println!("received: {}", msg.body().unwrap_or_default());
// DeleteMessage acks the message off the queue by its receipt handle.
let handle = msg.receipt_handle().ok_or("no receipt handle")?;
sqs.delete_message().queue_url(&url).receipt_handle(handle).send().await?;
Ok(())
}
```
## Supported languages [#supported-languages]
The connector speaks the genuine AWS SQS and SNS wire protocols, so any standard AWS SDK
works — you only override the endpoint URL. There is no KubeMQ SDK, no proto bindings, and
no published package; the examples pin one native AWS SDK per language.
| Language | AWS SDK / client library | Endpoint override |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| Go | [`aws-sdk-go-v2`](https://github.com/aws/aws-sdk-go-v2) (`service/sqs`, `service/sns`) | `config.WithBaseEndpoint` / `o.BaseEndpoint` |
| Python | [`boto3`](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) (`client('sqs')`, `client('sns')`) | `endpoint_url=` per client |
| Java | [AWS SDK for Java v2](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/home.html) (`sqs`, `sns`) | `.endpointOverride(URI.create(...))` |
| JavaScript / TypeScript | [AWS SDK v3](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html) (`@aws-sdk/client-sqs`, `@aws-sdk/client-sns`) | `{ endpoint }` |
| C# / .NET | [AWS SDK for .NET](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/welcome.html) (`AWSSDK.SQS`, `AWSSDK.SimpleNotificationService`) | `ServiceURL` |
| Ruby | [AWS SDK for Ruby v3](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/welcome.html) (`aws-sdk-sqs`, `aws-sdk-sns`) | `endpoint:` per client |
| Rust | [AWS SDK for Rust](https://docs.aws.amazon.com/sdk-for-rust/latest/dg/welcome.html) (`aws-sdk-sqs`, `aws-sdk-sns`) | `.endpoint_url(...)` |
Only `aws-sdk-go-v2` is proven by the KubeMQ server's integration tests; the other six SDKs
are wire-compatible and the connector's example suite is their proof. The Ruby SQS client
needs its `QueueUrls` plugin removed (shown above) so requests stay on the configured base
endpoint. See [Connections endpoint](/connectors/aws/reference/connections-endpoint).
## Next steps [#next-steps]
# CloudEvents (/connectors/cloudevents)
The **CloudEvents (CE) connector** is a built-in protocol gateway in kubemq-server
that speaks the [CNCF CloudEvents](https://cloudevents.io/) specification over HTTP.
It lets any HTTP client publish and subscribe to KubeMQ using a standard, interoperable
event envelope — no KubeMQ SDK required.
## What is the CloudEvents connector [#what-is-the-cloudevents-connector]
[CloudEvents](https://cloudevents.io/) is a CNCF specification that describes event
metadata in a common format: a standard envelope of `specversion`, `type`, `source`,
`id`, `subject`, `time`, `data`, and extensions that travels consistently across
platforms and languages.
The CE connector exposes this format natively over HTTP for **all five KubeMQ
messaging patterns** — Events, Events Store, Queues, Commands, and Queries. A
CloudEvent posted to `/ce/send/event` becomes a native KubeMQ message; a message
delivered over Server-Sent Events (SSE) is reconstructed back into a CloudEvent. The
connector is a *gateway*, not a client library — your application only needs an HTTP
client (and, optionally, a CloudEvents SDK to build the envelope for you).
Key capabilities:
* **All messaging patterns** — pub/sub events, persistent events store, durable
queues, and request/reply commands and queries, all over CloudEvents HTTP.
* **Structured and binary content modes** — send the whole event as a JSON body
(`application/cloudevents+json`) or carry attributes in `ce-*` HTTP headers; the
connector detects either automatically.
* **CESQL attribute routing** — route events to channels using CloudEvents SQL
expressions evaluated server-side against event attributes.
* **SSE subscriptions with replay** — subscribe to a long-lived event stream and
resume an events-store subscription from a chosen position using `Last-Event-ID`.
The CE connector runs on the **shared HTTP server (port 9090)** alongside the REST,
MCP, and A2A connectors and is **enabled by default** — start kubemq-server and
`/ce/*` is live. See [Shared HTTP server](/connectors/concepts/shared-http-server) for the
port, middleware chain, and the disable model.
## How it works [#how-it-works]
A CloudEvents client sends events to the CE connector, which maps them into native
KubeMQ messages and hands them to the broker; subscribers receive the same events
back as CloudEvents over SSE.
*The CloudEvents connector translates CloudEvents HTTP requests into native KubeMQ messages and streams them back to subscribers over SSE.*
## Endpoint surface [#endpoint-surface]
| Endpoint | Method | Pattern |
| ---------------------------- | --------- | ------------------------------------------------------ |
| `/ce/send/event` | POST | Events (fire-and-forget pub/sub) |
| `/ce/send/event-store` | POST | Events Store (persistent, replayable) |
| `/ce/send/command` | POST | Command request |
| `/ce/send/query` | POST | Query request |
| `/ce/send/response` | POST | Response to a command/query (`?request_id=`) |
| `/ce/queue/send` | POST | Queue send |
| `/ce/queue/receive` | POST | Queue receive (control op) |
| `/ce/queue/ack_all` | POST | Queue ack-all (control op) |
| `/ce/subscribe/events` | GET (SSE) | Subscribe to events |
| `/ce/subscribe/events-store` | GET (SSE) | Subscribe to events store (replay via `Last-Event-ID`) |
| `/ce/subscribe/commands` | GET (SSE) | Subscribe to commands |
| `/ce/subscribe/queries` | GET (SSE) | Subscribe to queries |
Every send endpoint accepts a CloudEvent in either structured or binary content mode.
Channels resolve from the CloudEvent `subject` attribute, falling back to a `?channel=`
query parameter. See [CE ↔ KubeMQ mapping](/connectors/cloudevents/reference/ce-to-kubemq-mapping)
for the full attribute table and resolution rules.
## Send a CloudEvent [#send-a-cloudevent]
Publish a fire-and-forget event with `POST /ce/send/event`. The example below sends a
structured-mode CloudEvent whose `subject` (`notifications`) becomes the KubeMQ
channel. A successful send returns HTTP 202 with `is_error: false`.
```bash
curl -X POST http://localhost:9090/ce/send/event \
-H "Content-Type: application/cloudevents+json" \
-d '{
"specversion": "1.0",
"type": "com.example.order.created",
"source": "order-service",
"subject": "notifications",
"datacontenttype": "application/json",
"data": {"order_id": "12345", "amount": 99.99}
}'
```
```csharp
using CloudNative.CloudEvents;
using CloudNative.CloudEvents.SystemTextJson;
using System.Net.Http.Headers;
var base_ = "http://localhost:9090";
var channel = "notifications";
// Build and publish a CloudEvent (structured mode).
var formatter = new JsonEventFormatter();
var cloudEvent = new CloudEvent
{
Id = Guid.NewGuid().ToString(),
Type = "com.kubemq.examples.events.sent",
Source = new Uri("urn:kubemq-ce-csharp-example"),
Subject = channel,
DataContentType = "application/json",
Data = new { message = "Hello from C# CloudEvents example!" },
};
cloudEvent.SetAttributeFromString("time", DateTimeOffset.UtcNow.ToString("O"));
var eventBytes = formatter.EncodeStructuredModeMessage(cloudEvent, out var contentType);
using var httpClient = new HttpClient();
using var content = new ByteArrayContent(eventBytes.ToArray());
content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType.ToString());
var resp = await httpClient.PostAsync($"{base_}/ce/send/event", content);
Console.WriteLine($"Published: status={resp.StatusCode}");
```
```go
import (
"encoding/json"
"net/http"
"strings"
cloudevents "github.com/cloudevents/sdk-go/v2"
)
base := "http://localhost:9090"
channel := "notifications"
// Build and send CloudEvent (structured mode).
event := cloudevents.NewEvent()
event.SetType("com.kubemq.examples.events.sent")
event.SetSource("kubemq-ce-go-example")
event.SetSubject(channel) // subject = KubeMQ channel
_ = event.SetData(cloudevents.ApplicationJSON, map[string]string{
"message": "Hello from Go CloudEvents example!",
})
body, _ := json.Marshal(event)
req, _ := http.NewRequest("POST", base+"/ce/send/event", strings.NewReader(string(body)))
req.Header.Set("Content-Type", "application/cloudevents+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import io.cloudevents.CloudEvent;
import io.cloudevents.core.builder.CloudEventBuilder;
import io.cloudevents.core.format.EventFormat;
import io.cloudevents.core.provider.EventFormatProvider;
import io.cloudevents.jackson.JsonFormat;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.OffsetDateTime;
import java.util.Map;
import java.util.UUID;
String base = "http://localhost:9090";
String channel = "notifications";
ObjectMapper mapper = new ObjectMapper();
// Build CloudEvent (structured mode).
EventFormatProvider.getInstance().registerFormat(new JsonFormat());
EventFormat format = EventFormatProvider.getInstance().resolveFormat(JsonFormat.CONTENT_TYPE);
CloudEvent event = CloudEventBuilder.v1()
.withId(UUID.randomUUID().toString())
.withType("com.kubemq.examples.events.sent")
.withSource(URI.create("kubemq-ce-java-example"))
.withSubject(channel)
.withDataContentType("application/json")
.withTime(OffsetDateTime.now())
.withData("application/json",
mapper.writeValueAsBytes(Map.of("message", "Hello from Java CloudEvents example!")))
.build();
byte[] body = format.serialize(event);
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(base + "/ce/send/event"))
.POST(HttpRequest.BodyPublishers.ofByteArray(body))
.header("Content-Type", "application/cloudevents+json")
.build();
HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.printf("Published: status=%d%n", response.statusCode());
```
```typescript
import { CloudEvent, HTTP } from 'cloudevents';
const base = 'http://localhost:9090';
const channel = 'notifications';
// Build and publish CloudEvent (structured mode).
const event = new CloudEvent({
type: 'com.kubemq.examples.events.sent',
source: 'kubemq-ce-js-example',
subject: channel,
datacontenttype: 'application/json',
data: { message: 'Hello from JavaScript/TypeScript CloudEvents example!' },
});
const message = HTTP.structured(event);
const resp = await fetch(`${base}/ce/send/event`, {
method: 'POST',
headers: message.headers as Record,
body: message.body as string,
});
const result = (await resp.json()) as { is_error: boolean };
console.log(`Published: status=${resp.status} is_error=${result.is_error}`);
```
```python
import requests
from cloudevents.v1.conversion import to_structured
from cloudevents.v1.http import CloudEvent
base = "http://localhost:9090"
channel = "notifications"
# Build and send CloudEvent (structured mode).
event = CloudEvent(
attributes={
"type": "com.kubemq.examples.events.sent",
"source": "kubemq-ce-python-example",
"subject": channel,
"datacontenttype": "application/json",
},
data={"message": "Hello from Python CloudEvents example!"},
)
headers, body = to_structured(event)
resp = requests.post(
f"{base}/ce/send/event",
data=body,
headers=dict(headers),
timeout=10,
)
result = resp.json()
print(f"Published: status={resp.status_code} is_error={result.get('is_error')}")
```
```ruby
require "net/http"
require "uri"
require "json"
require "securerandom"
require "cloud_events"
base = "http://localhost:9090"
channel = "notifications"
# Build and publish CloudEvent (structured mode).
sdk = CloudEvents::HttpBinding.default
event = CloudEvents::Event::V1.new(
id: SecureRandom.uuid,
type: "com.kubemq.examples.events.sent",
source: URI("urn:kubemq-ce-ruby-example"),
subject: channel,
spec_version: "1.0",
data_content_type: CloudEvents::ContentType.new("application/json"),
data: JSON.generate({ message: "Hello from Ruby CloudEvents example!" })
)
headers, body = sdk.encode_event(event, structured_format: "json")
uri = URI("#{base}/ce/send/event")
Net::HTTP.start(uri.host, uri.port) do |http|
req = Net::HTTP::Post.new(uri)
req["Content-Type"] = headers["Content-Type"]
req.body = body
res = http.request(req)
result = JSON.parse(res.body)
puts "Published: status=#{res.code} is_error=#{result['is_error']}"
end
```
```rust
use cloudevents::{EventBuilder, EventBuilderV10};
use reqwest::Client;
use serde_json::{json, Value};
use uuid::Uuid;
let base = "http://localhost:9090";
let channel = "notifications";
let client = Client::new();
// Build CloudEvent (structured mode using cloudevents-sdk).
let event = EventBuilderV10::new()
.id(Uuid::new_v4().to_string())
.ty("com.kubemq.examples.events.sent")
.source("urn:kubemq-ce-rust-example")
.subject(channel)
.data(
"application/json",
json!({"message": "Hello from Rust CloudEvents example!"}),
)
.build()?;
// Serialize to structured mode JSON.
let body = serde_json::to_string(&event)?;
let resp = client
.post(format!("{}/ce/send/event", base))
.header("Content-Type", "application/cloudevents+json")
.body(body)
.send()
.await?;
let result: Value = resp.json().await?;
println!("Published: is_error={}", result["is_error"]);
```
## Supported languages [#supported-languages]
The CE connector is plain HTTP, so any language with an HTTP client works. The
examples in this section use each language's official CloudEvents SDK to build the
envelope:
| Language | CloudEvents SDK | Version | Runtime |
| ----------------------- | ---------------------------------- | ------- | ------------ |
| Go | `github.com/cloudevents/sdk-go/v2` | 2.16.0 | Go 1.21+ |
| Python | `cloudevents` | 2.0.0 | Python 3.10+ |
| JavaScript / TypeScript | `cloudevents` | 10.0.0 | Node.js 18+ |
| Java | `io.cloudevents:cloudevents-core` | 4.0.1 | Java 21+ |
| C# | `CloudNative.CloudEvents` | 2.8.0 | .NET 8+ |
| Ruby | `cloud_events` | 0.9 | Ruby 3.1+ |
| Rust | `cloudevents-sdk` | 0.9 | Rust 1.75+ |
The CloudEvents SDK is a convenience for building and parsing the envelope — it is
not required. The structured-mode body and binary-mode `ce-*` headers are plain HTTP,
so curl and any raw HTTP client work just as well. See
[Content modes](/connectors/cloudevents/how-to/content-modes) for both wire formats.
## Next steps [#next-steps]
# Observability (/connectors/concepts/observability)
The connectors emit Prometheus metrics and OpenTelemetry traces on the same observability surface as the rest of kubemq-server, plus a dedicated **AI dashboard** for agents and MCP — so you watch connector traffic with the tools you already run.
## Overview [#overview]
Every gateway on the [shared HTTP server](/connectors/concepts/shared-http-server) shares one observability story. CloudEvents is documented here under Connectors; the AI gateways — [A2A and MCP](/aiway) — are documented under Aiway, but they run on the same server and report through this same surface:
* **Prometheus metrics** for A2A requests, MCP tool calls, registry operations, and active SSE streams, scraped from the management API port (`:8080`).
* **OpenTelemetry tracing** for every HTTP request through the connector middleware chain.
* A web **AI dashboard** (Agents and MCP) that reads cluster-aggregated metrics.
No extra configuration turns connector telemetry on — it follows the server's existing metrics and tracing setup.
## How it works [#how-it-works]
Connectors record metrics inline as they handle requests; the metrics exporter publishes them on the management API port (`:8080`) for Prometheus to scrape, while the dashboard reads the same data through the internal API.
*Connectors report metrics to the exporter on the management API port (`:8080`); Prometheus scrapes it and the AI dashboard reads the internal API.*
## Prometheus metrics [#prometheus-metrics]
Connector metrics are exposed on the **management API port (`:8080`)** at `/metrics`, alongside the core KubeMQ messaging metrics. Scrape it the same way:
```bash
curl http://localhost:8080/metrics
```
The connectors emit `kubemq_mcp_*` and `kubemq_a2a_*` series; the full series — names, types, and labels — is documented in [Observability → Prometheus Metrics](/operate/observability/metrics).
The A2A `method` label is sanitized against a fixed allowlist of known A2A methods. Any unrecognized method is recorded as `unknown` so a malformed or malicious request stream cannot explode Prometheus label cardinality.
In a cluster, these counters are **aggregated across all nodes** so the totals you see reflect the whole deployment rather than a single replica.
## OpenTelemetry tracing [#opentelemetry-tracing]
Every request that enters the shared HTTP server passes through OpenTelemetry instrumentation in the middleware chain, traced under the service name `kubemq-http`. When tracing is enabled on the server, connector requests appear in your traces automatically — there is nothing connector-specific to configure.
## The AI dashboard [#the-ai-dashboard]
The KubeMQ web dashboard includes an **AI** area for the agent platform:
* **Agents** — every registered agent and its live request stats (total requests, errors, average latency, last-seen time).
* **MCP** — tool usage drawn from the MCP metrics above.
The dashboard reads from an internal management API on the management API port (`:8080`):
| Method | Path | Description |
| ------ | ----------------- | -------------------------------------- |
| `GET` | `/api/agents` | List registered agents with pagination |
| `GET` | `/api/agents/:id` | Agent detail plus a stats snapshot |
```bash
curl http://localhost:8080/api/agents
```
The full `/api/agents` and `/api/agents/:id` reference — parameters, response envelope, and stats fields — is documented in [Observability → Dashboard Endpoints](/operate/observability/api-reference/dashboard-endpoints). Per-agent stats are populated from the same counters that feed `kubemq_a2a_requests_total`.
## Related [#related]
# Shared HTTP Server (/connectors/concepts/shared-http-server)
Three built-in gateways run on **one shared HTTP server** inside kubemq-server:
CloudEvents (documented here under Connectors) plus the AI gateways
[A2A and MCP](/aiway) (documented under Aiway). There is no separate port or
process per gateway: they register their routes on the same server, pass through the
same middleware chain, and inherit the same auth, CORS, and TLS configuration.
## One server, many connectors [#one-server-many-connectors]
When kubemq-server starts, each enabled connector registers its routes on the shared
HTTP server, and the server is started once. Requests to `/a2a/*`, `/mcp`, and `/ce/*`
all land on the same listener and flow through the same middleware pipeline before
reaching the connector that owns the route.
*A request passes through the middleware chain in order before reaching a connector route.*
## Port 9090 [#port-9090]
The shared HTTP server listens on **port 9090**. The port is configured by
`Connectors.Http.Port`; if it is left unset, it **inherits from `Rest.Port`** (which
defaults to `9090`). A warning is logged if both are set to different values.
Connector metrics are exposed separately on **port 8080** (`/metrics`), alongside the
internal dashboard API. See [Observability](/connectors/concepts/observability) for the
metrics surface and the AI dashboard.
Health and readiness probes are public and unauthenticated:
```bash
curl http://localhost:9090/ping
curl http://localhost:9090/health
curl http://localhost:9090/ready
```
## The middleware chain [#the-middleware-chain]
Every request flows through the same middleware stack, applied outermost-first:
| Order | Middleware | Purpose |
| ----- | ---------------- | ------------------------------------------------------------------------------- |
| 1 | **Recovery** | Catches panics so one bad request cannot crash the server. |
| 2 | **Traffic Gate** | Rejects requests with HTTP `503` while the broker is not ready. |
| 3 | **OTel Tracing** | OpenTelemetry instrumentation (`kubemq-http`), when telemetry is enabled. |
| 4 | **CORS** | Configurable cross-origin policy via `HttpConfig.Cors`. |
| 5 | **Auth** | Extracts a JWT Bearer token and sets claims; anonymous claims when auth is off. |
| 6 | **Body Limit** | Caps request body size (default `100M`). |
| 7 | **Logging** | Debug-level request start/end logging. |
The **traffic gate** is wired to the broker's readiness: the server automatically
starts accepting traffic when the broker becomes ready and rejects it (with `503`)
when it is not. This is why a connector can be enabled yet briefly return `503` during
startup.
Auth and TLS/mTLS are shared across all connectors and documented once in
[Auth & security](/connectors/reference/auth-and-security).
### SSE and request timeouts [#sse-and-request-timeouts]
The server's `WriteTimeout` is set to `0` so long-lived **Server-Sent Events** streams
(A2A `message/stream`, CloudEvents SSE subscriptions) stay open indefinitely. Non-SSE
route groups instead apply a per-route `TimeoutMiddleware` — default **60 seconds**,
returning HTTP `504 Gateway Timeout` if the deadline is exceeded before the response is
committed.
For requests that proxy to a downstream agent, a `GatewayTimeoutBuffer` of **10
seconds** is added on top of the caller-specified timeout, so the gateway does not time
out before the agent it is waiting on.
## Enable model: on by default [#enable-model-on-by-default]
All three gateways are **enabled by default**. Start kubemq-server and `/a2a/*`,
`/mcp`, and `/ce/*` are live — there is **no flag to turn them on**. (The A2A and MCP
gateways are documented under [Aiway](/aiway); their enable vars are listed here
because they share this server's enable model.) To turn one off, set its enable env var
to `false`:
| Connector | Disable with |
| ----------- | ----------------------------- |
| A2A | `CONNECTORSA2_A_ENABLE=false` |
| MCP | `CONNECTORSMCP_ENABLE=false` |
| CloudEvents | `CONNECTORSCE_ENABLE=false` |
For example, to run with MCP disabled:
**The enable var names are irregular by design.** Environment variables are derived
from the dotted config keys (`Connectors.A2A.Enable`, `Connectors.MCP.Enable`,
`Connectors.CE.Enable`) by a snake-casing transform that splits on letter-case
boundaries, strips dots, and uppercases. The boundaries fall in unexpected places — so
A2A becomes `CONNECTORSA2_A_ENABLE` (the `2`→`A` boundary inserts an underscore), while
MCP and CE join into `CONNECTORSMCP_ENABLE` and `CONNECTORSCE_ENABLE` with **no**
underscore before the connector name. Use these exact names; never invent a
`=true` flag to enable a connector. **CloudEvents is the one exception that also binds
an underscored alias** — `CONNECTORS_CE_ENABLE` works alongside the primary
`CONNECTORSCE_ENABLE`. MCP and A2A have no such alias: `CONNECTORS_MCP_ENABLE` and
`CONNECTORS_A2A_ENABLE` are silently ignored.
This differs from older KubeMQ behavior, where these gateways were off by default and
opted in. That framing is stale: today they ship on.
## Reserved channel prefix [#reserved-channel-prefix]
The shared server reserves the **`_AGENTS_.`** channel prefix for internal agent
platform subjects (agent request/reply, SSE stream relays, and registry replication).
Any user operation targeting a channel that begins with `_AGENTS_.` is **rejected** by
`IsReservedChannel`. Pick channel names outside this prefix for your own queues,
events, commands, and queries.
## Related [#related]
## Container command examples
```sh
docker run -d --pull always --platform linux/amd64 --name kubemq --hostname kubemq -p 127.0.0.1:50000:50000 -e STORE_ENGINE=next -e STORE_NEXT_ACK_POLICY=strict -e STORE_STORE_PATH=/kubemq/store -e API_BIND_ADDRESS=0.0.0.0 -e CONNECTORSMCP_ENABLE=false -v kubemq-data:/kubemq/store europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Google Cloud Pub/Sub (/connectors/gcp-pub-sub)
Point your Google Cloud Pub/Sub application at KubeMQ by setting **one environment
variable** — `PUBSUB_EMULATOR_HOST`. The **Google Cloud Pub/Sub connector** is a built-in,
wire-protocol bridge inside kubemq-server that speaks the genuine Pub/Sub v1 gRPC services on
a dedicated gRPC listener (default port **8085**, the Pub/Sub emulator convention). Any
standard, unmodified Pub/Sub client — the Go, Python, Java, Node.js, C#, and Ruby first-party
Google clients, plus `gcloud pubsub` — talks to KubeMQ exactly as it would to Google's local
emulator, with **no code changes, no library swap, and no KubeMQ SDK**.
## What is the Pub/Sub connector [#what-is-the-pubsub-connector]
The connector is a **single gRPC listener** that implements the real Pub/Sub v1 wire
protocol — **38 RPCs** across four services:
* **`google.pubsub.v1.Publisher`** (9 RPCs) — topics and publish.
* **`google.pubsub.v1.Subscriber`** (16 RPCs) — subscriptions, pull, streaming pull, ack,
snapshots, and seek.
* **`google.pubsub.v1.SchemaService`** (10 RPCs) — Avro and Protobuf schemas.
* **`google.iam.v1.IAMPolicy`** (3 permissive stubs) — emulator-parity IAM.
Every official Pub/Sub client library honours the `PUBSUB_EMULATOR_HOST` environment
variable: when it is set, the SDK **clears credentials, skips Google auth, and dials insecure
gRPC** — exactly as it would against Google's local emulator. **The connector *is* the
emulator** — there is no separate emulator to install, no LocalStack, and no boot-the-server
step beyond running kubemq-server.
Two KubeMQ primitives back the model: a **topic** maps onto a native KubeMQ **Events Store**
log `gcp.{topic}` (the authoritative, replayable source of truth), and each **subscription**
maps onto a native **Queue** channel `gcp.sub.{subscription}`. A publish is written **once**
to the topic log, then fanned out to one queue copy per subscription — so Pub/Sub producers
and native gRPC/REST consumers interoperate on the same messages.
The Pub/Sub connector is **opt-in (disabled by default)**. A stock kubemq-server does **not**
bind gRPC port 8085 until you enable it with `CONNECTORS_GCP_ENABLE=true` (Docker) or
`spec.gcp.enabled: true` (Kubernetes). See
[Getting started](/connectors/gcp-pub-sub/tutorials/getting-started).
## How it works [#how-it-works]
A Pub/Sub SDK client dials the connector's gRPC endpoint. A `Publish` is written once to the
topic's Events Store log `gcp.{topic}` through the message broker, then fanned out to one
Queue copy per subscription `gcp.sub.{subscription}` (applying each subscription's filter).
`Pull` / `StreamingPull` lease each delivered message under an ack-deadline, and `Acknowledge`
removes it from the subscription queue.
*A publish writes once to the Events Store log `gcp.{topic}` and fans out one Queue copy per subscription on `gcp.sub.{subscription}`, all backed by the message broker; consumers pull each message under an ack-deadline lease.*
## Ports & protocol surface [#ports--protocol-surface]
| Port | Transport | Protocol | Notes |
| ------ | ------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `8085` | Insecure gRPC | Pub/Sub v1 gRPC (emulator mode) | The Pub/Sub emulator convention. **Opt-in** — bound only when `CONNECTORS_GCP_ENABLE=true`. Must differ from the gRPC/REST/HTTP and AWS-connector ports. No auth, no TLS — exactly like Google's local emulator. |
| — | gRPC over TLS | Pub/Sub v1 gRPC | TLS is provided by the server-wide `Security` block — there is **no Pub/Sub-specific TLS option**. The default emulator path is unencrypted; do not expose port 8085 to untrusted networks. |
The connector is **gRPC only** — there is **no REST/JSON v1** surface (no grpc-gateway).
Clients and tools that only speak the Pub/Sub REST API will not work; use a gRPC client
library or `gcloud` (which uses gRPC for the emulator). See
[Architecture](/connectors/gcp-pub-sub/concepts/architecture) for the dispatch detail.
## Send a message [#send-a-message]
The example below runs the full round-trip — `CreateTopic` → `CreateSubscription` →
`Publish` → `Pull` → `Acknowledge` — over a stock Google Cloud Pub/Sub client. The only
change versus a real-GCP app is the **emulator endpoint**: each client reads
`PUBSUB_EMULATOR_HOST` (default `localhost:8085`) and a project id from `PUBSUB_PROJECT_ID`
(any value — the project segment is parsed but ignored).
```go
package main
import (
"context"
"fmt"
"log"
"os"
"sync"
"time"
"cloud.google.com/go/pubsub"
)
func projectID() string {
if v := os.Getenv("PUBSUB_PROJECT_ID"); v != "" {
return v
}
return "my-project" // any id; the project segment is parsed but ignored.
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// PUBSUB_EMULATOR_HOST (default localhost:8085) routes the official client at
// the connector over insecure gRPC with credentials cleared — no code change.
client, err := pubsub.NewClient(ctx, projectID())
if err != nil {
log.Fatalf("NewClient: %v", err)
}
defer client.Close()
// CreateTopic "orders" maps to Events Store log "gcp.orders".
topic, err := client.CreateTopic(ctx, "orders")
if err != nil {
log.Fatalf("CreateTopic: %v", err)
}
defer topic.Stop()
// CreateSubscription maps to Queue channel "gcp.sub.sub-orders".
sub, err := client.CreateSubscription(ctx, "sub-orders", pubsub.SubscriptionConfig{
Topic: topic,
AckDeadline: 10 * time.Second, // connector default; valid range 10..600s.
})
if err != nil {
log.Fatalf("CreateSubscription: %v", err)
}
id, err := topic.Publish(ctx, &pubsub.Message{Data: []byte("hello from cloud.google.com/go/pubsub")}).Get(ctx)
if err != nil {
log.Fatalf("Publish: %v", err)
}
fmt.Printf("published: %s\n", id)
recvCtx, recvCancel := context.WithTimeout(ctx, 15*time.Second)
defer recvCancel()
var once sync.Once
err = sub.Receive(recvCtx, func(_ context.Context, m *pubsub.Message) {
fmt.Printf("received: %q\n", string(m.Data))
m.Ack() // Acknowledge by ack_id under its lease.
once.Do(recvCancel)
})
if err != nil && recvCtx.Err() == nil {
log.Fatalf("Receive: %v", err)
}
}
```
```python
import os
from google.cloud import pubsub_v1
def project_id() -> str:
# Any id works — the project segment is parsed but ignored.
return os.environ.get("PUBSUB_PROJECT_ID", "my-project")
def main() -> None:
# Both clients honour PUBSUB_EMULATOR_HOST (default localhost:8085): they clear
# credentials, skip Google auth, and dial insecure gRPC.
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
proj = project_id()
topic_path = publisher.topic_path(proj, "orders") # -> gcp.orders
sub_path = subscriber.subscription_path(proj, "sub-orders") # -> gcp.sub.sub-orders
publisher.create_topic(request={"name": topic_path})
subscriber.create_subscription(request={"name": sub_path, "topic": topic_path})
future = publisher.publish(topic_path, b"hello from google-cloud-pubsub")
print(f"published: {future.result(timeout=15)}")
resp = subscriber.pull(request={"subscription": sub_path, "max_messages": 1}, timeout=20)
msg = resp.received_messages[0]
print(f"received: {msg.message.data.decode()!r}")
# Acknowledge by ack_id; the message leaves the subscription queue.
subscriber.acknowledge(request={"subscription": sub_path, "ack_ids": [msg.ack_id]})
subscriber.close()
if __name__ == "__main__":
main()
```
```java
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.rpc.FixedTransportChannelProvider;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.cloud.pubsub.v1.SubscriptionAdminSettings;
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.cloud.pubsub.v1.TopicAdminSettings;
import com.google.cloud.pubsub.v1.stub.GrpcSubscriberStub;
import com.google.cloud.pubsub.v1.stub.SubscriberStubSettings;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.AcknowledgeRequest;
import com.google.pubsub.v1.PublishRequest;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.PullRequest;
import com.google.pubsub.v1.PullResponse;
import com.google.pubsub.v1.PushConfig;
import com.google.pubsub.v1.ReceivedMessage;
import com.google.pubsub.v1.SubscriptionName;
import com.google.pubsub.v1.TopicName;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
public final class Main {
public static void main(String[] args) throws Exception {
String emulatorHost = System.getenv().getOrDefault("PUBSUB_EMULATOR_HOST", "localhost:8085");
String projectId = System.getenv().getOrDefault("PUBSUB_PROJECT_ID", "my-project");
// The Go/Python/Node clients auto-detect the emulator; Java points a plaintext
// gRPC channel at the host explicitly with NoCredentialsProvider.
ManagedChannel channel = ManagedChannelBuilder.forTarget(emulatorHost).usePlaintext().build();
TransportChannelProvider channelProvider =
FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
NoCredentialsProvider noCreds = NoCredentialsProvider.create();
TopicName topic = TopicName.of(projectId, "orders"); // -> gcp.orders
SubscriptionName sub = SubscriptionName.of(projectId, "sub-orders"); // -> gcp.sub.sub-orders
try (TopicAdminClient topicAdmin = TopicAdminClient.create(TopicAdminSettings.newBuilder()
.setTransportChannelProvider(channelProvider).setCredentialsProvider(noCreds).build());
SubscriptionAdminClient subAdmin = SubscriptionAdminClient.create(
SubscriptionAdminSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(noCreds).build());
GrpcSubscriberStub subStub = GrpcSubscriberStub.create(SubscriberStubSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(noCreds).build())) {
topicAdmin.createTopic(topic);
subAdmin.createSubscription(sub, topic, PushConfig.getDefaultInstance(), 10);
topicAdmin.publish(PublishRequest.newBuilder()
.setTopic(topic.toString())
.addMessages(PubsubMessage.newBuilder()
.setData(ByteString.copyFromUtf8("hello from google-cloud-pubsub")).build())
.build());
PullResponse resp = subStub.pullCallable().call(PullRequest.newBuilder()
.setSubscription(sub.toString()).setMaxMessages(1).build());
ReceivedMessage got = resp.getReceivedMessages(0);
System.out.printf("received: %s%n", got.getMessage().getData().toStringUtf8());
// Acknowledge by ack_id.
subStub.acknowledgeCallable().call(AcknowledgeRequest.newBuilder()
.setSubscription(sub.toString()).addAckIds(got.getAckId()).build());
} finally {
channel.shutdown();
}
}
}
```
```typescript
import { PubSub, v1 } from "@google-cloud/pubsub";
const projectId = process.env["PUBSUB_PROJECT_ID"] ?? "my-project";
// The high-level PubSub client reads PUBSUB_EMULATOR_HOST (default localhost:8085)
// and resolves the insecure emulator transport; reuse its options for the v1 clients.
const baseOptions = new PubSub({ projectId }).options;
const options = { ...baseOptions, port: baseOptions.port === undefined ? undefined : Number(baseOptions.port) };
const publisher = new v1.PublisherClient(options);
const subscriber = new v1.SubscriberClient(options);
async function main(): Promise {
const topic = publisher.projectTopicsPath(projectId, "orders"); // -> gcp.orders
const sub = subscriber.subscriptionPath(projectId, "sub-orders"); // -> gcp.sub.sub-orders
await publisher.createTopic({ name: topic });
await subscriber.createSubscription({ name: sub, topic, ackDeadlineSeconds: 10 });
const [published] = await publisher.publish({
topic,
messages: [{ data: Buffer.from("hello from @google-cloud/pubsub") }],
});
console.log(`published: ${published.messageIds?.[0]}`);
const [pull] = await subscriber.pull({ subscription: sub, maxMessages: 1 });
const received = pull.receivedMessages![0];
console.log(`received: ${Buffer.from(received.message!.data as Uint8Array).toString("utf8")}`);
// Acknowledge by ack_id.
await subscriber.acknowledge({ subscription: sub, ackIds: [received.ackId!] });
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
```
```csharp
using Google.Api.Gax;
using Google.Cloud.PubSub.V1;
using Google.Protobuf;
var projectId = Environment.GetEnvironmentVariable("PUBSUB_PROJECT_ID") ?? "my-project";
var topicName = TopicName.FromProjectTopic(projectId, "orders"); // -> gcp.orders
var subName = SubscriptionName.FromProjectSubscription(projectId, "sub-orders"); // -> gcp.sub.sub-orders
// The .NET client does NOT auto-detect the emulator — set EmulatorOnly so each
// client reads PUBSUB_EMULATOR_HOST (default localhost:8085) and dials insecurely.
var publisher = await new PublisherServiceApiClientBuilder
{
EmulatorDetection = EmulatorDetection.EmulatorOnly,
}.BuildAsync();
var subscriber = await new SubscriberServiceApiClientBuilder
{
EmulatorDetection = EmulatorDetection.EmulatorOnly,
}.BuildAsync();
await publisher.CreateTopicAsync(topicName);
await subscriber.CreateSubscriptionAsync(subName, topicName, pushConfig: null, ackDeadlineSeconds: 10);
var publishResponse = await publisher.PublishAsync(topicName, new[]
{
new PubsubMessage { Data = ByteString.CopyFromUtf8("hello from Google.Cloud.PubSub.V1") },
});
Console.WriteLine($"published: {publishResponse.MessageIds[0]}");
var pull = await subscriber.PullAsync(subName, maxMessages: 1);
var received = pull.ReceivedMessages[0];
Console.WriteLine($"received: {received.Message.Data.ToStringUtf8()}");
// Acknowledge by ack_id.
await subscriber.AcknowledgeAsync(subName, new[] { received.AckId });
```
```ruby
# frozen_string_literal: true
require "google/cloud/pubsub"
project_id = ENV["PUBSUB_PROJECT_ID"] || "my-project"
# Ruby needs the emulator host passed explicitly (it does not always read the env var).
emulator_host = ENV["PUBSUB_EMULATOR_HOST"] || "localhost:8085"
pubsub = Google::Cloud::PubSub.new(project_id: project_id, emulator_host: emulator_host)
topic_admin = pubsub.topic_admin
sub_admin = pubsub.subscription_admin
topic_path = pubsub.topic_path("orders") # -> gcp.orders
sub_path = pubsub.subscription_path("sub-orders") # -> gcp.sub.sub-orders
topic = topic_admin.create_topic(name: topic_path)
sub_admin.create_subscription(name: sub_path, topic: topic_path, ack_deadline_seconds: 10)
publisher = pubsub.publisher(topic.name)
msg = publisher.publish("hello from google-cloud-pubsub")
puts "published: #{msg.message_id}"
subscriber = pubsub.subscriber(sub_path)
received = subscriber.pull(immediate: false, max: 1)
rcv = received.first
puts "received: #{rcv.data.inspect}"
# Acknowledge by ack_id; the message leaves the subscription queue.
rcv.acknowledge!
```
## Supported languages [#supported-languages]
The connector speaks the genuine Pub/Sub v1 wire protocol, so any first-party Google Cloud
Pub/Sub client works — you only set `PUBSUB_EMULATOR_HOST`. There is no KubeMQ SDK, no proto
bindings, and no published package; the examples pin one official Google client per language.
| Language | Google Cloud Pub/Sub client | Emulator construction |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Go | [`cloud.google.com/go/pubsub`](https://pkg.go.dev/cloud.google.com/go/pubsub) | `pubsub.NewClient(ctx, projectID)` — auto-detects `PUBSUB_EMULATOR_HOST`, dials insecurely |
| Python | [`google-cloud-pubsub`](https://cloud.google.com/python/docs/reference/pubsub/latest) (via **uv**) | `pubsub_v1.PublisherClient()` — honours `PUBSUB_EMULATOR_HOST` |
| Java | [`com.google.cloud:google-cloud-pubsub`](https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/overview) (BOM) | plaintext `ManagedChannel` to the emulator host + `NoCredentialsProvider` |
| JavaScript / TypeScript | [`@google-cloud/pubsub`](https://cloud.google.com/nodejs/docs/reference/pubsub/latest) | `new PubSub({ projectId })` — auto-detects the emulator; run via `tsx` |
| C# / .NET | [`Google.Cloud.PubSub.V1`](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.PubSub.V1/latest) (.NET 8) | `…Builder { EmulatorDetection = EmulatorDetection.EmulatorOnly }.Build()` |
| Ruby | [`google-cloud-pubsub`](https://cloud.google.com/ruby/docs/reference/google-cloud-pubsub/latest) | `Google::Cloud::PubSub.new(project_id:, emulator_host:)` |
There is **no Rust tab** — Google ships no first-party Pub/Sub client for Rust. The connector's
verified example suite is the six languages above. Most clients auto-detect the emulator from
`PUBSUB_EMULATOR_HOST`; **C#** needs `EmulatorDetection.EmulatorOnly`, **Ruby** needs an
explicit `emulator_host:`, and **Java** points a plaintext channel at the host — see
[Connectivity & emulator mode](/connectors/gcp-pub-sub/how-to/connectivity-and-emulator-mode).
## Next steps [#next-steps]
# Kafka (/connectors/kafka)
Point your Kafka clients at KubeMQ by repointing `bootstrap.servers` — no client-library
swap, no code change. The **Kafka connector** is a built-in, wire-protocol bridge inside
kubemq-server that speaks the real Kafka request/response protocol — length-prefixed
frames, flexible versions, the `kmsg` codec — over plain TCP and TLS. Any off-the-shelf
Kafka client — Java `kafka-clients`/AdminClient/Spring, librdkafka/`kcat`/`confluent-kafka`,
or `franz-go`/`sarama`/`segmentio` — connects to KubeMQ exactly as it would to a real Kafka
broker.
## What is the Kafka connector [#what-is-the-kafka-connector]
The Kafka connector implements Kafka's Produce/Fetch/group-coordinator/admin request
surface directly inside kubemq-server — there's no separate broker process to run and no
protocol-translation layer for your application to configure around. Every produced record
lands in a persistent, ordered, replayable **Events Store** channel whose `Sequence`
maps one-to-one onto a Kafka offset: durable, restart-stable, and identical across every
node of a cluster.
Key capabilities:
* **Native produce/consume with classic consumer groups** — the large majority of everyday
Kafka usage, a straight repoint with no client changes.
* **OAUTHBEARER/OIDC federated auth**, alongside SASL/PLAIN, SASL/SCRAM, and mTLS client
certificates. [Rebuild Kafka ACLs as KubeMQ authorization rules](/connectors/kafka/how-to/acls)
before cutover; existing Kafka ACLs are not imported.
* **Compacted topics** (`cleanup.policy=compact`), which unlock the compaction-dependent
ecosystem — Kafka Connect and Kafka Streams both run against it.
* **Transactions and exactly-once semantics (EOS)** — a transactional producer with
`read_committed` isolation and producer fencing.
* **Static membership** (`group.instance.id`, KIP-345), so a consumer restart rejoins its
group without triggering a rebalance.
Before moving a production workload, review [What differs from Kafka](/connectors/kafka/concepts/differences-from-kafka).
**On by default.** A stock kubemq-server binds port `9092` out of the box (`9093` once TLS
is configured) — nothing to enable. To turn the connector off, set
`CONNECTORS_KAFKA_ENABLE=false` (Docker) or `spec.kafka.enabled: false` (Kubernetes). If
`9092` is already taken on the host — a real Kafka broker running locally, say — the server
logs an error and keeps running without the Kafka connector, even though the dashboard still
lists it as enabled. See [Getting started](/connectors/kafka/tutorials/getting-started).
## How it works [#how-it-works]
A Kafka client dials the connector's TCP listener and issues the same request types it
would send to a real broker. A `Produce` request is appended to the topic's Events Store
log; a `Fetch` request — including one driven by a consumer group's assigned partitions —
reads back from that same log. Because each Kafka offset maps one-to-one onto the log's durable `Sequence`, both
directions stay durable and ordered through the message broker underneath.
*A `Produce` request from a Kafka client is appended to the topic's Events Store log `kafka.{topic}` through the message broker; a `Fetch` request — including one driven by a consumer group's assigned partitions — reads back from that same log, so each Kafka offset maps one-to-one onto the log's durable `Sequence`.*
**Runs on the auto-selected `next` storage engine.** Kafka's headline capabilities —
compacted topics and the selectable strict and fast ack policies — exist only on KubeMQ's `next`
storage engine. On a **fresh** store, Kafka (on by default) **auto-selects `next`** with no
manual `store.engine` step. See
[Storage Engines → Zero-config engine selection](/configure/reference/storage-engines#zero-config-engine-selection)
for the full selection rules, including what happens on an existing store.
## Ports & protocol surface [#ports--protocol-surface]
| Port | Transport | Protocol | Notes |
| ------ | ------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `9092` | Plain TCP | Kafka wire protocol — `PLAINTEXT` / `SASL_PLAINTEXT` | Default listener. **On by default** — bound unless `CONNECTORS_KAFKA_ENABLE=false`. Disable just this listener by setting `CONNECTORS_KAFKA_PORT=""`. Must differ from the TLS port. |
| `9093` | TLS over TCP | Kafka wire protocol — `SSL` / `SASL_SSL` | Reuses the server-wide `Security` block (cert + key) — there is no Kafka-specific TLS option. **Required for OAUTHBEARER** (refused on plaintext). |
Clients read one setting, `bootstrap.servers` (or the client's equivalent), pointed at
`localhost:9092` for the plaintext listener. See
[Configuration](/connectors/kafka/concepts/configuration) for the enable flag, the
advertised-host/port pair, and where the full field-by-field settings reference lives.
## Send & receive a message [#send--receive-a-message]
The example below produces one message to the `orders` topic and reads it back on
`localhost:9092` — the only change versus a real Kafka client is the
**`bootstrap.servers` value**. No KubeMQ SDK, no code change: every tab uses a stock Kafka
client library.
```bash
# Produce one message to topic "orders"
echo "hello from kcat" | kcat -P -b localhost:9092 -t orders
# Consume from the beginning and exit after one message
kcat -C -b localhost:9092 -t orders -o beginning -c 1
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
ctx := context.Background()
// bootstrap.servers repoint only — no KubeMQ SDK, no code change.
cl, err := kgo.NewClient(
kgo.SeedBrokers("localhost:9092"),
kgo.ConsumeTopics("orders"),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
record := &kgo.Record{Topic: "orders", Value: []byte("hello from franz-go")}
if err := cl.ProduceSync(ctx, record).FirstErr(); err != nil {
log.Fatalf("produce: %v", err)
}
fmt.Println("produced to orders")
fetches := cl.PollFetches(ctx)
fetches.EachRecord(func(r *kgo.Record) {
fmt.Printf("received: %s\n", string(r.Value))
})
}
```
```python
from confluent_kafka import Consumer, Producer
BOOTSTRAP = "localhost:9092"
def main() -> None:
producer = Producer({"bootstrap.servers": BOOTSTRAP})
producer.produce("orders", value=b"hello from confluent-kafka")
producer.flush()
print("produced to orders")
consumer = Consumer({
"bootstrap.servers": BOOTSTRAP,
"group.id": "orders-consumer",
"auto.offset.reset": "earliest",
})
consumer.subscribe(["orders"])
msg = consumer.poll(timeout=10.0)
if msg is not None and msg.error() is None:
print(f"received: {msg.value().decode()!r}")
consumer.close()
if __name__ == "__main__":
main()
```
```java
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
public final class Main {
public static void main(String[] args) {
String bootstrap = "localhost:9092";
Properties producerProps = new Properties();
producerProps.put("bootstrap.servers", bootstrap);
producerProps.put("key.serializer", StringSerializer.class.getName());
producerProps.put("value.serializer", StringSerializer.class.getName());
try (KafkaProducer producer = new KafkaProducer<>(producerProps)) {
producer.send(new ProducerRecord<>("orders", "hello from kafka-clients"));
producer.flush();
System.out.println("produced to orders");
}
Properties consumerProps = new Properties();
consumerProps.put("bootstrap.servers", bootstrap);
consumerProps.put("group.id", "orders-consumer");
consumerProps.put("key.deserializer", StringDeserializer.class.getName());
consumerProps.put("value.deserializer", StringDeserializer.class.getName());
consumerProps.put("auto.offset.reset", "earliest");
try (KafkaConsumer consumer = new KafkaConsumer<>(consumerProps)) {
consumer.subscribe(Collections.singletonList("orders"));
ConsumerRecords records = consumer.poll(Duration.ofSeconds(10));
for (ConsumerRecord record : records) {
System.out.printf("received: %s%n", record.value());
}
}
}
}
```
```typescript
import { Kafka } from "kafkajs";
const kafka = new Kafka({
clientId: "kubemq-kafka-example",
brokers: ["localhost:9092"],
});
async function main(): Promise {
const producer = kafka.producer();
await producer.connect();
await producer.send({
topic: "orders",
messages: [{ value: "hello from kafkajs" }],
});
console.log("produced to orders");
await producer.disconnect();
const consumer = kafka.consumer({ groupId: "orders-consumer" });
await consumer.connect();
await consumer.subscribe({ topic: "orders", fromBeginning: true });
await consumer.run({
eachMessage: async ({ message }) => {
console.log(`received: ${message.value?.toString()}`);
await consumer.disconnect();
process.exit(0);
},
});
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
```
```csharp
using Confluent.Kafka;
const string bootstrapServers = "localhost:9092";
const string topic = "orders";
var producerConfig = new ProducerConfig { BootstrapServers = bootstrapServers };
using (var producer = new ProducerBuilder(producerConfig).Build())
{
await producer.ProduceAsync(topic, new Message { Value = "hello from Confluent.Kafka" });
Console.WriteLine("produced to orders");
}
var consumerConfig = new ConsumerConfig
{
BootstrapServers = bootstrapServers,
GroupId = "orders-consumer",
AutoOffsetReset = AutoOffsetReset.Earliest,
};
using var consumer = new ConsumerBuilder(consumerConfig).Build();
consumer.Subscribe(topic);
var result = consumer.Consume(TimeSpan.FromSeconds(10));
if (result is not null)
Console.WriteLine($"received: {result.Message.Value}");
consumer.Close();
```
```ruby
require "rdkafka"
BOOTSTRAP = "localhost:9092"
producer_config = Rdkafka::Config.new("bootstrap.servers" => BOOTSTRAP)
producer = producer_config.producer
producer.produce(topic: "orders", payload: "hello from rdkafka-ruby").wait
puts "produced to orders"
producer.close
consumer_config = Rdkafka::Config.new(
"bootstrap.servers" => BOOTSTRAP,
"group.id" => "orders-consumer",
"auto.offset.reset" => "earliest"
)
consumer = consumer_config.consumer
consumer.subscribe("orders")
consumer.each do |message|
puts "received: #{message.payload}"
break
end
consumer.close
```
```rust
use rdkafka::config::ClientConfig;
use rdkafka::consumer::{BaseConsumer, Consumer};
use rdkafka::message::Message;
use rdkafka::producer::{BaseProducer, BaseRecord, Producer};
use std::time::Duration;
fn main() {
let bootstrap = "localhost:9092";
let producer: BaseProducer = ClientConfig::new()
.set("bootstrap.servers", bootstrap)
.create()
.expect("producer creation failed");
producer
.send(
BaseRecord::to("orders")
.payload("hello from rust-rdkafka")
.key("order-1"),
)
.expect("produce failed");
producer.flush(Duration::from_secs(10)).expect("flush failed");
println!("produced to orders");
let consumer: BaseConsumer = ClientConfig::new()
.set("bootstrap.servers", bootstrap)
.set("group.id", "orders-consumer")
.set("auto.offset.reset", "earliest")
.create()
.expect("consumer creation failed");
consumer.subscribe(&["orders"]).expect("subscribe failed");
if let Some(result) = consumer.poll(Duration::from_secs(10)) {
let msg = result.expect("poll failed");
if let Some(payload) = msg.payload() {
println!("received: {}", String::from_utf8_lossy(payload));
}
}
}
```
## Supported clients [#supported-clients]
The connector speaks the genuine Kafka wire protocol, so any conformant client library
works — there is no KubeMQ SDK and no proto bindings. The examples above pin one client
per language; alternates are noted where the ecosystem commonly uses more than one.
| Language | Client library | Notes |
| ----------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| kcat | [`kcat`](https://github.com/edenhill/kcat) (librdkafka CLI) | The canonical quick-check Kafka client — no code, just a bootstrap address. |
| Go | [`github.com/twmb/franz-go`](https://github.com/twmb/franz-go) | Matches the connector's own conformance-harness client; `sarama` and `segmentio/kafka-go` also work. |
| Python | [`confluent-kafka`](https://github.com/confluentinc/confluent-kafka-python) (librdkafka bindings) | |
| Java | [`org.apache.kafka:kafka-clients`](https://kafka.apache.org/documentation/#api) | AdminClient and Spring Kafka run on top of the same client unchanged. |
| JavaScript / TypeScript | [`kafkajs`](https://kafka.js.org/) | |
| C# / .NET | [`Confluent.Kafka`](https://github.com/confluentinc/confluent-kafka-dotnet) (librdkafka bindings) | |
| Ruby | [`rdkafka`](https://github.com/karafka/rdkafka-ruby) (librdkafka bindings) | |
| Rust | [`rdkafka`](https://github.com/fede1024/rust-rdkafka) (librdkafka bindings) | |
**Share groups (KIP-932) are generally available.** Queue-style acquire/acknowledge
consumption is certified with Java's `KafkaShareConsumer` (`kafka-clients` 4.3) and the Kafka
4.3 console tools on a single node and on three-node clusters, including a killed share
coordinator with nothing lost and nothing accepted twice. **franz-go** works too; librdkafka's
share consumer is still an upstream preview. A few behaviors deliberately differ from Apache
Kafka — see [Share Groups](/connectors/kafka/how-to/share-groups) and
[the share-group differences](/connectors/kafka/concepts/differences-from-kafka#share-groups).
Not every capability above is proven to the same tier — see the
[fitness matrix](/connectors/kafka/reference/fitness-matrix) for the full
supported / caveat / roadmap / unsupported breakdown before you commit to a migration. Every
Kafka setting — ports, advertised host/port, SASL mechanisms, OAUTHBEARER, and the advanced
tuning knobs — is documented field-by-field in
[the Kafka settings reference](/configure/reference/connectors#kafka). Moving an
*existing* Kafka, MSK, or Confluent workload onto KubeMQ starts with the read-only
`kmq assess kafka` command, then the `kmq migrate` tool —
[Migrate from Kafka](/connectors/kafka/how-to/migrate-from-kafka) walks through the
full assess → replicate → translate → cutover playbook, and the full
[`kmq` CLI reference](/operate/kmq-cli) documents both commands.
## Next steps [#next-steps]
# MQTT (/connectors/mqtt)
Point your MQTT 3.1.1 / 5.0 application at KubeMQ by changing only the broker address.
The **MQTT connector** is a built-in, wire-protocol bridge inside kubemq-server: an
embedded MQTT broker that speaks the standard protocol natively, so any off-the-shelf
MQTT client (paho, MQTT.js, MQTTnet, rumqttc) reaches KubeMQ's Events, Events-Store,
Queues, Commands, and Queries with no KubeMQ SDK, no library swap, and no code rewrite.
## What is the MQTT connector [#what-is-the-mqtt-connector]
[MQTT](https://mqtt.org/) is a lightweight publish/subscribe protocol built around
*topics*: a client connects, subscribes to topic filters, and publishes messages with a
chosen *Quality of Service* (QoS 0/1/2). The KubeMQ MQTT connector exposes this protocol
on its own dedicated ports and maps it onto **all five KubeMQ messaging patterns**.
The **first segment of the MQTT topic** selects the KubeMQ pattern, and the remaining
segments become the KubeMQ channel with `/` translated to `.`. A publish to
`events/site1/temp` lands on the Events channel `site1.temp`; `queues/jobs` targets a
KubeMQ Queue; `commands/restart` and `queries/status` drive RPC. The connector is a
*gateway*, not a client library — your application only needs a stock MQTT client.
Key capabilities:
* **All five patterns over one wire** — Events, Events-Store, Queues, Commands, and
Queries, selected by the topic prefix.
* **Topic-driven pattern routing** — `events/`, `store/`, `queues/`, `commands/`,
`queries/` prefixes map a topic to a KubeMQ pattern; a bare (prefixless) topic routes
to the configured `DefaultPattern` (`events` by default).
* **MQTT 3.1.1 and 5.0** — both protocol levels on the same listener; MQTT 5.0 unlocks
User-Properties (carried as KubeMQ Tags) and RPC (Commands / Queries).
* **Cross-protocol interop** — a message published over MQTT to `events/it/cross` is
consumable by a gRPC or REST KubeMQ client on channel `it.cross`, and vice-versa.
**Retain is silently dropped.** The connector forces `RetainAvailable=0` in `CONNACK`. A
runtime publish with the retain flag set returns a success PUBACK (`0x00`) but the message
is stripped and **never delivered or stored**. A *Will*-retain requested at CONNECT time is
rejected outright with CONNACK `0x9A`. There are also **no durable subscriptions** — MQTT
sessions are in-memory and node-local. See
[QoS and sessions](/connectors/mqtt/concepts/qos-and-sessions).
**Opt-in — disabled by default.** A stock kubemq-server does **not** bind ports `1883` / `8883` / `8083`
until you turn the connector on with `CONNECTORSMQTT_ENABLE=true` (Docker) or
`spec.mqtt.enabled: true` (Kubernetes). See
[Getting started](/connectors/mqtt/tutorials/getting-started).
## How it works [#how-it-works]
An MQTT client connects to the connector and publishes to (or subscribes to) a topic. The
connector resolves the topic prefix to a KubeMQ `(pattern, channel)` pair, hands the
message to the message broker, and consumers on the same channel — over MQTT or any other
KubeMQ transport — receive it.
*The embedded broker accepts a standard MQTT connection, the topic mapper resolves the prefix to a KubeMQ pattern and channel, and the message broker fans it out to consumers on any transport.*
## Ports & protocol surface [#ports--protocol-surface]
| Port | Transport | Protocol | Notes |
| ------ | -------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `1883` | Plain TCP | MQTT 3.1.1 & 5.0 | Default listener. Disable by setting `CONNECTORSMQTT_PORT=""`. |
| `8883` | TLS over TCP | MQTT 3.1.1 & 5.0 | Binds only when the server-global `Security` block (cert + key) is configured; otherwise the port is open but the listener is inactive. |
| `8083` | WebSocket (path `/`) | MQTT 3.1.1 & 5.0 | MQTT-over-WebSocket at path `/`. Upgraded to `wss://` when `Security` is configured. |
Clients select the transport by URL scheme: `tcp://host:1883`, `tls://host:8883`, or
`ws://host:8083/`. The examples read one environment variable, `KUBEMQ_MQTT_URL` (default
`tcp://localhost:1883`). MQTT 3.1 (protocol level 3) is always rejected; the minimum
accepted level is 3.1.1. See [Configuration](/connectors/mqtt/concepts/configuration) for the
listener and capability settings.
## Publish an event [#publish-an-event]
The example below connects an MQTT 5.0 client and publishes one message to
`events/` at QoS 1. The topic prefix `events/` selects the Events pattern, and
`/` becomes `.` in the channel, so `events/demo/x` lands on the KubeMQ channel `demo.x`.
Every client reads the broker endpoint from `KUBEMQ_MQTT_URL` (default
`tcp://localhost:1883`).
```go
package main
import (
"context"
"fmt"
"log"
"net"
"os"
"strings"
"time"
"github.com/eclipse/paho.golang/paho"
)
func brokerURL() string {
if u := os.Getenv("KUBEMQ_MQTT_URL"); u != "" {
return u
}
return "tcp://localhost:1883"
}
// tcpAddr strips the scheme prefix to obtain "host:port".
func tcpAddr(rawURL string) string {
for _, pfx := range []string{"tcp://", "ws://", "tls://"} {
if strings.HasPrefix(rawURL, pfx) {
return rawURL[len(pfx):]
}
}
return rawURL
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// Prefix "events/" selects the Events pattern; '/' becomes '.' so
// "events/demo/x" maps to the KubeMQ channel "demo.x".
const topic = "events/demo/x"
conn, err := net.Dial("tcp", tcpAddr(brokerURL()))
if err != nil {
log.Fatalf("dial: %v", err)
}
client := paho.NewClient(paho.ClientConfig{Conn: conn})
connAck, err := client.Connect(ctx, &paho.Connect{
ClientID: "go-mqtt-events-pub",
KeepAlive: 30,
CleanStart: true,
})
if err != nil {
log.Fatalf("connect: %v", err)
}
if connAck.ReasonCode != 0 {
log.Fatalf("CONNACK reason=0x%02X", connAck.ReasonCode)
}
// QoS 1 returns a PUBACK. Do NOT set Retain — a retained publish is
// silently dropped (PUBACK 0x00, message never delivered).
pubAck, err := client.Publish(ctx, &paho.Publish{
Topic: topic,
QoS: 1,
Payload: []byte("hello from MQTT"),
Properties: &paho.PublishProperties{
// MQTT 5.0 User Properties round-trip as KubeMQ Tags.
User: []paho.UserProperty{{Key: "sensor", Value: "thermometer"}},
},
})
if err != nil {
log.Fatalf("publish: %v", err)
}
if pubAck.ReasonCode != 0 {
log.Fatalf("PUBACK reason=0x%02X", pubAck.ReasonCode)
}
fmt.Printf("published to %q (channel demo.x)\n", topic)
_ = client.Disconnect(&paho.Disconnect{ReasonCode: 0})
}
```
```python
import os
import paho.mqtt.client as mqtt
from paho.mqtt.enums import CallbackAPIVersion
from paho.mqtt.properties import Properties
from paho.mqtt.packettypes import PacketTypes
def parse_url(url: str) -> tuple[str, int]:
scheme, rest = url.split("://", 1)
host_port = rest.rstrip("/")
if ":" in host_port:
host, port = host_port.rsplit(":", 1)
return host, int(port)
return host_port, {"tcp": 1883, "tls": 8883, "ws": 8083}.get(scheme, 1883)
def main() -> None:
url = os.environ.get("KUBEMQ_MQTT_URL", "tcp://localhost:1883")
host, port = parse_url(url)
# Prefix "events/" selects the Events pattern; "/" becomes "." so
# "events/demo/x" maps to the KubeMQ channel "demo.x".
topic = "events/demo/x"
# paho-mqtt 2.x requires an explicit callback API version.
client = mqtt.Client(
callback_api_version=CallbackAPIVersion.VERSION2,
client_id="python-mqtt-events-pub",
protocol=mqtt.MQTTv5,
)
client.connect(host, port, keepalive=30, clean_start=True)
client.loop_start()
# MQTT 5.0 User Properties round-trip as KubeMQ Tags.
props = Properties(PacketTypes.PUBLISH)
props.UserProperty = [("sensor", "thermometer")]
# Do not set retain=True — a retained publish is silently dropped.
info = client.publish(topic, payload=b"hello from MQTT", qos=1, properties=props)
info.wait_for_publish(timeout=10)
print(f"published to {topic!r} (channel demo.x)")
client.loop_stop()
client.disconnect()
if __name__ == "__main__":
main()
```
```java
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.eclipse.paho.mqttv5.client.MqttAsyncClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
import org.eclipse.paho.mqttv5.common.packet.UserProperty;
public final class Main {
public static void main(String[] args) throws Exception {
String broker = System.getenv().getOrDefault("KUBEMQ_MQTT_URL", "tcp://localhost:1883");
// Prefix "events/" selects the Events pattern; "/" becomes "." so
// "events/demo/x" maps to the KubeMQ channel "demo.x".
String topic = "events/demo/x";
MqttConnectionOptions opts = new MqttConnectionOptions();
opts.setCleanStart(true);
opts.setKeepAliveInterval(30);
// org.eclipse.paho.mqttv5.client always uses MQTT protocol level 5.
MqttAsyncClient client = new MqttAsyncClient(broker, "java-mqtt-events-pub", new MemoryPersistence());
client.connect(opts).waitForCompletion(10_000);
MqttMessage msg = new MqttMessage("hello from MQTT".getBytes(StandardCharsets.UTF_8));
msg.setQos(1);
// Do NOT call msg.setRetained(true) — a retained publish is silently dropped.
// MQTT 5.0 User Properties round-trip as KubeMQ Tags.
MqttProperties props = new MqttProperties();
props.setUserProperties(List.of(new UserProperty("sensor", "thermometer")));
msg.setProperties(props);
client.publish(topic, msg).waitForCompletion(10_000);
System.out.printf("published to %s (channel demo.x)%n", topic);
client.disconnect().waitForCompletion(5_000);
client.close();
}
}
```
```typescript
import mqtt, { type MqttClient } from "mqtt";
function brokerUrl(): string {
return process.env["KUBEMQ_MQTT_URL"] ?? "tcp://localhost:1883";
}
async function main(): Promise {
// Prefix "events/" selects the Events pattern; "/" becomes "." so
// "events/demo/x" maps to the KubeMQ channel "demo.x".
const topic = "events/demo/x";
const client: MqttClient = mqtt.connect(brokerUrl(), {
clientId: "js-mqtt-events-pub",
protocolVersion: 5,
clean: true,
keepalive: 30,
});
await new Promise((resolve, reject) => {
client.once("connect", () => resolve());
client.once("error", reject);
});
await new Promise((resolve, reject) => {
client.publish(
topic,
"hello from MQTT",
{
qos: 1,
retain: false, // retain is NOT supported; a retained publish is silently dropped.
// MQTT 5.0 User Properties round-trip as KubeMQ Tags.
properties: { userProperties: { sensor: "thermometer" } },
},
(err) => (err ? reject(err) : resolve()),
);
});
console.log(`published to "${topic}" (channel demo.x)`);
await client.endAsync();
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
```
```csharp
using System.Text;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
static (string host, int port) ParseEndpoint(string url)
{
foreach (var prefix in new[] { "tcp://", "tls://", "ws://" })
if (url.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
url = url[prefix.Length..];
var parts = url.TrimEnd('/').Split(':');
return (parts[0], parts.Length > 1 ? int.Parse(parts[1]) : 1883);
}
var url = Environment.GetEnvironmentVariable("KUBEMQ_MQTT_URL") ?? "tcp://localhost:1883";
var (host, port) = ParseEndpoint(url);
// Prefix "events/" selects the Events pattern; "/" becomes "." so
// "events/demo/x" maps to the KubeMQ channel "demo.x".
const string topic = "events/demo/x";
var factory = new MqttFactory();
using var client = factory.CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithTcpServer(host, port)
.WithClientId("csharp-mqtt-events-pub")
.WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V500)
.WithCleanSession(true)
.Build();
await client.ConnectAsync(options);
var pubResult = await client.PublishAsync(
new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(Encoding.UTF8.GetBytes("hello from MQTT"))
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
// MQTT 5.0 User Property round-trips as a KubeMQ Tag.
// Do NOT call WithRetainFlag(true) — a retained publish is silently dropped.
.WithUserProperty("sensor", "thermometer")
.Build());
if (pubResult.ReasonCode != MqttClientPublishReasonCode.Success)
throw new Exception($"PUBACK reason: {pubResult.ReasonCode}");
Console.WriteLine($"published to '{topic}' (channel demo.x)");
await client.DisconnectAsync();
```
```ruby
# The Ruby `mqtt` gem speaks MQTT 3.1.1 only (no User Properties, no v5 RPC).
require "mqtt"
require "uri"
uri = URI.parse(ENV.fetch("KUBEMQ_MQTT_URL", "tcp://localhost:1883"))
# Prefix "events/" selects the Events pattern; "/" becomes "." so
# "events/demo/x" maps to the KubeMQ channel "demo.x".
topic = "events/demo/x"
MQTT::Client.connect(
host: uri.host,
port: uri.port,
ssl: uri.scheme == "tls",
client_id: "ruby-mqtt-events-pub",
clean_session: true,
keep_alive: 30
) do |client|
# retain=false is mandatory — the broker silently drops retained publishes.
client.publish(topic, "hello from MQTT", false, 1)
puts "published to '#{topic}' (channel demo.x)"
end
```
```rust
use rumqttc::v5::mqttbytes::v5::PublishProperties;
use rumqttc::v5::mqttbytes::QoS;
use rumqttc::v5::{AsyncClient, MqttOptions};
use std::env;
use std::time::Duration;
fn parse_host_port(url: &str) -> (String, u16) {
let stripped = url
.trim_start_matches("tcp://")
.trim_start_matches("tls://")
.trim_start_matches("ws://");
let host_port = stripped.split('/').next().unwrap_or(stripped);
let mut parts = host_port.splitn(2, ':');
let host = parts.next().unwrap_or("localhost").to_string();
let port: u16 = parts.next().and_then(|p| p.parse().ok()).unwrap_or(1883);
(host, port)
}
#[tokio::main]
async fn main() -> Result<(), Box> {
let url = env::var("KUBEMQ_MQTT_URL").unwrap_or_else(|_| "tcp://localhost:1883".to_string());
let (host, port) = parse_host_port(&url);
// Prefix "events/" selects the Events pattern; '/' becomes '.' so
// "events/demo/x" maps to the KubeMQ channel "demo.x".
let topic = "events/demo/x";
let mut opts = MqttOptions::new("rust-mqtt-events-pub", host, port);
opts.set_keep_alive(Duration::from_secs(30));
let (client, mut eventloop) = AsyncClient::new(opts, 10);
// Drive the event loop so the PUBLISH is flushed and the PUBACK is processed.
tokio::spawn(async move { while eventloop.poll().await.is_ok() {} });
// MQTT 5.0 User Properties round-trip as KubeMQ Tags.
let props = PublishProperties {
user_properties: vec![("sensor".to_string(), "thermometer".to_string())],
..Default::default()
};
// retain = false — a retained publish is silently dropped.
client
.publish_with_properties(topic, QoS::AtLeastOnce, false, b"hello from MQTT".as_ref(), props)
.await?;
println!("published to '{topic}' (channel demo.x)");
Ok(())
}
```
## Supported languages [#supported-languages]
The connector speaks standard MQTT, so any conformant client works. The examples pin one
native MQTT client per language — there is no KubeMQ SDK and no proto bindings.
| Language | Client library | Protocol | Notes |
| ----------------------- | ----------------------------------------------------------------------------------------------- | ---------- | -------------------------------------------------------------- |
| Go | [`eclipse/paho.golang`](https://github.com/eclipse/paho.golang) (`paho.mqtt.golang` for v3.1.1) | MQTT 5.0 | The connector's reference client. |
| Python | [`paho-mqtt`](https://pypi.org/project/paho-mqtt/) ≥ 2.1 | MQTT 5.0 | Callback-API v2. |
| Java | [Eclipse Paho `mqttv5`](https://eclipse.dev/paho/) | MQTT 5.0 | `org.eclipse.paho.mqttv5.client`. |
| JavaScript / TypeScript | [`mqtt.js`](https://github.com/mqttjs/MQTT.js) ≥ 5.15 | MQTT 5.0 | Works over TCP, TLS, and WebSocket. |
| C# / .NET | [`MQTTnet`](https://github.com/dotnet/MQTTnet) ≥ 4.3.7 | MQTT 5.0 | Task-based async. |
| Ruby | [`mqtt` gem](https://github.com/njh/ruby-mqtt) ≥ 0.6 | MQTT 3.1.1 | v3.1.1 subset only — no User Properties, no RPC, no WebSocket. |
| Rust | [`rumqttc`](https://github.com/bytebeamio/rumqtt) ≥ 0.24 | MQTT 5.0 | async/await on Tokio. |
The Ruby `mqtt` gem implements **MQTT 3.1.1 only**. The MQTT 5.0-only features — RPC
(Commands / Queries), shared-subscription queue consume, and User-Properties — are not
available from Ruby. Use a v5 client (Go, Python, Java, JavaScript, C#, Rust) for those
patterns. See [Topic grammar](/connectors/mqtt/reference/topic-grammar).
## Next steps [#next-steps]
# RabbitMQ (AMQP 0-9-1) (/connectors/rabbitmq)
Point a RabbitMQ app at KubeMQ by changing only the connection string. The **RabbitMQ
(AMQP 0-9-1) connector** is a built-in, wire-protocol bridge inside kubemq-server that
speaks the RabbitMQ wire dialect natively — any standard AMQP 0-9-1 client (`amqp091-go`,
`pika`, `amqp-client`, `amqplib`, `RabbitMQ.Client`, `bunny`, `lapin`) talks to KubeMQ's
Queues with no KubeMQ SDK, no library swap, and no code rewrite.
## What is the RabbitMQ connector [#what-is-the-rabbitmq-connector]
[AMQP 0-9-1](https://www.rabbitmq.com/tutorials/amqp-concepts) is the wire protocol that
RabbitMQ popularized: a client opens a connection, multiplexes *channels* over it, declares
*queues* and *exchanges*, and publishes messages routed by exchange type and routing key.
The KubeMQ connector accepts every one of these operations from a stock client and bridges
them onto KubeMQ — it is a *gateway*, not a client library, so your application only needs
its existing AMQP 0-9-1 client.
**Mental model — everything is a Queue.** Every AMQP queue maps to exactly one KubeMQ
**Queue** channel named `amqp.{vhost}.{queue}`. Exchanges and bindings are **virtual**,
connector-side routing metadata resolved at publish time — not data stores. AMQP only ever
touches the KubeMQ Queue primitive, so the connector's "patterns" mirror AMQP routing
concepts (work queues, pub/sub, routing, topics, RPC), not KubeMQ's five messaging
patterns.
Key capabilities:
* **Drop-in connection-string migration** — keep your RabbitMQ client and code; change only
the broker host in the URL.
* **Everything is a Queue** — every AMQP queue is a durable KubeMQ Queue channel
`amqp.{vhost}.{queue}`; exchanges (default, direct, fanout, topic, headers) route to those
queues virtually at publish time.
* **Native RPC** — request/reply uses RabbitMQ's `amq.rabbitmq.reply-to` (direct reply-to);
there is no gRPC responder.
* **Cross-protocol interop** — a message published over AMQP to `amqp.default.orders` is
consumable by a gRPC or REST KubeMQ client on the same channel, and vice-versa.
**On by default.** A stock kubemq-server binds port `5672` out of the box (`5671` as well
once TLS is configured) — no enable variable is needed. To turn the connector off, set
`CONNECTORS_AMQP_ENABLE=false` (Docker) or `spec.amqp.enabled: false` (Kubernetes). If
`5672` is already taken on the host (a real RabbitMQ running locally), the server logs an
error and keeps running without the connector, while the dashboard still lists it as
enabled — stop the other broker or move the port with `CONNECTORS_AMQP_PORT`. See
[Getting started](/connectors/rabbitmq/tutorials/getting-started).
## How it works [#how-it-works]
An AMQP client publishes to an exchange with a routing key. The connector resolves the
exchange routing (default / direct / fanout / topic / headers) to a set of target queues
*at publish time*, then writes each message to that queue's KubeMQ Queue channel through the
message broker. A consumer on the same queue — over AMQP or any other KubeMQ transport —
receives it.
*A publish to queue `orders` on vhost `/` resolves to the KubeMQ Queue channel `amqp.default.orders`; any consumer on that channel — AMQP or gRPC/REST — receives the message.*
## Ports & protocol surface [#ports--protocol-surface]
| Port | Transport | Protocol | Notes |
| ------ | --------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `5672` | Plain TCP (SASL PLAIN / AMQPLAIN) | AMQP 0-9-1 (RabbitMQ wire dialect) | Default plain listener. **Shared with the AMQP 1.0 connector** via the internal `amqpmux`. |
| `5671` | TLS / AMQPS over TCP | AMQP 0-9-1 | Binds only when the server-global `Security` block is configured. Shared TLS listener with AMQP 1.0. |
A single `amqpmux` listener accepts every connection on `5672`/`5671`, reads the 8-byte AMQP
protocol header, and routes it to the matching dialect engine — so AMQP 0-9-1 and AMQP 1.0
coexist on the same ports. SASL offers **`PLAIN` and `AMQPLAIN`** always, and `EXTERNAL`
(certificate login) once it is switched on; `ANONYMOUS` is never offered. The AMQP vhost `/` maps to the
connector's configured `DefaultVhost` segment (literal `"default"`); see
[Architecture](/connectors/rabbitmq/concepts/architecture) for the dispatch detail.
## Publish to a queue [#publish-to-a-queue]
The example below declares a queue, publishes one `text/plain` message to it through the
default exchange (routing key = queue name), and consumes it back. Queue `hello` on vhost
`/` lands on the KubeMQ Queue channel `amqp.default.hello`. Every client reads the broker
endpoint from `KUBEMQ_AMQP_URL` (default `amqp://guest:guest@localhost:5672/`).
This is the same round trip as the [Getting started](/connectors/rabbitmq/tutorials/getting-started)
tutorial, shown here inline for reference. For a step-by-step walkthrough — enabling the
connector, running a local broker, and verifying each step — use Getting started instead.
```go
package main
import (
"context"
"log"
"os"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
func amqpURL() string {
if v := os.Getenv("KUBEMQ_AMQP_URL"); v != "" {
return v
}
return "amqp://guest:guest@localhost:5672/"
}
func main() {
conn, err := amqp.Dial(amqpURL())
if err != nil {
log.Fatalf("dial: %v", err)
}
defer func() { _ = conn.Close() }()
ch, err := conn.Channel()
if err != nil {
log.Fatalf("channel: %v", err)
}
defer func() { _ = ch.Close() }()
// Declare "hello" → KubeMQ Queue channel amqp.default.hello.
q, err := ch.QueueDeclare("hello", false, false, false, false, nil)
if err != nil {
log.Fatalf("declare queue: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// Publish on the default exchange — routing key = queue name.
if err := ch.PublishWithContext(ctx, "", q.Name, false, false, amqp.Publishing{
ContentType: "text/plain",
Body: []byte("Hello World!"),
}); err != nil {
log.Fatalf("publish: %v", err)
}
log.Printf(" [x] Sent %q", "Hello World!")
// Consume with auto-ack and print the exact body.
msgs, err := ch.Consume(q.Name, "", true, false, false, false, nil)
if err != nil {
log.Fatalf("consume: %v", err)
}
select {
case d := <-msgs:
log.Printf(" [x] Received %q", string(d.Body))
case <-ctx.Done():
log.Fatalf("timed out: %v", ctx.Err())
}
}
```
```python
import os
import pika
URL = os.environ.get("KUBEMQ_AMQP_URL", "amqp://guest:guest@localhost:5672/")
QUEUE = "hello" # → KubeMQ Queue channel amqp.default.hello
def main() -> None:
connection = pika.BlockingConnection(pika.URLParameters(URL))
channel = connection.channel()
# Default (nameless) exchange: routing key == queue name.
channel.queue_declare(queue=QUEUE, durable=False, exclusive=False, auto_delete=False)
channel.basic_publish(
exchange="",
routing_key=QUEUE,
body=b"Hello World!",
properties=pika.BasicProperties(content_type="text/plain"),
)
print(" [x] Sent 'Hello World!'")
method, _props, body = channel.basic_get(queue=QUEUE, auto_ack=True)
if method is None:
raise SystemExit("no message received from queue")
print(f" [x] Received {body.decode()!r}")
channel.close()
connection.close()
if __name__ == "__main__":
main()
```
```java
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public final class Main {
private static final String QUEUE = "hello"; // → amqp.default.hello
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUri(System.getenv().getOrDefault(
"KUBEMQ_AMQP_URL", "amqp://guest:guest@localhost:5672/"));
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
// queue.declare: non-durable, non-exclusive, no auto-delete.
channel.queueDeclare(QUEUE, false, false, false, null);
// Publish via the default exchange ("") with routing key = queue name.
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
.contentType("text/plain")
.build();
channel.basicPublish("", QUEUE, props, "Hello World!".getBytes("UTF-8"));
System.out.println("[x] Sent 'Hello World!'");
BlockingQueue received = new ArrayBlockingQueue<>(1);
DeliverCallback onDeliver = (tag, delivery) ->
received.offer(new String(delivery.getBody(), "UTF-8"));
channel.basicConsume(QUEUE, true, onDeliver, tag -> { });
String got = received.poll(15, TimeUnit.SECONDS);
if (got == null) {
throw new IllegalStateException("timed out waiting for the message");
}
System.out.println("[x] Received '" + got + "'");
}
}
}
```
```javascript
import amqp from "amqplib";
// amqplib reads the URL path as the vhost; the bare trailing "/" in the dev URL
// resolves to the default vhost (KubeMQ segment "default").
const URL = process.env.KUBEMQ_AMQP_URL ?? "amqp://guest:guest@localhost:5672/";
const QUEUE = "hello"; // → KubeMQ Queue channel amqp.default.hello
async function main() {
const conn = await amqp.connect(URL);
const ch = await conn.createChannel();
await ch.assertQueue(QUEUE, { durable: false, autoDelete: false, exclusive: false });
const received = new Promise((resolve) => {
ch.consume(
QUEUE,
(msg) => {
if (msg === null) return;
console.log(`[x] Received: ${msg.content.toString()}`);
resolve();
},
{ noAck: true },
);
});
// Default exchange ("") routes by queue name.
ch.publish("", QUEUE, Buffer.from("Hello World!"), { contentType: "text/plain" });
console.log("[x] Sent: Hello World!");
await received;
await ch.close();
await conn.close();
}
main().catch((err) => {
console.error("publish failed:", err);
process.exit(1);
});
```
```csharp
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
const string queueName = "hello"; // → KubeMQ Queue channel amqp.default.hello
var factory = new ConnectionFactory
{
Uri = new Uri(Environment.GetEnvironmentVariable("KUBEMQ_AMQP_URL")
?? "amqp://guest:guest@localhost:5672/"),
};
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var ct = cts.Token;
await using var connection = await factory.CreateConnectionAsync(ct);
await using var channel = await connection.CreateChannelAsync(cancellationToken: ct);
// Non-durable, not exclusive, not auto-delete — a plain shared queue.
await channel.QueueDeclareAsync(queueName, durable: false, exclusive: false,
autoDelete: false, arguments: null, cancellationToken: ct);
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += (_, ea) =>
{
received.TrySetResult(Encoding.UTF8.GetString(ea.Body.Span));
return Task.CompletedTask;
};
await channel.BasicConsumeAsync(queueName, autoAck: true, consumer: consumer, cancellationToken: ct);
// Publish to the default exchange with routing key = queue name.
var props = new BasicProperties { ContentType = "text/plain" };
await channel.BasicPublishAsync(exchange: "", routingKey: queueName, mandatory: false,
basicProperties: props, body: Encoding.UTF8.GetBytes("Hello World!"), cancellationToken: ct);
Console.WriteLine("[x] Sent 'Hello World!'");
var message = await received.Task.WaitAsync(ct);
Console.WriteLine($"[x] Received '{message}'");
```
```ruby
# frozen_string_literal: true
require "bunny"
URL = ENV.fetch("KUBEMQ_AMQP_URL", "amqp://guest:guest@localhost:5672/")
QUEUE = "hello" # → KubeMQ Queue channel amqp.default.hello
conn = Bunny.new(URL)
conn.start
ch = conn.create_channel
# Publisher confirms: wait for the broker to accept and route the publish before
# reading it back, so a fire-and-forget publish is never lost in flight.
ch.confirm_select
queue = ch.queue(QUEUE, durable: false, auto_delete: false, exclusive: false)
# Default ("") exchange routes by queue name.
ch.default_exchange.publish("Hello World!", routing_key: queue.name, content_type: "text/plain")
ch.wait_for_confirms
puts " [x] Sent 'Hello World!'"
body = nil
deadline = Time.now + 5
while body.nil? && Time.now < deadline
_info, _props, body = queue.pop(manual_ack: false)
sleep 0.2 if body.nil?
end
puts " [x] Received '#{body}'"
conn.close
```
```rust
use futures_lite::StreamExt;
use lapin::{
options::{BasicConsumeOptions, BasicPublishOptions, QueueDeclareOptions},
types::FieldTable,
BasicProperties, Connection, ConnectionProperties,
};
const QUEUE: &str = "hello"; // → KubeMQ Queue channel amqp.default.hello
// lapin reads the URL path as the vhost and treats a bare trailing "/" as an
// empty vhost, which the connector rejects. The default "/" vhost must be
// percent-encoded as "%2f".
fn amqp_url() -> String {
let url = std::env::var("KUBEMQ_AMQP_URL")
.unwrap_or_else(|_| "amqp://guest:guest@localhost:5672/".into());
let host = url.rsplit_once('@').map_or(url.as_str(), |(_, h)| h);
if host.ends_with('/') && !host.ends_with("/%2f") {
format!("{url}%2f")
} else {
url
}
}
#[tokio::main]
async fn main() -> Result<(), Box> {
let conn = Connection::connect(&amqp_url(), ConnectionProperties::default()).await?;
let channel = conn.create_channel().await?;
channel
.queue_declare(QUEUE, QueueDeclareOptions::default(), FieldTable::default())
.await?;
// Publish to the default exchange, routing key = queue name.
channel
.basic_publish(
"",
QUEUE,
BasicPublishOptions::default(),
b"Hello World!",
BasicProperties::default().with_content_type("text/plain".into()),
)
.await?
.await?;
println!("[x] Sent 'Hello World!'");
let mut consumer = channel
.basic_consume(
QUEUE,
"hello-consumer",
BasicConsumeOptions { no_ack: true, ..Default::default() },
FieldTable::default(),
)
.await?;
if let Some(delivery) = consumer.next().await {
let delivery = delivery?;
println!("[x] Received '{}'", String::from_utf8_lossy(&delivery.data));
}
conn.close(0, "done").await?;
Ok(())
}
```
## Supported languages [#supported-languages]
The connector speaks standard AMQP 0-9-1, so any conformant RabbitMQ client works. The
examples pin one native client per language — there is no KubeMQ SDK, no proto bindings,
and no published package.
| Language | Client library | Notes |
| ----------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------- |
| Go | [`github.com/rabbitmq/amqp091-go`](https://github.com/rabbitmq/amqp091-go) | The RabbitMQ team's Go client. |
| Python | [`pika`](https://pika.readthedocs.io/) | `BlockingConnection` with `URLParameters`. |
| Java | [`com.rabbitmq:amqp-client`](https://www.rabbitmq.com/client-libraries/java-api-guide) | The official RabbitMQ Java client. |
| JavaScript / TypeScript | [`amqplib`](https://github.com/amqp-node/amqplib) | Encode the default `/` vhost as `%2f` in the URL. |
| C# / .NET | [`RabbitMQ.Client`](https://www.rabbitmq.com/client-libraries/dotnet-api-guide) | Task-based async API (v7+). |
| Ruby | [`bunny`](https://github.com/ruby-amqp/bunny) | Use publisher confirms before consuming. |
| Rust | [`lapin`](https://github.com/amqp-rs/lapin) | async/await on Tokio; percent-encode the `/` vhost. |
## Next steps [#next-steps]
# Auth & Security (/connectors/reference/auth-and-security)
Every gateway on the [shared HTTP server](/connectors/concepts/shared-http-server) sits
behind the same security middleware. CloudEvents is documented here under Connectors;
the AI gateways — [A2A and MCP](/aiway) — are documented under Aiway, but they run
on the same server and inherit this identical security model. The authentication, CORS,
origin-validation, and TLS rules described here apply uniformly to `/a2a/*`, `/mcp`, and
`/ce/*`; each gateway's own auth guide simply points back to this page.
## How requests are secured [#how-requests-are-secured]
A request crosses three security stages before it reaches the broker: TLS terminates
the transport, CORS and origin validation screen browser callers, and the auth
middleware verifies the Bearer token and attaches identity claims. Public routes skip
authentication entirely.
*Transport security, browser screening, and JWT auth guard every connector request.*
## Authentication [#authentication]
The auth middleware extracts a **`Bearer` token** from the `Authorization` header and
verifies it against KubeMQ's authentication singleton. On success it attaches the
caller's claims (including `ClientID`) to the request context, where the connector and
the broker use them for authorization and identity propagation.
When server authentication is **disabled**, the middleware injects synthetic anonymous
claims (`ClientID: "anonymous"`) so requests still carry an identity. When it is
**enabled**, an unverified or missing token is rejected.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Authorization: Bearer ' \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":"1","method":"tools/list"}'
```
### How auth failures are reported [#how-auth-failures-are-reported]
The error shape depends on the endpoint family. JSON-RPC connectors return a protocol
error object; the REST-style CloudEvents endpoints return a standard HTTP status.
| Endpoint | On auth failure |
| --------------------------------- | ------------------------------------------ |
| JSON-RPC (`/mcp`, `/a2a/*`) | JSON-RPC error with code **`-32010`** |
| HTTP / REST (`/ce/*`, management) | **HTTP 401 Unauthorized** |
### Public routes [#public-routes]
A small set of routes bypass authentication entirely so health probes and agent
discovery work without credentials:
| Route | Purpose |
| ------------------------------- | --------------------------------------------- |
| `/ping` | Liveness probe |
| `/health` | Health check |
| `/ready` | Readiness probe |
| `*/.well-known/agent-card.json` | Agent card discovery (platform and per-agent) |
The platform card `GET /.well-known/agent-card.json` and any per-agent card path
ending in `/.well-known/agent-card.json` are public by design — A2A discovery must be
reachable before a caller has a token.
## CORS [#cors]
Browser-based callers are governed by the connectors' CORS configuration on
`Connectors.Http.Cors`. The defaults are permissive on origin but explicit about the
headers connectors need — in particular the MCP session/protocol headers and the
CloudEvents replay header.
| Setting | Default |
| ------------------ | ------------------------------------------------------------------------------------------ |
| `AllowOrigins` | `["*"]` |
| `AllowMethods` | `GET, POST, DELETE, OPTIONS` |
| `AllowHeaders` | `Authorization, Content-Type, MCP-Protocol-Version, MCP-Session-Id, Last-Event-ID, Accept` |
| `ExposeHeaders` | `MCP-Session-Id, MCP-Protocol-Version` |
| `AllowCredentials` | `false` |
| `MaxAge` | `86400` (preflight cache, seconds) |
A browser preflight is answered by the CORS middleware before the request reaches the
connector:
```bash
curl -i -X OPTIONS http://localhost:9090/mcp \
-H 'Origin: https://app.example.com' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: Authorization, MCP-Session-Id'
```
## Origin validation [#origin-validation]
In addition to CORS, browser requests are checked by **origin validation** against a
list of trusted origins. This is independent of CORS and guards against
cross-site request forgery from untrusted pages.
| `TrustedOrigins` value | Behavior |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `auto` (default) | Matches localhost variants (`localhost`, `127.0.0.1`, and for MCP also `::1`, `[::1]`, `0.0.0.0`) plus the server's bind address |
| `*` | Allows all origins |
| *(custom list)* | Allows exactly the listed origins |
An **empty `Origin` header** — which non-browser clients such as curl, SDKs, and
server-to-server calls send — is **always allowed**. MCP applies its own origin check
(`McpConfig.TrustedOrigins`) in addition to the shared HTTP origin middleware; A2A
uses `A2aConfig.TrustedOrigins`. Both default to `["auto"]`.
## TLS and mTLS [#tls-and-mtls]
Transport security is read from the server's `SecurityConfig` and applies to the
shared HTTP listener that fronts every connector. Three modes are supported:
| Mode | Behavior |
| ------------------ | -------------------------------------------------------- |
| `SecurityModeNone` | Plain TCP listener (no TLS) |
| `SecurityModeTLS` | TLS with a server certificate |
| `SecurityModeMTLS` | Mutual TLS — clients must present a verified certificate |
TLS here secures the **inbound** connection from callers to the connectors. The A2A
gateway's **outbound** calls to agent URLs are a separate concern, controlled by
`AgentTLSSkipVerify` — see the [A2A configuration](/aiway/a2a/configuration).
## Reserved channel prefix [#reserved-channel-prefix]
Channel-name validation rejects any user channel beginning with the reserved
**`_AGENTS_.`** prefix. This prefix is owned by the agent platform's internal
channels (registry, streaming, discovery); rejecting it prevents user operations from
colliding with platform traffic. Attempting to send to or subscribe on such a channel
through any connector is refused.
## Related [#related]
# STOMP (/connectors/stomp)
Point your existing STOMP application at KubeMQ by changing only the broker address. The
**STOMP connector** is a built-in, wire-protocol bridge inside kubemq-server — an embedded
STOMP server with its own dedicated TCP/TLS listeners and a hand-rolled frame codec. Any
standard, unmodified STOMP client (go-stomp, stomp.py, Stomp.Net, Spring) talks to KubeMQ's
Queues, Events, Events-Store, Commands, and Queries with no code change, no library swap, and
no KubeMQ SDK.
## What is the STOMP connector [#what-is-the-stomp-connector]
[STOMP](https://stomp.github.io/) (Simple Text Oriented Messaging Protocol) is a frame-based
text protocol: a client opens a connection with a `CONNECT` frame, then `SEND`s to and
`SUBSCRIBE`s on **destinations**. The KubeMQ STOMP connector negotiates STOMP **1.0, 1.1, and
1.2** (it picks the highest common version; the examples default to `1.2`) over raw TCP, and
maps the STOMP wire protocol onto KubeMQ's five native messaging patterns by **destination
prefix**.
The first path segment of a destination selects the pattern; the remaining segments are joined
with `.` into the KubeMQ channel — `/topic/orders/new` becomes Events channel `orders.new`. The
connector is a *gateway*, not a client library: your application only needs a stock STOMP
client.
Key capabilities:
* **All five patterns over one wire** — Queues, Events, Events-Store, Commands, and Queries,
selected by the destination prefix.
* **ActiveMQ-style primary names, MQTT-style aliases** — lead with `/queue/`, `/topic/`,
`/topic-store/`, `/command/`, `/query/`; the aliases `/queues/`, `/events/`, `/store/`,
`/commands/`, `/queries/` resolve to the same patterns, and egress always canonicalizes back
to the primary name.
* **RPC requester-only** — a STOMP client `SEND`s to `/command/` or `/query/` and receives the
reply on a connection-local `/reply/` subscription; the responder runs on the KubeMQ (gRPC)
side.
* **Cross-protocol interop** — a message sent over STOMP to `/topic/orders/new` is consumable
by a gRPC or REST KubeMQ client on channel `orders.new`, and vice-versa.
**Opt-in — disabled by default.** A stock kubemq-server does **not** bind ports `61613` / `61614`
until you turn the connector on with `CONNECTORS_STOMP_ENABLE=true` (Docker) or
`spec.stomp.enabled: true` (Kubernetes). See
[Getting started](/connectors/stomp/tutorials/getting-started).
## How it works [#how-it-works]
A STOMP client connects to the connector and `SEND`s to a destination. The connector resolves
the destination to a KubeMQ `(pattern, channel)` pair, hands the message to the message broker,
and consumers on the same channel — over STOMP or any other KubeMQ transport — receive it.
*The connector parses the destination prefix into a KubeMQ pattern and joins the remaining segments (slash→dot) into the channel `orders.new`, then bridges onto the shared KubeMQ array.*
## Ports & protocol surface [#ports--protocol-surface]
| Port | Transport | Protocol | Notes |
| ------- | ------------ | --------------------- | ----------------------------------------------------------------------------------------------------------- |
| `61613` | Plain TCP | STOMP 1.0 / 1.1 / 1.2 | Default plain listener; binds all interfaces. |
| `61614` | TLS over TCP | STOMP 1.0 / 1.1 / 1.2 | Binds only when the server-wide `Security` block resolves to TLS. **Must differ from the plain port.** |
There is **no STOMP-over-WebSocket listener** — the connector speaks raw TCP only, so a
WebSocket-only client (such as `@stomp/stompjs`) cannot drive it. TLS has no STOMP-specific
configuration: certificate material, mTLS, and the minimum TLS version come from the
server-wide `Security` block. Connecting over TLS is purely a transport swap
(`tls://host:61614`); the STOMP frames on top are identical. See
[Architecture](/connectors/stomp/concepts/architecture) for the protocol stack.
## Send a message [#send-a-message]
The example below produces one message to a Queue over a stock STOMP client. The `/queue/`
prefix selects the **Queues** pattern (competing consumer, at-least-once); the remaining
segments become the KubeMQ channel with `/` translated to `.` — `/queue/orders/new` lands on
channel `orders.new`. Every client reads the broker endpoint from `KUBEMQ_STOMP_URL` (default
`tcp://localhost:61613`); the scheme selects the transport.
```go
package main
import (
"fmt"
"log"
"os"
"github.com/go-stomp/stomp/v3"
)
func stompURL() string {
if v := os.Getenv("KUBEMQ_STOMP_URL"); v != "" {
return v
}
return "tcp://localhost:61613"
}
func main() {
// The scheme in KUBEMQ_STOMP_URL selects the transport; strip it for net.Dial.
addr := stompURL()[len("tcp://"):]
const destination = "/queue/orders/new" // Queues pattern, channel "orders.new"
// CONNECT: accept-version 1.2, default heart-beat, no-auth.
conn, err := stomp.Dial("tcp", addr,
stomp.ConnOpt.AcceptVersion(stomp.V12),
stomp.ConnOpt.Login("my-app", ""))
if err != nil {
log.Fatalf("connect: %v", err)
}
defer conn.Disconnect() //nolint:errcheck
// SEND one message; the receipt blocks until KubeMQ accepts the frame.
if err := conn.Send(destination, "text/plain",
[]byte("hello from STOMP"), stomp.SendOpt.Receipt); err != nil {
log.Fatalf("send: %v", err)
}
fmt.Printf("sent 1 message to %s (channel orders.new)\n", destination)
}
```
```python
import os
import stomp
def stomp_endpoint() -> tuple[str, int]:
url = os.environ.get("KUBEMQ_STOMP_URL", "tcp://localhost:61613")
host_port = url.split("://", 1)[1]
host, port = host_port.split(":", 1)
return host, int(port)
def main() -> None:
destination = "/queue/orders/new" # Queues pattern, channel "orders.new"
host, port = stomp_endpoint()
# CONNECT: accept-version 1.2, default heart-beat, no-auth.
conn = stomp.Connection([(host, port)], heartbeats=(10000, 10000))
conn.connect(login="my-app", passcode="", wait=True)
try:
conn.send(destination=destination, body="hello from STOMP",
content_type="text/plain")
print(f"sent 1 message to {destination} (channel orders.new)")
finally:
conn.disconnect()
if __name__ == "__main__":
main()
```
```java
import java.net.URI;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.messaging.tcp.reactor.ReactorNettyTcpClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.messaging.simp.stomp.ReactorNettyTcpStompClient;
public final class Main {
public static void main(String[] args) throws Exception {
String url = System.getenv().getOrDefault("KUBEMQ_STOMP_URL", "tcp://localhost:61613");
URI uri = URI.create(url);
String destination = "/queue/orders/new"; // Queues pattern, channel "orders.new"
// CONNECT over raw TCP; Spring negotiates STOMP 1.2 by default.
ReactorNettyTcpStompClient client =
new ReactorNettyTcpStompClient(uri.getHost(), uri.getPort());
StompSession session =
client.connect(new StompSessionHandlerAdapter() {}).get();
StompHeaders headers = new StompHeaders();
headers.setDestination(destination);
headers.add("content-type", "text/plain");
session.send(headers, "hello from STOMP".getBytes());
System.out.printf("sent 1 message to %s (channel orders.new)%n", destination);
session.disconnect();
client.shutdown();
}
}
```
```typescript
import { connect, type Client } from "stompit";
function endpoint(): { host: string; port: number } {
const url = new URL(process.env["KUBEMQ_STOMP_URL"] ?? "tcp://localhost:61613");
return { host: url.hostname, port: Number(url.port) || 61613 };
}
async function main(): Promise {
const destination = "/queue/orders/new"; // Queues pattern, channel "orders.new"
const { host, port } = endpoint();
// CONNECT over raw TCP — stompit, NOT @stomp/stompjs (which is WebSocket-only).
const client: Client = await new Promise((resolve, reject) => {
connect({ host, port, connectHeaders: { "accept-version": "1.2",
"heart-beat": "10000,10000", login: "my-app" } },
(err, c) => (err ? reject(err) : resolve(c)));
});
const frame = client.send({ destination, "content-type": "text/plain" });
frame.write("hello from STOMP");
frame.end();
console.log(`sent 1 message to ${destination} (channel orders.new)`);
client.disconnect();
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
```
```csharp
using System.Text;
using Stomp.Net;
static string BrokerUri()
{
var url = Environment.GetEnvironmentVariable("KUBEMQ_STOMP_URL") ?? "tcp://localhost:61613";
var u = new Uri(url);
// Stomp.Net dispatches on the outer scheme: tcp:// or ssl://.
var transport = u.Scheme == "tls" ? "ssl" : "tcp";
return $"{transport}://{u.Host}:{(u.Port > 0 ? u.Port : 61613)}";
}
const string destination = "/queue/orders/new"; // Queues pattern, channel "orders.new"
// CONNECT: Stomp.Net performs the STOMP 1.2 handshake; no-auth default.
var factory = new ConnectionFactory(BrokerUri(), new StompConnectionSettings());
using var connection = factory.CreateConnection();
connection.Start();
using var session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
using var producer = session.CreateProducer(session.GetQueue(destination));
var message = session.CreateBytesMessage(Encoding.UTF8.GetBytes("hello from STOMP"));
message.StompType = "text/plain";
producer.Send(message);
Console.WriteLine($"sent 1 message to {destination} (channel orders.new)");
```
```ruby
require "stomp"
require "uri"
uri = URI.parse(ENV.fetch("KUBEMQ_STOMP_URL", "tcp://localhost:61613"))
destination = "/queue/orders/new" # Queues pattern, channel "orders.new"
# CONNECT: accept-version 1.2, default heart-beat, no-auth.
client = Stomp::Client.new(
hosts: [{ host: uri.host, port: uri.port }],
connect_headers: { "accept-version" => "1.2", "heart-beat" => "10000,10000",
"login" => "my-app", "passcode" => "" },
)
client.publish(destination, "hello from STOMP", { "content-type" => "text/plain" })
puts "sent 1 message to #{destination} (channel orders.new)"
client.close
```
```rust
use async_stomp::client::Connector;
use async_stomp::ToServer;
use futures::SinkExt;
#[tokio::main]
async fn main() -> Result<(), Box> {
let url = std::env::var("KUBEMQ_STOMP_URL").unwrap_or_else(|_| "tcp://localhost:61613".into());
let host_port = url.split("://").nth(1).unwrap_or("localhost:61613");
let destination = "/queue/orders/new"; // Queues pattern, channel "orders.new"
// CONNECT over raw TCP; async-stomp negotiates STOMP 1.2.
let mut conn = Connector::builder()
.server(host_port)
.login("my-app".to_string())
.passcode(String::new())
.connect()
.await?;
conn.send(ToServer::Send {
destination: destination.to_string(),
transaction: None,
headers: Some(vec![("content-type".to_string(), "text/plain".to_string())]),
body: Some(b"hello from STOMP".to_vec()),
})
.await?;
println!("sent 1 message to {destination} (channel orders.new)");
conn.send(ToServer::Disconnect { receipt: None }).await?;
Ok(())
}
```
## Supported languages [#supported-languages]
The connector speaks standard STOMP over raw TCP, so any conformant native STOMP client works.
The examples pin one client per language — there is no KubeMQ SDK, no proto bindings, and no
published package. Only `go-stomp/v3` and `stomp.py` are proven by kubemq-server integration
tests; the others are wire-compatible.
| Language | Client library | Notes |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- |
| Go | [`github.com/go-stomp/stomp/v3`](https://github.com/go-stomp/stomp) | The connector's reference client. |
| Python | [`stomp.py`](https://github.com/jasonrbriggs/stomp.py) | Listener-based; install via `uv`. |
| Java | Spring [`ReactorNettyTcpStompClient`](https://docs.spring.io/spring-framework/reference/web/websocket/stomp.html) (spring-messaging) | Raw-TCP STOMP over Reactor Netty. |
| JavaScript / TypeScript | [`stompit`](https://github.com/gdaws/stompit) | Raw TCP — **not** `@stomp/stompjs` (WebSocket-only). |
| C# / .NET | [`Stomp.Net`](https://github.com/DaveSenn/Stomp.Net) | NMS-style API over STOMP 1.2. |
| Ruby | [`stomp`](https://github.com/stompgem/stomp) gem | Native STOMP 1.0/1.1/1.2 client. |
| Rust | [`async-stomp`](https://docs.rs/async-stomp) | async/await on Tokio. |
**`@stomp/stompjs` is WebSocket-only and cannot drive the STOMP connector.** The connector
listens on raw TCP (61613/61614) with no WebSocket upgrade, so the JavaScript/TypeScript
examples use `stompit` (raw TCP). See
[Connectivity and security](/connectors/stomp/how-to/connectivity-and-security).
## Next steps [#next-steps]
# Install air-gapped (/deploy/install/air-gapped)
This page licenses a KubeMQ cluster on Kubernetes that has no internet access. You request an offline license file, store it in the cluster, and install from a bundle that KubeMQ support provides. Time: about 60 minutes.
The work happens in two sittings: steps 1–2, then a wait for KubeMQ to send your offline license file, then step 3. Need an offline Docker server? [Contact support](mailto:support@kubemq.io).
These commands are for bash on macOS and Linux. On Windows, run them in WSL (Windows Subsystem for Linux), or use the kmq tab of [Try KubeMQ](/deploy/quickstart), which runs natively on Windows.
## Before you start [#before-you-start]
Do this on the administration machine inside your network.
Create a private folder, readable only by you, and work inside it:
```bash
mkdir -p -m 700 kubemq-private
```
```bash
cd kubemq-private
```
* `kubectl` with a context for the target cluster.
* An offline license file, requested in step 2 ([Plans compared](/licensing#compare-the-options)).
* The software bundle. Contact support for the offline artifact bundle.
## Steps [#steps]
### Create the namespace [#create-the-namespace]
```bash
kubectl --context YOUR_KUBE_CONTEXT create namespace kubemq --dry-run=client -o yaml | kubectl --context YOUR_KUBE_CONTEXT apply -f -
```
Replace: `YOUR_KUBE_CONTEXT` — the target cluster's kubectl context.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
### Request your offline license file [#request-your-offline-license-file]
```bash
kubectl --context YOUR_KUBE_CONTEXT get namespace kube-system -o jsonpath='{.metadata.uid}'
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
This one line is your cluster ID. Send it and your server count through [Plans compared](/licensing#buy). Put the `kubemq.license` you receive in `kubemq-private`.
### Apply the offline license file [#apply-the-offline-license-file]
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq create secret generic messaging-license --from-file=licenseFile=kubemq.license --dry-run=client -o yaml | kubectl --context YOUR_KUBE_CONTEXT apply -f -
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Install the operator and the cluster from the support bundle. Its cluster values reference this Secret with `licenseFileSecretRef`.
### Renew before it expires [#renew-before-it-expires]
The file does not renew itself: the servers stop on the `license_expires_at` date `kmq license` shows (after a port-forward and sign-in, as in [Licensing troubleshooting](/licensing/troubleshooting#check-the-license-status)). Monitor it as [How licensing works](/licensing/how-it-works#check-license-status) describes. To renew, repeat step 2, replace `kubemq.license`, and repeat step 3. Servers restart one at a time, keeping their data.
## If something goes wrong [#if-something-goes-wrong]
* **No servers start.** If `kubectl describe` on the `messaging` cluster shows `LicenseInvalid`, the operator rejected the file ([Troubleshooting](/licensing/troubleshooting#invalid-signature)).
* **A server logs `#fingerprint-mismatch`.** The file is for another cluster ([Troubleshooting](/licensing/troubleshooting#fingerprint-mismatch)).
## Next steps [#next-steps]
# Install with Docker (/deploy/install/docker)
This page turns the server you started in [Try KubeMQ](/deploy/quickstart) into a licensed server you keep, using your own container commands. When you finish, `kmq license` reports that license adoption is accepted and durable and your data is unchanged. Time: about 10 minutes.
With Podman, use `podman` in place of `docker` in every command.
These commands are for bash on macOS and Linux. On Windows, run them in WSL (Windows Subsystem for Linux), or use the kmq tab of [Try KubeMQ](/deploy/quickstart), which runs natively on Windows.
## Before you start [#before-you-start]
Create a private folder, readable only by you, and work inside it:
```bash
mkdir -p -m 700 kubemq-private
```
```bash
cd kubemq-private
```
* A server from [Try KubeMQ](/deploy/quickstart), Docker tab. After the kmq tab, use [Install with kmq](/deploy/install/kmq). No server? See [If something goes wrong](#if-something-goes-wrong).
* kmq, the KubeMQ command-line tool, installed as in [Try KubeMQ](/deploy/quickstart#install-kmq).
* A trial key or a license key: see [Plans compared](/licensing#compare-the-options).
## Steps [#steps]
### Add your license [#add-your-license]
1. Open the [trial page](https://onboarding.kubemq.io/trial).
2. Choose **Docker (1 server)**.
3. Enter your work email, name and company; accept the trial terms .
4. Enter the code KubeMQ emails you. The trial key arrives by email.
No email? Use **Recover a trial key** on the same page.
Or use the kmq trial steps on [Install with kmq](/deploy/install/kmq#add-your-license) with `"platform": "docker"` in the request file, then run `kmq license export --credential YOUR_LICENSE_REF --out license.key` instead of saving the key below. Replace: `YOUR_LICENSE_REF` — the `credential` value that `kmq trial claim` printed.
Use the key from your KubeMQ order email.
Save the license key as `license.key` in this folder. The file holds only the key, on one line, with no quotes and no `KUBEMQ_LICENSE_KEY=` prefix. Then make it readable by you alone:
```bash
chmod 600 license.key
```
This file is a secret. Do not commit it, paste it into chat, or attach it to a support ticket.
Write the key into a Docker environment file:
```bash
(umask 077; { printf 'KUBEMQ_LICENSE_KEY='; cat license.key; } > kubemq-license.env)
```
Stop and remove the container; `kubemq-data` keeps the data:
```bash
docker stop kubemq
```
```bash
docker rm kubemq
```
Start it again with the license:
With Podman:
Check that the server is running:
```bash
docker ps --filter name=kubemq --format '{{.Names}}: {{.Status}}'
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
| Flag | What it does |
| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-p 127.0.0.1:…` | Publishes four ports to this machine only: `50000` gRPC, `9090` REST, `8080` dashboard and management API, `9092` Kafka-compatible. |
| `--name kubemq`, `--hostname kubemq` | Name the container and the server. The server files its data under the hostname, so keep both when you recreate the container. |
| `-v kubemq-data:/kubemq/store` | Keeps messages, the administrator, the server's identity and its license in the `kubemq-data` volume. |
| `--env-file kubemq-license.env` | Sets `KUBEMQ_LICENSE_KEY`. Keep it on every start: once the server accepts a key, it refuses to start without one. See [Core & Licensing](/configure/reference/core#license). |
| `-e STORE_ENGINE=next` | Selects the storage engine. |
| `-e STORE_NEXT_ACK_POLICY=strict` | Confirms a message only after it is written to disk. |
| `-e STORE_STORE_PATH=/kubemq/store` | Stores data on the volume. |
| `-e API_BIND_ADDRESS=0.0.0.0` | Lets the published management port reach the server inside the container. |
| `--pull always` | Fetches the latest release on every start. |
| `--platform linux/amd64` | Runs the x86-64 image; an Arm machine emulates it. |
### Check the license [#check-the-license]
If kmq has no saved connection to this server (you started it with the Docker command, not with kmq), sign in first:
```bash
kmq auth login --api-address http://127.0.0.1:8080 --context-name kubemq --username admin
```
Select the context saved by the login:
```bash
kmq context use kubemq
```
```bash
kmq license
```
You should see:
```json title="Output"
{
"server_version": "...",
"adoption": {
"configured_input_sha256": "...",
"accepted_input_sha256": "...",
"state": "accepted",
"durable": true
},
"plan": "trial",
"mode": "online",
"source": "key",
"license_expires_at": "...",
"lease_expires_at": "...",
"run_until": "...",
"over_cap": false,
"stop_cause": null
}
```
In the `adoption` object, `state` is `accepted`, `durable` is `true`, and the configured and accepted input hashes match. `plan` and `license_expires_at` match your license. `stop_cause` is `null` and `over_cap` is `false`. Other states: [How licensing works](/licensing/how-it-works#check-license-status). If kmq cannot connect, wait a few seconds and run it again.
Sign in at `http://localhost:8080`: the `orders` channel from Try KubeMQ is still there.
Open the [Release notes](/release-notes) and copy the version they list for the server image. Wherever a command names `kubemq-next:latest`, write `kubemq-next:YOUR_VERSION` instead, and remove `--pull always` from the `docker run` or `podman run` command.
Replace: `YOUR_VERSION` — the release number you copied, with a leading `v`.
To pin by digest, write `kubemq-next@YOUR_DIGEST` instead, with the server image digest the release notes list.
Replace: `YOUR_DIGEST` — the digest, starting `sha256:`.
Pinned installs do not update themselves. Check the release notes and move to the latest release regularly.
### Use Docker Compose instead [#use-docker-compose-instead]
Instead of step 1's start command, use Compose:
```bash
curl -fsSLO https://docs.kubemq.io/docker-compose.yml
```
Turn on its `env_file` line:
```bash
sed -i.bak 's|# env_file:|env_file:|' docker-compose.yml
```
Then:
```bash
docker compose pull
```
```bash
docker compose up -d
```
Compose reuses `kubemq-data`; expect a warning that Compose did not create it. Check it:
```bash
docker compose ps
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Then step 2.
Open the [Release notes](/release-notes) and copy the version they list for the server image. In `docker-compose.yml`, change the `image:` line to `europe-docker.pkg.dev/kubemq/images/kubemq-next:YOUR_VERSION`, keep the file under version control, and run `docker compose up -d`.
Replace: `YOUR_VERSION` — the release number you copied, with a leading `v`.
To pin by digest, write `kubemq-next@YOUR_DIGEST` instead, with the server image digest the release notes list.
Replace: `YOUR_DIGEST` — the digest, starting `sha256:`.
Pinned installs do not update themselves. Check the release notes and move to the latest release regularly.
### Replace the license later [#replace-the-license-later]
Run `mv license.key license.key.old`, save the new key, and repeat step 1 from the environment file on (with Compose, after the environment file, run `docker compose up -d --force-recreate`), then step 2. If the server does not start, restore the old key the same way; see [Troubleshooting](/licensing/troubleshooting#license-not-accepted).
## Remove the server [#remove-the-server]
`docker stop kubemq` and `docker rm kubemq`, or `docker compose down`, keep the `kubemq-data` volume. Never run `docker compose down -v`.
This deletes every message, the administrator and the server's identity.
```bash
docker volume rm kubemq-data
```
## If something goes wrong [#if-something-goes-wrong]
* **Start with a trial key or license key.** Do step 1 without stopping or removing a container, then step 2, then create the administrator at `http://localhost:8080`.
* **A port is in use.** Change the host side of its `-p` flag, such as `-p 127.0.0.1:18080:8080`. For 8080, also run `kmq license --endpoint http://127.0.0.1:18080`.
* **The container stops at start.** `docker logs kubemq` ends with a [Troubleshooting](/licensing/troubleshooting) link, for example `#first-boot-bad-key` (key refused) or `#no-license-input` (license env file missing).
* **Compose keeps restarting it after a licensing stop.** Run `docker compose stop`, fix the license, then `docker compose up -d`.
## Next steps [#next-steps]
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-p 127.0.0.1:9092:9092 \
--env-file kubemq-license.env \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
```sh
podman run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-p 127.0.0.1:9092:9092 \
--env-file kubemq-license.env \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Install with kmq (/deploy/install/kmq)
This page adds a license to the server you started in Try KubeMQ. When you finish, `kmq license` reports that license adoption is accepted and durable and your data is unchanged. Time: about 10 minutes.
## Before you start [#before-you-start]
* A server from the kmq tab of [Try KubeMQ](/deploy/quickstart#install-kmq).
* A trial key or a license key: see [Plans compared](/licensing#which-one-fits).
## Steps [#steps]
### Add your license [#add-your-license]
Save the request in `kubemq-private` as `trial-request.json`. `"consent": true` records that you accept the trial terms and the [privacy notice](https://kubemq.io/privacy-policy-2/); an AI agent must ask you before writing it.
```json title="trial-request.json"
{ "email": "YOUR_EMAIL", "name": "YOUR_NAME", "company": "YOUR_COMPANY", "platform": "docker", "consent": true }
```
Replace: `YOUR_EMAIL`, `YOUR_NAME`, `YOUR_COMPANY` — your work email, full name and company.
```bash
kmq trial request --input trial-request.json
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Type the emailed code yourself, never in chat.
```bash
kmq trial verify --request YOUR_REQUEST_ID
```
Replace: `YOUR_REQUEST_ID` — the `request_id` printed above.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
```bash
kmq trial claim --request YOUR_REQUEST_ID
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
`credential` is `YOUR_LICENSE_REF`.
Create a private folder, readable only by you, and work inside it:
```bash
mkdir -p -m 700 kubemq-private
```
```bash
cd kubemq-private
```
Save the license key as `license.key` in this folder. The file holds only the key, on one line, with no quotes and no `KUBEMQ_LICENSE_KEY=` prefix. Then make it readable by you alone:
```bash
chmod 600 license.key
```
This file is a secret. Do not commit it, paste it into chat, or attach it to a support ticket.
On Windows, in PowerShell:
```powershell
New-Item -ItemType Directory -Force kubemq-private
```
```powershell
Set-Location kubemq-private
```
```powershell
icacls . /inheritance:r /grant:r "${env:USERNAME}:(OI)(CI)F"
```
```powershell
icacls license.key /inheritance:r /grant:r "${env:USERNAME}:F"
```
Save `license.key` before the last command. Use a non-administrator window.
In any shell:
```bash
kmq license import --file license.key
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
`reference` is `YOUR_LICENSE_REF`.
### Apply it to your server [#apply-it-to-your-server]
```bash
kmq deploy update --installation YOUR_INSTALLATION_ID --credential YOUR_LICENSE_REF --deadline 10m
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq onboard` or `kmq deploy apply` printed; `YOUR_LICENSE_REF` — the reference from step 1.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Data stays; the old container is kept, stopped, as `kubemq-retained-…`.
### Check the license [#check-the-license]
In the `adoption` object, check that `state` is `accepted`, `durable` is `true`, and the configured and accepted input hashes match. `plan` and `license_expires_at` must match your license. `stop_cause` must be `null` and `over_cap` must be `false`.
```bash
kmq license
```
You should see:
```json title="Output"
{
"server_version": "...",
"adoption": {
"configured_input_sha256": "...",
"accepted_input_sha256": "...",
"state": "accepted",
"durable": true
},
"plan": "trial",
"mode": "online",
"source": "key",
"license_expires_at": "...",
"lease_expires_at": "...",
"run_until": "...",
"over_cap": false,
"stop_cause": null
}
```
Other states: [How licensing works](/licensing/how-it-works#check-license-status).
### Replace the license later [#replace-the-license-later]
Repeat steps 1 to 3 without the folder commands. If it does not show, rerun step 2 with the previous reference; see [Troubleshooting](/licensing/troubleshooting#license-not-accepted). Never start a second installation to extend a license.
## Manage your server [#manage-your-server]
To remove the server and keep `kubemq-data`:
```bash
kmq deploy remove --installation YOUR_INSTALLATION_ID
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq onboard` or `kmq deploy apply` printed.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
## Update or remove kmq [#update-or-remove-kmq]
```bash
kmq update
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
[Upgrade KubeMQ](/deploy/upgrade) then updates your server.
Open the [Release notes](/release-notes) and copy the kmq version they list.
If kmq is installed, switch it to that release:
```bash
kmq update --version YOUR_VERSION
```
Replace: `YOUR_VERSION` — the release number you copied, with a leading `v`.
On a machine without kmq, download the installer as [Try KubeMQ](/deploy/quickstart#install-kmq) shows, then run it with that release:
```bash
sh install-kmq.sh --version YOUR_VERSION
```
On Windows, in PowerShell:
```powershell
& .\install-kmq.ps1 -Version YOUR_VERSION
```
That kmq installs its matching server release. A pinned install does not update itself: read the release notes and move to the latest release regularly. `kmq update` with no `--version` returns kmq to the latest release.
To remove kmq, delete `kmq` from `/usr/local/bin`, `~/.local/bin` or `~/bin` (Windows: `%LOCALAPPDATA%\Programs\kmq`).
## Use kmq from an AI coding agent [#use-kmq-from-an-ai-coding-agent]
```bash
kmq skills install
```
It adds the kmq skill to `.claude/skills/kmq` and `AGENTS.md` here; `--global` installs it for your user ([kmq CLI](/operate/kmq-cli#agent-skill-distribution)). A starting prompt:
```text title="Prompt"
Use kmq to install KubeMQ on this machine. Run `kmq schema -o json` first. Ask me before creating anything. I will type passwords and email codes myself; never ask me to paste them.
```
## If something goes wrong [#if-something-goes-wrong]
* **Try KubeMQ found no evaluation left.** Get a reference in step 1 and run `kmq onboard --goal trial --name kubemq --credential YOUR_LICENSE_REF --pull --continue-volume --deadline 10m` (first `docker rm kubemq` if needed); `--goal trial` runs a Docker server on any saved license, trial or paid. Replace: `YOUR_LICENSE_REF` — as in step 2. Then do Try KubeMQ steps 3 and 4 (`kmq auth login` if an administrator exists) and step 3 here.
* **No email code, or a lost trial key.** Run `kmq trial resend-verification --request YOUR_REQUEST_ID` or `kmq trial resume --request YOUR_REQUEST_ID`, or `kmq license recover --email YOUR_EMAIL` for a lost key, then verify and claim. Replace: `YOUR_REQUEST_ID`, `YOUR_EMAIL` — as in step 1.
* **`credential_storage_unavailable`.** On Linux with no keyring, add `--credential-backend file` to every `kmq trial`, `kmq license`, `kmq deploy`, `kmq auth` and `kmq onboard` command, and check `chmod 600 license.key`.
* **`docker volume rm kubemq-data` says the volume is in use.** Remove the `kubemq-retained-…` containers with `docker rm`.
## Next steps [#next-steps]
# Install on Kubernetes (/deploy/install/kubernetes)
This page shows how to install the KubeMQ operator and a cluster of three servers on Kubernetes, with kmq or with Helm. When you finish, `kmq license` reports the license on every server, a test message round-trips, and you know the address your applications use. Time: about 30 minutes.
Hardening for production traffic is on the [Production checklist](/deploy/production-checklist).
These commands are for bash on macOS and Linux. On Windows, run them in WSL (Windows Subsystem for Linux), or use the kmq tab of [Try KubeMQ](/deploy/quickstart), which runs natively on Windows.
The cluster `messaging`, as the operator runs it:
## Before you start [#before-you-start]
Create a private folder, readable only by you, and work inside it:
```bash
mkdir -p -m 700 kubemq-private
```
```bash
cd kubemq-private
```
* kubectl, Helm, curl and jq, with a context for the target cluster. The kmq tab runs kubectl and Helm for you.
* kmq, installed as in [Try KubeMQ](/deploy/quickstart#install-kmq). Both tabs use it.
* Permission to create custom resource definitions and cluster roles.
* A storage class that creates volumes on demand. Note its name:
```bash
kubectl --context YOUR_KUBE_CONTEXT get storageclass
```
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context, from `kubectl config get-contexts`.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Node and network needs: [Requirements and supported setups](/deploy/install/requirements#kubernetes).
## Add your license [#add-your-license]
A trial key for Kubernetes is not self-serve yet: KubeMQ issues it after a request. Ask for one through [Plans compared](/licensing#buy), naming Kubernetes and 3 servers. The key arrives by email as `license.key`; then follow the **License key** tab. The key covers one cluster of 3 servers and binds to the first cluster it starts on.
Use the key from your KubeMQ order email. It must cover at least 3 servers.
Save the license key as `license.key` in this folder. The file holds only the key, on one line, with no quotes and no `KUBEMQ_LICENSE_KEY=` prefix. Then make it readable by you alone:
```bash
chmod 600 license.key
```
This file is a secret. Do not commit it, paste it into chat, or attach it to a support ticket.
```bash
kmq license import --file license.key
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
kmq printed a license reference, `credential` or `reference`. The kmq tab uses it and creates its own license Secret; Helm step 2 stores `license.key` as the Secret `messaging-license`, exporting a trial key first.
## Steps [#steps]
### Write the install file [#write-the-install-file]
In `kubemq-private`:
```json title="kubernetes.json"
{
"schema_version": 1,
"goal": "production",
"target": "kubernetes",
"name": "messaging",
"credential": "YOUR_LICENSE_REF",
"kubernetes": {
"context": "YOUR_KUBE_CONTEXT",
"namespace": "kubemq",
"operator_release": "kubemq-operator",
"cluster_release": "messaging",
"server_count": 3,
"storage_class": "YOUR_STORAGE_CLASS",
"volume_size": "20Gi"
}
}
```
Replace: `YOUR_LICENSE_REF` — your license reference; `YOUR_KUBE_CONTEXT` — your cluster's kubectl context; `YOUR_STORAGE_CLASS` — the storage class you noted.
### Check the cluster and save a plan [#check-the-cluster-and-save-a-plan]
Download the current public release recipe:
```bash
curl -fsSL https://docs.kubemq.io/recipes/onboarding-v1.json -o onboarding-v1.json
```
Write its independently released server image, chart and operator image into the deployment input. When `--input` is used, the input file supplies these values:
```bash
jq -e --slurpfile recipe onboarding-v1.json '
$recipe[0] as $r |
if (($r.server_image // "") != "" and
($r.chart_version // "") != "" and
($r.operator_image // "") != "")
then .image = $r.server_image |
.kubernetes.chart_version = $r.chart_version |
.kubernetes.operator_image = $r.operator_image
else error("release recipe is missing a required Kubernetes artifact")
end
' kubernetes.json > kubernetes.resolved.json &&
mv kubernetes.resolved.json kubernetes.json
```
Prepare the resolved input:
```bash
kmq deploy prepare --input kubernetes.json --out prepared.json --deadline 10m
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
It creates the namespace, a license Secret and a management certificate Secret that kmq trusts.
```bash
kmq deploy plan --input prepared.json --out plan.json
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
### Install the operator and the cluster [#install-the-operator-and-the-cluster]
```bash
kmq deploy apply --plan plan.json --deadline 15m
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
After an interruption, run it again; it resumes.
### Create the namespace [#create-the-namespace]
```bash
kubectl --context YOUR_KUBE_CONTEXT create namespace kubemq --dry-run=client -o yaml | kubectl --context YOUR_KUBE_CONTEXT apply -f -
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
### Store the license as a Secret [#store-the-license-as-a-secret]
With a trial key, export it first (delete an old `license.key`; kmq never overwrites):
```bash
kmq license export --credential YOUR_LICENSE_REF --out license.key
```
Replace: `YOUR_LICENSE_REF` — your license reference.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Create the Secret; the same command replaces it:
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq create secret generic messaging-license --from-file=licenseKey=license.key --dry-run=client -o yaml | kubectl --context YOUR_KUBE_CONTEXT apply -f -
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Create the management TLS Secret before installing the cluster. The certificate must cover `messaging-api.kubemq.svc`, `messaging-api.kubemq.svc.cluster.local` and `127.0.0.1`:
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq create secret tls messaging-api-tls --cert=YOUR_TLS_CERT_FILE --key=YOUR_TLS_KEY_FILE --dry-run=client -o yaml | kubectl --context YOUR_KUBE_CONTEXT apply -f -
```
Replace: `YOUR_TLS_CERT_FILE` — the certificate; `YOUR_TLS_KEY_FILE` — its key; `YOUR_KUBE_CONTEXT` — your cluster's kubectl context. Keep the issuing authority certificate as `YOUR_CA_FILE` for sign-in.
Never use `--set licenseKey=`, `--from-literal` or a key in `cluster-values.yaml`: Helm stores values in the cluster.
### Install the operator [#install-the-operator]
```bash
helm repo add kubemq-next https://kubemq-io.github.io/charts-next
```
```bash
helm repo update kubemq-next
```
```bash
helm upgrade --install kubemq-operator kubemq-next/kubemq-next \
--kube-context YOUR_KUBE_CONTEXT \
-n kubemq \
--set operator.enabled=true \
--set cluster.enabled=false \
--wait
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
### Install the cluster [#install-the-cluster]
In `kubemq-private`:
```yaml title="cluster-values.yaml"
operator:
enabled: false
cluster:
enabled: true
fullnameOverride: messaging
replicas: 3
licenseKeySecretRef:
name: messaging-license
key: licenseKey
volume:
size: 20Gi
storageClass: YOUR_STORAGE_CLASS
api:
tlsSecret: messaging-api-tls
expose: ClusterIP
auth:
enable: true
adminUsername: admin
env:
STORE_NEXT_ACK_POLICY: "strict"
```
Replace: `YOUR_STORAGE_CLASS` — the storage class you noted.
License fields, resources and node spread: [Deployment & High Availability](/configure/reference/deployment#license).
```bash
helm upgrade --install messaging kubemq-next/kubemq-next \
--kube-context YOUR_KUBE_CONTEXT \
-n kubemq \
-f cluster-values.yaml
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Then wait until every server is ready:
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq wait --for=condition=Ready kubemqclusters.next.kubemq.io/messaging --timeout=10m
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Check the license the operator reports:
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq describe kubemqclusters.next.kubemq.io messaging
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Check that the conditions include neither `LicenseInvalid` nor `ReplicasOverLicenseCap`. Per-server detail comes from `kmq license` once you sign in below; it shows the server behind the open management port, and any state other than `active` needs attention: [How licensing works](/licensing/how-it-works#check-license-status).
Open the [Release notes](/release-notes) and copy the kmq version they list.
If kmq is installed, switch it to that release:
```bash
kmq update --version YOUR_VERSION
```
Replace: `YOUR_VERSION` — the release number you copied, with a leading `v`.
On a machine without kmq, download the installer as [Try KubeMQ](/deploy/quickstart#install-kmq) shows, then run it with that release:
```bash
sh install-kmq.sh --version YOUR_VERSION
```
On Windows, in PowerShell:
```powershell
& .\install-kmq.ps1 -Version YOUR_VERSION
```
That kmq installs its matching server release. A pinned install does not update itself: read the release notes and move to the latest release regularly. `kmq update` with no `--version` returns kmq to the latest release.
Open the [Release notes](/release-notes) and copy the version they list for the Helm chart. Add `--version YOUR_VERSION` to every `helm upgrade --install` command and, when you upgrade, to `helm show crds`. Use the same value for the operator release and the cluster release, so the custom resource definitions match the pinned operator. `helm search repo kubemq-next/kubemq-next --versions` lists every published chart version.
Replace: `YOUR_VERSION` — the release number you copied, with no leading `v`.
Pinned installs do not update themselves. Check the release notes and move to the latest release regularly.
To install with Argo CD or Flux, pin the chart in your deployment repository. Open the [Release notes](/release-notes) and copy the version they list for the Helm chart.
* Deploy the chart `kubemq-next` from `https://kubemq-io.github.io/charts-next` twice, as the operator release and the cluster release, with the same values as the Helm commands on this page.
* Pin both releases to the same version: Argo CD `spec.source.targetRevision: YOUR_VERSION`, or Flux HelmRelease `spec.chart.spec.version: YOUR_VERSION`.
* On Flux, set `spec.install.crds: CreateReplace` and `spec.upgrade.crds: CreateReplace`. The defaults never upgrade the custom resource definitions.
* Sync the cluster release after the operator release: Flux `spec.dependsOn`, or Argo CD sync waves.
* Create the Secret `messaging-license`, key `licenseKey`, from your secret manager, for example External Secrets or Sealed Secrets. Never put the key in the values.
* Point update tools such as Renovate or Flux image automation at the `charts-next` chart index, never at an image's `latest` tag.
Replace: `YOUR_VERSION` — the release number you copied, with no leading `v`.
Pinned installs do not update themselves. Check the release notes and move to the latest release regularly.
## Send a test message [#send-a-test-message]
### Open the management port [#open-the-management-port]
```bash title="Terminal 2"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq port-forward pod/messaging-0 18080:8080
```
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Leave it running.
### Sign in [#sign-in]
```bash
kmq auth login --bootstrap --installation YOUR_INSTALLATION_ID --username admin --api-address https://127.0.0.1:18080
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq onboard` or `kmq deploy apply` printed.
kmq reads the first password from the cluster and asks for a new one. You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Save the first password in `kubemq-private`:
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq get secret messaging-api-admin -o jsonpath='{.data.admin-password}' | base64 -d > admin-password
```
```bash
kmq auth login --username admin --api-address https://127.0.0.1:18080 --ca-file YOUR_CA_FILE --context-name messaging --service-name messaging-kmq-tls
```
Replace: `YOUR_CA_FILE` — the certificate authority that issued the management certificate. Paste the contents of `admin-password` when kmq asks, then set a new password. You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
The Secret's `operator-token` key belongs to the operator. Never use it.
Repeat the login only when its output explicitly says that no account was created and nothing changed. If it reports `account_created: true`, do not repeat the login because the service account already exists. When it also reports that the credential and context were saved, select that context in the next step and wait for the credential to verify. If either was not saved, follow the printed `next_action` to repair the selected store or context; if the key is unavailable, ask [support](mailto:support@kubemq.io) to remove the orphaned account before another login.
### Point kmq at the cluster [#point-kmq-at-the-cluster]
```bash
kmq context use messaging
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Confirm the saved service credential without creating another account:
```bash
verified=false
for attempt in $(seq 1 30); do
if kmq whoami; then
verified=true
break
fi
sleep 2
done
[ "$verified" = true ] || { echo "The saved service credential did not become ready." >&2; exit 1; }
```
### Send and receive [#send-and-receive]
```bash
kmq queue send onboarding-check '{"id":1}'
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
```bash
kmq queue receive onboarding-check
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
## Connect your applications [#connect-your-applications]
Applications inside the cluster use these Services, all `ClusterIP`:
| Interface | In-cluster address | Port |
| -------------------------------- | ------------------------------------------ | ------- |
| gRPC | `messaging-grpc.kubemq.svc.cluster.local` | `50000` |
| REST | `messaging-rest.kubemq.svc.cluster.local` | `9090` |
| Kafka-compatible | `messaging-kafka.kubemq.svc.cluster.local` | `9092` |
| RabbitMQ-compatible (AMQP 0-9-1) | `messaging-amqp.kubemq.svc.cluster.local` | `5672` |
From outside Kubernetes: [Interfaces (gRPC · REST · API · HTTP)](/configure/reference/interfaces). Client code: [Client SDKs](/sdks).
## Replace the license later [#replace-the-license-later]
Get the new license as in [Add your license](#add-your-license).
```bash
OLD_REVISION="$(kubectl --context YOUR_KUBE_CONTEXT -n kubemq get statefulset messaging -o jsonpath='{.status.currentRevision}')"
kmq deploy update --installation YOUR_INSTALLATION_ID --credential YOUR_LICENSE_REF --deadline 15m
for attempt in $(seq 1 150); do
NEW_REVISION="$(kubectl --context YOUR_KUBE_CONTEXT -n kubemq get statefulset messaging -o jsonpath='{.status.updateRevision}')"
[ -n "$NEW_REVISION" ] && [ "$NEW_REVISION" != "$OLD_REVISION" ] && break
sleep 2
done
[ -n "$NEW_REVISION" ] && [ "$NEW_REVISION" != "$OLD_REVISION" ] || { echo "The license replacement did not start a new StatefulSet revision." >&2; exit 1; }
kubectl --context YOUR_KUBE_CONTEXT -n kubemq rollout status statefulset/messaging --timeout=10m
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq onboard` or `kmq deploy apply` printed; `YOUR_LICENSE_REF` — the new reference; `YOUR_KUBE_CONTEXT` — your cluster's kubectl context.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Put the new key in `license.key`. Record the current StatefulSet revision, replace the Secret and wait for the new revision to finish rolling out:
```bash
OLD_REVISION="$(kubectl --context YOUR_KUBE_CONTEXT -n kubemq get statefulset messaging -o jsonpath='{.status.currentRevision}')"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq create secret generic messaging-license --from-file=licenseKey=license.key --dry-run=client -o yaml | kubectl --context YOUR_KUBE_CONTEXT apply -f -
for attempt in $(seq 1 150); do
NEW_REVISION="$(kubectl --context YOUR_KUBE_CONTEXT -n kubemq get statefulset messaging -o jsonpath='{.status.updateRevision}')"
[ -n "$NEW_REVISION" ] && [ "$NEW_REVISION" != "$OLD_REVISION" ] && break
sleep 2
done
[ -n "$NEW_REVISION" ] && [ "$NEW_REVISION" != "$OLD_REVISION" ] || { echo "The license replacement did not start a new StatefulSet revision." >&2; exit 1; }
kubectl --context YOUR_KUBE_CONTEXT -n kubemq rollout status statefulset/messaging --timeout=10m
```
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context.
The operator restarts the servers one at a time, keeping their data; an online key needs internet access meanwhile. Then run the `kmq license` command again. If a server does not become ready, put the previous license back and see [Troubleshooting](/licensing/troubleshooting#license-not-accepted).
## Remove the cluster [#remove-the-cluster]
```bash
kmq deploy remove --installation YOUR_INSTALLATION_ID --deadline 15m
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq onboard` or `kmq deploy apply` printed.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Helm keeps the cluster resource, so delete it first:
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq delete kubemqclusters.next.kubemq.io messaging --wait
```
```bash
helm uninstall messaging --kube-context YOUR_KUBE_CONTEXT -n kubemq
```
Both keep the volumes and the operator. Remove the operator once no cluster uses it:
```bash
helm uninstall kubemq-operator --kube-context YOUR_KUBE_CONTEXT -n kubemq
```
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context.
Deleting the volume claims or the namespace deletes every message and the cluster's identity. Keep your administrator password; a cluster on these volumes needs it.
## Use your own management certificate [#management-certificate]
For production, use a management certificate your organization issues. The Helm steps above create the required Secret from certificate files before installing the cluster. With cert-manager, apply this after creating the namespace and before installing the cluster instead:
```yaml title="management-certificate.yaml"
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: messaging-api
namespace: kubemq
spec:
secretName: messaging-api-tls
dnsNames:
- messaging-api.kubemq.svc
- messaging-api.kubemq.svc.cluster.local
ipAddresses:
- 127.0.0.1
issuerRef:
name: YOUR_ISSUER
```
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq apply -f management-certificate.yaml
```
Replace: `YOUR_ISSUER` — a cert-manager issuer in `kubemq` (for a cluster issuer, add `kind: ClusterIssuer`); `YOUR_KUBE_CONTEXT` — your cluster's kubectl context.
At first install only, before kmq step 2, add two fields to `kubernetes.json`:
```json title="kubernetes.json"
{
"schema_version": 1,
"goal": "production",
"target": "kubernetes",
"name": "messaging",
"credential": "YOUR_LICENSE_REF",
"kubernetes": {
"context": "YOUR_KUBE_CONTEXT",
"namespace": "kubemq",
"operator_release": "kubemq-operator",
"cluster_release": "messaging",
"server_count": 3,
"storage_class": "YOUR_STORAGE_CLASS",
"volume_size": "20Gi",
"tls_secret": "messaging-api-tls",
"ca_file": "YOUR_CA_FILE"
}
}
```
Replace: `YOUR_CA_FILE` — your issuing authority's certificate; `YOUR_LICENSE_REF`, `YOUR_KUBE_CONTEXT`, `YOUR_STORAGE_CLASS` — as in kmq step 1.
On a cluster kmq already installed, [contact support](mailto:support@kubemq.io).
The Helm install already sets `tlsSecret: messaging-api-tls`. To rotate the certificate, replace the certificate, key and authority file at the same paths. Then replace the Secret, explicitly restart the StatefulSet and verify that the new revision finishes rolling out:
```bash
OLD_REVISION="$(kubectl --context YOUR_KUBE_CONTEXT -n kubemq get statefulset messaging -o jsonpath='{.status.currentRevision}')"
kubectl --context YOUR_KUBE_CONTEXT -n kubemq create secret tls messaging-api-tls --cert=YOUR_TLS_CERT_FILE --key=YOUR_TLS_KEY_FILE --dry-run=client -o yaml | kubectl --context YOUR_KUBE_CONTEXT apply -f -
kubectl --context YOUR_KUBE_CONTEXT -n kubemq rollout restart statefulset/messaging
kubectl --context YOUR_KUBE_CONTEXT -n kubemq rollout status statefulset/messaging --timeout=10m
NEW_REVISION="$(kubectl --context YOUR_KUBE_CONTEXT -n kubemq get statefulset messaging -o jsonpath='{.status.currentRevision}')"
[ -n "$NEW_REVISION" ] && [ "$NEW_REVISION" != "$OLD_REVISION" ] || { echo "The certificate restart did not finish a new StatefulSet revision." >&2; exit 1; }
```
Replace: `YOUR_TLS_CERT_FILE` — the replacement certificate; `YOUR_TLS_KEY_FILE` — its key; `YOUR_KUBE_CONTEXT` — your cluster's kubectl context. Restart the Terminal 2 port-forward after the rollout. The saved context verifies the new authority file on its next request.
## If something goes wrong [#if-something-goes-wrong]
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context.
* **Pods stay `Pending`.** `kubectl --context YOUR_KUBE_CONTEXT -n kubemq describe pod messaging-0` says why: usually storage or too few nodes; see [Requirements and supported setups](/deploy/install/requirements#kubernetes).
* **`ImagePullBackOff`.** The nodes cannot reach the registry; see [Requirements and supported setups](/deploy/install/requirements#network) or [Install air-gapped](/deploy/install/air-gapped).
* **`credential_storage_unavailable`.** On Linux with no keyring, add `--credential-backend file` to every `kmq trial`, `kmq license`, `kmq deploy` and `kmq auth` command.
* **A server stops with a licensing message.** `kubectl --context YOUR_KUBE_CONTEXT -n kubemq logs messaging-0` prints a [Troubleshooting](/licensing/troubleshooting) link, such as `#cluster-over-cap`.
## Next steps [#next-steps]
# Requirements and supported setups (/deploy/install/requirements)
This page lists the setups KubeMQ supports, Kubernetes and platform requirements, sizing, network access, and the artifacts every install pulls. The install pages link here.
## Supported setups [#supported-setups]
| Setup | Use it for | Install page |
| ---------------------------------------------------------------------------- | -------------------------------- | ---------------------------------------------------------------------------------------- |
| One KubeMQ server on Docker or Podman | Development and test | [Install with kmq](/deploy/install/kmq) or [Install with Docker](/deploy/install/docker) |
| A cluster of 3 or more servers on Kubernetes, created by the KubeMQ operator | Production and staging | [Install on Kubernetes](/deploy/install/kubernetes) |
| The same Kubernetes cluster with no internet access | Production at an air-gapped site | [Install air-gapped](/deploy/install/air-gapped) |
Not supported:
* A server run directly on a host or virtual machine, in another container runtime, or as several Docker or Podman servers joined into a cluster. The server refuses to start.
* Kubernetes pods that the operator did not create. The server exits; see [Troubleshooting](/licensing/troubleshooting#unmanaged-kubernetes).
* A Kubernetes cluster of fewer than 3 servers, including `standalone: true`.
* Changing the number of servers after the cluster is created, including autoscaling.
* A single Docker server with no internet access. [Contact support](mailto:support@kubemq.io).
## Kubernetes [#kubernetes]
| Requirement | Detail |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Servers | An odd number, at least 3 (3, 5 or 7). The number is fixed when the cluster is created. |
| Operator | The KubeMQ operator creates and manages every server. Each namespace gets one operator release, and its cluster releases go in the same namespace. |
| Storage | A storage class that creates volumes on demand. Each server gets its own persistent volume claim. |
| Server-to-server network | Servers reach each other by stable DNS names through a headless Service on ports 5228 and 5229. The operator creates it. |
| Cluster identity | The server's service account, `kubemq-cluster-next`, reads the `kube-system` namespace, the cluster's license identity. The operator release grants this. |
| Installer permissions | The account that installs KubeMQ can create custom resource definitions, cluster roles and cluster role bindings. |
| Nodes | An x86-64 node for the operator, whose image is x86-64 only. Servers run on x86-64 or Arm nodes. |
| Kubernetes and Helm versions | KubeMQ does not publish minimum versions yet. |
## Platforms [#platforms]
| Requirement | Detail |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Server images | Linux, on x86-64 or 64-bit Arm; kmq pulls the one that matches your machine. The Docker commands on these pages ask for x86-64, so on Apple silicon or another Arm machine they need x86-64 emulation. |
| kmq | Runs natively on macOS, Linux and Windows (x86-64 only on Windows). A server kmq starts still needs Docker Desktop or Podman, but you never open a WSL shell. |
| Shell | The Docker, Kubernetes and air-gapped pages use bash: on Windows, run them in WSL. |
| Podman | Works for one server: add `--runtime podman` to `kmq onboard`, or use the "With Podman" line on [Install with Docker](/deploy/install/docker). |
| File permissions | The server runs as user ID 1001. A file you mount into the container must be readable by that user. |
| FIPS 140-3 | FIPS builds of the server and operator images are listed under [Artifacts and versions](#artifacts-and-versions). |
## Sizing [#sizing]
KubeMQ does not publish CPU, memory or disk sizing yet. Size volumes for the messages you keep.
| Setup | Disk per server | CPU and memory |
| -------------------------------------------------------------------------- | --------------------------------------------------------- | ------------------------- |
| One Docker server | The `kubemq-data` volume, limited only by the host's disk | No limits set |
| Kubernetes, as [Install on Kubernetes](/deploy/install/kubernetes) sets it | A 20 GiB volume | No requests or limits set |
| Kubernetes, when your values set no size | A 5 GiB volume, the chart's and kmq's default | No requests or limits set |
Set volume size, CPU and memory for Kubernetes as [Deployment & High Availability](/configure/reference/deployment#resources) describes.
## Network [#network]
Outbound access, over HTTPS on port 443:
| Host | Used by | When |
| ---------------------------------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `license.kubemq.io` | Every server on an evaluation, trial key or license key | At start and while it runs. [Data sent to KubeMQ](/licensing/data-sent) lists every field |
| `onboarding.kubemq.io` | kmq | Only when you request, verify, claim or recover a trial key |
| `europe-docker.pkg.dev` | Docker, Podman, Kubernetes nodes and kmq | Pulling KubeMQ images |
| `kubemq-io.github.io` | Helm, and kmq on Kubernetes | Downloading the Helm chart |
| `raw.githubusercontent.com` | You | Downloading the kmq installer |
| `github.com`, `release-assets.githubusercontent.com` | The kmq installer, `kmq update`, `kmq version --check` | Installing or updating kmq |
| `api.github.com` | The Windows kmq installer | Finding the latest kmq release |
Behind a proxy, set `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` in the server's environment. An air-gapped cluster needs none of these hosts; see [Install air-gapped](/deploy/install/air-gapped).
Server ports, inbound:
| Port | Interface | Where |
| ---------- | -------------------------------- | ----------------------------------- |
| 50000 | gRPC, for client SDKs | Every server, on by default |
| 9090 | REST and WebSocket | Every server, on by default |
| 8080 | Management API and web dashboard | Every server, on by default |
| 9092 | Kafka-compatible | Every server, on by default |
| 5672 | AMQP 0-9-1, RabbitMQ-compatible | Every server, on by default |
| 5228, 5229 | Server to server | Kubernetes only, inside the cluster |
The commands on these pages publish ports on this machine only (`127.0.0.1`). [Interfaces (gRPC · REST · API · HTTP)](/configure/reference/interfaces) covers exposing them.
## Artifacts and versions [#artifacts-and-versions]
| Artifact | Name |
| ------------------------------------------------ | --------------------------------------------------------------- |
| Server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next` |
| FIPS 140-3 server image | `europe-docker.pkg.dev/kubemq/images/kubemq-next-fips` |
| Operator image (the chart sets it; you never do) | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next` |
| FIPS 140-3 operator image | `europe-docker.pkg.dev/kubemq/images/kubemq-operator-next-fips` |
| Helm repository and chart | `https://kubemq-io.github.io/charts-next`, chart `kubemq-next` |
| kmq | Releases of [kubemq-io/kmq](https://github.com/kubemq-io/kmq) |
`-next` is part of each artifact's name. It is not a preview channel. The image named `kubemq` without `-next` is legacy KubeMQ, and its `latest` tag is a legacy build. See [Move from legacy KubeMQ](/deploy/upgrade/from-legacy).
Every command on these pages installs the latest KubeMQ release; you never edit a version number. kmq installs the server release matching its own version. On Kubernetes, the latest chart sets exact images, so every server runs the same release. To install a specific release, for GitOps, change control or a mirror, open "Pin a version" under the command. The [Release notes](/release-notes) list each release's exact artifacts.
To see what you run:
| What | Command |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| kmq | `kmq version` |
| Helm chart and app version | `helm list --kube-context YOUR_KUBE_CONTEXT -n kubemq`. Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context. |
| A running server | The `server_version` field from `kmq license` |
## Related [#related]
* [Choose your path](/deploy)
* [Production checklist](/deploy/production-checklist)
* [Plans compared](/licensing)
# Move from legacy KubeMQ (/deploy/upgrade/from-legacy)
Legacy KubeMQ is KubeMQ v2 and v3 up to v3.1.x: the older `kubemq` image and the `kubemq-io/charts` Helm charts. Moving to the current release is a new installation plus a switch of your application traffic. KubeMQ support guides each move.
## What changes when you move? [#what-changes-when-you-move]
* **New artifact names.** The current release uses the `kubemq-next` image and chart; see [Requirements and supported setups](/deploy/install/requirements#artifacts-and-versions). The `latest` tag of the `kubemq` image is a legacy build, listed in [Legacy KubeMQ (kubemq image)](/release-notes/legacy).
* **A new Kubernetes API group.** The current operator manages only `next.kubemq.io/v1` resources and does not adopt a legacy `core.k8s.kubemq.io` cluster, so both can run in one Kubernetes cluster. Name the group in kubectl: `kubemqclusters.next.kubemq.io` or `kubemqclusters.core.k8s.kubemq.io`.
* **New licensing.** Legacy licenses are not carried over; see [Plans compared](/licensing). Remove any license block from old configuration files: the server refuses to start with one.
* **Connectors by manifest.** Connectors are installed from a `KubemqConnector` manifest, not from connector charts; see [Connectors](/connectors).
* **kmq replaces kubemqctl.** See [Install with kmq](/deploy/install/kmq).
* **Your clients keep working.** Upgrading SDKs is a separate step.
* **Security fixes only.** Legacy KubeMQ gets no new features. [Contact support](mailto:support@kubemq.io) for your version's support timeline.
## How does the move work? [#how-does-the-move-work]
Install the current release beside the legacy one, with [Install on Kubernetes](/deploy/install/kubernetes) or, for one server, [Install with Docker](/deploy/install/docker). Run both and move your applications pattern by pattern. Retire the legacy installation once its queues are drained; no data is copied between the two. Support plans the order of the move with you.
Unsupported setups (servers on hosts, Docker clusters, Kubernetes without the operator) follow the same path; see [Requirements and supported setups](/deploy/install/requirements#supported-setups).
## How do I get a guided migration? [#get-a-guided-migration]
Email [KubeMQ support](mailto:support@kubemq.io) with:
* the image or chart you run, and its version
* where it runs: Kubernetes or Docker, and how many servers
* the messaging patterns and connectors you use
* your target date
To buy a license, see [Plans compared](/licensing#buy).
## Related [#related]
* [Upgrade KubeMQ](/deploy/upgrade)
* [Choose your path](/deploy)
# Upgrade KubeMQ (/deploy/upgrade)
This page upgrades a running KubeMQ installation to the latest release. When you finish, `kmq license` shows the new release in `server_version`, the license remains accepted and durable, and a test message round-trips. Time: about 15 minutes.
Commands use the default names `kubemq-operator`, `messaging`, `kubemq` and the namespace `kubemq`; use your own if they differ.
These commands are for bash on macOS and Linux. On Windows, run them in WSL (Windows Subsystem for Linux), or use the kmq tab of [Try KubeMQ](/deploy/quickstart), which runs natively on Windows.
## Before you start [#before-you-start]
1. Update kmq, the KubeMQ command-line tool:
```bash
kmq update
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
If kmq reports `unknown command "update"`, re-run the installer from [Try KubeMQ](/deploy/quickstart#install-kmq).
For either kmq upgrade path, install `curl` and `jq`, then download the current public release recipe:
```bash
curl -fsSL https://docs.kubemq.io/recipes/onboarding-v1.json -o "$HOME/.kubemq-onboarding-v1.json"
```
For the Helm Kubernetes path, install Python 3. The upgrade uses it to update the existing `cluster-values.yaml` without replacing the other settings.
2. Find what you run: the `server_version` field from `kmq license` (on Kubernetes, after a port-forward and sign-in as in [Licensing troubleshooting](/licensing/troubleshooting#check-the-license-status)). For Helm, list the releases:
```bash
helm list --kube-context YOUR_KUBE_CONTEXT -A
```
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context; `kubectl config get-contexts` lists them.
If one Helm release holds both the operator and the cluster, go to [Move from the old combined chart release](#combined-release) first. Artifact names: [Requirements and supported setups](/deploy/install/requirements#artifacts-and-versions).
3. Read [Release notes](/release-notes) for each release after yours, especially "Before you upgrade". A release can require a fresh data directory; its release note says so. Then the steps below that keep the volume do not apply: export the messages you need first, and start on a new volume.
4. Back up: on one server, steps 1 to 4 of [Back up and restore](/operate/backup-and-restore#steps). For Kubernetes, [contact support](mailto:support@kubemq.io) before relying on a restore.
## Steps [#steps]
### Upgrade one server [#upgrade-one-server]
#### Upgrade the server [#upgrade-the-server]
```bash
kmq deploy update --installation YOUR_INSTALLATION_ID \
--image "$(jq -r '.server_image' "$HOME/.kubemq-onboarding-v1.json")" \
--deadline 10m
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq onboard` printed.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
The `kubemq-data` volume and your data stay.
#### Pull the latest image [#pull-the-latest-image]
```bash
docker pull --platform linux/amd64 europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
#### Remove the old container [#remove-the-old-container]
```bash
docker stop kubemq
```
```bash
docker rm kubemq
```
Check that the volume stays:
```bash
docker volume ls --filter name=kubemq-data --format '{{.Name}}'
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
#### Start the server again [#start-the-server-again]
In `kubemq-private`, rerun your install command; from [Install with Docker](/deploy/install/docker), that is:
Check that the server is running:
```bash
docker ps --filter name=kubemq --format '{{.Names}}: {{.Status}}'
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
With Docker Compose, run `docker compose pull`, then `docker compose up -d`. With Podman, use `podman` in place of `docker`.
Then select the signed-in context and check the license:
```bash
kmq context use kubemq
```
```bash
kmq license
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
`server_version` shows the new release. In the `adoption` object, `state` remains `accepted` and `durable` remains `true`. `stop_cause` remains `null`. If kmq cannot connect, the server is still starting: wait a few seconds and run it again. Sign in at `http://localhost:8080`: your channels are still there.
### Upgrade a Kubernetes cluster [#upgrade-a-kubernetes-cluster]
#### Upgrade the cluster [#upgrade-the-cluster]
```bash
kmq deploy update --installation YOUR_INSTALLATION_ID \
--image "$(jq -r '.server_image as $image | .server_digest as $digest | ($image | sub(":[^/:]+$"; "")) + "@" + $digest' "$HOME/.kubemq-onboarding-v1.json")" \
--deadline 20m
```
Replace: `YOUR_INSTALLATION_ID` — the `installation_id` value that `kmq deploy apply` printed.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
kmq applies the custom resource definitions first, then upgrades the operator and cluster.
`--reuse-values` keeps the old chart's images: the servers stay on the old release, and a later rollback can meet a store it cannot read.
#### Update the chart list [#update-the-chart-list]
```bash
helm repo update kubemq-next
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
#### Update the custom resource definitions [#update-the-custom-resource-definitions]
Helm never upgrades them itself.
```bash
helm show crds kubemq-next/kubemq-next | kubectl --context YOUR_KUBE_CONTEXT apply --server-side --force-conflicts -f -
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
#### Upgrade the operator [#upgrade-the-operator]
```bash
helm upgrade --install kubemq-operator kubemq-next/kubemq-next --kube-context YOUR_KUBE_CONTEXT -n kubemq \
--set operator.enabled=true --set cluster.enabled=false --wait
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
The servers then restart one at a time on the release the operator sets.
#### Enable management TLS [#enable-management-tls]
In `kubemq-private`, where `cluster-values.yaml` and your certificate files live, create a management TLS Secret before upgrading the cluster. The current release refuses administrator session login over plain HTTP. The certificate must cover `messaging-api.kubemq.svc`, `messaging-api.kubemq.svc.cluster.local` and `127.0.0.1`:
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq create secret tls messaging-api-tls --cert=YOUR_TLS_CERT_FILE --key=YOUR_TLS_KEY_FILE --dry-run=client -o yaml | kubectl --context YOUR_KUBE_CONTEXT apply -f -
```
Replace: `YOUR_TLS_CERT_FILE` — the certificate; `YOUR_TLS_KEY_FILE` — its key. Keep the issuing authority certificate as `YOUR_CA_FILE` for sign-in.
Add the Secret reference to the existing `cluster-values.yaml` while preserving every other setting:
```bash
python3 - <<'PY'
from pathlib import Path
path = Path("cluster-values.yaml")
lines = path.read_text().splitlines()
start = next((i for i, line in enumerate(lines) if line == "api:"), None)
if start is None:
raise SystemExit("cluster-values.yaml has no top-level api mapping")
end = next((i for i in range(start + 1, len(lines)) if lines[i] and not lines[i].startswith((" ", "#"))), len(lines))
body = [line for line in lines[start + 1:end] if not line.lstrip().startswith("tlsSecret:")]
lines[start + 1:end] = [" tlsSecret: messaging-api-tls", *body]
path.write_text("\n".join(lines) + "\n")
PY
grep -A1 '^api:$' cluster-values.yaml
```
#### Upgrade the cluster [#upgrade-the-cluster-1]
In `kubemq-private`, where `cluster-values.yaml` lives:
```bash
helm upgrade --install messaging kubemq-next/kubemq-next --kube-context YOUR_KUBE_CONTEXT -n kubemq -f cluster-values.yaml
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Then wait until every server is ready:
```bash
kubectl --context YOUR_KUBE_CONTEXT -n kubemq wait --for=condition=Ready kubemqclusters.next.kubemq.io/messaging --timeout=10m
```
Replace: `YOUR_KUBE_CONTEXT` — your cluster's kubectl context; `kubectl config get-contexts` lists them.
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Check the license on each server: open its management port and sign in, one pod at a time, as in [Licensing troubleshooting](/licensing/troubleshooting#check-the-license-status), then:
Select the context saved for the first server:
```bash
kmq context use messaging
```
```bash
kmq license
```
You should see:
```text title="Output"
HARNESS_OUTPUT_PENDING
```
Then send a test message as in [Install on Kubernetes](/deploy/install/kubernetes#send-a-test-message).
**kmq**
Open the [Release notes](/release-notes) and copy the kmq version they list.
If kmq is installed, switch it to that release:
```bash
kmq update --version YOUR_VERSION
```
Replace: `YOUR_VERSION` — the release number you copied, with a leading `v`.
On a machine without kmq, download the installer as [Try KubeMQ](/deploy/quickstart#install-kmq) shows, then run it with that release:
```bash
sh install-kmq.sh --version YOUR_VERSION
```
On Windows, in PowerShell:
```powershell
& .\install-kmq.ps1 -Version YOUR_VERSION
```
That kmq installs its matching server release. A pinned install does not update itself: read the release notes and move to the latest release regularly. `kmq update` with no `--version` returns kmq to the latest release.
**Docker**
Open the [Release notes](/release-notes) and copy the version they list for the server image. Wherever a command names `kubemq-next:latest`, write `kubemq-next:YOUR_VERSION` instead, and remove `--pull always` from the `docker run` or `podman run` command.
Replace: `YOUR_VERSION` — the release number you copied, with a leading `v`.
To pin by digest, write `kubemq-next@YOUR_DIGEST` instead, with the server image digest the release notes list.
Replace: `YOUR_DIGEST` — the digest, starting `sha256:`.
Pinned installs do not update themselves. Check the release notes and move to the latest release regularly.
**Helm**
Open the [Release notes](/release-notes) and copy the version they list for the Helm chart. Add `--version YOUR_VERSION` to every `helm upgrade --install` command and, when you upgrade, to `helm show crds`. Use the same value for the operator release and the cluster release, so the custom resource definitions match the pinned operator. `helm search repo kubemq-next/kubemq-next --versions` lists every published chart version.
Replace: `YOUR_VERSION` — the release number you copied, with no leading `v`.
Pinned installs do not update themselves. Check the release notes and move to the latest release regularly.
## Roll back [#roll-back]
A store written by a newer release may not be readable by an older one. Roll back only when the release notes say the upgrade is reversible: install the previous release as "Pin a version" shows, and on Kubernetes also run `helm rollback` for the operator. Otherwise, restore your backup as in [Back up and restore](/operate/backup-and-restore); for Kubernetes, contact support first.
## Move from the old combined chart release [#combined-release]
Older charts put the operator and the cluster in one Helm release. The current chart refuses a release that enables both: `operator and cluster must use independent releases`. [Contact support](mailto:support@kubemq.io) before upgrading a release that contains both the operator and the cluster.
## If something goes wrong [#if-something-goes-wrong]
* **The servers still run the old release.** Run the wait command again. If they stay old, repeat the Helm steps without `--reuse-values`.
* **A server restarts with a storage error in its log.** Restore your backup and check the release notes.
* **A licensing message in the log.** Look up the anchor it prints in [Troubleshooting](/licensing/troubleshooting).
## Next steps [#next-steps]
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-p 127.0.0.1:9092:9092 \
--env-file kubemq-license.env \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Channels & Routing (/learn/concepts/channels-and-routing)
Think of a channel like the address on an envelope. You do not hand a letter directly to a person — you drop it in the mail with an address, and the postal system delivers it to whoever picks up mail at that address. Senders and receivers never need to know about each other; they only need to agree on the address.
A **channel** is that address: a named destination that a broker uses to route messages. Publishers send to a channel name; subscribers express interest in a channel name. The broker connects the two. This indirection is what makes messaging *loosely coupled* — you can add, remove, or move services without either side changing the other's code.
## Channels — the idea [#channels--the-idea]
A channel is just a string name, chosen by you. Publishers attach that name to each message; the broker matches it against the names subscribers asked for and delivers accordingly. Nothing is hard-wired — the channel is created the moment something uses it.
Good channel names follow a **hierarchy**, read left to right from broad to specific, with a separator between each level. A common convention is `{domain}.{entity}.{action}`:
```text
orders.created
orders.updated
orders.us-east.created
payments.completed
inventory.reserved
```
That hierarchy is not decoration. It is what makes the next idea — wildcards — possible.
*Channels are named destinations; the broker matches a publisher's channel name to the subscribers that asked for it.*
## Wildcards — subscribing to a pattern [#wildcards--subscribing-to-a-pattern]
Naming channels one by one works until you have dozens of them. A monitoring service that needs *every* order event would have to subscribe to `orders.created`, `orders.updated`, `orders.shipped`, and remember to add a new subscription every time someone invents `orders.cancelled`.
A **wildcard subscription** solves this: instead of naming exact channels, the subscriber names a *pattern*, and the broker delivers every message whose channel matches. The hierarchy makes the pattern meaningful — each level can be matched broadly or exactly.
Two wildcard tokens are common, and KubeMQ uses both:
| Token | Matches | Example |
| ----- | ------------------ | ------------------------------------------------------------------ |
| `*` | exactly one level | `orders.*` matches `orders.created`, not `orders.us-east.created` |
| `>` | one or more levels | `orders.>` matches `orders.created` *and* `orders.us-east.created` |
A standalone `>` subscribes to everything — a firehose for audit or debugging.
*One pattern subscription captures many channels: `orders.*` matches single-level order events, while `>` captures everything.*
**Pitfall:** wildcards belong to *subscriptions*, not *publishes*. A publisher must always send to a concrete channel name — `orders.created`, never `orders.*`. The `*` and `>` characters are illegal in a publish channel.
## Routing — one publish, many channels [#routing--one-publish-many-channels]
Wildcards let one subscriber listen to many channels. **Multicast routing** is the mirror image: it lets one *publish* reach many channels at once, without the publisher looping or opening multiple connections.
The publisher encodes a list of targets into the channel name, and the broker fans the message out to each. This is how you tee a single business event to several consumers with different needs — a live feed *and* a durable copy *and* a work queue — from one call.
*A single publish fans out to channels of different types at once — a real-time feed, a durable store, and a reliable work queue.*
## Precise definition [#precise-definition]
* **Channel** — a named destination string. Created on first use, addressed by publishers and subscribers; the unit the broker routes on.
* **Hierarchical naming** — a dot-separated convention (`domain.entity.action`) that gives channels structure so patterns can match levels.
* **Wildcard subscription** — a subscription whose channel is a *pattern* using `*` (one level) or `>` (one or more levels). The broker delivers every message whose channel matches.
* **Multicast routing** — a single publish addressed to multiple channels at once, encoded in the channel string; the broker delivers a copy to each target.
## Trade-offs [#trade-offs]
| When it helps | When it bites |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| A consumer needs a whole category of channels — one `orders.>` beats a dozen explicit subscriptions. | A too-broad pattern (`>`) hauls in traffic you do not need, wasting bandwidth and processing. |
| You want to tee one event to several patterns (live + durable + queue) without publisher-side loops. | Routing to many targets multiplies broker work per publish; very wide fan-outs add latency. |
| A naming hierarchy lets new channels appear without changing subscribers. | Inconsistent naming breaks wildcards — `order.created` and `orders.created` will not match the same pattern. |
| Routing keeps publishers simple — they do not track who consumes what. | Routing hides destinations in a string; an inspectable, documented naming scheme is essential to avoid surprise delivery. |
## In KubeMQ [#in-kubemq]
KubeMQ channels are exactly the named destinations above — a plain string you choose, created on first use. **Wildcard subscriptions** are supported for **Events** (Pub/Sub): subscribe to `orders.*` or `>` and the broker matches every event channel against your pattern. **Multicast routing** is encoded directly in the channel string: `;` separates targets and a `type:` prefix selects the pattern.
| Routing string | Effect |
| ---------------------------------------------- | ---------------------------------------------- |
| `events:order-live;events_store:order-archive` | one publish → a live feed *and* a durable copy |
| `events:notify;queues:order-fulfilment` | broadcast *and* a reliable work queue |
The snippet below is the canonical wildcard subscribe from the Events tutorial — one subscription to `orders.*` captures every single-level order channel.
```go title="orders_monitor.go"
sub, err := client.SubscribeToEvents(ctx, "orders.*", "",
kubemq.WithOnEvent(func(event *kubemq.Event) {
fmt.Printf("[Orders Monitor] channel=%s body=%s\n",
event.Channel, string(event.Body))
}),
kubemq.WithOnError(func(err error) {
log.Println("Error:", err)
}),
)
```
```python title="orders_monitor.py"
client.subscribe_to_events(
subscription=EventsSubscription(
channel="orders.*",
on_receive_event_callback=lambda e: print(
f"[Orders Monitor] channel={e.channel} body={e.body.decode()}"
),
on_error_callback=lambda e: print(f"Error: {e}"),
),
cancel=CancellationToken(),
)
```
```javascript title="orders_monitor.js"
client.subscribeToEvents({
channel: "orders.*",
onEvent: (msg) =>
console.log(
`[Orders Monitor] channel=${msg.channel} body=${Buffer.from(msg.body).toString()}`
),
onError: (err) => console.error("Error:", err.message),
});
```
```java title="OrdersMonitor.java"
client.subscribeToEvents(EventsSubscription.builder()
.channel("orders.*")
.onReceiveEventCallback(event ->
System.out.printf("[Orders Monitor] channel=%s body=%s%n",
event.getChannel(), new String(event.getBody())))
.onErrorCallback(err ->
System.err.println("Error: " + err.getMessage()))
.build());
```
```csharp title="OrdersMonitor.cs"
await foreach (var msg in client.SubscribeToEventsAsync(
new EventsSubscription { Channel = "orders.*" }))
{
Console.WriteLine($"[Orders Monitor] channel={msg.Channel} "
+ $"body={Encoding.UTF8.GetString(msg.Body.Span)}");
}
```
```kotlin title="OrdersMonitor.kt"
client.subscribeToEvents(
channel = "orders.*",
onEvent = { event ->
println("[Orders Monitor] channel=${event.channel} body=${String(event.body)}")
},
onError = { err -> System.err.println("Error: ${err.message}") }
)
```
```cpp title="orders_monitor.cpp"
client.subscribeToEvents("orders.*", "",
[](const kubemq::Event& event) {
std::cout << "[Orders Monitor] channel=" << event.channel
<< " body=" << event.body << std::endl;
},
[](const std::string& err) {
std::cerr << "Error: " << err << std::endl;
}
);
```
```rust title="orders_monitor.rs"
// A single wildcard subscription matches every channel under the pattern.
let sub = client
.subscribe_to_events(
"orders.*",
"",
|event| {
Box::pin(async move {
println!(
"[Orders Monitor] channel={}, body={}",
event.channel,
String::from_utf8_lossy(&event.body)
);
})
},
None,
)
.await?;
```
```ruby title="orders_monitor.rb"
cancel = KubeMQ::CancellationToken.new
sub = KubeMQ::PubSub::EventsSubscription.new(channel: "orders.*")
client.subscribe_to_events(sub, cancellation_token: cancel,
on_error: ->(e) { puts "Error: #{e.message}" }) do |event|
puts "[Orders Monitor] channel=#{event.channel} body=#{event.body}"
end
```
```elixir title="orders_monitor.exs"
{:ok, sub} =
KubeMQ.Client.subscribe_to_events(client, "orders.*",
on_event: fn event ->
IO.puts("[Orders Monitor] channel=#{event.channel} body=#{event.body}")
end
)
```
**In KubeMQ:** wildcard subscriptions are an **Events** feature. Events Store, Queues, and RPC use exact channel names — they do not match `*` or `>` patterns. Multicast routing, by contrast, works across patterns: one routing string can tee an event into Events, Events Store, and Queues at the same time.
### How KubeMQ does this → [#how-kubemq-does-this-]
# Delivery Guarantees (/learn/concepts/delivery-guarantees)
Imagine mailing a contract. You could drop it in a mailbox and hope it arrives — fast, but if it gets lost you never know. You could send it certified mail, where the courier keeps trying until someone signs for it — nothing is lost, but a frazzled courier might leave two copies. Or you could number every envelope and have the recipient ignore duplicates — slower and more bookkeeping, but each contract lands exactly once.
Those three choices are the three **delivery guarantees** every messaging system makes you pick between. The guarantee decides what happens when something fails — a subscriber is offline, a network blips, a consumer crashes mid-work. There is no "always perfect" option for free: stronger guarantees cost latency, storage, and complexity. This page explains the three guarantees, the acknowledgement mechanics that make the stronger ones possible, and the safety nets (idempotency and dead-letter queues) that keep them honest.
## Delivery guarantees — the idea [#delivery-guarantees--the-idea]
A delivery guarantee is a promise about how many times a message is processed by a consumer in the face of failure. There are three:
* **at-most-once** — deliver the message, never retry. A message is processed zero or one times. Fastest and cheapest; messages can be silently lost.
* **at-least-once** — keep delivering until the consumer confirms success. A message is processed one or more times. Nothing is lost, but duplicates are possible.
* **exactly-once** — the message is processed once and only once, even across failures. No loss, no duplicates. The strongest promise and the most expensive to provide.
The pivot between them is the **acknowledgement** — a small signal the consumer sends back after handling a message. Whether the system waits for an ack, and what it does when an ack never arrives, is what separates the three guarantees.
### at-most-once: fire and forget [#at-most-once-fire-and-forget]
The broker hands the message to whoever is listening right now and immediately forgets it. There is no ack, no retry, no stored copy. If a subscriber is offline or the message is dropped in transit, it is gone.
*at-most-once: the broker delivers to active subscribers only; an offline subscriber misses the message and it is never retried.*
### at-least-once: acknowledge or redeliver [#at-least-once-acknowledge-or-redeliver]
The broker keeps the message until the consumer **acks** it. If the consumer fails to ack — it crashes, times out, or sends a **nack** (negative acknowledgement) — the broker redelivers. Nothing is lost, but a consumer that did the work and then crashed *before* acking will see the same message again.
*at-least-once: with no ack inside the window, the broker redelivers; the message is never lost but may arrive more than once.*
### exactly-once: acknowledge, then deduplicate [#exactly-once-acknowledge-then-deduplicate]
You reach effectively-once by combining at-least-once delivery with **deduplication** on the consumer side. The consumer records which message IDs it has already handled; a redelivered duplicate is recognized and skipped before it has any effect. The work happens once even though the message may be delivered twice.
*exactly-once (effectively-once): at-least-once delivery plus a dedup check on the message ID means the redelivered duplicate has no effect.*
## Precise definition [#precise-definition]
A **delivery guarantee** is the contract a messaging system upholds for how many times a given message is successfully processed when failures occur. It is realized through three mechanics:
* **Acknowledgement (ack)** — a signal from the consumer that a message was processed successfully and can be discarded by the broker. A **negative acknowledgement (nack)** signals failure and asks for redelivery.
* **Redelivery window** — the time the broker waits for an ack before assuming failure and redelivering. (When a consumer holds a message during processing, this is the **visibility timeout**.)
* **Idempotency** — a processing operation is *idempotent* if applying it twice has the same effect as applying it once. Idempotent consumers turn at-least-once delivery into effectively-once results, because duplicates do no extra harm.
A **dead letter queue (DLQ)** is the final safety net: after a message fails and is redelivered up to a configured maximum number of times, the broker stops retrying and moves it to a separate channel for inspection. This prevents a single "poison" message from being redelivered forever and blocking the queue behind it.
> True end-to-end **exactly-once** across independent systems is impossible in the general case (a consumer cannot atomically both ack the broker and commit a side effect). In practice, "exactly-once" means **at-least-once delivery + idempotent processing (or dedup)** — often called **effectively-once**.
## Trade-offs [#trade-offs]
| Guarantee | Loss? | Duplicates? | Cost | Use when |
| ----------------- | -------- | -------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------- |
| **at-most-once** | Possible | Never | Lowest latency, no storage | Telemetry, live dashboards, cache invalidation — a missed message is harmless |
| **at-least-once** | Never | Possible | Storage + ack round-trip | Orders, payments, jobs — losing a message is unacceptable; you can tolerate (or dedup) a repeat |
| **exactly-once** | Never | Never (effect) | All of the above + dedup/idempotency | Financial postings, inventory decrements — a duplicate would corrupt state |
**Pitfall:** "at-least-once" guarantees delivery, not single processing. If your consumer is **not idempotent** — for example it blindly increments a balance — a redelivered duplicate will double-charge. Make the handler idempotent (key side effects by message ID, or upsert instead of insert) before relying on at-least-once for anything stateful.
## In KubeMQ [#in-kubemq]
**In KubeMQ:** the guarantee is a property of the **pattern you choose**, not a per-message flag. Events are fire-and-forget (at-most-once). Events Store persists every message so durable subscribers never lose one (at-least-once on the delivery path). Queues give each consumer an explicit **ack / nack** decision plus a **dead-letter queue** after `maxReceiveCount` retries — the basis for exactly-once-processing when your handler is idempotent. RPC is request/reply: the response *is* the acknowledgement.
Each KubeMQ pattern occupies a different point on the guarantee spectrum:
| Delivery guarantee | KubeMQ pattern | How it is provided |
| --------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **at-most-once** | [Events](/learn/events) | Fire-and-forget pub/sub — delivered to active subscribers only, no persistence, no retry |
| **at-least-once** | [Events Store](/learn/events-store) | Every message is persisted; durable subscriptions track their position and replay anything missed |
| **exactly-once-processing** | [Queues](/learn/queues) | Explicit ack/nack settlement + redelivery on nack/timeout + a dead-letter queue; pair with an idempotent handler for effectively-once |
| **request/reply** | [RPC](/learn/rpc) | The reply confirms processing synchronously; a Command returns an ack, a Query returns data — no separate ack step |
The clearest place to see ack/nack in code is the Queues consumer. After receiving a message, you decide its fate: **ack** removes it, **nack** returns it for redelivery. If it is nacked past `maxReceiveCount`, KubeMQ routes it to the configured dead-letter queue.
```go title="settle.go"
resp, err := client.PollQueue(ctx, &kubemq.PollRequest{
Channel: "orders",
MaxItems: 1,
WaitTimeoutSeconds: 5,
})
if err != nil {
log.Fatal(err)
}
for _, m := range resp.Messages {
if err := process(m.Message.Body); err != nil {
m.NAck() // failed — return to queue for redelivery
continue
}
m.Ack() // success — remove from queue
}
```
```python title="settle.py"
response = client.receive_queue_messages(
channel="orders",
max_messages=1,
wait_timeout_in_seconds=5,
)
for msg in response.messages:
try:
process(msg.body)
msg.ack() # success — remove from queue
except Exception:
msg.nack() # failed — return to queue for redelivery
```
```typescript title="settle.ts"
const messages = await client.receiveQueueMessages({
channel: 'orders',
maxMessages: 1,
waitTimeoutSeconds: 5,
});
for (const msg of messages) {
try {
await process(msg.body);
await msg.ack(); // success — remove from queue
} catch {
await msg.nack(); // failed — return to queue for redelivery
}
}
```
```java title="Settle.java"
ReceiveQueueMessagesResponse response = client.receiveQueueMessages(
ReceiveQueueMessagesRequest.builder()
.channel("orders")
.maxMessages(1)
.waitTimeoutSeconds(5)
.build());
for (QueueMessageReceived msg : response.getMessages()) {
try {
process(msg.getBody());
msg.ack(); // success — remove from queue
} catch (Exception e) {
msg.nack(); // failed — return to queue for redelivery
}
}
```
```csharp title="Settle.cs"
var response = await client.ReceiveQueueMessagesAsync(new ReceiveQueueMessagesRequest
{
Channel = "orders",
MaxMessages = 1,
WaitTimeoutSeconds = 5,
});
foreach (var msg in response.Messages)
{
try
{
Process(msg.Body);
await msg.AckAsync(); // success — remove from queue
}
catch
{
await msg.NAckAsync(); // failed — return to queue for redelivery
}
}
```
```kotlin title="Settle.kt"
val response = client.receiveQueueMessages(
channel = "orders",
maxMessages = 1,
waitTimeoutSeconds = 5
)
for (msg in response.messages) {
try {
process(msg.body)
msg.ack() // success — remove from queue
} catch (e: Exception) {
msg.nack() // failed — return to queue for redelivery
}
}
```
```cpp title="settle.cpp"
auto response = client.receiveQueueMessages("orders", 1, 5);
for (const auto& msg : response.messages) {
try {
process(msg.body);
msg.ack(); // success — remove from queue
} catch (const std::exception&) {
msg.nack(); // failed — return to queue for redelivery
}
}
```
```rust title="settle.rs"
let mut receiver = client.new_queue_downstream_receiver().await?;
let response = receiver
.poll(PollRequest {
channel: "orders".to_string(),
max_items: 1,
wait_timeout_seconds: 5,
auto_ack: false,
})
.await?;
for msg in &response.messages {
match process(&msg.message.body) {
Ok(_) => msg.ack().await?, // success — remove from queue
Err(_) => msg.nack().await?, // failed — return to queue for redelivery
}
}
```
```ruby title="settle.rb"
receiver = client.create_downstream_receiver
request = KubeMQ::Queues::QueuePollRequest.new(
channel: 'orders', max_items: 1, wait_timeout: 5
)
response = receiver.poll(request)
response.messages.each do |m|
begin
process(m.body)
m.ack # success — remove from queue
rescue StandardError
m.nack # failed — return to queue for redelivery
end
end
```
```elixir title="settle.exs"
{:ok, poll} =
KubeMQ.Client.poll_queue(client,
channel: "orders",
max_items: 1,
wait_timeout: 5_000
)
# Settle the whole transaction: ack on success, nack to redeliver
case process(poll.messages) do
:ok -> KubeMQ.PollResponse.ack_all(poll)
_ -> KubeMQ.PollResponse.nack_all(poll)
end
```
*The same receive-then-settle loop in every SDK: ack a processed message, nack a failed one. After `maxReceiveCount` nacks, KubeMQ moves the message to the dead-letter queue.*
### How KubeMQ does this → [#how-kubemq-does-this-]
# Messaging Fundamentals (/learn/concepts)
Two services need to work together: an Orders service takes a customer's order, and a dozen other things have to happen because of it — charge a card, reserve stock, email a receipt, update a dashboard. How do those services *talk*? You can have the Orders service call each of the others directly, or you can put something in the middle that carries the messages for it. That "something in the middle" is what this whole track is about.
Think of it like a busy office. People could walk to each other's desks every time they need something — fast when the other person is there, useless when they're out. Or they could drop notes in a central mailroom that sorts and delivers them. The mailroom never forgets to deliver, doesn't care who's at their desk right now, and lets one announcement reach a hundred people at once. **Messaging** is software's mailroom.
## Synchronous vs asynchronous — the idea [#synchronous-vs-asynchronous--the-idea]
The first choice in any conversation between two services is *whether the sender waits*.
**Synchronous** communication is a phone call. You dial, the other person picks up, you talk, you get an answer, and only then do you hang up and move on. The caller is blocked the whole time — if the other side is slow or down, the caller is stuck. It is simple and immediate, and you get an answer right away.
**Asynchronous** communication is leaving a voicemail or sending a letter. You say your piece and move on with your day; the recipient picks it up when they can and acts on it later. The sender is not blocked, the recipient does not have to be available at the same moment, and the work happens in the background.
*Top: a synchronous call — the caller waits for a reply. Bottom: an asynchronous message — the sender hands off and continues; delivery happens when the receiver is ready.*
Neither is "better." A phone call is right when you genuinely need the answer *now* to continue (checking whether a credit card is valid). A voicemail is right when you just need the other side to *eventually* know something (a receipt should be emailed). Most real systems use both.
## Tight vs loose coupling — the idea [#tight-vs-loose-coupling--the-idea]
When the Orders service calls the Payments service directly, it has to know Payments exists, where it lives, that it is up, and how to talk to it. If Payments moves, scales, slows down, or fails, Orders feels it immediately. That is **tight coupling**: the two are wired straight to each other, and a change or failure in one ripples into the other.
Now add a fifth, sixth, and seventh thing that must happen on every order — fulfillment, analytics, fraud checks, loyalty points. With direct calls, the Orders service grows a hard-wired dependency on each one, and every new consumer means editing and redeploying Orders.
Put a broker in the middle and the picture changes. Orders publishes "an order was placed" to a channel and stops caring who listens. Payments, fulfillment, and analytics each subscribe on their own terms. Orders does not know they exist; they do not know Orders exists. That is **loose coupling**: services depend on a shared *channel*, not on each other. New consumers slot in without touching the producer, and one service being down no longer takes the sender down with it.
*Left: direct calls — the producer is wired to every consumer and must change when the set of consumers changes. Right: via a broker — the producer publishes to one channel; consumers come and go independently.*
**Pitfall:** loose coupling is not free. Asynchronous, broker-mediated messaging adds a hop, makes end-to-end flows harder to trace, and means "done" no longer means "everyone who cares has finished." You trade immediate, all-or-nothing simplicity for independence and resilience. Reach for it when services must scale, fail, and evolve separately — not for a single call that needs an answer right now.
## What a message broker is [#what-a-message-broker-is]
A **message broker** is the piece of infrastructure in the middle. Its job is narrow and important: accept messages from producers, hold them in named **channels**, and deliver them to the right consumers — then get out of the way.
A broker does the work that every messaging system would otherwise reinvent:
* **Decouples** producers from consumers in space (they need not know each other's location), in time (they need not run at the same moment), and in number (one producer, many consumers — or the reverse).
* **Buffers** bursts so a fast producer does not overwhelm a slow consumer.
* **Routes** each message to the consumers that asked for it, by channel name and pattern.
* **Applies delivery rules** — try once, try until acknowledged, preserve order, allow replay — depending on the channel type.
*A simple topology: producers send to channels through one broker, which delivers to the consumers that subscribed — over whatever transport each client speaks.*
## Why distinct messaging patterns exist [#why-distinct-messaging-patterns-exist]
If a broker just "delivers messages," why does this track have four different patterns? Because **one size does not fit all**. Different jobs need different delivery contracts, and trying to serve them all with one mechanism makes every job worse.
Consider what changes from job to job:
| Question | Notifications | Order processing | Audit log | "Is the card valid?" |
| ------------------------------------------------------------ | ------------- | ---------------- | ------------------ | -------------------- |
| Does the sender need a reply? | No | No | No | **Yes, now** |
| Must every message survive a crash? | No | **Yes** | **Yes** | No |
| Should each message go to *one* worker or *all* subscribers? | All | **One** | Replayable by many | One responder |
| Does order matter? | No | Often | **Yes** | N/A |
| Can old messages be replayed later? | No | No | **Yes** | No |
No single delivery rule answers all of these well. A pattern that guarantees nothing is lost and lets you replay history is overkill (and slower) for a fleeting "user is typing" notification. A fire-and-forget broadcast is dangerous for a payment that must not be processed twice. So messaging gives you a small set of **patterns**, each a deliberate trade-off between speed, durability, ordering, and shape of delivery. Picking the right one is most of the skill — and the rest of this track teaches you how.
## In KubeMQ [#in-kubemq]
**In KubeMQ:** KubeMQ *is* the broker — a single engine that hosts every channel type. Your services connect once, then publish to and subscribe from named channels using one client SDK. The same connection speaks Events, Events Store, Queues, and RPC; the channel type you choose decides the delivery contract. The channels in the topology above are just KubeMQ channels of different types behind one address (`localhost:50000`).
Connecting and publishing a single message is the smallest possible "hello, broker." Here the Orders service sends one order event to a channel — it does not know or care who is listening.
```go title="publish.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("order-placed").
SetBody([]byte(`{"orderId":"ORD-1234","status":"placed"}`)),
)
if err != nil {
log.Fatal(err)
}
log.Println("Message sent — Orders does not wait for any consumer")
}
```
```python title="publish.py"
from kubemq.pubsub import Client as PubSubClient
from kubemq.pubsub import EventMessage
client = PubSubClient(address="localhost:50000")
client.send_event(
EventMessage(
channel="order-placed",
body=b'{"orderId":"ORD-1234","status":"placed"}',
)
)
print("Message sent — Orders does not wait for any consumer")
client.close()
```
```javascript title="publish.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000" });
await client.sendEvent({
channel: "order-placed",
body: Buffer.from(JSON.stringify({ orderId: "ORD-1234", status: "placed" })),
});
console.log("Message sent — Orders does not wait for any consumer");
```
```java title="Publish.java"
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("orders-service")
.build();
client.sendEventsMessage(EventMessage.builder()
.channel("order-placed")
.body("{\"orderId\":\"ORD-1234\",\"status\":\"placed\"}".getBytes())
.build());
System.out.println("Message sent — Orders does not wait for any consumer");
client.close();
```
```csharp title="Publish.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
await client.SendEventAsync(new EventMessage
{
Channel = "order-placed",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-1234\",\"status\":\"placed\"}")
});
Console.WriteLine("Message sent — Orders does not wait for any consumer");
```
```kotlin title="Publish.kt"
val client = PubSubClient("localhost:50000")
client.sendEvent(EventMessage(
channel = "order-placed",
body = """{"orderId":"ORD-1234","status":"placed"}""".toByteArray()
))
println("Message sent — Orders does not wait for any consumer")
client.close()
```
```cpp title="publish.cpp"
#include
#include
auto client = kubemq::PubSubClient("localhost:50000");
kubemq::EventMessage event;
event.channel = "order-placed";
event.body = R"({"orderId":"ORD-1234","status":"placed"})";
client.sendEvent(event);
std::cout << "Message sent — Orders does not wait for any consumer" << std::endl;
```
```rust title="publish.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("order-placed")
.body(br#"{"orderId":"ORD-1234","status":"placed"}"#.to_vec())
.build();
client.send_event(event).await?;
println!("Message sent — Orders does not wait for any consumer");
client.close().await?;
Ok(())
}
```
```ruby title="publish.rb"
require 'kubemq'
client = KubeMQ::PubSubClient.new(address: "localhost:50000", client_id: "orders-service")
msg = KubeMQ::PubSub::EventMessage.new(
channel: "order-placed",
body: '{"orderId":"ORD-1234","status":"placed"}'
)
client.send_event(msg)
puts "Message sent — Orders does not wait for any consumer"
client.close
```
```elixir title="publish.exs"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "orders-service")
event = KubeMQ.Event.new(channel: "order-placed", body: ~s({"orderId":"ORD-1234","status":"placed"}))
case KubeMQ.Client.send_event(client, event) do
:ok -> IO.puts("Message sent — Orders does not wait for any consumer")
{:error, err} -> IO.puts("Send failed: #{err.message}")
end
KubeMQ.Client.close(client)
```
That same `client` connection can also persist events, queue work for a single worker, or make a request and wait for a reply — each is one of the four patterns below.
### How KubeMQ does this → [#how-kubemq-does-this-]
## Where to go next [#where-to-go-next]
You now have the vocabulary: synchronous vs asynchronous, tight vs loose coupling, what a broker does, and why patterns differ. Next, learn the small set of shapes every messaging system reduces to — then how delivery, ordering, scaling, and routing actually work.
# Interaction Styles (/learn/concepts/interaction-styles)
Pick apart any messaging system and you find the same three conversation shapes underneath. A pattern's name and its bells and whistles vary, but the way a message travels from sender to receiver always reduces to one of three styles: **one-to-many** (pub/sub), **one-to-one-of-many** (point-to-point), or **there-and-back** (request/reply).
Think of how people communicate. A speaker at a conference addresses the whole room at once — everyone listening hears it (pub/sub). A help desk has a single ticket line feeding several agents — your ticket goes to whichever agent is free, and to exactly one of them (point-to-point). A phone call is a back-and-forth — you ask, you wait, you get an answer (request/reply). Learn these three shapes and every messaging pattern becomes a variation on a theme you already understand.
## Pub/Sub — one sender, many receivers [#pubsub--one-sender-many-receivers]
In **pub/sub** (publish/subscribe), a sender publishes a message to a named destination and **every** active receiver subscribed to that destination gets its own copy. The sender does not know or care who is listening — it could be zero receivers or a thousand. This shape is called **fan-out**: one message in, many copies out.
The sender and receivers are decoupled. You can add a new subscriber tomorrow without touching the publisher, and a slow or absent subscriber does not hold anyone else up.
*One published message is copied to every active subscriber — fan-out, one-to-many.*
**Reach for pub/sub when** every interested party needs the same message: broadcasting state changes, notifying multiple services of an event, feeding live dashboards, or invalidating caches across a fleet.
## Point-to-Point — one sender, one-of-many receivers [#point-to-point--one-sender-one-of-many-receivers]
In **point-to-point**, a sender puts a message on a shared queue and **exactly one** receiver consumes it. When several receivers read from the same queue, they form a pool of **competing consumers** — the queue hands each message to whichever consumer is free, spreading the work across all of them. One message in, delivered once, to one worker.
This is how you scale a workload horizontally. Add more workers and throughput goes up; each message is still processed exactly once, and no two workers do the same job.
*Each queued message goes to exactly one of the competing workers — load-balanced, one-to-one-of-many. The dotted line is the acknowledgment that removes the message.*
**Reach for point-to-point when** each message represents a unit of work that should be done once: order processing, background jobs, task distribution, or anything where you want to add workers to handle more load.
**Pub/sub vs point-to-point** is the most consequential choice you make. Pub/sub *copies* a message to everyone; point-to-point *hands* a message to one worker. Same starting point, opposite outcomes.
## Request/Reply — there and back [#requestreply--there-and-back]
In **request/reply**, a sender issues a request and **waits** for a response from a receiver before continuing. It is the synchronous shape: the round-trip is part of the flow, and the sender blocks (up to a timeout) until the answer arrives or it gives up. One request out, one matching response back.
Unlike the other two styles, the sender expects a reply and is coupled to it in time — if the receiver is down or slow, the sender waits. That tight coupling is the point: you want the result *now*, before moving on.
*The sender blocks until the response returns through the broker — synchronous, there-and-back. A request that returns data is a query; one that only confirms an action is a command.*
**Reach for request/reply when** the sender needs an answer to proceed: looking up data, calling a service-to-service API, confirming a write succeeded, or any classic remote-procedure call.
## The three styles at a glance [#the-three-styles-at-a-glance]
| | Pub/Sub | Point-to-Point | Request/Reply |
| ------------------------- | -------------------------------- | ------------------------------ | -------------------------------- |
| **Direction** | one → many | one → one-of-many | one ↔ one |
| **Receivers per message** | every subscriber | exactly one consumer | one responder |
| **Coupling** | loose (sender ignores receivers) | loose (sender ignores workers) | tight (sender waits for reply) |
| **Timing** | asynchronous | asynchronous | synchronous |
| **Adds receivers to…** | reach more listeners (fan-out) | share more work (scale) | distribute load behind one reply |
| **Typical use** | broadcasts, notifications | jobs, task queues | lookups, RPC, confirmations |
**Pitfall:** don't force a synchronous request/reply where a one-way style fits. Blocking a sender on a slow downstream service is a common cause of cascading timeouts — if you only need to *tell* someone something, publish an event or enqueue a job and move on.
## In KubeMQ [#in-kubemq]
KubeMQ implements all three interaction styles natively, so you choose the conversation shape rather than wiring it together yourself:
| Interaction style | KubeMQ pattern | Why |
| ------------------------------------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Pub/Sub (fan-out) | **Events** and **Events Store** | A publish is copied to every active subscriber on the channel. Events is at-most-once and in-memory; Events Store persists messages so subscribers can also replay. |
| Point-to-Point (competing consumers) | **Queues** | Each queued message is delivered to one consumer and removed on acknowledgment; multiple consumers on a channel compete for messages and share the load. |
| Request/Reply (round-trip) | **RPC** (Commands & Queries) | The sender blocks until a responder answers or the timeout expires. A Query returns a payload; a Command returns an execution acknowledgment. |
The snippets below show the *send* side of each style against `localhost:50000`, using the same e-commerce orders domain. They are deliberately minimal — see the pattern pages for full subscribe/receive/respond flows.
### Pub/Sub — publish an event [#pubsub--publish-an-event]
```go title="publish.go"
err = client.SendEvent(ctx, kubemq.NewEvent().
SetChannel("order-events").
SetMetadata("order.created").
SetBody([]byte(`{"orderId":"ORD-1234","status":"created"}`)),
)
```
```python title="publish.py"
client.send_event(
EventMessage(
channel="order-events",
metadata="order.created",
body=b'{"orderId":"ORD-1234","status":"created"}',
)
)
```
```javascript title="publish.js"
await client.sendEvent({
channel: "order-events",
metadata: "order.created",
body: Buffer.from(JSON.stringify({ orderId: "ORD-1234", status: "created" })),
});
```
```java title="Publish.java"
client.sendEventsMessage(EventMessage.builder()
.channel("order-events")
.metadata("order.created")
.body("{\"orderId\":\"ORD-1234\",\"status\":\"created\"}".getBytes())
.build());
```
```csharp title="Publish.cs"
await client.SendEventAsync(new EventMessage
{
Channel = "order-events",
Metadata = "order.created",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-1234\",\"status\":\"created\"}")
});
```
```kotlin title="Publish.kt"
client.sendEvent(EventMessage(
channel = "order-events",
metadata = "order.created",
body = """{"orderId":"ORD-1234","status":"created"}""".toByteArray()
))
```
```cpp title="publish.cpp"
kubemq::EventMessage event;
event.channel = "order-events";
event.metadata = "order.created";
event.body = R"({"orderId":"ORD-1234","status":"created"})";
client.sendEvent(event);
```
```rust title="publish.rs"
let event = EventBuilder::new()
.channel("order-events")
.metadata("order.created")
.body(br#"{"orderId":"ORD-1234","status":"created"}"#.to_vec())
.build();
client.send_event(event).await?;
```
```ruby title="publish.rb"
msg = KubeMQ::PubSub::EventMessage.new(
channel: "order-events",
metadata: "order.created",
body: '{"orderId":"ORD-1234","status":"created"}'
)
client.send_event(msg)
```
```elixir title="publish.exs"
event = KubeMQ.Event.new(
channel: "order-events",
metadata: "order.created",
body: ~s({"orderId":"ORD-1234","status":"created"})
)
KubeMQ.Client.send_event(client, event)
```
### Point-to-Point — enqueue a job [#point-to-point--enqueue-a-job]
```go title="enqueue.go"
msg := kubemq.NewQueueMessage().
SetChannel("order-jobs").
SetBody([]byte(`{"orderId":"ORD-1234","total":99.99}`))
result, err := client.SendQueueMessage(ctx, msg)
```
```python title="enqueue.py"
result = client.send_queue_message(
QueueMessage(
channel="order-jobs",
body=b'{"orderId":"ORD-1234","total":99.99}',
)
)
```
```typescript title="enqueue.ts"
const result = await client.sendQueueMessage(
createQueueMessage({
channel: "order-jobs",
body: JSON.stringify({ orderId: "ORD-1234", total: 99.99 }),
}),
);
```
```java title="Enqueue.java"
SendQueueMessageResult result = client.sendQueueMessage(
QueueMessage.builder()
.channel("order-jobs")
.body("{\"orderId\":\"ORD-1234\",\"total\":99.99}".getBytes())
.build());
```
```csharp title="Enqueue.cs"
var result = await client.SendQueueMessageAsync(new QueueMessage
{
Channel = "order-jobs",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-1234\",\"total\":99.99}")
});
```
```kotlin title="Enqueue.kt"
val result = client.sendQueueMessage(QueueMessage(
channel = "order-jobs",
body = """{"orderId":"ORD-1234","total":99.99}""".toByteArray()
))
```
```cpp title="enqueue.cpp"
kubemq::QueueMessage msg;
msg.channel = "order-jobs";
msg.body = R"({"orderId":"ORD-1234","total":99.99})";
auto result = client.sendQueueMessage(msg);
```
```rust title="enqueue.rs"
let msg = QueueMessageBuilder::new()
.channel("order-jobs")
.body(br#"{"orderId":"ORD-1234","total":99.99}"#.to_vec())
.build();
let result = client.send_queue_message(msg).await?;
```
```ruby title="enqueue.rb"
msg = KubeMQ::Queues::QueueMessage.new(
channel: "order-jobs",
body: '{"orderId":"ORD-1234","total":99.99}'
)
result = client.send_queue_message(msg)
```
```elixir title="enqueue.exs"
msg = KubeMQ.QueueMessage.new(
channel: "order-jobs",
body: ~s({"orderId":"ORD-1234","total":99.99})
)
{:ok, result} = KubeMQ.Client.send_queue_message(client, msg)
```
### Request/Reply — send a command and wait [#requestreply--send-a-command-and-wait]
```go title="send_command.go"
resp, err := client.SendCommand(ctx, kubemq.NewCommand().
SetChannel("orders.process").
SetBody([]byte(`{"action":"create","orderId":"ORD-1234"}`)).
SetTimeout(10 * time.Second))
log.Printf("executed: %v", resp.Executed)
```
```python title="send_command.py"
response = client.send_command(
CommandMessage(
channel="orders.process",
body=b'{"action":"create","orderId":"ORD-1234"}',
timeout_in_seconds=10,
)
)
print(f"executed: {response.is_executed}")
```
```javascript title="send_command.js"
const response = await client.sendCommand({
channel: "orders.process",
body: Buffer.from(JSON.stringify({ action: "create", orderId: "ORD-1234" })),
timeoutInSeconds: 10,
});
console.log("executed:", response.isExecuted);
```
```java title="SendCommand.java"
CommandResponseMessage response = client.sendCommandRequest(
CommandMessage.builder()
.channel("orders.process")
.body("{\"action\":\"create\",\"orderId\":\"ORD-1234\"}".getBytes())
.timeout(10000)
.build());
System.out.println("executed: " + response.isExecuted());
```
```csharp title="SendCommand.cs"
var response = await client.SendCommandAsync(new CommandMessage
{
Channel = "orders.process",
Body = Encoding.UTF8.GetBytes("{\"action\":\"create\",\"orderId\":\"ORD-1234\"}"),
Timeout = TimeSpan.FromSeconds(10)
});
Console.WriteLine($"executed: {response.IsExecuted}");
```
```kotlin title="SendCommand.kt"
val response = client.sendCommand(CommandMessage(
channel = "orders.process",
body = """{"action":"create","orderId":"ORD-1234"}""".toByteArray(),
timeout = 10000
))
println("executed: ${response.isExecuted}")
```
```cpp title="send_command.cpp"
kubemq::CommandMessage cmd;
cmd.channel = "orders.process";
cmd.body = R"({"action":"create","orderId":"ORD-1234"})";
cmd.timeout = 10000;
auto response = client.sendCommand(cmd);
std::cout << "executed: " << response.isExecuted << std::endl;
```
```rust title="send_command.rs"
let command = CommandBuilder::new()
.channel("orders.process")
.body(br#"{"action":"create","orderId":"ORD-1234"}"#.to_vec())
.timeout(Duration::from_secs(10))
.build();
let response = client.send_command(command).await?;
println!("executed: {}", response.executed);
```
```ruby title="send_command.rb"
msg = KubeMQ::CQ::CommandMessage.new(
channel: "orders.process",
timeout: 10,
body: '{"action":"create","orderId":"ORD-1234"}'
)
result = client.send_command(msg)
puts "executed: #{result.executed}"
```
```elixir title="send_command.exs"
command = KubeMQ.Command.new(
channel: "orders.process",
body: ~s({"action":"create","orderId":"ORD-1234"}),
timeout: 10_000
)
{:ok, response} = KubeMQ.Client.send_command(client, command)
IO.puts("executed: #{response.executed}")
```
### How KubeMQ does this → [#how-kubemq-does-this-]
# Ordering & Replay (/learn/concepts/ordering-and-replay)
Imagine a deli counter that hands out numbered tickets. Everyone is served in the order they arrived — ticket 41 before 42 before 43 — and the numbers never repeat or skip. Now imagine the deli also kept a logbook of every ticket it ever served. A clerk arriving for the late shift could open the book, find where the morning clerk left off, and pick up from exactly that ticket — no customer served twice, none missed.
Those two ideas — **serving in a fixed order** and **rewinding the log to any point** — are *ordering* and *replay*. They are what separate a fleeting stream of notifications from a durable, rebuildable record of what happened.
## Ordering — the idea [#ordering--the-idea]
**Ordering** is the guarantee about *what sequence consumers observe messages in*. The strongest common form is **FIFO** (first-in, first-out): messages come out in exactly the order they went in. A queue gives you this naturally — like a single-file line, the message enqueued first is delivered first.
*A FIFO queue delivers messages in the exact order they were enqueued.*
Global FIFO across an entire channel is simple but limits throughput — only one consumer can safely process at a time without reordering. In practice most systems offer **per-key ordering** instead: messages that share a *partition key* (an order ID, a user ID) stay strictly ordered relative to each other, while unrelated keys flow in parallel. You get order where it matters and parallelism everywhere else.
## Replay — the idea [#replay--the-idea]
A real-time channel is a PA announcement: hear it now or miss it forever. A **replayable** channel is a recording. To replay, the system has to do two things:
1. **Number every message** with a monotonically increasing **sequence number** (also called an **offset**) — a stable address for each message in the log.
2. **Persist the log** so messages survive after delivery, and let a consumer say *"start me at offset N"* instead of always "start me at the newest."
*Every message is numbered and written to a persistent log; a late subscriber rewinds to any offset and re-reads history, while a live subscriber follows the tail.*
Because the log keeps the sequence intact, replay and ordering reinforce each other: re-reading from offset 42 always returns 42, 43, 44… in the same order, every time. That determinism is what makes a log trustworthy as a system of record.
### The event-sourcing idea [#the-event-sourcing-idea]
If the log is the source of truth, you do not need to store the *current state* of anything — you can **rebuild it by replaying the events that produced it**. This is **event sourcing**: instead of saving "account balance = $80," you save the sequence of facts (`Deposited $100`, `Withdrew $20`) and replay them to compute the balance on demand. A new service, a rebuilt cache, or a bug fix that needs to reprocess history all start the same way: replay from the beginning.
**Concept:** A sequence number (offset) is just a message's permanent position in the log. "Replay" means asking the log to start delivering from a chosen position instead of from the newest message.
## Precise definition [#precise-definition]
* **Ordering** — a delivery guarantee that consumers observe messages in a defined sequence. **FIFO** orders an entire channel; **per-key ordering** orders only messages sharing a partition key, allowing parallel processing across keys.
* **Sequence number / offset** — a monotonically increasing integer assigned to each message as it is persisted, giving every message a stable, addressable position in the log.
* **Replay** — re-reading messages from a persisted log starting at a chosen **start position** (a sequence number, a timestamp, the first message, or the last), rather than receiving only messages published after subscribing.
* **Event sourcing** — modeling state as the ordered log of events that produced it, and reconstructing current state by replaying that log from the start.
## Trade-offs [#trade-offs]
| Property | When it helps | When it bites |
| ---------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| **Strict FIFO** | Steps that must happen in order (state machines, financial postings) | Caps throughput — one in-flight consumer per ordered stream |
| **Per-key ordering** | Order per entity (per order, per user) plus parallelism across entities | Requires choosing a good key; a hot key still serializes |
| **Persistent log + offsets** | Late joiners, audit trails, reprocessing, event sourcing | Costs disk and retention management; the log grows |
| **Replay from a position** | Recovery, backfills, rebuilding state from history | Re-delivering old events can re-trigger side effects if consumers are not idempotent |
**Pitfall:** Replaying history re-delivers messages a consumer may have already handled. If processing a message has side effects — charging a card, sending an email — make consumers **idempotent** (safe to run twice for the same message), keyed on the sequence number or a message ID. Otherwise a replay double-charges. See [delivery guarantees](/learn/concepts/delivery-guarantees) for idempotency.
## In KubeMQ [#in-kubemq]
**In KubeMQ:** **Queues** preserve FIFO order — messages are delivered in the order they were sent. **Events Store** persists every message with a **sequence number** and lets a subscriber choose a **start position**: `StartNewOnly`, `StartFromFirst`, `StartFromLast`, `StartAtSequence`, `StartAtTime`, or `StartAtTimeDelta`. Pointing a subscriber at `StartFromFirst` and rebuilding state from the result is exactly event sourcing.
The snippet below subscribes to a persisted channel from **sequence 3** — replaying every stored event at or after that offset, then streaming new ones as they arrive. Swapping `StartAtSequence` for `StartFromFirst` replays the entire history; `StartAtTimeDelta` replays a recent time window.
```go title="replay_from_sequence.go"
sub, err := client.SubscribeToEventsStore(ctx, "orders.events", "",
kubemq.StartAtSequence(3),
kubemq.WithOnEvent(func(event *kubemq.Event) {
fmt.Printf("[replay] seq=%d body=%s\n",
event.Sequence, string(event.Body))
}),
kubemq.WithOnError(func(err error) { log.Println(err) }),
)
```
```python title="replay_from_sequence.py"
client.subscribe_to_events_store(
subscription=EventsStoreSubscription(
channel="orders.events",
start_position=EventStoreStartPosition.StartAtSequence,
start_position_value=3,
on_receive_event_callback=lambda e: print(
f"[replay] seq={e.sequence} body={e.body.decode('utf-8')}"
),
on_error_callback=lambda e: print(f"Error: {e}"),
),
cancel=CancellationToken(),
)
```
```typescript title="replay_from_sequence.ts"
client.subscribeToEventsStore({
channel: 'orders.events',
startPosition: EventStoreStartPosition.StartAtSequence,
startPositionValue: 3,
onEvent: (msg) =>
console.log(`[replay] seq=${msg.sequence} body=${new TextDecoder().decode(msg.body)}`),
onError: (err) => console.error(err.message),
});
```
```java title="ReplayFromSequence.java"
client.subscribeToEventsStore(EventsStoreSubscription.builder()
.channel("orders.events")
.startPosition(EventStoreStartPosition.StartAtSequence)
.startPositionValue(3)
.onReceiveEventCallback(event ->
System.out.printf("[replay] seq=%d body=%s%n",
event.getSequence(), new String(event.getBody())))
.onErrorCallback(err -> System.err.println(err.getMessage()))
.build());
```
```csharp title="ReplayFromSequence.cs"
await foreach (var msg in client.SubscribeToEventsStoreAsync(
new EventsStoreSubscription
{
Channel = "orders.events",
StartPosition = EventStoreStartPosition.StartAtSequence,
StartPositionValue = 3,
}))
{
Console.WriteLine($"[replay] seq={msg.Sequence} body={Encoding.UTF8.GetString(msg.Body.Span)}");
}
```
```kotlin title="ReplayFromSequence.kt"
client.subscribeToEventsStore {
channel = "orders.events"
startPosition = StartPosition.StartAtSequence
startPositionValue = 3
}.collect { msg ->
println("[replay] seq=${msg.sequence} body=${String(msg.body)}")
}
```
```cpp title="replay_from_sequence.cc"
client->SubscribeToEventsStore("orders.events", "",
kubemq::StartPosition::StartAtSequence, 3,
[](const kubemq::EventStoreReceived& msg) {
std::cout << "[replay] seq=" << msg.sequence()
<< " body=" << msg.body() << std::endl;
},
[](const std::string& err) { std::cerr << err << std::endl; });
```
```rust title="replay_from_sequence.rs"
use kubemq::prelude::*;
use kubemq::EventsStoreSubscription;
let sub = client
.subscribe_to_events_store(
"orders.events",
"",
EventsStoreSubscription::StartAtSequence(3),
|event| {
Box::pin(async move {
println!(
"[replay] seq={} body={}",
event.sequence,
String::from_utf8_lossy(&event.body)
);
})
},
None,
)
.await?;
```
```ruby title="replay_from_sequence.rb"
sub = KubeMQ::PubSub::EventsStoreSubscription.new(
channel: "orders.events",
start_position: KubeMQ::PubSub::EventStoreStartPosition::START_AT_SEQUENCE,
start_position_value: 3
)
client.subscribe_to_events_store(sub, cancellation_token: cancel, on_error: lambda { |e|
puts "Error: #{e.message}"
}) do |event|
puts "[replay] seq=#{event.sequence} body=#{event.body}"
end
```
```elixir title="replay_from_sequence.exs"
{:ok, sub} =
KubeMQ.Client.subscribe_to_events_store(client, "orders.events",
start_at: {:start_at_sequence, 3},
on_event: fn event ->
IO.puts("[replay] seq #{event.sequence}: #{event.body}")
end
)
```
Queues deliver in FIFO order with no start-position parameter — order is inherent to the queue. The start positions above apply to **Events Store**, where the persistent log makes any offset addressable.
### How KubeMQ does this → [#how-kubemq-does-this-]
# Scaling & Flow Control (/learn/concepts/scaling-and-flow)
When work piles up faster than one worker can handle it, you have two completely different levers — and reaching for the wrong one quietly breaks your system. This page is about telling them apart: **scaling out** (adding workers to share the load) and **flow control** (keeping a fast producer from drowning a slow consumer).
Picture a busy coffee shop. To serve more customers, you put more baristas behind **one** counter — each drink order goes to whichever barista is free. That is scaling by *competing consumers*. Now picture the shop's radio: every barista hears the same announcement, no matter how many you hire. That is *fan-out*. Adding baristas speeds up the counter; it does nothing to the radio. Confusing the two is how you end up processing every order three times — or building a "load balancer" that never balances.
## Competing consumers vs fan-out — the idea [#competing-consumers-vs-fan-out--the-idea]
Both shapes start with one stream of messages and several consumers. The difference is **who gets each message**.
**Competing consumers** (point-to-point): the consumers share a single logical destination, and each message is handed to **exactly one** of them. Add a consumer and total throughput goes up, because the work is split. This is how you scale processing.
**Fan-out** (pub/sub): every consumer is an independent subscriber, and each message is **copied to all** of them. Add a subscriber and you get one more *full copy* of the stream — useful for independent reactions, not for sharing load.
*Competing consumers: one destination, each message to exactly one worker — add workers to share the load.*
*Fan-out: one channel, every subscriber gets its own copy — add subscribers for independent reactions, not for throughput.*
### Consumer groups: getting both from one channel [#consumer-groups-getting-both-from-one-channel]
What if you want load-balancing **and** broadcast on the same channel? A **consumer group** is the bridge. Each consumer declares a group name when it subscribes. Within a group, members compete — a message goes to exactly one of them. Across groups, each group gets its own copy.
So three workers in group `billing` split the stream between them, while a separate `analytics` group (its own members) receives the full stream in parallel. One channel, two behaviors, decided entirely by group membership.
The group mechanics on this page apply to both Events and Events Store, but durability does not: **Events** groups are fire-and-forget — a member that is offline simply misses messages, with nothing to replay. **Events Store** groups are durable and position-tracked — the store remembers each group's progress, so a member that reconnects resumes from where it left off instead of losing messages. The example below uses plain Events; see [In KubeMQ](#in-kubemq) for the Events Store distinction in full.
*Group `billing` competes for messages (load-balanced); group `analytics` gets its own full copy — group name decides the behavior.*
## Backpressure and slow consumers [#backpressure-and-slow-consumers]
Scaling out assumes consumers can keep up. When they cannot — a producer bursts, a downstream API slows down, a worker stalls on a long job — the system needs a way to push back. That feedback is **backpressure**: signalling upstream to slow down (or buffer, or shed load) so a fast producer does not overwhelm a slow consumer.
Without backpressure, the gap has to go *somewhere*, and every option is bad: an unbounded in-memory buffer grows until the process runs out of memory; a fixed buffer overflows and silently drops messages; or the producer blocks and the whole pipeline stalls. The healthy outcome is the producer feeling resistance and easing off — exactly like water pressure backing up a pipe when the drain is too small.
*A buffer absorbs short bursts; when it fills, backpressure flows back to the producer so it eases off instead of overflowing.*
A durable queue is itself a form of backpressure-by-buffering: it absorbs bursts on disk so producers never block on slow consumers, and you drain the backlog by adding more competing workers. A broadcast (fire-and-forget) channel has no such buffer — a subscriber that cannot keep up simply misses messages.
### Visibility timeout and in-flight messages [#visibility-timeout-and-in-flight-messages]
There is a subtler flow-control problem hiding inside competing consumers: what happens to a message **while** a worker is processing it? If the destination handed the same message to a second worker, you would process it twice. If it deleted the message immediately on delivery, a crash mid-processing would lose it.
The standard answer is the **visibility timeout**. When a worker receives a message, the message is not deleted — it is hidden from other consumers for a bounded window and counts as **in-flight**. The worker has until the timeout to finish and acknowledge (ack), which deletes it. If the worker crashes or the timeout expires first, the message becomes visible again and is redelivered to another worker.
*Visibility timeout: a received message is in-flight and hidden; ack within the window deletes it, otherwise it reappears for another worker.*
The timeout is a balance. Too short, and a legitimately slow job gets redelivered (and processed twice) before it finishes. Too long, and a crashed worker's messages sit invisible for ages before anyone retries them. The limit on in-flight messages also caps real concurrency: a destination only lets so many messages be in-flight at once, which is itself a backpressure knob.
## Precise definitions [#precise-definitions]
* **Competing consumers (point-to-point):** a distribution model where multiple consumers read from one shared destination and each message is delivered to exactly one consumer. Throughput scales with the number of consumers.
* **fan-out (pub/sub):** a distribution model where each message is copied to every independent subscriber on a channel. Adding subscribers adds parallel copies, not shared load.
* **Consumer Group:** a named set of consumers on one channel that compete as a unit — each message goes to one member of the group, while every group on the channel receives its own copy.
* **backpressure:** flow control that signals a producer to slow down (or buffer, or shed) when consumers cannot keep up, preventing overflow and loss.
* **Visibility timeout:** the bounded window during which a received-but-unacknowledged message is hidden from other consumers and counts as in-flight; on expiry without an ack it is redelivered.
* **In-flight message:** a message that has been delivered to a consumer but not yet acknowledged — held, not deleted, so it can be redelivered if processing fails.
## Trade-offs [#trade-offs]
| Goal | Reach for | Why | Watch out for |
| ------------------------------- | ----------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------ |
| Process more, faster | Competing consumers / a group | Each message done once; add workers to scale | One slow worker holds its in-flight messages until timeout |
| React independently in N places | fan-out / separate groups | Every consumer sees every message | Adds load, not throughput — N copies of the work |
| Absorb bursts without dropping | Durable queue (buffer) | Disk soaks up the spike; drain with more workers | Backlog grows if consumers stay too slow — monitor depth |
| Don't overwhelm a slow consumer | Backpressure | Producer eases off instead of overflowing | Fire-and-forget channels have no buffer — slow subscribers miss messages |
| Survive crashes mid-processing | Visibility timeout + ack | Unacked work reappears for another worker | Wrong timeout → double-processing (too short) or stalls (too long) |
**Pitfall — "scaling" a broadcast.** Adding subscribers to a fire-and-forget channel does **not** share the load: every subscriber still receives every message, so you multiply the work instead of dividing it. To actually scale processing, put the consumers in the same group so they compete for messages.
**Pitfall — designing for exactly-once consumers.** Visibility-timeout redelivery means a consumer can see the same message more than once (a slow job, a crash, an expired timeout). Make handlers **idempotent** so a redelivery is harmless rather than betting on never seeing a duplicate.
## In KubeMQ [#in-kubemq]
KubeMQ exposes both levers directly:
* **Fan-out vs competing consumers is one parameter.** On Events and Events Store, subscribers that pass the **same group name** compete (each message to one member); subscribers with **no group** (or different groups) each get a full copy. Same channel, different `group` argument.
* **Queues give you the buffer and the visibility timeout.** A queue durably stores messages, so producers never block on slow consumers — you scale by running more receivers, and each received message is hidden for its **visibility timeout** until you ack it, then redelivered if you don't.
The snippet below is the same load-balanced subscribe from the [Events Consumer Groups](/learn/events/tutorials/consumer-groups) tutorial: several consumers join one **group** on `order-events`, and KubeMQ delivers each event to exactly one of them. Drop the group name and the very same subscribers turn into fan-out.
```go title="grouped_worker.go"
sub, err := client.SubscribeToEvents(ctx, "order-events", "workers",
kubemq.WithOnEvent(func(event *kubemq.Event) {
fmt.Printf("Processing: %s\n", string(event.Body))
}),
)
if err != nil {
log.Fatal(err)
}
defer sub.Unsubscribe()
// Members sharing group "workers" compete; pass "" for fan-out instead.
```
```python title="grouped_worker.py"
from kubemq.pubsub import Client as PubSubClient
from kubemq.pubsub import EventsSubscription, CancellationToken
client = PubSubClient(address="localhost:50000")
client.subscribe_to_events(
subscription=EventsSubscription(
channel="order-events",
group="workers", # same group -> competing consumers; omit for fan-out
on_receive_event_callback=lambda e: print(f"Processing: {e.body.decode()}"),
),
cancel=CancellationToken(),
)
```
```javascript title="grouped_worker.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000" });
client.subscribeToEvents({
channel: "order-events",
group: "workers", // same group -> competing consumers; omit for fan-out
onEvent: (msg) =>
console.log(`Processing: ${Buffer.from(msg.body).toString()}`),
onError: (err) => console.error(err.message),
});
```
```java title="GroupedWorker.java"
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("worker-1")
.build();
client.subscribeToEvents(EventsSubscription.builder()
.channel("order-events")
.group("workers") // same group -> competing consumers; omit for fan-out
.onReceiveEventCallback(event ->
System.out.printf("Processing: %s%n", new String(event.getBody())))
.build());
```
```csharp title="GroupedWorker.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
await foreach (var msg in client.SubscribeToEventsAsync(
new EventsSubscription { Channel = "order-events", Group = "workers" }))
{
// same Group -> competing consumers; leave Group unset for fan-out
Console.WriteLine($"Processing: {Encoding.UTF8.GetString(msg.Body.Span)}");
}
```
```kotlin title="GroupedWorker.kt"
val client = PubSubClient("localhost:50000")
client.subscribeToEvents(
channel = "order-events",
group = "workers", // same group -> competing consumers; omit for fan-out
onEvent = { event -> println("Processing: ${String(event.body)}") },
onError = { err -> System.err.println(err.message) },
)
```
```cpp title="grouped_worker.cpp"
auto client = kubemq::PubSubClient("localhost:50000");
// same group ("workers") -> competing consumers; pass "" for fan-out
client.subscribeToEvents("order-events", "workers",
[](const kubemq::Event& event) {
std::cout << "Processing: " << event.body << std::endl;
},
[](const std::string& err) { std::cerr << err << std::endl; }
);
```
```rust title="grouped_worker.rs"
let group = "workers"; // same group -> competing consumers; "" for fan-out
let sub = client
.subscribe_to_events(
"order-events",
group,
|event| {
Box::pin(async move {
println!("Processing: {}", String::from_utf8_lossy(&event.body));
})
},
None,
)
.await?;
```
```ruby title="grouped_worker.rb"
client = KubeMQ::PubSubClient.new(address: "localhost:50000", client_id: "worker-1")
cancel = KubeMQ::CancellationToken.new
# group: -> competing consumers; omit group: for fan-out
sub = KubeMQ::PubSub::EventsSubscription.new(channel: "order-events", group: "workers")
client.subscribe_to_events(sub, cancellation_token: cancel) do |event|
puts "Processing: #{event.body}"
end
```
```elixir title="grouped_worker.exs"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "worker-1")
# group: -> competing consumers; omit group: for fan-out
{:ok, _sub} =
KubeMQ.Client.subscribe_to_events(client, "order-events",
group: "workers",
on_event: fn event -> IO.puts("Processing: #{event.body}") end
)
```
The same group switch applies to **Events Store** (durable, position-tracked groups) and to **Queues**, where competing receivers share the buffer and each delivery is governed by a visibility timeout you ack to clear.
### How KubeMQ does this [#how-kubemq-does-this]
# Getting Started with Events (/learn/events/getting-started)
**Prerequisites:** KubeMQ server running on `localhost:50000` and your SDK installed. See [Getting Started](/deploy) for setup.
## What You Will Build [#what-you-will-build]
A notification publisher that sends order events and a subscriber that receives them in real time.
The publisher fans out one event to every connected subscriber. Because Events are **at-most-once**, a subscriber that is offline (Subscriber C) misses the message — there is no replay.
## Steps [#steps]
### Install the SDK [#install-the-sdk]
```bash
go get github.com/kubemq-io/kubemq-go/v2
```
```bash
pip install kubemq
```
```bash
npm install kubemq-js
```
```xml
io.kubemq.sdk
kubemq-sdk-Java
3.1.1
```
```xml
```
```kotlin
implementation("io.kubemq.sdk:kubemq-sdk-kotlin:1.0.1")
```
```bash
vcpkg install kubemq
```
```toml
[dependencies]
kubemq = "1.0"
tokio = { version = "1", features = ["full"] }
```
```bash
gem install kubemq
```
```elixir
# mix.exs
def deps do
[{:kubemq, "~> 1.0"}]
end
```
### Create a Subscriber [#create-a-subscriber]
Start the subscriber first. Events are fire-and-forget, so the subscriber must be connected before the publisher sends events.
```go title="subscriber.go"
package main
import (
"context"
"fmt"
"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()
sub, err := client.SubscribeToEvents(ctx, "order-notifications", "",
kubemq.WithOnEvent(func(event *kubemq.Event) {
fmt.Printf("Received: %s\n", string(event.Body))
}),
kubemq.WithOnError(func(err error) {
log.Println("Subscription error:", err)
}),
)
if err != nil {
log.Fatal(err)
}
defer sub.Unsubscribe()
log.Println("Subscriber listening on 'order-notifications'...")
<-ctx.Done()
}
```
```python title="subscriber.py"
import time
from kubemq.pubsub import Client as PubSubClient
from kubemq.pubsub import EventsSubscription, CancellationToken
def on_event(event):
print(f"Received: {event.body.decode('utf-8')}")
def on_error(err):
print(f"Subscription error: {err}")
client = PubSubClient(address="localhost:50000")
cancel = CancellationToken()
client.subscribe_to_events(
subscription=EventsSubscription(
channel="order-notifications",
on_receive_event_callback=on_event,
on_error_callback=on_error,
),
cancel=cancel,
)
print("Subscriber listening on 'order-notifications'...")
time.sleep(120)
client.close()
```
```javascript title="subscriber.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000" });
client.subscribeToEvents({
channel: "order-notifications",
onEvent: (msg) =>
console.log(`Received: ${Buffer.from(msg.body).toString()}`),
onError: (err) => console.error("Subscription error:", err.message),
});
console.log("Subscriber listening on 'order-notifications'...");
```
```java title="Subscriber.java"
import io.kubemq.sdk.pubsub.PubSubClient;
import io.kubemq.sdk.pubsub.EventsSubscription;
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("order-subscriber")
.build();
client.subscribeToEvents(EventsSubscription.builder()
.channel("order-notifications")
.onReceiveEventCallback(event ->
System.out.println("Received: " + new String(event.getBody())))
.onErrorCallback(err ->
System.err.println("Subscription error: " + err.getMessage()))
.build());
System.out.println("Subscriber listening on 'order-notifications'...");
Thread.sleep(120_000);
client.close();
```
```csharp title="Subscriber.cs"
using KubeMQ.Sdk.Client;
using KubeMQ.Sdk.Events;
using System.Text;
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
Console.WriteLine("Subscriber listening on 'order-notifications'...");
await foreach (var msg in client.SubscribeToEventsAsync(
new EventsSubscription { Channel = "order-notifications" }))
{
Console.WriteLine($"Received: {Encoding.UTF8.GetString(msg.Body.Span)}");
}
```
```kotlin title="Subscriber.kt"
import io.kubemq.sdk.client.KubeMQClient
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val pubsub = KubeMQClient.pubSub {
address = "localhost:50000"
clientId = "order-subscriber"
}
println("Subscriber listening on 'order-notifications'...")
pubsub.subscribeToEvents {
channel = "order-notifications"
}.collect { event ->
println("Received: ${String(event.body)}")
}
}
```
```cpp title="subscriber.cpp"
#include
#include
auto client = kubemq::PubSubClient("localhost:50000");
client.subscribeToEvents("order-notifications", "",
[](const kubemq::Event& event) {
std::cout << "Received: " << event.body << std::endl;
},
[](const std::string& err) {
std::cerr << "Subscription error: " << err << std::endl;
}
);
std::cout << "Subscriber listening on 'order-notifications'..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(120));
```
```rust title="subscriber.rs"
use kubemq::prelude::*;
use kubemq::Subscription;
use std::time::Duration;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
let sub: Subscription = client
.subscribe_to_events(
"order-notifications",
"",
|event| {
Box::pin(async move {
println!("Received: {}", String::from_utf8_lossy(&event.body));
})
},
None,
)
.await?;
println!("Subscriber listening on 'order-notifications'...");
tokio::time::sleep(Duration::from_secs(120)).await;
sub.unsubscribe().await;
client.close().await?;
Ok(())
}
```
```ruby title="subscriber.rb"
require 'kubemq'
client = KubeMQ::PubSubClient.new(address: "localhost:50000", client_id: "order-subscriber")
cancel = KubeMQ::CancellationToken.new
sub = KubeMQ::PubSub::EventsSubscription.new(channel: "order-notifications")
client.subscribe_to_events(sub, cancellation_token: cancel,
on_error: ->(e) { puts "Subscription error: #{e.message}" }) do |event|
puts "Received: #{event.body}"
end
puts "Subscriber listening on 'order-notifications'..."
sleep 120
cancel.cancel
client.close
```
```elixir title="subscriber.exs"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-subscriber")
{:ok, sub} =
KubeMQ.Client.subscribe_to_events(client, "order-notifications",
on_event: fn event -> IO.puts("Received: #{event.body}") end,
on_error: fn err -> IO.puts("Subscription error: #{err.message}") end
)
IO.puts("Subscriber listening on 'order-notifications'...")
Process.sleep(120_000)
KubeMQ.Subscription.cancel(sub)
KubeMQ.Client.close(client)
```
### Create a Publisher [#create-a-publisher]
In a separate terminal, run the publisher. The subscriber receives the event instantly.
```go title="publisher.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("order-notifications").
SetBody([]byte(`{"orderId":"ORD-1234","status":"created"}`)),
)
if err != nil {
log.Fatal(err)
}
log.Println("Event published to 'order-notifications'")
}
```
```python title="publisher.py"
from kubemq.pubsub import Client as PubSubClient
from kubemq.pubsub import EventMessage
client = PubSubClient(address="localhost:50000")
client.send_event(
EventMessage(
channel="order-notifications",
body=b'{"orderId":"ORD-1234","status":"created"}',
)
)
print("Event published to 'order-notifications'")
client.close()
```
```javascript title="publisher.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000" });
await client.sendEvent({
channel: "order-notifications",
body: Buffer.from(JSON.stringify({ orderId: "ORD-1234", status: "created" })),
});
console.log("Event published to 'order-notifications'");
```
```java title="Publisher.java"
import io.kubemq.sdk.pubsub.PubSubClient;
import io.kubemq.sdk.pubsub.EventMessage;
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("order-publisher")
.build();
client.sendEventsMessage(EventMessage.builder()
.channel("order-notifications")
.body("{\"orderId\":\"ORD-1234\",\"status\":\"created\"}".getBytes())
.build());
System.out.println("Event published to 'order-notifications'");
client.close();
```
```csharp title="Publisher.cs"
using KubeMQ.Sdk.Client;
using KubeMQ.Sdk.Events;
using System.Text;
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
await client.SendEventAsync(new EventMessage
{
Channel = "order-notifications",
Body = Encoding.UTF8.GetBytes(
"{\"orderId\":\"ORD-1234\",\"status\":\"created\"}")
});
Console.WriteLine("Event published to 'order-notifications'");
```
```kotlin title="Publisher.kt"
import io.kubemq.sdk.client.KubeMQClient
import io.kubemq.sdk.pubsub.eventMessage
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val pubsub = KubeMQClient.pubSub {
address = "localhost:50000"
clientId = "order-publisher"
}
pubsub.publishEvent(eventMessage {
channel = "order-notifications"
body = """{"orderId":"ORD-1234","status":"created"}""".toByteArray()
})
println("Event published to 'order-notifications'")
}
```
```cpp title="publisher.cpp"
#include
#include
auto client = kubemq::PubSubClient("localhost:50000");
kubemq::EventMessage event;
event.channel = "order-notifications";
event.body = R"({"orderId":"ORD-1234","status":"created"})";
client.sendEvent(event);
std::cout << "Event published to 'order-notifications'" << std::endl;
```
```rust title="publisher.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("order-notifications")
.body(br#"{"orderId":"ORD-1234","status":"created"}"#.to_vec())
.build();
client.send_event(event).await?;
println!("Event published to 'order-notifications'");
client.close().await?;
Ok(())
}
```
```ruby title="publisher.rb"
require 'kubemq'
client = KubeMQ::PubSubClient.new(address: "localhost:50000", client_id: "order-publisher")
client.send_event(KubeMQ::PubSub::EventMessage.new(
channel: "order-notifications",
body: '{"orderId":"ORD-1234","status":"created"}'
))
puts "Event published to 'order-notifications'"
client.close
```
```elixir title="publisher.exs"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-publisher")
event = KubeMQ.Event.new(
channel: "order-notifications",
body: ~s({"orderId":"ORD-1234","status":"created"})
)
:ok = KubeMQ.Client.send_event(client, event)
IO.puts("Event published to 'order-notifications'")
KubeMQ.Client.close(client)
```
### Run the Example [#run-the-example]
1. Start the **subscriber** in one terminal
2. Run the **publisher** in a separate terminal
3. The subscriber receives the event in real time
### Verify [#verify]
The subscriber terminal should display:
```text
Subscriber listening on 'order-notifications'...
Received: {"orderId":"ORD-1234","status":"created"}
```
The publisher terminal should display:
```text
Event published to 'order-notifications'
```
## What Just Happened [#what-just-happened]
1. The **subscriber** connected to KubeMQ and registered interest in `order-notifications`
2. The **publisher** sent an event containing an order payload to the same channel
3. KubeMQ delivered the event to the subscriber in real time
4. Because Events are fire-and-forget, the publisher does not wait for acknowledgment
Events have **at-most-once** delivery. If the subscriber was not connected when the event was published, the message would be lost. For persistent delivery with replay, use [Events Store](/learn/events-store/getting-started).
## Next Steps [#next-steps]
# Events — Real-Time Pub/Sub (/learn/events)
Think of Events like a PA system in a building — when an announcement is made, everyone currently listening hears it. If you step outside, you miss the announcement. There's no recording, no replay.
KubeMQ Events implement fire-and-forget publish/subscribe with at-most-once delivery. Publishers send messages to a named channel, and all active subscribers receive the message in real time. There is no persistence — if a subscriber is offline, the message is lost for that subscriber.
## The concept it implements [#the-concept-it-implements]
Events is KubeMQ's implementation of two fundamental ideas. The interaction style is **[pub/sub](/learn/concepts/interaction-styles)** (fan-out) — one publisher, many subscribers, each receiving every message. The delivery guarantee is **[at-most-once](/learn/concepts/delivery-guarantees)** — messages reach only the subscribers connected at publish time and are never persisted or redelivered. New to these terms? Start with the [Fundamentals](/learn/concepts) track.
## Key Properties [#key-properties]
| Property | This pattern | Learn the concept |
| ------------------ | --------------------------------------------- | ---------------------------------------------------------- |
| Interaction style | pub/sub (fan-out) | [Interaction styles](/learn/concepts/interaction-styles) |
| Delivery guarantee | at-most-once | [Delivery guarantees](/learn/concepts/delivery-guarantees) |
| Persistence | None — fire-and-forget | [Ordering & replay](/learn/concepts/ordering-and-replay) |
| Ordering | Not guaranteed | [Ordering & replay](/learn/concepts/ordering-and-replay) |
| Scaling | Fan-out, or load-balance with consumer groups | [Scaling & flow](/learn/concepts/scaling-and-flow) |
| Addressing | Named channels, wildcards, multicast routing | [Channels & routing](/learn/concepts/channels-and-routing) |
## Key Features [#key-features]
* **At-most-once delivery** — messages delivered to active subscribers only
* **Lowest latency** — no disk I/O or acknowledgment overhead
* **Multicast delivery** — every subscriber on the channel receives every message (fan-out)
* **Channel groups** — load balance across subscribers in a named group
* **Multicast routing** — publish to multiple channels using routing syntax
* **Stream publishing** — high-throughput batched delivery via bidirectional streaming
## How It Works [#how-it-works]
*Fan-out: a publisher broadcasts to the channel, every connected subscriber receives the message, and offline subscribers miss it.*
## Quick Example [#quick-example]
```go title="publish.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("order-notifications").
SetMetadata("order.created").
SetBody([]byte(`{"orderId":"ORD-1234","status":"created"}`)),
)
if err != nil {
log.Fatal(err)
}
log.Println("Event sent successfully")
}
```
```python title="publish.py"
from kubemq.pubsub import Client as PubSubClient
from kubemq.pubsub import EventMessage
client = PubSubClient(address="localhost:50000")
client.send_event(
EventMessage(
channel="order-notifications",
metadata="order.created",
body=b'{"orderId":"ORD-1234","status":"created"}',
)
)
print("Event sent successfully")
client.close()
```
```javascript title="publish.js"
import { KubeMQClient } from 'kubemq-js';
const client = await KubeMQClient.create({ address: 'localhost:50000' });
await client.sendEvent({
channel: "order-notifications",
metadata: "order.created",
body: Buffer.from(JSON.stringify({ orderId: "ORD-1234", status: "created" })),
});
console.log("Event sent successfully");
```
```java title="Publish.java"
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("order-publisher")
.build();
client.sendEventsMessage(EventMessage.builder()
.channel("order-notifications")
.metadata("order.created")
.body("{\"orderId\":\"ORD-1234\",\"status\":\"created\"}".getBytes())
.build());
System.out.println("Event sent successfully");
client.close();
```
```csharp title="Publish.cs"
using KubeMQ.Sdk.Client;
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
await client.SendEventAsync(new EventMessage
{
Channel = "order-notifications",
Metadata = "order.created",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-1234\",\"status\":\"created\"}")
});
Console.WriteLine("Event sent successfully");
```
```kotlin title="Publish.kt"
val client = PubSubClient("localhost:50000")
client.sendEvent(EventMessage(
channel = "order-notifications",
metadata = "order.created",
body = """{"orderId":"ORD-1234","status":"created"}""".toByteArray()
))
println("Event sent successfully")
client.close()
```
```cpp title="publish.cpp"
#include
auto client = kubemq::PubSubClient("localhost:50000");
kubemq::EventMessage event;
event.channel = "order-notifications";
event.metadata = "order.created";
event.body = R"({"orderId":"ORD-1234","status":"created"})";
client.sendEvent(event);
std::cout << "Event sent successfully" << std::endl;
```
```rust title="publish.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("order-notifications")
.metadata("order.created")
.body(br#"{"orderId":"ORD-1234","status":"created"}"#.to_vec())
.build();
client.send_event(event).await?;
println!("Event sent successfully");
client.close().await?;
Ok(())
}
```
```ruby title="publish.rb"
require 'kubemq'
client = KubeMQ::PubSubClient.new(address: "localhost:50000", client_id: "order-publisher")
client.send_event(KubeMQ::PubSub::EventMessage.new(
channel: "order-notifications",
metadata: "order.created",
body: '{"orderId":"ORD-1234","status":"created"}'
))
puts "Event sent successfully"
client.close
```
```elixir title="publish.exs"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-publisher")
event = KubeMQ.Event.new(
channel: "order-notifications",
metadata: "order.created",
body: ~s({"orderId":"ORD-1234","status":"created"})
)
:ok = KubeMQ.Client.send_event(client, event)
IO.puts("Event sent successfully")
KubeMQ.Client.close(client)
```
## When to Use Events [#when-to-use-events]
| Scenario | Events | Events Store |
| ----------------------- | ---------------------- | ----------------------------- |
| Real-time notifications | ✅ Best choice | Overkill |
| Log/metric streaming | ✅ Best choice | Use if logs must not be lost |
| Live dashboards | ✅ Best choice | Use if historical data needed |
| Cache invalidation | ✅ Best choice | Not needed |
| Audit trails | ❌ Messages can be lost | ✅ Use Events Store |
| Event sourcing | ❌ No persistence | ✅ Use Events Store |
Need guaranteed delivery or replay capability? Use [Events Store](/learn/events-store) instead.
Events are also available via the [CloudEvents protocol](/connectors/cloudevents/how-to/events) — use any language with a CloudEvents SDK, no KubeMQ client library needed.
## Learn More [#learn-more]
# Events Reference (/learn/events/reference)
## Message Structure [#message-structure]
### Event Message (Send) [#event-message-send]
### Event Receive (Subscribe) [#event-receive-subscribe]
Unlike Events Store, plain Events do not include `Timestamp` or `Sequence` fields because there is no persistence layer.
### Send Result [#send-result]
## Subscription Options [#subscription-options]
### Consumer Groups [#consumer-groups]
When multiple subscribers specify the same `group` value on the same channel:
* Each event is delivered to exactly **one** member of the group (round-robin)
* When `group` is empty, every subscriber receives every event (standard fan-out)
* Groups are independent per channel
* There is no limit on the number of group members
See [Consumer Groups](/learn/events/tutorials/consumer-groups) and [Scale Subscribers](/learn/events/how-to/scale-subscribers) for examples.
## Channel Naming Rules [#channel-naming-rules]
| Rule | Constraint | Error Code |
| ---------------------- | ----------------------------------------- | ---------- |
| Required | Cannot be empty | 102 |
| No trailing dot | Cannot end with `.` | 119 |
| No whitespace | Cannot contain spaces | 108 |
| No wildcards (publish) | Cannot contain `*` or `>` when publishing | 107 |
| Max length | 256 characters | — |
**Valid channel regex (publish):** `^[^\s*>]+[^.]$`
Wildcards (`*` and `>`) are allowed in **subscription** channel patterns only. See [Wildcard Subscriptions](/learn/events/tutorials/wildcard-subscriptions).
### Channel Naming Conventions [#channel-naming-conventions]
Use dot-separated hierarchical names for best results with wildcard subscriptions:
```text
{domain}.{entity}.{action}
orders.created
orders.us-east.shipped
payments.completed
inventory.reserved
```
## Routing (Multicast) [#routing-multicast]
Events support multicast publishing through special channel syntax:
| Character | Purpose | Example |
| --------- | ---------------------------------- | ---------------------------------- |
| `;` | Separate channels of the same type | `orders;notifications` |
| `:` | Specify target pattern type | `events:orders;events_store:audit` |
### Pattern Type Prefixes [#pattern-type-prefixes]
| Prefix | Target Pattern |
| --------------- | ---------------------------- |
| `events:` | Events (fire-and-forget) |
| `events_store:` | Events Store (persistent) |
| `queues:` | Queues (guaranteed delivery) |
Routed messages are automatically tagged with `X-KUBEMQ-ROUTED=true`. See [Multicast Events](/learn/events/tutorials/multicast).
## Transport Protocols [#transport-protocols]
### gRPC [#grpc]
* **Publish:** `SendEvent(pb.Event)` — unary RPC
* **Publish Stream:** `SendEventsStream()` — bidirectional streaming for high-throughput publishing
* **Subscribe:** `SubscribeToEvents(pb.Subscribe)` — server-streaming RPC
* Default port: `50000`
* Max message size: \~1 GB (configurable)
### REST [#rest]
* **Publish:** `POST /send` with JSON body
* **Subscribe:** WebSocket upgrade for streaming delivery
* Default port: `9090`
* Max body size: 100 MB (configurable)
### WebSocket [#websocket]
* Publish and subscribe over persistent WebSocket connections
* JSON-encoded messages
* Read limit: 1 MB
## Configuration [#configuration]
### Server Configuration [#server-configuration]
| Setting | Default | Description |
| --------------------------- | ------- | --------------------- |
| `Connectors.Grpc.BodyLimit` | \~1 GB | Max gRPC message size |
| `Connectors.Rest.BodyLimit` | 100 MB | Max REST body size |
### Client Configuration [#client-configuration]
## Slow Consumer Handling [#slow-consumer-handling]
When a subscriber's receive buffer is full, KubeMQ waits up to the **write deadline** (default 2 seconds) for the buffer to clear. If the deadline expires:
* The event is **dropped** for that subscriber
* A warning is logged server-side with the channel, event ID, and metadata
* Other subscribers are not affected
See [Handle Slow Consumers](/learn/events/how-to/handle-slow-consumers) for mitigation strategies.
## Delivery Semantics [#delivery-semantics]
| Aspect | Behavior |
| ------------------ | ------------------------------------------------- |
| Delivery guarantee | **At-most-once** |
| Persistence | None — events flow through memory only |
| Ordering | Events are delivered in publish order per channel |
| Duplicates | No duplicates (single delivery attempt) |
| Acknowledgment | None — fire-and-forget |
| Retry | None — failed deliveries are not retried |
## Events vs Events Store [#events-vs-events-store]
| Feature | Events | Events Store |
| ---------------------- | ---------------------------------- | --------------------------------- |
| Persistence | No | Yes (disk-backed) |
| Replay | No | Yes (from offset, time, sequence) |
| Delivery guarantee | At-most-once | At-least-once |
| Wildcard subscriptions | Yes (`*`, `>`) | No |
| Consumer groups | Yes (round-robin) | Yes (durable) |
| Latency | Lowest | Slightly higher (disk write) |
| Use cases | Real-time notifications, streaming | Audit trails, event sourcing |
## Error Codes [#error-codes]
| Code | Error | Description |
| ---- | ------------------------- | ------------------------------------------ |
| 101 | Invalid ClientID | ClientID is empty |
| 102 | Invalid Channel | Channel is empty |
| 107 | Invalid Wildcards | Channel contains `*` or `>` (publish only) |
| 108 | Invalid Whitespace | Channel contains spaces |
| 110 | Invalid Message | Both `Body` and `Metadata` are empty |
| 119 | Invalid Channel Separator | Channel ends with `.` |
### Runtime Errors [#runtime-errors]
| Error | Cause | Resolution |
| -------------------------- | ------------------------------------ | ---------------------------------------- |
| `ErrShutdownMode` | Server is shutting down | Reconnect after server restart |
| `ErrConnectionNoAvailable` | broker connection is down | SDK auto-reconnects; check server health |
| Authorization denied | Casbin policy rejected the operation | Verify client permissions |
## SDK Quick Reference [#sdk-quick-reference]
```go
// Publish
client.SendEvent(ctx, kubemq.NewEvent().
SetChannel("ch").SetBody([]byte("data")))
// Subscribe
client.SubscribeToEvents(ctx, "ch", "group",
kubemq.WithOnEvent(handler),
kubemq.WithOnError(errHandler))
// Stream Publish
streamCh := make(chan *kubemq.Event, 100)
resultCh := make(chan *kubemq.EventSendResult, 100)
go client.StreamEvents(ctx, streamCh, resultCh)
```
```python
# Publish
client.send_event(EventMessage(channel="ch", body=b"data"))
# Subscribe
client.subscribe_to_events(
EventsSubscription(channel="ch", group="group",
on_receive_event_callback=handler,
on_error_callback=err_handler),
cancel=CancellationToken())
# Stream Publish
stream = client.open_events_stream()
stream.send(EventMessage(channel="ch", body=b"data"))
```
```javascript
// Publish
await client.sendEvent({ channel: "ch", body: Buffer.from("data") });
// Subscribe
client.subscribeToEvents({
channel: "ch", group: "group",
onEvent: handler, onError: errHandler
});
// Stream Publish
const stream = client.createEventStream();
stream.send({ channel: "ch", body: Buffer.from("data") });
```
```java
// Publish
client.sendEventsMessage(EventMessage.builder()
.channel("ch").body("data".getBytes()).build());
// Subscribe
client.subscribeToEvents(EventsSubscription.builder()
.channel("ch").group("group")
.onReceiveEventCallback(handler)
.onErrorCallback(errHandler).build());
// Stream Publish
EventsStream stream = client.openEventsStream();
stream.send(EventMessage.builder()
.channel("ch").body("data".getBytes()).build());
```
```csharp
// Publish
await client.SendEventAsync(new EventMessage {
Channel = "ch", Body = Encoding.UTF8.GetBytes("data") });
// Subscribe
await foreach (var msg in client.SubscribeToEventsAsync(
new EventsSubscription { Channel = "ch", Group = "group" })) { }
// Stream Publish
var stream = client.OpenEventsStream();
await stream.SendAsync(new EventMessage {
Channel = "ch", Body = Encoding.UTF8.GetBytes("data") });
```
```kotlin
// Publish
client.sendEvent(EventMessage(
channel = "ch", body = "data".toByteArray()))
// Subscribe
client.subscribeToEvents(
channel = "ch", group = "group",
onEvent = handler, onError = errHandler)
// Stream Publish
val stream = client.openEventsStream()
stream.send(EventMessage(channel = "ch", body = "data".toByteArray()))
```
```cpp
// Publish
kubemq::EventMessage event;
event.channel = "ch";
event.body = "data";
client.sendEvent(event);
// Subscribe
client.subscribeToEvents("ch", "group", handler, errHandler);
// Stream Publish
auto stream = client.openEventsStream();
stream.send(event);
```
```rust
// Publish
let event = EventBuilder::new()
.channel("ch").body(b"data".to_vec()).build();
client.send_event(event).await?;
// Subscribe
let sub = client.subscribe_to_events("ch", "group",
|event| Box::pin(async move { handle(event).await }),
None).await?;
// Stream Publish
let mut stream = client.send_event_stream().await?;
stream.send(EventBuilder::new()
.channel("ch").body(b"data".to_vec()).build()).await?;
```
```ruby
# Publish
client.send_event(KubeMQ::PubSub::EventMessage.new(
channel: "ch", body: "data"))
# Subscribe
sub = KubeMQ::PubSub::EventsSubscription.new(channel: "ch", group: "group")
client.subscribe_to_events(sub, cancellation_token: cancel,
on_error: ->(e) { handle_error(e) }) { |event| handle(event) }
# Stream Publish
sender = client.create_events_sender
sender.publish(KubeMQ::PubSub::EventMessage.new(
channel: "ch", body: "data"))
```
```elixir
# Publish
event = KubeMQ.Event.new(channel: "ch", body: "data")
KubeMQ.Client.send_event(client, event)
# Subscribe
{:ok, sub} = KubeMQ.Client.subscribe_to_events(client, "ch",
group: "group", on_event: fn event -> handle(event) end)
# Stream Publish
{:ok, handle} = KubeMQ.Client.send_event_stream(client)
KubeMQ.EventStreamHandle.send(handle,
KubeMQ.Event.new(channel: "ch", body: "data"))
```
## Related [#related]
* [Getting Started with Events](/learn/events/getting-started)
* [Events Store Reference](/learn/events-store/reference) for the persistent variant
* [Queues Reference](/learn/queues/reference) for guaranteed delivery
# Getting Started with Events Store (/learn/events-store/getting-started)
This guide walks you through publishing persistent events and subscribing with replay. By the end, you will see how Events Store preserves messages for subscribers that connect after the event was published.
This is the **quickstart** — a single publisher and subscriber in 5 minutes. For the deep-dive covering multiple subscriber types (audit replay vs. real-time-only) and durable subscriptions, see [Persistent Publish & Subscribe](/learn/events-store/tutorials/persistent-publish-subscribe).
## Prerequisites [#prerequisites]
* **KubeMQ server** running on `localhost:50000`
* One of the supported SDKs installed
Need to install KubeMQ? Run it with Docker in seconds:
## What You Will Build [#what-you-will-build]
An order tracking system where:
* A **publisher** stores order events to a persistent channel
* A **subscriber** connects later and replays the full order history using `StartFromFirst`
*Events are stored on publish; a later subscriber replays the full history, then continues live.*
## Step-by-Step Guide [#step-by-step-guide]
### Install the SDK [#install-the-sdk]
```bash
go get github.com/kubemq-io/kubemq-go/v2
```
```bash
pip install kubemq
```
```bash
npm install kubemq-js
```
```xml
io.kubemq.sdk
kubemq-sdk-Java
2.1.1
```
```bash
dotnet add package KubeMQ.SDK.CSharp
```
```kotlin
implementation("io.kubemq.sdk:kubemq-sdk-kotlin:2.1.0")
```
```bash
vcpkg install kubemq
```
```bash
cargo add kubemq
```
```bash
gem install kubemq
```
```elixir
# mix.exs
def deps do
[{:kubemq, "~> 1.0"}]
end
```
### Publish Persistent Events [#publish-persistent-events]
Publish several order events **before** starting the subscriber. With Events Store, messages are persisted and available for replay.
```go title="publisher.go"
package main
import (
"context"
"fmt"
"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()
orders := []string{
`{"action":"order.created","orderId":"ORD-1001","total":149.99}`,
`{"action":"order.paid","orderId":"ORD-1001","method":"credit_card"}`,
`{"action":"order.shipped","orderId":"ORD-1001","carrier":"fedex"}`,
}
for i, body := range orders {
result, err := client.SendEventStore(ctx, kubemq.NewEvent().
SetChannel("orders.events").
SetBody([]byte(body)),
)
if err != nil {
log.Printf("Failed to store event %d: %v", i+1, err)
continue
}
log.Printf("Stored event %d: ID=%s", i+1, result.EventID)
}
}
```
```python title="publisher.py"
from kubemq import PubSubClient, EventStoreMessage
orders = [
b'{"action":"order.created","orderId":"ORD-1001","total":149.99}',
b'{"action":"order.paid","orderId":"ORD-1001","method":"credit_card"}',
b'{"action":"order.shipped","orderId":"ORD-1001","carrier":"fedex"}',
]
with PubSubClient(address="localhost:50000") as client:
for i, body in enumerate(orders, 1):
result = client.publish_event_store(
EventStoreMessage(channel="orders.events", body=body)
)
print(f"Stored event {i}: ID={result.id}")
```
```typescript title="publisher.ts"
import { KubeMQClient, createEventStoreMessage } from 'kubemq-js';
const client = await KubeMQClient.create({ address: 'localhost:50000' });
const orders = [
'{"action":"order.created","orderId":"ORD-1001","total":149.99}',
'{"action":"order.paid","orderId":"ORD-1001","method":"credit_card"}',
'{"action":"order.shipped","orderId":"ORD-1001","carrier":"fedex"}',
];
for (const [i, body] of orders.entries()) {
const result = await client.sendEventStore(
createEventStoreMessage({ channel: 'orders.events', body })
);
console.log(`Stored event ${i + 1}: ID=${result.id}`);
}
```
```java title="Publisher.java"
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("order-publisher")
.build();
String[] orders = {
"{\"action\":\"order.created\",\"orderId\":\"ORD-1001\",\"total\":149.99}",
"{\"action\":\"order.paid\",\"orderId\":\"ORD-1001\",\"method\":\"credit_card\"}",
"{\"action\":\"order.shipped\",\"orderId\":\"ORD-1001\",\"carrier\":\"fedex\"}"
};
for (int i = 0; i < orders.length; i++) {
EventSendResult result = client.sendEventsStoreMessage(
EventStoreMessage.builder()
.channel("orders.events")
.body(orders[i].getBytes())
.build());
System.out.printf("Stored event %d: ID=%s%n", i + 1, result.getId());
}
client.close();
```
```csharp title="Publisher.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
string[] orders = {
"{\"action\":\"order.created\",\"orderId\":\"ORD-1001\",\"total\":149.99}",
"{\"action\":\"order.paid\",\"orderId\":\"ORD-1001\",\"method\":\"credit_card\"}",
"{\"action\":\"order.shipped\",\"orderId\":\"ORD-1001\",\"carrier\":\"fedex\"}"
};
for (var i = 0; i < orders.Length; i++)
{
var result = await client.SendEventStoreAsync(new EventStoreMessage
{
Channel = "orders.events",
Body = Encoding.UTF8.GetBytes(orders[i]),
});
Console.WriteLine($"Stored event {i + 1}: ID={result.Id}");
}
```
```kotlin title="Publisher.kt"
val client = KubeMQClient.pubSub {
address = "localhost:50000"
clientId = "order-publisher"
}
val orders = listOf(
"""{"action":"order.created","orderId":"ORD-1001","total":149.99}""",
"""{"action":"order.paid","orderId":"ORD-1001","method":"credit_card"}""",
"""{"action":"order.shipped","orderId":"ORD-1001","carrier":"fedex"}""",
)
client.use {
orders.forEachIndexed { i, body ->
val result = client.sendEventStore(eventStoreMessage {
channel = "orders.events"
this.body = body.toByteArray()
})
println("Stored event ${i + 1}: ID=${result.id}")
}
}
```
```cpp title="publisher.cc"
kubemq::ClientOptions options;
options.set_address("localhost", 50000);
options.set_client_id("order-publisher");
auto client = kubemq::Client::Create(options).value();
std::vector orders = {
R"({"action":"order.created","orderId":"ORD-1001","total":149.99})",
R"({"action":"order.paid","orderId":"ORD-1001","method":"credit_card"})",
R"({"action":"order.shipped","orderId":"ORD-1001","carrier":"fedex"})"
};
for (size_t i = 0; i < orders.size(); ++i) {
kubemq::EventStoreMessage msg;
msg.set_channel("orders.events");
msg.set_body(orders[i]);
auto result = client->SendEventStore(msg);
if (result.ok()) {
std::cout << "Stored event " << i + 1 << ": ID=" << result->id() << std::endl;
}
}
```
```rust title="publisher.rs"
use kubemq::prelude::*;
use kubemq::EventStoreBuilder;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
let orders = [
r#"{"action":"order.created","orderId":"ORD-1001","total":149.99}"#,
r#"{"action":"order.paid","orderId":"ORD-1001","method":"credit_card"}"#,
r#"{"action":"order.shipped","orderId":"ORD-1001","carrier":"fedex"}"#,
];
for (i, body) in orders.iter().enumerate() {
let event = EventStoreBuilder::new()
.channel("orders.events")
.body(body.as_bytes().to_vec())
.build();
let result = client.send_event_store(event).await?;
println!("Stored event {}: id={}", i + 1, result.id);
}
client.close().await?;
Ok(())
}
```
```ruby title="publisher.rb"
require 'kubemq'
client = KubeMQ::PubSubClient.new(address: 'localhost:50000', client_id: 'order-publisher')
orders = [
'{"action":"order.created","orderId":"ORD-1001","total":149.99}',
'{"action":"order.paid","orderId":"ORD-1001","method":"credit_card"}',
'{"action":"order.shipped","orderId":"ORD-1001","carrier":"fedex"}'
]
orders.each_with_index do |body, i|
msg = KubeMQ::PubSub::EventStoreMessage.new(channel: 'orders.events', body: body)
result = client.send_event_store(msg)
puts "Stored event #{i + 1}: sent=#{result.sent}"
end
client.close
```
```elixir title="publisher.exs"
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-publisher")
orders = [
~s({"action":"order.created","orderId":"ORD-1001","total":149.99}),
~s({"action":"order.paid","orderId":"ORD-1001","method":"credit_card"}),
~s({"action":"order.shipped","orderId":"ORD-1001","carrier":"fedex"})
]
orders
|> Enum.with_index(1)
|> Enum.each(fn {body, i} ->
event = KubeMQ.EventStore.new(channel: "orders.events", body: body)
{:ok, result} = KubeMQ.Client.send_event_store(client, event)
IO.puts("Stored event #{i}: sent=#{result.sent}")
end)
KubeMQ.Client.close(client)
```
### Subscribe with Replay from Beginning [#subscribe-with-replay-from-beginning]
Start the subscriber **after** all events have been published. Using `StartFromFirst`, it replays the entire history.
```go title="subscriber.go"
package main
import (
"context"
"fmt"
"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()
sub, err := client.SubscribeToEventsStore(ctx, "orders.events", "",
kubemq.StartFromFirst(),
kubemq.WithOnEvent(func(event *kubemq.Event) {
fmt.Printf("Received: seq=%d body=%s\n",
event.Sequence, string(event.Body))
}),
kubemq.WithOnError(func(err error) {
log.Println("Error:", err)
}),
)
if err != nil {
log.Fatal(err)
}
defer sub.Unsubscribe()
log.Println("Replaying order history...")
<-ctx.Done()
}
```
```python title="subscriber.py"
import time
from kubemq import (
PubSubClient, EventsStoreSubscription,
EventStoreStartPosition, CancellationToken,
)
def on_event(event):
print(f"Received: seq={event.sequence} body={event.body.decode('utf-8')}")
with PubSubClient(address="localhost:50000") as client:
client.subscribe_to_events_store(
subscription=EventsStoreSubscription(
channel="orders.events",
start_position=EventStoreStartPosition.StartFromFirst,
on_receive_event_callback=on_event,
on_error_callback=lambda e: print(f"Error: {e}"),
),
cancel=CancellationToken(),
)
print("Replaying order history...")
time.sleep(120)
```
```typescript title="subscriber.ts"
import { KubeMQClient, EventStoreStartPosition } from 'kubemq-js';
const client = await KubeMQClient.create({ address: 'localhost:50000' });
client.subscribeToEventsStore({
channel: 'orders.events',
startPosition: EventStoreStartPosition.StartFromFirst,
onEvent: (msg) =>
console.log(
`Received: seq=${msg.sequence} body=${new TextDecoder().decode(msg.body)}`
),
onError: (err) => console.error('Error:', err.message),
});
console.log('Replaying order history...');
```
```java title="Subscriber.java"
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("order-subscriber")
.build();
client.subscribeToEventsStore(EventsStoreSubscription.builder()
.channel("orders.events")
.startPosition(EventStoreStartPosition.StartFromFirst)
.onReceiveEventCallback(event ->
System.out.printf("Received: seq=%d body=%s%n",
event.getSequence(), new String(event.getBody())))
.onErrorCallback(err ->
System.err.println("Error: " + err.getMessage()))
.build());
System.out.println("Replaying order history...");
Thread.sleep(120_000);
client.close();
```
```csharp title="Subscriber.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
Console.WriteLine("Replaying order history...");
await foreach (var msg in client.SubscribeToEventsStoreAsync(
new EventsStoreSubscription
{
Channel = "orders.events",
StartPosition = EventStoreStartPosition.StartFromFirst,
}))
{
Console.WriteLine($"Received: seq={msg.Sequence} "
+ $"body={Encoding.UTF8.GetString(msg.Body.Span)}");
}
```
```kotlin title="Subscriber.kt"
val client = KubeMQClient.pubSub {
address = "localhost:50000"
clientId = "order-subscriber"
}
client.use {
val flow = client.subscribeToEventsStore {
channel = "orders.events"
startPosition = StartPosition.StartFromFirst
}
println("Replaying order history...")
flow.collect { msg ->
println("Received: seq=${msg.sequence} body=${String(msg.body)}")
}
}
```
```cpp title="subscriber.cc"
kubemq::ClientOptions options;
options.set_address("localhost", 50000);
options.set_client_id("order-subscriber");
auto client = kubemq::Client::Create(options).value();
std::cout << "Replaying order history..." << std::endl;
client->SubscribeToEventsStore(
"orders.events", "",
kubemq::StartPosition::StartFromFirst,
[](const kubemq::EventStoreReceived& msg) {
std::cout << "Received: seq=" << msg.sequence()
<< " body=" << msg.body() << std::endl;
},
[](const std::string& err) {
std::cerr << "Error: " << err << std::endl;
});
```
```rust title="subscriber.rs"
use kubemq::prelude::*;
use kubemq::EventsStoreSubscription;
use std::time::Duration;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
println!("Replaying order history...");
let sub = client
.subscribe_to_events_store(
"orders.events",
"",
EventsStoreSubscription::StartFromFirst,
|event| {
Box::pin(async move {
println!(
"Received: seq={} body={}",
event.sequence,
String::from_utf8_lossy(&event.body)
);
})
},
None,
)
.await?;
tokio::time::sleep(Duration::from_secs(120)).await;
sub.unsubscribe().await;
client.close().await?;
Ok(())
}
```
```ruby title="subscriber.rb"
require 'kubemq'
client = KubeMQ::PubSubClient.new(address: 'localhost:50000', client_id: 'order-subscriber')
cancel = KubeMQ::CancellationToken.new
sub = KubeMQ::PubSub::EventsStoreSubscription.new(
channel: 'orders.events',
start_position: KubeMQ::PubSub::EventStoreStartPosition::START_FROM_FIRST
)
client.subscribe_to_events_store(sub, cancellation_token: cancel, on_error: lambda { |e|
puts "Error: #{e.message}"
}) do |event|
puts "Received: seq=#{event.sequence} body=#{event.body}"
end
puts 'Replaying order history...'
sleep 120
cancel.cancel
client.close
```
```elixir title="subscriber.exs"
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-subscriber")
IO.puts("Replaying order history...")
{:ok, _sub} =
KubeMQ.Client.subscribe_to_events_store(client, "orders.events",
start_at: :start_from_first,
on_event: fn event ->
IO.puts("Received: seq=#{event.sequence} body=#{event.body}")
end
)
Process.sleep(120_000)
KubeMQ.Client.close(client)
```
### Verify the Output [#verify-the-output]
The subscriber receives all 3 previously published events, then continues waiting for new ones:
```text
Replaying order history...
Received: seq=1 body={"action":"order.created","orderId":"ORD-1001","total":149.99}
Received: seq=2 body={"action":"order.paid","orderId":"ORD-1001","method":"credit_card"}
Received: seq=3 body={"action":"order.shipped","orderId":"ORD-1001","carrier":"fedex"}
```
Any new events published after the subscriber connects are delivered in real time.
## Understanding What Happened [#understanding-what-happened]
*The store assigns each event a sequence number; a `StartFromFirst` subscriber replays the full history, then receives live events.*
1. The **publisher** stored 3 events in the `orders.events` channel
2. Each event received a **sequence number** (1, 2, 3) and a **server timestamp**
3. The **subscriber** connected later and requested `StartFromFirst`
4. KubeMQ replayed the entire history, then continues delivering new events
5. The subscription is **durable** — if the subscriber disconnects and reconnects with the same client ID and group, it resumes from the last delivered sequence
With plain [Events](/learn/events), the subscriber would have received nothing because Events are not persisted. Events Store is essential when subscribers must not miss messages.
## What's Next [#whats-next]
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-p 127.0.0.1:8080:8080 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Events Store — Persistent Pub/Sub (/learn/events-store)
Think of Events Store as a **DVR for your messages**. Just like a DVR records live TV so you can watch it later, Events Store records every event published to a channel. Subscribers can rewind to the beginning, fast-forward to a specific point, or jump in live — all from the same persistent stream.
KubeMQ Events Store implements persistent publish/subscribe with at-least-once delivery. Publishers send messages to a named channel; KubeMQ writes each event to disk with a monotonically increasing sequence number, and subscribers choose a start position to receive historical events, new events, or both. Because events are durable, a subscriber that was offline at publish time can still replay everything it missed.
## The concept it implements [#the-concept-it-implements]
Events Store is KubeMQ's implementation of two fundamental ideas. The interaction style is **[pub/sub](/learn/concepts/interaction-styles)** (fan-out) — one publisher, many subscribers — extended with durable storage so subscribers can **[replay from any position](/learn/concepts/ordering-and-replay)**. The delivery guarantee is **[at-least-once](/learn/concepts/delivery-guarantees)** — events are persisted and durable subscriptions track their position, so a message is redelivered until the subscriber has processed it. New to these terms? Start with the [Fundamentals](/learn/concepts) track.
## Key Properties [#key-properties]
| Property | This pattern | Learn the concept |
| ------------------ | ----------------------------------------------------- | ---------------------------------------------------------- |
| Interaction style | pub/sub (fan-out) with replay | [Interaction styles](/learn/concepts/interaction-styles) |
| Delivery guarantee | at-least-once | [Delivery guarantees](/learn/concepts/delivery-guarantees) |
| Persistence | Disk-backed — survives restarts | [Ordering & replay](/learn/concepts/ordering-and-replay) |
| Ordering | Sequenced per channel (sequence number + timestamp) | [Ordering & replay](/learn/concepts/ordering-and-replay) |
| Scaling | Fan-out, or load-balance with durable consumer groups | [Scaling & flow](/learn/concepts/scaling-and-flow) |
| Addressing | Named channels | [Channels & routing](/learn/concepts/channels-and-routing) |
## Key Features [#key-features]
* **Persistent storage** — events are written to disk and survive server restarts
* **Replay from any point** — subscribe from the first message, last message, a specific sequence number, an absolute timestamp, or a relative time delta
* **Durable subscriptions** — subscribers resume from their last position after reconnecting
* **Consumer groups** — distribute event processing across multiple consumers with automatic position tracking
* **Sequenced messages** — every stored event receives a monotonically increasing sequence number and a server timestamp
* **Stream publishing** — high-throughput bidirectional streaming with per-event acknowledgment
## How It Works [#how-it-works]
*A publisher persists events to a durable channel; a live subscriber streams new events while a late subscriber replays missed history from a chosen offset.*
1. A **publisher** sends an event to a named channel with persistence enabled
2. KubeMQ writes the event to the **store** on disk
3. Each event receives a **sequence number** and **timestamp**
4. **Subscribers** connect and specify a start position — they receive historical and/or new events based on that position
5. **Durable subscriptions** track the subscriber's position so reconnections resume automatically
For fire-and-forget pub/sub without persistence, use [Events](/learn/events) instead.
## Quick Example [#quick-example]
```go title="publish_store.go"
ctx := context.Background()
client, err := kubemq.NewClient(ctx,
kubemq.WithAddress("localhost", 50000),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
result, err := client.SendEventStore(ctx, kubemq.NewEvent().
SetChannel("orders.events").
SetBody([]byte(`{"action":"order.created","orderId":"ORD-1001"}`)),
)
if err != nil {
log.Fatal(err)
}
log.Printf("Event stored: ID=%s, Sent=%v", result.EventID, result.Sent)
```
```python title="publish_store.py"
from kubemq import PubSubClient, EventStoreMessage
with PubSubClient(address="localhost:50000") as client:
result = client.publish_event_store(
EventStoreMessage(
channel="orders.events",
body=b'{"action":"order.created","orderId":"ORD-1001"}',
)
)
print(f"Event stored: ID={result.id}, Sent={result.sent}")
```
```typescript title="publish_store.ts"
import { KubeMQClient, createEventStoreMessage } from 'kubemq-js';
const client = await KubeMQClient.create({ address: 'localhost:50000' });
const result = await client.sendEventStore(
createEventStoreMessage({
channel: 'orders.events',
body: '{"action":"order.created","orderId":"ORD-1001"}',
})
);
console.log(`Event stored: ID=${result.id}, Sent=${result.sent}`);
```
```java title="PublishStore.java"
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("order-publisher")
.build();
EventSendResult result = client.sendEventsStoreMessage(
EventStoreMessage.builder()
.channel("orders.events")
.body("{\"action\":\"order.created\",\"orderId\":\"ORD-1001\"}".getBytes())
.build());
System.out.println("Event stored: " + result.getId());
client.close();
```
```csharp title="PublishStore.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
var result = await client.SendEventStoreAsync(new EventStoreMessage
{
Channel = "orders.events",
Body = Encoding.UTF8.GetBytes(
"{\"action\":\"order.created\",\"orderId\":\"ORD-1001\"}")
});
Console.WriteLine($"Event stored: ID={result.Id}, Sent={result.Sent}");
```
```kotlin title="PublishStore.kt"
val client = KubeMQClient.pubSub {
address = "localhost:50000"
clientId = "order-publisher"
}
client.use {
val result = client.sendEventStore(eventStoreMessage {
channel = "orders.events"
body = """{"action":"order.created","orderId":"ORD-1001"}""".toByteArray()
})
println("Event stored: ID=${result.id}, Sent=${result.sent}")
}
```
```cpp title="publish_store.cc"
kubemq::ClientOptions options;
options.set_address("localhost", 50000);
options.set_client_id("order-publisher");
auto client = kubemq::Client::Create(options).value();
kubemq::EventStoreMessage msg;
msg.set_channel("orders.events");
msg.set_body(R"({"action":"order.created","orderId":"ORD-1001"})");
auto result = client->SendEventStore(msg);
if (result.ok()) {
std::cout << "Event stored: " << result->id() << std::endl;
}
```
```rust title="publish_store.rs"
use kubemq::prelude::*;
use kubemq::EventStoreBuilder;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
let event = EventStoreBuilder::new()
.channel("orders.events")
.body(br#"{"action":"order.created","orderId":"ORD-1001"}"#.to_vec())
.build();
let result = client.send_event_store(event).await?;
println!("Event stored: id={}, sent={}", result.id, result.sent);
client.close().await?;
Ok(())
}
```
```ruby title="publish_store.rb"
require 'kubemq'
client = KubeMQ::PubSubClient.new(address: 'localhost:50000', client_id: 'order-publisher')
msg = KubeMQ::PubSub::EventStoreMessage.new(
channel: 'orders.events',
body: '{"action":"order.created","orderId":"ORD-1001"}'
)
result = client.send_event_store(msg)
puts "Event stored: id=#{result.id}, sent=#{result.sent}"
client.close
```
```elixir title="publish_store.exs"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-publisher")
event =
KubeMQ.EventStore.new(
channel: "orders.events",
body: ~s({"action":"order.created","orderId":"ORD-1001"})
)
{:ok, result} = KubeMQ.Client.send_event_store(client, event)
IO.puts("Event stored: sent=#{result.sent}")
KubeMQ.Client.close(client)
```
## Subscription Start Positions [#subscription-start-positions]
| Position | Description | Use Case |
| ------------------ | ------------------------------------------- | ----------------------------------- |
| `StartNewOnly` | Only new events published after subscribing | Live monitoring, real-time alerting |
| `StartFromFirst` | Replay all events from the beginning | State rebuild, full audit replay |
| `StartFromLast` | Start from the last stored event, then new | Resume from most recent |
| `StartAtSequence` | Start from a specific sequence number | Checkpoint-based recovery |
| `StartAtTime` | Start from a specific timestamp | Point-in-time recovery |
| `StartAtTimeDelta` | Start from N seconds ago | Recent history replay |
## When to Use Events Store [#when-to-use-events-store]
| Scenario | Events | Events Store |
| ---------------------------- | -------------------------------------- | ----------------------------- |
| Audit trails | ❌ Messages can be lost | ✅ Best choice |
| Event sourcing | ❌ No persistence | ✅ Best choice |
| Late or offline subscribers | ❌ Miss everything published while away | ✅ Replay missed history |
| Real-time notifications | ✅ Best choice | Overkill |
| Live dashboards (no history) | ✅ Best choice | Use if historical data needed |
| Wildcard subscriptions | ✅ Supported | ❌ Not supported |
**When not to use Events Store:** if you never need replay, persistence, or guaranteed delivery — fire-and-forget [Events](/learn/events) have lower latency and support wildcard subscriptions. If a message must be processed by exactly one of several competing workers (work distribution, not fan-out), reach for [Queues](/learn/queues) instead.
### Events vs Events Store at a glance [#events-vs-events-store-at-a-glance]
| Feature | Events | Events Store |
| ---------------------- | --------------- | ----------------------- |
| Persistence | No | Yes (disk-backed) |
| Replay | No | Yes (6 start positions) |
| Delivery guarantee | at-most-once | at-least-once |
| Wildcard subscriptions | Yes | No |
| Consumer groups | Yes (ephemeral) | Yes (durable) |
| Sequence numbers | No | Yes |
| Timestamps | No | Yes (server-assigned) |
| Latency | Lowest | Slightly higher |
Events Store is also available via the [CloudEvents protocol](/connectors/cloudevents/how-to/events-store) — use any language with a CloudEvents SDK, no KubeMQ client library needed.
## Learn More [#learn-more]
# Events Store Reference (/learn/events-store/reference)
This reference documents every aspect of the KubeMQ Events Store messaging pattern.
## Message Structure [#message-structure]
### Event Store Message (Publish) [#event-store-message-publish]
### Event Store Receive (Subscription Callback) [#event-store-receive-subscription-callback]
The `Sequence` and `Timestamp` fields are assigned by the server at persistence time and are not set by the publisher. They are available only on received events.
### Send Result [#send-result]
## Subscription Start Positions [#subscription-start-positions]
## Subscribe Request [#subscribe-request]
## Channel Naming Rules [#channel-naming-rules]
| Rule | Constraint | Error Code |
| --------------- | ------------------------- | ---------- |
| Required | Cannot be empty | 102 |
| No trailing dot | Cannot end with `.` | 119 |
| No whitespace | Cannot contain spaces | 108 |
| No wildcards | Cannot contain `*` or `>` | 107 |
**Valid channel regex:** `^[^\s*>]+[^.]$`
Events Store does **not** support wildcard subscriptions. Both publish and subscribe channel names must be exact. For wildcard support, use plain [Events](/learn/events).
## Durable Subscriptions [#durable-subscriptions]
Every Events Store subscription creates a durable name:
```text
DurableName = "{channel}-{group}"
```
* On first connection, the `EventsStoreTypeData` determines the start position
* On subsequent connections with the same durable name, the start position is **ignored** — the subscription resumes from the last tracked position
* To force a fresh replay, use a different `group` name
## Consumer Groups [#consumer-groups]
When multiple subscribers specify the same `Group` on the same channel:
* Each event is delivered to exactly **one** member (round-robin)
* The group's position is tracked durably
* Adding or removing members rebalances delivery automatically
* Groups are independent per channel
## Routing (Multicast) [#routing-multicast]
| Character | Purpose | Example |
| --------- | ---------------------------------- | ------------------------------------------------- |
| `;` | Separate channels of the same type | `audit;compliance` |
| `:` | Specify target pattern type | `events_store:audit;events:notify;queues:process` |
For Events Store publish, channels without a prefix default to `events_store`. Routed messages are tagged with `X-KUBEMQ-ROUTED=true`.
## Storage Configuration [#storage-configuration]
## File Store Configuration [#file-store-configuration]
## Storage Utilization Thresholds [#storage-utilization-thresholds]
| Utilization | Level | Polling Interval | Publishing |
| ----------- | -------- | ---------------- | ------------------------- |
| 0-80% | Normal | 5 seconds | Allowed |
| 80-90% | Warning | 3 seconds | Allowed (warnings logged) |
| 90-95% | Critical | 2 seconds | Allowed (errors logged) |
| Above 95% | Disabled | 1 second | **Blocked** |
Publishing automatically resumes when utilization drops below 95%.
## Transport Protocols [#transport-protocols]
### gRPC [#grpc]
* **Publish:** `SendEvent(pb.Event)` with `Store=true`
* **Publish Stream:** `SendEventsStream()` — bidirectional streaming, result sent for every store event
* **Subscribe:** `SubscribeToEvents(pb.Subscribe)` with `SubscribeType=EventsStore`
* Default port: `50000`
### REST [#rest]
* **Publish:** `POST /send` with `isEvents=false`
* **Subscribe:** WebSocket with `subscribe_type=events_store`
* Default port: `9090`
## Delivery Semantics [#delivery-semantics]
| Aspect | Behavior |
| ------------------ | ----------------------------------------------------- |
| Delivery guarantee | **At-least-once** |
| Persistence | Disk-backed file store |
| Ordering | Events delivered in sequence order per channel |
| Sequence numbers | Monotonically increasing, starting from 1 per channel |
| Acknowledgment | Asynchronous publish ack |
| Durable names | Position tracked across reconnections |
| Replay | Yes (6 start positions) |
## Events Store vs Events [#events-store-vs-events]
| Feature | Events Store | Events |
| -------------------------- | ---------------------------- | ---------------- |
| Persistence | Yes (disk-backed) | No (memory only) |
| Replay | Yes (6 start positions) | No |
| Delivery guarantee | At-least-once | At-most-once |
| Wildcard subscriptions | No | Yes (`*`, `>`) |
| Consumer groups | Durable | Ephemeral |
| Sequence numbers | Yes | No |
| Server timestamps | Yes | No |
| Latency | Slightly higher (disk write) | Lowest |
| Storage utilization limits | Yes (80/90/95% thresholds) | No |
## SDK Quick Reference [#sdk-quick-reference]
```go
client.SendEventStore(ctx, event)
client.SendEventsStoreStream(ctx, opts...)
client.SubscribeToEventsStore(ctx, channel, group, startPos, opts...)
```
```python
client.publish_event_store(message)
client.open_events_store_stream(on_result, on_error)
client.subscribe_to_events_store(subscription, cancel)
```
```typescript
client.sendEventStore(message)
client.sendEventsStoreStream(opts)
client.subscribeToEventsStore(opts)
```
```java
client.sendEventsStoreMessage(message)
client.openEventsStoreStream(onResult, onError)
client.subscribeToEventsStore(subscription)
```
```csharp
client.SendEventStoreAsync(message)
client.OpenEventsStoreStream(onResult, onError)
client.SubscribeToEventsStoreAsync(subscription)
```
```kotlin
client.sendEventStore(message)
client.openEventsStoreStream(onResult, onError)
client.subscribeToEventsStore { ... }
```
```cpp
client->SendEventStore(message)
client->OpenEventsStoreStream(onResult, onError)
client->SubscribeToEventsStore(channel, group, startPos, onEvent, onError)
```
```rust
client.send_event_store(event).await
client.send_event_store_stream().await // returns a stream; stream.send(event)
client.subscribe_to_events_store(channel, group, EventsStoreSubscription::StartFromFirst, on_event, None).await
```
```ruby
client.send_event_store(msg)
client.create_events_store_sender # sender.publish(msg)
client.subscribe_to_events_store(subscription, cancellation_token:, on_error:) { |event| ... }
```
```elixir
KubeMQ.Client.send_event_store(client, event)
KubeMQ.Client.send_event_store(client, event) # stream-style: send in rapid succession
KubeMQ.Client.subscribe_to_events_store(client, channel, start_at: :start_new_only, on_event: fn event -> ... end)
```
## Error Codes [#error-codes]
### Validation Errors [#validation-errors]
| Code | Error | Description |
| ---- | ------------------------- | ------------------------------------------------------------------ |
| 101 | Invalid ClientID | ClientID is empty |
| 102 | Invalid Channel | Channel is empty |
| 107 | Invalid Wildcards | Channel contains `*` or `>` |
| 108 | Invalid Whitespace | Channel contains spaces |
| 110 | Invalid Message | Both `Body` and `Metadata` are empty |
| 111 | Invalid Subscription Type | `EventsStoreTypeData` is `Undefined` (0) |
| 112 | Invalid Sequence Value | `StartAtSequence` value is 0 or negative |
| 113 | Invalid Time Value | `StartAtTime` value is 0 or negative |
| 114 | Invalid Time Delta Value | `StartAtTimeDelta` value is 0 or negative |
| 118 | Wrong Subscribe Type | Event store parameters set but subscribe type is not events\_store |
| 119 | Invalid Channel Separator | Channel ends with `.` |
### Runtime Errors [#runtime-errors]
| Error | Cause | Resolution |
| ---------------------------- | ------------------------------------ | -------------------------------------------- |
| `ErrShutdownMode` | Server is shutting down | Reconnect after server restart |
| `ErrConnectionNoAvailable` | Connection is down | SDK auto-reconnects; check server health |
| Storage utilization exceeded | Disk usage above 95% | Free disk space or adjust retention settings |
| Authorization denied | Casbin policy rejected the operation | Verify client permissions |
## Related [#related]
* [Getting Started with Events Store](/learn/events-store/getting-started)
* [Events Reference](/learn/events/reference) for the non-persistent variant
* Core Concepts for foundational KubeMQ concepts
# Getting Started with Queues (/learn/queues/getting-started)
**Prerequisites:** KubeMQ server running on `localhost:50000` and your SDK installed. See [Getting Started](/deploy) for setup.
## What You Will Build [#what-you-will-build]
An order message sender that places a task on a queue, and a receiver that pulls the task, processes it, and acknowledges completion.
## Steps [#steps]
### Install the SDK [#install-the-sdk]
```bash
go get github.com/kubemq-io/kubemq-go/v2
```
```bash
pip install kubemq
```
```bash
npm install kubemq-js
```
```xml
io.kubemq.sdk
kubemq-sdk-Java
3.1.1
```
```bash
dotnet add package KubeMQ.SDK.CSharp --version 3.0.1
```
```kotlin
implementation("io.kubemq.sdk:kubemq-sdk-kotlin:1.0.1")
```
```bash
vcpkg install kubemq
```
```toml
[dependencies]
kubemq = "1.0.1"
tokio = { version = "1", features = ["full"] }
```
```bash
gem install kubemq
```
```elixir
def deps do
[{:kubemq, "~> 1.0"}]
end
```
### Create the Sender [#create-the-sender]
Connect to KubeMQ and send an order message to the `orders` queue.
```go title="sender.go"
package main
import (
"context"
"fmt"
"log"
"github.com/kubemq-io/kubemq-go/v2"
)
func main() {
ctx := context.Background()
client, err := kubemq.NewClient(ctx,
kubemq.WithAddress("localhost", 50000),
kubemq.WithClientId("order-sender"),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
msg := kubemq.NewQueueMessage().
SetChannel("orders").
SetBody([]byte(`{"orderId":"ORD-1234","total":99.99}`)).
SetMetadata("order.created")
result, err := client.SendQueueMessage(ctx, msg)
if err != nil {
log.Fatal(err)
}
if result.IsError {
log.Fatalf("Send failed: %s", result.Error)
}
fmt.Printf("Sent: id=%s\n", result.MessageID)
}
```
```python title="sender.py"
from kubemq.queues import Client as QueuesClient
from kubemq import QueueMessage
client = QueuesClient(
address="localhost:50000",
client_id="order-sender",
)
result = client.send_queue_message(
QueueMessage(
channel="orders",
body=b'{"orderId":"ORD-1234","total":99.99}',
metadata="order.created",
)
)
print(f"Sent: id={result.id}")
client.close()
```
```typescript title="sender.ts"
import { KubeMQClient, createQueueMessage } from 'kubemq-js';
const client = await KubeMQClient.create({
address: 'localhost:50000',
clientId: 'order-sender',
});
const result = await client.sendQueueMessage(
createQueueMessage({
channel: 'orders',
body: JSON.stringify({ orderId: 'ORD-1234', total: 99.99 }),
metadata: 'order.created',
}),
);
console.log('Sent:', result.messageId);
await client.close();
```
```java title="Sender.java"
import io.kubemq.sdk.queues.QueuesClient;
import io.kubemq.sdk.queues.QueueMessage;
import io.kubemq.sdk.queues.QueueSendResult;
QueuesClient client = QueuesClient.builder()
.address("localhost:50000")
.clientId("order-sender")
.build();
QueueMessage msg = QueueMessage.builder()
.channel("orders")
.body("{\"orderId\":\"ORD-1234\",\"total\":99.99}".getBytes())
.metadata("order.created")
.build();
QueueSendResult result = client.sendQueueMessage(msg);
System.out.println("Sent: id=" + result.getId());
client.close();
```
```csharp title="Sender.cs"
using System.Text;
using KubeMQ.Sdk.Client;
using KubeMQ.Sdk.Queues;
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
var result = await client.SendQueueMessageAsync(new QueueMessage
{
Channel = "orders",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-1234\",\"total\":99.99}"),
Metadata = "order.created"
});
Console.WriteLine($"Sent: id={result.MessageId}");
```
```kotlin title="Sender.kt"
import io.kubemq.sdk.client.KubeMQClient
import io.kubemq.sdk.queues.QueueMessage
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val client = KubeMQClient.queues {
address = "localhost:50000"
clientId = "order-sender"
}
val result = client.sendQueuesMessage(QueueMessage(
channel = "orders",
body = """{"orderId":"ORD-1234","total":99.99}""".toByteArray(),
metadata = "order.created"
))
println("Sent: id=${result.messageId}")
client.close()
}
```
```cpp title="sender.cpp"
#include
#include
auto client = kubemq::QueuesClient("localhost:50000");
kubemq::QueueMessage msg;
msg.channel = "orders";
msg.body = R"({"orderId":"ORD-1234","total":99.99})";
msg.metadata = "order.created";
auto result = client.sendQueueMessage(msg);
std::cout << "Sent: id=" << result.messageId << std::endl;
```
```rust title="sender.rs"
use kubemq::prelude::*;
use kubemq::QueueMessageBuilder;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.client_id("order-sender")
.build()
.await?;
let msg = QueueMessageBuilder::new()
.channel("orders")
.body(br#"{"orderId":"ORD-1234","total":99.99}"#.to_vec())
.metadata("order.created")
.build();
let result = client.send_queue_message(msg).await?;
println!("Sent: id={}", result.message_id);
client.close().await?;
Ok(())
}
```
```ruby title="sender.rb"
require 'kubemq'
client = KubeMQ::QueuesClient.new(
address: 'localhost:50000',
client_id: 'order-sender'
)
msg = KubeMQ::Queues::QueueMessage.new(
channel: 'orders',
body: '{"orderId":"ORD-1234","total":99.99}',
metadata: 'order.created'
)
result = client.send_queue_message(msg)
puts "Sent: id=#{result.id}"
client.close
```
```elixir title="sender.exs"
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-sender")
msg =
KubeMQ.QueueMessage.new(
channel: "orders",
body: ~s({"orderId":"ORD-1234","total":99.99}),
metadata: "order.created"
)
{:ok, result} = KubeMQ.Client.send_queue_message(client, msg)
IO.puts("Sent: id=#{result.message_id}")
KubeMQ.Client.close(client)
```
### Create the Receiver [#create-the-receiver]
In a separate terminal, receive the message and acknowledge it.
```go title="receiver.go"
package main
import (
"context"
"fmt"
"log"
"github.com/kubemq-io/kubemq-go/v2"
)
func main() {
ctx := context.Background()
client, err := kubemq.NewClient(ctx,
kubemq.WithAddress("localhost", 50000),
kubemq.WithClientId("order-receiver"),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
resp, err := client.PollQueue(ctx, &kubemq.PollRequest{
Channel: "orders",
MaxItems: 1,
WaitTimeoutSeconds: 10,
AutoAck: false,
})
if err != nil {
log.Fatal(err)
}
for _, m := range resp.Messages {
fmt.Printf("Received: %s\n", string(m.Message.Body))
fmt.Printf("Metadata: %s\n", m.Message.Metadata)
}
if err := resp.AckAll(); err != nil {
log.Fatal(err)
}
fmt.Println("All messages acknowledged")
}
```
```python title="receiver.py"
from kubemq.queues import Client as QueuesClient
client = QueuesClient(
address="localhost:50000",
client_id="order-receiver",
)
response = client.receive_queue_messages(
channel="orders",
max_messages=1,
wait_timeout_in_seconds=10,
)
for msg in response.messages:
print(f"Received: {msg.body.decode('utf-8')}")
print(f"Metadata: {msg.metadata}")
msg.ack()
print("Message acknowledged")
client.close()
```
```typescript title="receiver.ts"
import { KubeMQClient } from 'kubemq-js';
const client = await KubeMQClient.create({
address: 'localhost:50000',
clientId: 'order-receiver',
});
const messages = await client.receiveQueueMessages({
channel: 'orders',
maxMessages: 1,
waitTimeoutSeconds: 10,
});
for (const msg of messages) {
console.log('Received:', new TextDecoder().decode(msg.body));
console.log('Metadata:', msg.metadata);
await msg.ack();
console.log('Message acknowledged');
}
await client.close();
```
```java title="Receiver.java"
import io.kubemq.sdk.queues.QueuesClient;
import io.kubemq.sdk.queues.QueuesPollRequest;
import io.kubemq.sdk.queues.QueuesPollResponse;
import io.kubemq.sdk.queues.QueueMessageReceived;
QueuesClient client = QueuesClient.builder()
.address("localhost:50000")
.clientId("order-receiver")
.build();
QueuesPollResponse response = client.receiveQueueMessages(
QueuesPollRequest.builder()
.channel("orders")
.pollMaxMessages(1)
.pollWaitTimeoutInSeconds(10)
.autoAckMessages(false)
.build());
for (QueueMessageReceived msg : response.getMessages()) {
System.out.println("Received: " + new String(msg.getBody()));
System.out.println("Metadata: " + msg.getMetadata());
msg.ack();
System.out.println("Message acknowledged");
}
client.close();
```
```csharp title="Receiver.cs"
using System.Text;
using KubeMQ.Sdk.Client;
using KubeMQ.Sdk.Queues;
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
var response = await client.ReceiveQueueMessagesAsync(new QueuePollRequest
{
Channel = "orders",
MaxMessages = 1,
WaitTimeoutSeconds = 10,
AutoAck = false,
});
foreach (var msg in response.Messages)
{
Console.WriteLine($"Received: {Encoding.UTF8.GetString(msg.Body.Span)}");
Console.WriteLine($"Metadata: {msg.Metadata}");
await msg.AckAsync();
Console.WriteLine("Message acknowledged");
}
```
```kotlin title="Receiver.kt"
import io.kubemq.sdk.client.KubeMQClient
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val client = KubeMQClient.queues {
address = "localhost:50000"
clientId = "order-receiver"
}
val response = client.receiveQueuesMessages {
channel = "orders"
maxItems = 1
waitTimeoutMs = 10_000
autoAck = false
}
for (msg in response.messages) {
println("Received: ${String(msg.body)}")
println("Metadata: ${msg.metadata}")
msg.ack()
println("Message acknowledged")
}
client.close()
}
```
```cpp title="receiver.cpp"
#include
#include
auto client = kubemq::QueuesClient("localhost:50000");
auto response = client.receiveQueueMessages("orders", 1, 10);
for (const auto& msg : response.messages) {
std::cout << "Received: " << msg.body << std::endl;
std::cout << "Metadata: " << msg.metadata << std::endl;
msg.ack();
std::cout << "Message acknowledged" << std::endl;
}
```
```rust title="receiver.rs"
use kubemq::prelude::*;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.client_id("order-receiver")
.build()
.await?;
let (response, _receiver) = client
.poll_queue(PollRequest {
channel: "orders".to_string(),
max_items: 1,
wait_timeout_seconds: 10,
auto_ack: false,
})
.await?;
for m in &response.messages {
println!("Received: {}", String::from_utf8_lossy(&m.message.body));
println!("Metadata: {}", m.message.metadata);
}
response.ack_all().await?;
println!("All messages acknowledged");
client.close().await?;
Ok(())
}
```
```ruby title="receiver.rb"
require 'kubemq'
client = KubeMQ::QueuesClient.new(
address: 'localhost:50000',
client_id: 'order-receiver'
)
messages = client.receive_queue_messages(
channel: 'orders',
max_messages: 1,
wait_timeout_seconds: 10
)
messages.each do |msg|
puts "Received: #{msg.body}"
puts "Metadata: #{msg.metadata}"
end
client.close
```
```elixir title="receiver.exs"
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-receiver")
{:ok, result} =
KubeMQ.Client.receive_queue_messages(client, "orders",
max_messages: 1,
wait_timeout: 10_000
)
Enum.each(result.messages, fn msg ->
IO.puts("Received: #{msg.body}")
IO.puts("Metadata: #{msg.metadata}")
end)
KubeMQ.Client.close(client)
```
### Verify [#verify]
Run the sender first, then the receiver. You should see:
```text
Sent: id=
Received: {"orderId":"ORD-1234","total":99.99}
Metadata: order.created
Message acknowledged
```
## What Just Happened [#what-just-happened]
*Send → durable queue → poll & deliver to one receiver → acknowledge to remove.*
The full round-trip, step by step:
1. The **sender** connected to KubeMQ and placed an order message on the `orders` queue
2. The message was **stored durably** — it persists even if no receiver is connected yet
3. The **receiver** polled the queue and received the message (hidden from other consumers)
4. After processing, the receiver **acknowledged** the message, permanently removing it from the queue
Unlike Events, queue messages persist until acknowledged. If the receiver crashes before acknowledging, the message becomes available again after the visibility timeout expires.
## Next Steps [#next-steps]
# Queues — Point-to-Point Messaging (/learn/queues)
Think of Queues like a mailbox — you drop a letter in, and it waits safely until the recipient picks it up. Even if the recipient is away, the letter doesn't disappear. Each letter is delivered to exactly one person, and they confirm receipt by opening it.
KubeMQ Queues provide durable, point-to-point messaging with guaranteed delivery. Each message is persisted to a named queue and delivered to exactly one consumer, where it remains until that consumer explicitly acknowledges it. When several consumers poll the same queue, they form a pool of *competing consumers* — the broker hands each message to just one of them, load-balancing the work. Queues are ideal for task distribution, job processing, and any workflow where reliable, ordered, exactly-once processing is required.
## The concept it implements [#the-concept-it-implements]
Queues realize the **point-to-point** interaction style with **exactly-once processing**. To understand the underlying ideas first, see the Fundamentals layer:
* [Interaction styles → point-to-point](/learn/concepts/interaction-styles) — competing consumers, one message → one consumer.
* [Delivery guarantees → exactly-once](/learn/concepts/delivery-guarantees) — manual ack/nack, redelivery, and idempotency.
* [Scaling & flow → competing consumers](/learn/concepts/scaling-and-flow) — visibility timeout, backpressure, and adding consumers to drain a queue faster.
## Key Features [#key-features]
* **Guaranteed delivery** — messages persist in the queue until a consumer acknowledges them. No message is lost, even if consumers restart.
* **Exactly-once processing** — each message is delivered to a single consumer with manual acknowledgment, preventing duplicate processing.
* **FIFO ordering** — messages are delivered in the order they were sent, maintaining strict first-in, first-out semantics.
* **Visibility timeout** — while a consumer processes a message, it is hidden from other consumers. If not acknowledged within the timeout, the message becomes available again.
* **Dead Letter Queue (DLQ)** — messages that exceed a configurable retry count are automatically routed to a DLQ for inspection and recovery.
* **Delayed delivery** — schedule messages to become available after a specified delay, enabling deferred processing and retry patterns.
* **Batch operations** — send and receive multiple messages in a single request for high-throughput scenarios.
* **Peek without consuming** — inspect queue contents without removing messages, useful for monitoring and debugging.
* **Message expiration (TTL)** — set time-to-live on messages so unprocessed items auto-expire.
## How It Works [#how-it-works]
A queue is a durable, first-in-first-out buffer. Producers append messages to a named queue; a pool of consumers polls the same queue and competes for messages. The broker delivers each message to **exactly one** consumer, hides it from the others while it is being processed, and removes it only after that consumer acknowledges it.
*Producers append to the queue; competing consumers each receive a different message and confirm with a dotted acknowledgment.*
## Key Properties [#key-properties]
| Property | Behavior | Learn more |
| ---------------- | ---------------------------------------- | --------------------------------------------------------------- |
| Delivery | Exactly one consumer per message | [Send & Receive](/learn/queues/tutorials/send-receive) |
| Settlement | Manual `ack` / `nack` / requeue | [Ack, Nack & Requeue](/learn/queues/tutorials/ack-nack-requeue) |
| Visibility | Hidden from others during processing | [Visibility timeout](/learn/queues/how-to/visibility-timeout) |
| Failure handling | Redeliver, then route to DLQ | [Dead Letter Queue](/learn/queues/tutorials/dead-letter-queue) |
| Scheduling | Delay before a message becomes available | [Delayed Messages](/learn/queues/tutorials/delayed-messages) |
| Expiration | TTL auto-discards unprocessed messages | [Message expiration](/learn/queues/how-to/message-expiration) |
## Message Lifecycle [#message-lifecycle]
*A message moves from queued to delivered to acked; on failure it is requeued or, after exhausting retries, routed to a dead letter queue.*
## When to Use Queues [#when-to-use-queues]
| Scenario | Queues | Events / Events Store |
| ------------------------------------- | -------------------------- | ----------------------------------------- |
| Task & job distribution | ✅ Best choice | ❌ No load balancing per message |
| Exactly-once work processing | ✅ Best choice | ❌ At-most/at-least-once |
| Order-sensitive pipelines (FIFO) | ✅ Best choice | Use Events Store for replay |
| Retry with backoff & dead-letter | ✅ Best choice | ❌ Not built in |
| Real-time fan-out to many subscribers | ❌ One consumer per message | ✅ Use [Events](/learn/events) |
| Durable history / replay | ❌ Messages removed on ack | ✅ Use [Events Store](/learn/events-store) |
Need to broadcast every message to **all** listeners instead of distributing work? Use [Events](/learn/events). Need a durable, replayable log? Use [Events Store](/learn/events-store).
## Quick Example [#quick-example]
```go title="main.go"
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/kubemq-io/kubemq-go/v2"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
client, err := kubemq.NewClient(ctx,
kubemq.WithAddress("localhost", 50000),
kubemq.WithClientId("queue-demo"),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
msg := kubemq.NewQueueMessage().
SetChannel("orders").
SetBody([]byte(`{"orderId":"ORD-1234","total":99.99}`))
result, err := client.SendQueueMessage(ctx, msg)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Sent: id=%s\n", result.MessageID)
resp, err := client.PollQueue(ctx, &kubemq.PollRequest{
Channel: "orders",
MaxItems: 1,
WaitTimeoutSeconds: 5,
AutoAck: false,
})
if err != nil {
log.Fatal(err)
}
for _, m := range resp.Messages {
fmt.Printf("Received: %s\n", string(m.Message.Body))
}
resp.AckAll()
}
```
```python title="main.py"
from kubemq.queues import Client as QueuesClient
from kubemq import QueueMessage
client = QueuesClient(
address="localhost:50000",
client_id="queue-demo",
)
result = client.send_queue_message(
QueueMessage(
channel="orders",
body=b'{"orderId":"ORD-1234","total":99.99}',
)
)
print(f"Sent: id={result.id}")
response = client.receive_queue_messages(
channel="orders",
max_messages=1,
wait_timeout_in_seconds=5,
)
for msg in response.messages:
print(f"Received: {msg.body.decode('utf-8')}")
msg.ack()
client.close()
```
```typescript title="main.ts"
import { KubeMQClient, createQueueMessage } from 'kubemq-js';
const client = await KubeMQClient.create({
address: 'localhost:50000',
clientId: 'queue-demo',
});
const result = await client.sendQueueMessage(
createQueueMessage({
channel: 'orders',
body: JSON.stringify({ orderId: 'ORD-1234', total: 99.99 }),
}),
);
console.log('Sent:', result.messageId);
const messages = await client.receiveQueueMessages({
channel: 'orders',
maxMessages: 1,
waitTimeoutSeconds: 5,
});
for (const msg of messages) {
console.log('Received:', new TextDecoder().decode(msg.body));
await msg.ack();
}
await client.close();
```
```java title="Main.java"
QueuesClient client = QueuesClient.builder()
.address("localhost:50000")
.clientId("queue-demo")
.build();
QueueMessage msg = QueueMessage.builder()
.channel("orders")
.body("{\"orderId\":\"ORD-1234\",\"total\":99.99}".getBytes())
.build();
SendQueueMessageResult result = client.sendQueueMessage(msg);
System.out.println("Sent: id=" + result.getMessageId());
ReceiveQueueMessagesResponse response = client.receiveQueueMessages(
ReceiveQueueMessagesRequest.builder()
.channel("orders")
.maxMessages(1)
.waitTimeoutSeconds(5)
.build());
for (QueueMessageReceived m : response.getMessages()) {
System.out.println("Received: " + new String(m.getBody()));
m.ack();
}
client.close();
```
```csharp title="Program.cs"
using KubeMQ.Sdk.Client;
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
var result = await client.SendQueueMessageAsync(new QueueMessage
{
Channel = "orders",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-1234\",\"total\":99.99}")
});
Console.WriteLine($"Sent: id={result.MessageId}");
var response = await client.ReceiveQueueMessagesAsync(new ReceiveQueueMessagesRequest
{
Channel = "orders",
MaxMessages = 1,
WaitTimeoutSeconds = 5,
});
foreach (var msg in response.Messages)
{
Console.WriteLine($"Received: {Encoding.UTF8.GetString(msg.Body.Span)}");
await msg.AckAsync();
}
```
```kotlin title="Main.kt"
val client = QueuesClient("localhost:50000")
val result = client.sendQueueMessage(QueueMessage(
channel = "orders",
body = """{"orderId":"ORD-1234","total":99.99}""".toByteArray()
))
println("Sent: id=${result.messageId}")
val response = client.receiveQueueMessages(
channel = "orders",
maxMessages = 1,
waitTimeoutSeconds = 5
)
for (msg in response.messages) {
println("Received: ${String(msg.body)}")
msg.ack()
}
client.close()
```
```cpp title="main.cpp"
#include
#include
auto client = kubemq::QueuesClient("localhost:50000");
kubemq::QueueMessage msg;
msg.channel = "orders";
msg.body = R"({"orderId":"ORD-1234","total":99.99})";
auto result = client.sendQueueMessage(msg);
std::cout << "Sent: id=" << result.messageId << std::endl;
auto response = client.receiveQueueMessages("orders", 1, 5);
for (const auto& m : response.messages) {
std::cout << "Received: " << m.body << std::endl;
m.ack();
}
```
```rust title="main.rs"
use kubemq::prelude::*;
use kubemq::QueueMessageBuilder;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.client_id("queue-demo")
.build()
.await?;
let msg = QueueMessageBuilder::new()
.channel("orders")
.body(br#"{"orderId":"ORD-1234","total":99.99}"#.to_vec())
.build();
let result = client.send_queue_message(msg).await?;
println!("Sent: id={}", result.message_id);
// receive_queue_messages(channel, max_messages, wait_timeout_secs, auto_ack)
let messages = client
.receive_queue_messages("orders", 1, 5, false)
.await?;
for m in &messages {
println!("Received: {}", String::from_utf8_lossy(&m.body));
m.ack().await?;
}
client.close().await?;
Ok(())
}
```
```ruby title="main.rb"
require 'kubemq'
client = KubeMQ::QueuesClient.new(address: 'localhost:50000', client_id: 'queue-demo')
msg = KubeMQ::Queues::QueueMessage.new(
channel: 'orders',
body: '{"orderId":"ORD-1234","total":99.99}'
)
result = client.send_queue_message(msg)
puts "Sent: id=#{result.id}"
messages = client.receive_queue_messages(channel: 'orders', max_messages: 1, wait_timeout_seconds: 5)
messages.each do |m|
puts "Received: #{m.body}"
m.ack
end
client.close
```
```elixir title="main.exs"
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "queue-demo")
msg =
KubeMQ.QueueMessage.new(
channel: "orders",
body: ~s({"orderId":"ORD-1234","total":99.99})
)
{:ok, result} = KubeMQ.Client.send_queue_message(client, msg)
IO.puts("Sent: id=#{result.message_id}")
{:ok, response} =
KubeMQ.Client.receive_queue_messages(client, "orders",
max_messages: 1,
wait_timeout: 5_000
)
Enum.each(response.messages, fn m ->
IO.puts("Received: #{m.body}")
KubeMQ.Client.ack_queue_message(client, m)
end)
KubeMQ.Client.close(client)
```
Queues are also available via the [CloudEvents protocol](/connectors/cloudevents/how-to/queues) — use any language with a CloudEvents SDK, no KubeMQ client library needed.
## Learn More [#learn-more]
# Queue Reference (/learn/queues/reference)
This reference documents every aspect of the KubeMQ Queues messaging pattern.
## Message Structure [#message-structure]
### Send Request [#send-request]
### Message Policy Fields [#message-policy-fields]
Policy fields control delivery behavior and are set per message at send time.
### Send Response [#send-response]
### Receive Response (per message) [#receive-response-per-message]
## Receive Request [#receive-request]
## Channel Name Rules [#channel-name-rules]
| Rule | Constraint | Error Code |
| --------------- | ------------------------- | ---------- |
| Required | Cannot be empty | 120 |
| No trailing dot | Cannot end with `.` | 119 |
| No whitespace | Cannot contain spaces | 108 |
| No wildcards | Cannot contain `*` or `>` | 107 |
Valid channel name pattern: `^[^\s*>]+[^.]$`
**Examples:**
* `orders` — valid
* `payments.us-east` — valid
* `orders processing` — invalid (contains space)
* `orders.` — invalid (trailing dot)
* `orders.*` — invalid (contains wildcard)
## Server Configuration [#server-configuration]
| Transport | Default Limit | Setting |
| --------- | ------------- | --------------------------- |
| gRPC | \~1 GB | `Connectors.Grpc.BodyLimit` |
| REST | 100 MB | `Connectors.Rest.BodyLimit` |
## Message Lifecycle [#message-lifecycle]
*A queue message moves through delay, availability, processing, and settlement — ending in removal, redelivery, expiration, or the dead letter queue.*
## Dead Letter Queue Behavior [#dead-letter-queue-behavior]
When a message exceeds the maximum receive count:
1. If `maxReceiveQueue` is set, the message is copied to the DLQ channel with:
* `reRouted` set to `true`
* `reRoutedFromQueue` set to the original channel name
* `receiveCount` reset to `0`
* Policy reset to server defaults
2. If `maxReceiveQueue` is not set, the message is silently discarded
3. The original message is acknowledged (removed from the source queue)
## Delayed Message Behavior [#delayed-message-behavior]
Messages with `delaySeconds > 0` follow this path:
1. Message is published to an internal delay channel (`_QUEUE_DELAY_`)
2. A background processor checks for expired delays every 500ms
3. When the delay elapses, the message is moved to the target queue
4. The `delaySeconds` and `delayedTo` attributes are cleared before delivery
5. If both delay and expiration are set, the expiration clock starts after the delay
## Error Codes [#error-codes]
### Queue-Specific Errors [#queue-specific-errors]
| Code | Error | Cause |
| ---- | ------------------------------------ | ------------------------------------------------- |
| 120 | Invalid queue name | Empty channel or invalid characters |
| 122 | Max messages exceeded config limit | Receive request exceeds `MaxNumberOfMessages` |
| 125 | Ack sequence cannot be 0 or negative | Invalid sequence in stream ack |
| 127 | Invalid visibility time | Visibility timeout exceeds `MaxVisibilitySeconds` |
| 133 | Invalid expiration seconds | Expiration exceeds `MaxExpirationSeconds` |
| 134 | Invalid max receive count | Max receive count exceeds server config |
| 135 | Invalid delay seconds | Delay exceeds `MaxDelaySeconds` |
| 136 | Invalid wait timeout | Wait timeout exceeds `MaxWaitTimeoutSeconds` |
| 139 | Invalid max items | Value must be at least 1 |
| 140 | Invalid wait time | Value must be at least 1 second |
### General Errors [#general-errors]
| Code | Error | Applies To |
| ---- | -------------------------------------- | ------------------------------ |
| 101 | Invalid clientID, cannot be empty | All patterns |
| 107 | Invalid channel, no wildcards allowed | All patterns |
| 108 | Invalid channel, no whitespace allowed | All patterns |
| 110 | Invalid message, cannot be empty | Body and metadata both missing |
| 119 | Invalid channel, cannot end with dot | All patterns |
## SDK Quick Reference [#sdk-quick-reference]
```go
// go get github.com/kubemq-io/kubemq-go/v2
msg := kubemq.NewQueueMessage().
SetChannel("orders").
SetBody([]byte("payload")).
SetMetadata("metadata").
SetTags(map[string]string{"key": "value"}).
SetDelaySeconds(10).
SetExpirationSeconds(300).
SetMaxReceiveCount(3).
SetMaxReceiveQueue("orders.dlq")
result, err := client.SendQueueMessage(ctx, msg)
results, err := client.SendQueueMessages(ctx, msgs)
resp, err := client.PollQueue(ctx, &kubemq.PollRequest{
Channel: "orders", MaxItems: 10, WaitTimeoutSeconds: 5,
AutoAck: false, VisibilitySeconds: 120, IsPeek: false,
})
resp.AckAll()
resp.NAckAll()
resp.ReQueueAll("other-channel")
```
```python
# pip install kubemq
from kubemq.queues import Client as QueuesClient
from kubemq import QueueMessage
result = client.send_queue_message(QueueMessage(
channel="orders", body=b"payload", metadata="metadata",
tags={"key": "value"}, delay_in_seconds=10,
expiration_in_seconds=300, max_receive_count=3,
max_receive_queue="orders.dlq",
))
response = client.receive_queue_messages(
channel="orders", max_messages=10, wait_timeout_in_seconds=5,
is_peek=False, visibility_seconds=120,
)
msg.ack()
msg.nack()
msg.requeue("other-channel")
```
```typescript
// npm install kubemq-js
import { KubeMQClient, createQueueMessage } from 'kubemq-js';
const result = await client.sendQueueMessage(createQueueMessage({
channel: 'orders', body: 'payload', metadata: 'metadata',
tags: { key: 'value' },
policy: { delaySeconds: 10, expirationSeconds: 300,
maxReceiveCount: 3, maxReceiveQueue: 'orders.dlq' },
}));
const msgs = await client.receiveQueueMessages({
channel: 'orders', maxMessages: 10, waitTimeoutSeconds: 5,
isPeek: false, visibilitySeconds: 120,
});
await msg.ack();
await msg.nack();
await msg.requeue('other-channel');
```
```java
// io.kubemq.sdk:kubemq-sdk-Java:2.1.1
QueueMessage msg = QueueMessage.builder()
.channel("orders").body("payload".getBytes())
.metadata("metadata").tags(Map.of("key", "value"))
.delaySeconds(10).expirationSeconds(300)
.maxReceiveCount(3).maxReceiveQueue("orders.dlq").build();
SendQueueMessageResult result = client.sendQueueMessage(msg);
ReceiveQueueMessagesResponse response = client.receiveQueueMessages(
ReceiveQueueMessagesRequest.builder()
.channel("orders").maxMessages(10).waitTimeoutSeconds(5)
.isPeek(false).visibilitySeconds(120).build());
msg.ack();
msg.nack();
msg.requeue("other-channel");
```
```csharp
// dotnet add package KubeMQ.SDK.CSharp
var result = await client.SendQueueMessageAsync(new QueueMessage {
Channel = "orders", Body = Encoding.UTF8.GetBytes("payload"),
Metadata = "metadata", Tags = new() { ["key"] = "value" },
DelaySeconds = 10, ExpirationSeconds = 300,
MaxReceiveCount = 3, MaxReceiveQueue = "orders.dlq"
});
var response = await client.ReceiveQueueMessagesAsync(new ReceiveQueueMessagesRequest {
Channel = "orders", MaxMessages = 10, WaitTimeoutSeconds = 5,
IsPeek = false, VisibilitySeconds = 120,
});
await msg.AckAsync();
await msg.NAckAsync();
await msg.ReQueueAsync("other-channel");
```
```kotlin
// io.kubemq.sdk:kubemq-sdk-kotlin:2.1.0
val result = client.sendQueueMessage(QueueMessage(
channel = "orders", body = "payload".toByteArray(),
metadata = "metadata", tags = mapOf("key" to "value"),
delaySeconds = 10, expirationSeconds = 300,
maxReceiveCount = 3, maxReceiveQueue = "orders.dlq"
))
val response = client.receiveQueueMessages(
channel = "orders", maxMessages = 10, waitTimeoutSeconds = 5,
isPeek = false, visibilitySeconds = 120)
msg.ack()
msg.nack()
msg.requeue("other-channel")
```
```cpp
// vcpkg install kubemq
kubemq::QueueMessage msg;
msg.channel = "orders";
msg.body = "payload";
msg.metadata = "metadata";
msg.tags = {{"key", "value"}};
msg.delaySeconds = 10;
msg.expirationSeconds = 300;
msg.maxReceiveCount = 3;
msg.maxReceiveQueue = "orders.dlq";
auto result = client.sendQueueMessage(msg);
auto response = client.receiveQueueMessages("orders", 10, 5);
msg.ack();
msg.nack();
msg.requeue("other-channel");
```
```rust
// cargo add kubemq
use kubemq::prelude::*;
use kubemq::{PollRequest, QueueMessageBuilder};
let msg = QueueMessageBuilder::new()
.channel("orders")
.body(b"payload".to_vec())
.metadata("metadata")
.tags([("key", "value")])
.delay_seconds(10)
.expiration_seconds(300)
.max_receive_count(3)
.max_receive_queue("orders.dlq")
.build();
let result = client.send_queue_message(msg).await?;
// receive_queue_messages(channel, max_items, wait_timeout_seconds, is_peek)
let messages = client.receive_queue_messages("orders", 10, 5, false).await?;
// Stream poll for explicit settlement (ack / nack / re-queue)
let mut receiver = client.new_queue_downstream_receiver().await?;
let response = receiver.poll(PollRequest {
channel: "orders".to_string(),
max_items: 10, wait_timeout_seconds: 5, auto_ack: false,
}).await?;
response.ack_all().await?;
response.nack_all().await?;
for m in &response.messages { m.re_queue("other-channel").await?; }
```
```ruby
# gem install kubemq
require 'kubemq'
policy = KubeMQ::Queues::QueueMessagePolicy.new(
delay_seconds: 10, expiration_seconds: 300,
max_receive_count: 3, max_receive_queue: 'orders.dlq'
)
msg = KubeMQ::Queues::QueueMessage.new(
channel: 'orders', body: 'payload', metadata: 'metadata',
tags: { 'key' => 'value' }, policy: policy
)
result = client.send_queue_message(msg)
messages = client.receive_queue_messages(
channel: 'orders', max_messages: 10, wait_timeout_seconds: 5
)
# Stream poll for explicit settlement (ack / nack / requeue)
receiver = client.create_downstream_receiver
request = KubeMQ::Queues::QueuePollRequest.new(
channel: 'orders', max_items: 10, wait_timeout: 5
)
response = receiver.poll(request)
response.messages.each(&:ack)
response.messages.each(&:nack)
response.requeue_all(channel: 'other-channel')
```
```elixir
# {:kubemq, "~> 1.0"} in mix.exs
msg = KubeMQ.QueueMessage.new(
channel: "orders", body: "payload", metadata: "metadata",
tags: %{"key" => "value"},
policy: KubeMQ.QueuePolicy.new(
delay_seconds: 10, expiration_seconds: 300,
max_receive_count: 3, max_receive_queue: "orders.dlq"
)
)
{:ok, result} = KubeMQ.Client.send_queue_message(client, msg)
{:ok, received} = KubeMQ.Client.receive_queue_messages(client, "orders",
max_messages: 10, wait_timeout: 5_000)
# Stream poll for explicit settlement (ack / nack / requeue)
{:ok, poll} = KubeMQ.Client.poll_queue(client,
channel: "orders", max_items: 10, wait_timeout: 5_000)
KubeMQ.PollResponse.ack_all(poll)
KubeMQ.PollResponse.nack_all(poll)
KubeMQ.PollResponse.requeue_all(poll, "other-channel")
```
## Related Pages [#related-pages]
* [Queues Overview](/learn/queues) — Introduction and key features
* [Getting Started](/learn/queues/getting-started) — Step-by-step first message guide
* [Ack, Nack & Requeue](/learn/queues/tutorials/ack-nack-requeue) — Settlement options
* [Dead Letter Queue](/learn/queues/tutorials/dead-letter-queue) — DLQ routing and monitoring
* [Delayed Messages](/learn/queues/tutorials/delayed-messages) — Schedule future delivery
* [Visibility Timeout](/learn/queues/how-to/visibility-timeout) — Processing time configuration
* [Batch Operations](/learn/queues/tutorials/batch-operations) — High-throughput send and receive
# Channel Management (/learn/guides/channel-management)
For the conceptual model behind channels and how messages reach subscribers, see [Channels & Routing](/learn/concepts/channels-and-routing) in Fundamentals.
## Overview [#overview]
KubeMQ channels are created implicitly when a message is first published or subscribed to. However, you can also manage channels explicitly — creating, listing, deleting, and purging them through the SDK.
## Create Channel [#create-channel]
Create a channel before publishing to pre-register it with the server. The channel type must be specified: `events`, `events_store`, or `queues`.
```go title="create_channel.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.CreateChannel(ctx, "queues", "order-processing")
if err != nil {
log.Fatal(err)
}
log.Println("Channel created: order-processing")
}
```
```python title="create_channel.py"
from kubemq.queues import Client as QueuesClient
client = QueuesClient(address="localhost:50000")
client.create_channel("order-processing")
print("Channel created: order-processing")
client.close()
```
```javascript title="create_channel.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000" });
await client.createChannel("queues", "order-processing");
console.log("Channel created: order-processing");
```
```java title="CreateChannel.java"
QueuesClient client = QueuesClient.builder()
.address("localhost:50000")
.clientId("admin-client")
.build();
client.createChannel("order-processing");
System.out.println("Channel created: order-processing");
client.close();
```
```csharp title="CreateChannel.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions
{
Address = "localhost:50000",
});
await client.ConnectAsync();
await client.CreateChannelAsync("queues", "order-processing");
Console.WriteLine("Channel created: order-processing");
```
```kotlin title="CreateChannel.kt"
val client = KubeMQClient.queues {
address = "localhost:50000"
clientId = "admin-client"
}
client.createChannel("order-processing")
println("Channel created: order-processing")
client.close()
```
```cpp title="create_channel.cpp"
#include
#include
kubemq::QueuesClient client("localhost:50000");
client.createChannel("order-processing");
std::cout << "Channel created: order-processing" << std::endl;
```
```rust title="create_channel.rs"
use kubemq::prelude::*;
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
client.create_queues_channel("order-processing").await?;
println!("Channel created: order-processing");
```
```ruby title="create_channel.rb"
require "kubemq"
client = KubeMQ::QueuesClient.new(address: "localhost:50000", client_id: "admin-client")
client.create_queues_channel(channel_name: "order-processing")
puts "Channel created: order-processing"
client.close
```
```elixir title="create_channel.exs"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "admin-client")
:ok = KubeMQ.Client.create_channel(client, "order-processing", :queues)
IO.puts("Channel created: order-processing")
KubeMQ.Client.close(client)
```
## Delete Channel [#delete-channel]
Remove a channel and its configuration from the server. Messages in the channel are discarded.
Deleting a channel is irreversible. All pending messages in a queue channel are lost. Active subscriptions on the channel will receive an error.
```go title="delete_channel.go"
err = client.DeleteChannel(ctx, "queues", "order-processing")
if err != nil {
log.Fatal(err)
}
log.Println("Channel deleted: order-processing")
```
```python title="delete_channel.py"
client.delete_channel("order-processing")
print("Channel deleted: order-processing")
```
```javascript title="delete_channel.js"
await client.deleteChannel("queues", "order-processing");
console.log("Channel deleted: order-processing");
```
```java title="DeleteChannel.java"
client.deleteChannel("order-processing");
System.out.println("Channel deleted: order-processing");
```
```csharp title="DeleteChannel.cs"
await client.DeleteChannelAsync("queues", "order-processing");
Console.WriteLine("Channel deleted: order-processing");
```
```kotlin title="DeleteChannel.kt"
client.deleteChannel("order-processing")
println("Channel deleted: order-processing")
```
```cpp title="delete_channel.cpp"
client.deleteChannel("order-processing");
std::cout << "Channel deleted: order-processing" << std::endl;
```
```rust title="delete_channel.rs"
client.delete_queues_channel("order-processing").await?;
println!("Channel deleted: order-processing");
```
```ruby title="delete_channel.rb"
client.delete_queues_channel(channel_name: "order-processing")
puts "Channel deleted: order-processing"
```
```elixir title="delete_channel.exs"
:ok = KubeMQ.Client.delete_channel(client, "order-processing", :queues)
IO.puts("Channel deleted: order-processing")
```
## List Channels [#list-channels]
Query the server for all active channels, optionally filtering by channel type or name pattern.
```go title="list_channels.go"
channels, err := client.ListChannels(ctx, "queues", "order")
if err != nil {
log.Fatal(err)
}
for _, ch := range channels {
log.Printf("Channel: %s | Type: %s | Subscribers: %d | Messages: %d",
ch.Name, ch.Type, ch.LastActivity, ch.Incoming)
}
```
```python title="list_channels.py"
channels = client.list_channels("order")
for ch in channels:
print(f"Channel: {ch.name} | Type: {ch.type} | Messages: {ch.incoming}")
```
```javascript title="list_channels.js"
const channels = await client.listChannels("queues", "order");
for (const ch of channels) {
console.log(`Channel: ${ch.name} | Type: ${ch.type} | Messages: ${ch.incoming}`);
}
```
```java title="ListChannels.java"
List channels = client.listChannels("order");
for (ChannelInfo ch : channels) {
System.out.printf("Channel: %s | Type: %s | Messages: %d%n",
ch.getName(), ch.getType(), ch.getIncoming());
}
```
```csharp title="ListChannels.cs"
var channels = await client.ListChannelsAsync("queues", "order");
foreach (var ch in channels)
{
Console.WriteLine($"Channel: {ch.Name} | Type: {ch.Type} | Messages: {ch.Incoming}");
}
```
```kotlin title="ListChannels.kt"
val channels = client.listChannels("order")
for (ch in channels) {
println("Channel: ${ch.name} | Type: ${ch.type} | Messages: ${ch.incoming}")
}
```
```cpp title="list_channels.cpp"
auto channels = client.listChannels("order");
for (const auto& ch : channels) {
std::cout << "Channel: " << ch.name
<< " | Type: " << ch.type
<< " | Messages: " << ch.incoming << std::endl;
}
```
```rust title="list_channels.rs"
use kubemq::channel_type;
let channels = client.list_channels(channel_type::QUEUES, "order").await?;
for ch in &channels {
println!("Channel: {} | Active: {} | Last activity: {}",
ch.name, ch.is_active, ch.last_activity);
}
```
```ruby title="list_channels.rb"
channels = client.list_queues_channels(search: "order")
channels.each do |ch|
puts "Channel: #{ch.name} | Active: #{ch.is_active} | Messages: #{ch.incoming}"
end
```
```elixir title="list_channels.exs"
{:ok, channels} = KubeMQ.Client.list_queues_channels(client, "order")
Enum.each(channels, fn ch ->
IO.puts("Channel: #{ch.name} | Active: #{ch.is_active} | Messages: #{ch.incoming}")
end)
```
## Purge Queue [#purge-queue]
Remove all pending messages from a queue channel without deleting the channel itself. This is useful for clearing a backlog during development or after recovering from a failure.
Purge permanently removes all messages from the queue. This cannot be undone.
```go title="purge_queue.go"
resp, err := client.PurgeQueue(ctx, "order-processing")
if err != nil {
log.Fatal(err)
}
log.Printf("Purged %d messages from order-processing", resp.MessagesCount)
```
```python title="purge_queue.py"
result = client.purge_queue("order-processing")
print(f"Purged {result.messages_count} messages from order-processing")
```
```javascript title="purge_queue.js"
const result = await client.purgeQueue("order-processing");
console.log(`Purged ${result.messagesCount} messages from order-processing`);
```
```java title="PurgeQueue.java"
PurgeResult result = client.purgeQueue("order-processing");
System.out.printf("Purged %d messages from order-processing%n", result.getMessagesCount());
```
```csharp title="PurgeQueue.cs"
var result = await client.PurgeQueueAsync("order-processing");
Console.WriteLine($"Purged {result.MessagesCount} messages from order-processing");
```
```kotlin title="PurgeQueue.kt"
val result = client.purgeQueue("order-processing")
println("Purged ${result.messagesCount} messages from order-processing")
```
```cpp title="purge_queue.cpp"
auto result = client.purgeQueue("order-processing");
std::cout << "Purged " << result.messagesCount << " messages from order-processing"
<< std::endl;
```
```rust title="purge_queue.rs"
// The Rust SDK purges a queue by acking all pending messages.
client.ack_all_queue_messages("order-processing").await?;
println!("Purged all messages from order-processing");
```
```ruby title="purge_queue.rb"
client.purge_queue_channel(channel_name: "order-processing")
puts "Purged all messages from order-processing"
```
```elixir title="purge_queue.exs"
:ok = KubeMQ.Client.purge_queue_channel(client, "order-processing")
IO.puts("Purged all messages from order-processing")
```
## Key Points [#key-points]
* **Implicit creation** — channels are automatically created on first use (publish or subscribe)
* **Explicit management** — use the SDK for administrative operations like cleanup or provisioning
* **Type-scoped** — create and list operations require specifying the channel type (`events`, `events_store`, or `queues`)
* **Purge is queue-only** — only queue channels support purging; events and events\_store channels have different lifecycle semantics
## Next Steps [#next-steps]
# Channel Routing (/learn/guides/channel-routing)
New to channel naming and fan-out? Start with [Channels & Routing](/learn/concepts/channels-and-routing) in Fundamentals to understand how channels and patterns work before applying the routing syntax below.
## Routing Syntax [#routing-syntax]
KubeMQ supports publishing to multiple channels and patterns in a single operation using a routing syntax built into the channel name:
* **`;`** separates multiple channel targets
* **`:`** prefixes the pattern type (`events`, `events_store`, `queues`)
| Syntax | Meaning |
| ----------------------------------- | ------------------------------- |
| `events:channel-a;events:channel-b` | Two event channels |
| `events:live;events_store:archive` | Event + persistent copy |
| `events:notify;queues:process` | Broadcast + reliable work queue |
| `events:a;events_store:b;queues:c` | All three patterns |
Routing is transparent to subscribers — each target channel receives the message as if it were published directly.
## Examples [#examples]
### Events + Events Store [#events--events-store]
Publish an order event to a live channel and persist a copy to an archive channel in a single call.
```go title="route_events_store.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),
kubemq.WithClientId("order-router"),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
err = client.SendEvent(ctx, kubemq.NewEvent().
SetChannel("events:order-live;events_store:order-archive").
SetMetadata("order.created").
SetBody([]byte(`{"orderId":"ORD-100","amount":59.99}`)),
)
if err != nil {
log.Fatal(err)
}
log.Println("Routed to events + events_store")
}
```
```python title="route_events_store.py"
from kubemq.pubsub import Client as PubSubClient, EventMessage
client = PubSubClient(address="localhost:50000", client_id="order-router")
client.send_event(
EventMessage(
channel="events:order-live;events_store:order-archive",
metadata="order.created",
body=b'{"orderId":"ORD-100","amount":59.99}',
)
)
print("Routed to events + events_store")
client.close()
```
```javascript title="route_events_store.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000", clientId: "order-router" });
await client.sendEvent({
channel: "events:order-live;events_store:order-archive",
metadata: "order.created",
body: Buffer.from('{"orderId":"ORD-100","amount":59.99}'),
});
console.log("Routed to events + events_store");
```
```java title="RouteEventsStore.java"
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("order-router")
.build();
client.sendEventsMessage(EventMessage.builder()
.channel("events:order-live;events_store:order-archive")
.metadata("order.created")
.body("{\"orderId\":\"ORD-100\",\"amount\":59.99}".getBytes())
.build());
System.out.println("Routed to events + events_store");
client.close();
```
```csharp title="RouteEventsStore.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions
{
Address = "localhost:50000",
ClientId = "order-router"
});
await client.ConnectAsync();
await client.SendEventAsync(new EventMessage
{
Channel = "events:order-live;events_store:order-archive",
Metadata = "order.created",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-100\",\"amount\":59.99}"),
});
Console.WriteLine("Routed to events + events_store");
```
```kotlin title="RouteEventsStore.kt"
val client = PubSubClient("localhost:50000")
client.sendEvent(EventMessage(
channel = "events:order-live;events_store:order-archive",
metadata = "order.created",
body = """{"orderId":"ORD-100","amount":59.99}""".toByteArray(),
))
println("Routed to events + events_store")
client.close()
```
```cpp title="route_events_store.cpp"
#include
#include
auto client = kubemq::PubSubClient("localhost:50000");
kubemq::EventMessage event;
event.channel = "events:order-live;events_store:order-archive";
event.metadata = "order.created";
event.body = R"({"orderId":"ORD-100","amount":59.99})";
client.sendEvent(event);
std::cout << "Routed to events + events_store" << std::endl;
```
```rust title="route_events_store.rs"
use kubemq::prelude::*;
use kubemq::EventBuilder;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.client_id("order-router")
.build()
.await?;
let event = EventBuilder::new()
.channel("events:order-live;events_store:order-archive")
.metadata("order.created")
.body(br#"{"orderId":"ORD-100","amount":59.99}"#.to_vec())
.build();
client.send_event(event).await?;
println!("Routed to events + events_store");
client.close().await?;
Ok(())
}
```
```ruby title="route_events_store.rb"
require 'kubemq'
client = KubeMQ::PubSubClient.new(address: 'localhost:50000', client_id: 'order-router')
msg = KubeMQ::PubSub::EventMessage.new(
channel: 'events:order-live;events_store:order-archive',
metadata: 'order.created',
body: '{"orderId":"ORD-100","amount":59.99}'
)
client.send_event(msg)
puts 'Routed to events + events_store'
client.close
```
```elixir title="route_events_store.exs"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-router")
event = KubeMQ.Event.new(
channel: "events:order-live;events_store:order-archive",
metadata: "order.created",
body: ~s({"orderId":"ORD-100","amount":59.99})
)
:ok = KubeMQ.Client.send_event(client, event)
IO.puts("Routed to events + events_store")
KubeMQ.Client.close(client)
```
### Events + Queue [#events--queue]
Broadcast an event for real-time subscribers and queue a copy for reliable processing.
```go title="route_events_queue.go"
err = client.SendEvent(ctx, kubemq.NewEvent().
SetChannel("events:order-notify;queues:order-process").
SetMetadata("order.created").
SetBody([]byte(`{"orderId":"ORD-200","amount":129.00}`)),
)
```
```python title="route_events_queue.py"
client.send_event(
EventMessage(
channel="events:order-notify;queues:order-process",
metadata="order.created",
body=b'{"orderId":"ORD-200","amount":129.00}',
)
)
```
```javascript title="route_events_queue.js"
await client.sendEvent({
channel: "events:order-notify;queues:order-process",
metadata: "order.created",
body: Buffer.from('{"orderId":"ORD-200","amount":129.00}'),
});
```
```java title="RouteEventsQueue.java"
client.sendEventsMessage(EventMessage.builder()
.channel("events:order-notify;queues:order-process")
.metadata("order.created")
.body("{\"orderId\":\"ORD-200\",\"amount\":129.00}".getBytes())
.build());
```
```csharp title="RouteEventsQueue.cs"
await client.SendEventAsync(new EventMessage
{
Channel = "events:order-notify;queues:order-process",
Metadata = "order.created",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-200\",\"amount\":129.00}"),
});
```
```kotlin title="RouteEventsQueue.kt"
client.sendEvent(EventMessage(
channel = "events:order-notify;queues:order-process",
metadata = "order.created",
body = """{"orderId":"ORD-200","amount":129.00}""".toByteArray(),
))
```
```cpp title="route_events_queue.cpp"
kubemq::EventMessage event;
event.channel = "events:order-notify;queues:order-process";
event.metadata = "order.created";
event.body = R"({"orderId":"ORD-200","amount":129.00})";
client.sendEvent(event);
```
```rust title="route_events_queue.rs"
let event = EventBuilder::new()
.channel("events:order-notify;queues:order-process")
.metadata("order.created")
.body(br#"{"orderId":"ORD-200","amount":129.00}"#.to_vec())
.build();
client.send_event(event).await?;
```
```ruby title="route_events_queue.rb"
msg = KubeMQ::PubSub::EventMessage.new(
channel: 'events:order-notify;queues:order-process',
metadata: 'order.created',
body: '{"orderId":"ORD-200","amount":129.00}'
)
client.send_event(msg)
```
```elixir title="route_events_queue.exs"
event = KubeMQ.Event.new(
channel: "events:order-notify;queues:order-process",
metadata: "order.created",
body: ~s({"orderId":"ORD-200","amount":129.00})
)
:ok = KubeMQ.Client.send_event(client, event)
```
### All Three Patterns [#all-three-patterns]
Route a single publish to an event channel, persistent store, and a work queue simultaneously.
```go title="route_all.go"
err = client.SendEvent(ctx, kubemq.NewEvent().
SetChannel("events:order-live;events_store:order-archive;queues:order-fulfill").
SetMetadata("order.created").
SetBody([]byte(`{"orderId":"ORD-300","amount":349.99}`)),
)
```
```python title="route_all.py"
client.send_event(
EventMessage(
channel="events:order-live;events_store:order-archive;queues:order-fulfill",
metadata="order.created",
body=b'{"orderId":"ORD-300","amount":349.99}',
)
)
```
```javascript title="route_all.js"
await client.sendEvent({
channel: "events:order-live;events_store:order-archive;queues:order-fulfill",
metadata: "order.created",
body: Buffer.from('{"orderId":"ORD-300","amount":349.99}'),
});
```
```java title="RouteAll.java"
client.sendEventsMessage(EventMessage.builder()
.channel("events:order-live;events_store:order-archive;queues:order-fulfill")
.metadata("order.created")
.body("{\"orderId\":\"ORD-300\",\"amount\":349.99}".getBytes())
.build());
```
```csharp title="RouteAll.cs"
await client.SendEventAsync(new EventMessage
{
Channel = "events:order-live;events_store:order-archive;queues:order-fulfill",
Metadata = "order.created",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-300\",\"amount\":349.99}"),
});
```
```kotlin title="RouteAll.kt"
client.sendEvent(EventMessage(
channel = "events:order-live;events_store:order-archive;queues:order-fulfill",
metadata = "order.created",
body = """{"orderId":"ORD-300","amount":349.99}""".toByteArray(),
))
```
```cpp title="route_all.cpp"
kubemq::EventMessage event;
event.channel = "events:order-live;events_store:order-archive;queues:order-fulfill";
event.metadata = "order.created";
event.body = R"({"orderId":"ORD-300","amount":349.99})";
client.sendEvent(event);
```
```rust title="route_all.rs"
let event = EventBuilder::new()
.channel("events:order-live;events_store:order-archive;queues:order-fulfill")
.metadata("order.created")
.body(br#"{"orderId":"ORD-300","amount":349.99}"#.to_vec())
.build();
client.send_event(event).await?;
```
```ruby title="route_all.rb"
msg = KubeMQ::PubSub::EventMessage.new(
channel: 'events:order-live;events_store:order-archive;queues:order-fulfill',
metadata: 'order.created',
body: '{"orderId":"ORD-300","amount":349.99}'
)
client.send_event(msg)
```
```elixir title="route_all.exs"
event = KubeMQ.Event.new(
channel: "events:order-live;events_store:order-archive;queues:order-fulfill",
metadata: "order.created",
body: ~s({"orderId":"ORD-300","amount":349.99})
)
:ok = KubeMQ.Client.send_event(client, event)
```
## How Routing Works Internally [#how-routing-works-internally]
When the server receives a channel string containing `;` or `:` delimiters, it splits the targets and fans the message out to each pattern and channel independently.
Each target is processed independently — a failure on one target does not affect the others. The server returns an error only if the routing syntax itself is invalid.
## Key Points [#key-points]
* **Atomic fan-out** — a single SDK call routes to all targets without client-side loops
* **Mixed patterns** — combine events, events\_store, and queues in any combination
* **Independent delivery** — each target processes the message according to its own pattern semantics
* **Subscriber transparency** — subscribers see messages as if published directly to their channel
# Choosing a Messaging Pattern (/learn/guides/choosing-a-pattern)
Every messaging pattern is a variation on one of three [interaction styles](/learn/concepts/interaction-styles) — pub/sub fan-out, point-to-point work distribution, or request/reply round-trips — tuned to a particular [delivery guarantee](/learn/concepts/delivery-guarantees). Choosing a pattern is really two questions: *what shape is the conversation*, and *how much can you afford to lose*. Answer those and the pattern falls out.
## Decision Guide [#decision-guide]
Answer a few questions to find the right messaging pattern for your use case.
### Decision Flowchart [#decision-flowchart]
The same logic as a flowchart. The first fork is the interaction style (does the sender wait for a reply?); the second is the delivery guarantee (can a message be lost?).
*Decision flowchart: the first fork is whether the sender waits for a reply, the second is whether a message can be lost, and the leaves are the five patterns.*
The two branches map straight onto the Fundamentals:
* **The sender waits → request/reply.** [Commands](/learn/concepts/interaction-styles) and Queries are the there-and-back style. Commands carry a write that returns only success/failure; Queries carry a read that returns a full body.
* **The sender hands off and moves on → pub/sub or point-to-point.** Now the [delivery guarantee](/learn/concepts/delivery-guarantees) decides: at-most-once fire-and-forget (Events), or persisted delivery you can replay (Events Store). If each message must be handled by exactly one worker, that is point-to-point work distribution (Queues).
## Pattern Comparison [#pattern-comparison]
| Feature | Events | Events Store | Queues | Commands | Queries |
| ----------------- | ------------ | ------------- | -------------- | ------------- | ------------- |
| Interaction style | Pub/sub | Pub/sub | Point-to-point | Request/reply | Request/reply |
| Delivery | At-most-once | At-least-once | Exactly-once | At-most-once | At-most-once |
| Persistence | No | Yes | Yes | No | No |
| Response | No | No | No | Executed only | Full body |
| Ordering | No | Sequenced | FIFO | N/A | N/A |
| Replay | No | 6 positions | No | No | No |
| DLQ | No | No | Yes | No | No |
| Caching | No | No | No | No | Yes |
| Groups | Yes | Yes | N/A | Yes | Yes |
## When to Use Each Pattern [#when-to-use-each-pattern]
### Events — Real-Time Broadcasting [#events--real-time-broadcasting]
Pub/sub fan-out with [at-most-once](/learn/concepts/delivery-guarantees) delivery. Best for real-time notifications, log streaming, live dashboards, and cache invalidation where occasional message loss is acceptable.
**Trade-offs:** Fastest (no disk I/O), but messages are lost if no subscriber is connected — there is no acknowledgement and nothing to replay.
*Events: the publisher fires once, every connected subscriber gets the message, and anyone offline simply misses it.*
### Events Store — Persistent Pub/Sub [#events-store--persistent-pubsub]
Pub/sub fan-out with [at-least-once](/learn/concepts/delivery-guarantees) delivery, persisted to disk. Best for audit trails, event sourcing, cross-service state sync, and any scenario where messages must not be lost.
**Trade-offs:** Higher latency than Events (disk I/O), but subscribers can replay from any point — a late subscriber can read the whole history.
*Events Store: messages are persisted to disk as they are delivered live, so a subscriber that connects later can replay the full history.*
### Queues — Work Distribution [#queues--work-distribution]
Point-to-point competing consumers with [exactly-once](/learn/concepts/delivery-guarantees) processing. Best for order processing, background jobs, webhook delivery, and any task where each message must be handled by exactly one worker.
**Trade-offs:** Requires an explicit ack/nack, but in return you get the full reliability toolkit — DLQ, delayed delivery, visibility timeout, and retry.
*Queues: one consumer receives the message and acknowledges it, and only then is the message removed from the queue.*
### RPC — Request/Reply [#rpc--requestreply]
The there-and-back interaction style. Best for service-to-service communication, API gateways, CQRS, and device command/control.
**Trade-offs:** Synchronous (sender blocks), but provides a direct response. Commands strip the response body (write semantics), Queries preserve it (read semantics).
*RPC: the sender blocks while KubeMQ routes the request to a responder and returns the single response back.*
## Combining Patterns [#combining-patterns]
Real systems rarely pick one pattern. The same message often fans out across several styles at once — broadcast for visibility, queue for reliable work. KubeMQ does this with [channel routing](/learn/concepts/channels-and-routing): one send, multiple destinations.
### Event-Driven with Work Queue [#event-driven-with-work-queue]
Broadcast events for monitoring (pub/sub, loss OK), and route critical work to a queue for reliable point-to-point processing.
*Event-driven with work queue: a single send fans out to a dashboard for monitoring and to a queue for reliable point-to-point processing.*
### CQRS with Events [#cqrs-with-events]
Commands write data (request/reply), events propagate the change (pub/sub), queries read projections (request/reply).
*CQRS with events: commands write through the event store, the read service subscribes to build projections, and clients query that read side.*
### Fan-Out with Routing [#fan-out-with-routing]
Publish once, deliver to multiple patterns using channel routing syntax.
| Syntax | Meaning |
| ----------------------------------- | ------------------------- |
| `events:channel-a;events:channel-b` | Two event channels |
| `events:live;events_store:archive` | Event + persistent copy |
| `events:notify;queues:process` | Broadcast + reliable work |
## Decision Matrix [#decision-matrix]
| Requirement | Recommended Pattern |
| --------------------------- | -------------------- |
| Real-time notifications | Events |
| Log/metric streaming | Events |
| Cache invalidation | Events |
| Audit trail | Events Store |
| Event sourcing | Events Store |
| Cross-service state sync | Events Store |
| Order processing | Queues |
| Background jobs | Queues |
| Scheduled/delayed tasks | Queues |
| Webhook delivery with retry | Queues |
| Service-to-service calls | RPC Commands/Queries |
| API gateway backend | RPC Commands/Queries |
| Device command & control | RPC Commands |
| Cached lookups | RPC Queries |
# Connect with TLS & mTLS (/learn/guides/connect-with-tls)
Securing connections applies across every messaging pattern. See the [Messaging Patterns Fundamentals](/learn/concepts) for the conceptual model these guides build on.
## Prerequisites [#prerequisites]
* KubeMQ server configured with TLS certificates
* CA certificate file (for TLS and mTLS)
* Client certificate and key files (for mTLS only)
Server-side TLS configuration is managed in the KubeMQ deployment.
## TLS Connection [#tls-connection]
Server-side TLS encrypts all traffic between the client and KubeMQ. The client verifies the server's identity using a CA certificate, preventing man-in-the-middle attacks.
### Configure TLS [#configure-tls]
```go title="tls_connect.go"
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/kubemq-io/kubemq-go/v2"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := kubemq.NewClient(ctx,
kubemq.WithAddress("kubemq.example.com", 50000),
kubemq.WithClientId("secure-client"),
kubemq.WithTLS("path/to/ca-cert.pem"),
)
if err != nil {
log.Fatalf("TLS connection failed: %v", err)
}
defer client.Close()
info, err := client.Ping(ctx)
if err != nil {
log.Fatalf("Ping failed: %v", err)
}
fmt.Printf("TLS connected: host=%s version=%s\n", info.Host, info.Version)
}
```
```python title="tls_connect.py"
from kubemq import TLSConfig
from kubemq.pubsub import Client as PubSubClient
tls_config = TLSConfig(
enabled=True,
ca_file="/path/to/ca.pem",
)
with PubSubClient(
address="kubemq.example.com:50000",
client_id="secure-client",
tls=tls_config,
) as client:
info = client.ping()
print(f"TLS connected: host={info.host}")
```
```typescript title="tls_connect.ts"
import { KubeMQClient, ConnectionError } from "kubemq-js";
try {
const client = await KubeMQClient.create({
address: "kubemq.example.com:50000",
clientId: "secure-client",
tls: {
enabled: true,
caCert: "/path/to/ca-cert.pem",
},
});
console.log("TLS connected:", client.state);
await client.close();
} catch (err) {
if (err instanceof ConnectionError) {
console.error("TLS connection failed:", err.message);
}
}
```
```java title="TlsConnect.java"
QueuesClient client = QueuesClient.builder()
.address("kubemq.example.com:50000")
.clientId("secure-client")
.tls(true)
.caCertFile("/path/to/ca.pem")
.build();
ServerInfo info = client.ping();
System.out.println("TLS connected: " + info);
client.close();
```
```csharp title="TlsConnect.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions
{
Address = "kubemq.example.com:50000",
ClientId = "secure-client",
Tls = new TlsOptions
{
Enabled = true,
CaFile = "/path/to/ca.pem",
},
});
await client.ConnectAsync();
var info = await client.PingAsync();
Console.WriteLine($"TLS connected: {info}");
```
```kotlin title="TlsConnect.kt"
val client = KubeMQClient.queues {
address = "kubemq.example.com:50000"
clientId = "secure-client"
tls {
caCertFile = "/path/to/ca.pem"
}
}
client.use {
val info = it.ping()
println("TLS connected: host=${info.host}")
}
```
```cpp title="tls_connect.cpp"
#include
#include
kubemq::ClientOptions opts;
opts.address = "kubemq.example.com:50000";
opts.client_id = "secure-client";
opts.set_tls_config(kubemq::TlsConfig::FromCertFile("/path/to/ca-cert.pem"));
kubemq::PubSubClient client(opts);
auto info = client.ping();
std::cout << "TLS connected: " << info.host << std::endl;
```
```rust title="tls_connect.rs"
use kubemq::prelude::*;
use kubemq::TlsConfig;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let tls = TlsConfig {
ca_cert_file: Some("/path/to/ca.pem".to_string()),
..Default::default()
};
let client = KubemqClient::builder()
.host("kubemq.example.com")
.port(50000)
.tls_config(tls)
.build()
.await?;
let info = client.ping().await?;
println!("TLS connected. Server version: {}", info.version);
client.close().await?;
Ok(())
}
```
```ruby title="tls_connect.rb"
require 'kubemq'
tls = KubeMQ::TLSConfig.new(enabled: true, ca_file: '/path/to/ca.pem')
client = KubeMQ::PubSubClient.new(
address: 'kubemq.example.com:50000',
client_id: 'secure-client',
tls: tls
)
info = client.ping
puts "TLS connected: host=#{info.host}, version=#{info.version}"
client.close
```
```elixir title="tls_connect.exs"
{:ok, client} =
KubeMQ.Client.start_link(
address: "kubemq.example.com:50000",
client_id: "secure-client",
tls: [cacertfile: "/path/to/ca.pem"]
)
{:ok, info} = KubeMQ.Client.ping(client)
IO.puts("TLS connected: version=#{info.version}")
KubeMQ.Client.close(client)
```
### Verify Connection [#verify-connection]
After establishing a TLS connection, call `Ping` (or equivalent) to confirm the secure channel is working. A successful ping confirms both network connectivity and certificate validation.
## Mutual TLS (mTLS) [#mutual-tls-mtls]
mTLS extends standard TLS by requiring both the client and server to present certificates. The server verifies the client's identity, and the client verifies the server — establishing bidirectional trust.
### Configure mTLS [#configure-mtls]
```go title="mtls_connect.go"
client, err := kubemq.NewClient(ctx,
kubemq.WithAddress("kubemq.example.com", 50000),
kubemq.WithClientId("mtls-client"),
kubemq.WithMTLS(
"path/to/client-cert.pem",
"path/to/client-key.pem",
"path/to/ca-cert.pem",
),
)
if err != nil {
log.Fatalf("mTLS connection failed: %v", err)
}
defer client.Close()
info, err := client.Ping(ctx)
if err != nil {
log.Fatalf("Ping failed: %v", err)
}
fmt.Printf("mTLS connected: host=%s\n", info.Host)
```
```python title="mtls_connect.py"
from kubemq import TLSConfig
from kubemq.pubsub import Client as PubSubClient
tls_config = TLSConfig(
enabled=True,
cert_file="/path/to/client-cert.pem",
key_file="/path/to/client-key.pem",
ca_file="/path/to/ca.pem",
)
with PubSubClient(
address="kubemq.example.com:50000",
client_id="mtls-client",
tls=tls_config,
) as client:
info = client.ping()
print(f"mTLS connected: host={info.host}")
```
```typescript title="mtls_connect.ts"
const client = await KubeMQClient.create({
address: "kubemq.example.com:50000",
clientId: "mtls-client",
tls: {
enabled: true,
caCert: "/path/to/ca-cert.pem",
clientCert: "/path/to/client-cert.pem",
clientKey: "/path/to/client-key.pem",
},
});
console.log("mTLS connected:", client.state);
await client.close();
```
```java title="MtlsConnect.java"
QueuesClient client = QueuesClient.builder()
.address("kubemq.example.com:50000")
.clientId("mtls-client")
.tls(true)
.caCertFile("/path/to/ca.pem")
.tlsCertFile("/path/to/client-cert.pem")
.tlsKeyFile("/path/to/client-key.pem")
.build();
ServerInfo info = client.ping();
System.out.println("mTLS connected: " + info);
client.close();
```
```csharp title="MtlsConnect.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions
{
Address = "kubemq.example.com:50000",
ClientId = "mtls-client",
Tls = new TlsOptions
{
Enabled = true,
CaFile = "/path/to/ca.pem",
CertFile = "/path/to/client-cert.pem",
KeyFile = "/path/to/client-key.pem",
},
});
await client.ConnectAsync();
var info = await client.PingAsync();
Console.WriteLine($"mTLS connected: {info}");
```
```kotlin title="MtlsConnect.kt"
val client = KubeMQClient.queues {
address = "kubemq.example.com:50000"
clientId = "mtls-client"
tls {
caCertFile = "/path/to/ca.pem"
certFile = "/path/to/client-cert.pem"
keyFile = "/path/to/client-key.pem"
}
}
client.use {
val info = it.ping()
println("mTLS connected: host=${info.host}")
}
```
```cpp title="mtls_connect.cpp"
kubemq::ClientOptions opts;
opts.address = "kubemq.example.com:50000";
opts.client_id = "mtls-client";
opts.set_tls_config(kubemq::TlsConfig::FromMutualTls(
"/path/to/client-cert.pem",
"/path/to/client-key.pem",
"/path/to/ca-cert.pem"
));
kubemq::PubSubClient client(opts);
auto info = client.ping();
std::cout << "mTLS connected: " << info.host << std::endl;
```
```rust title="mtls_connect.rs"
use kubemq::prelude::*;
use kubemq::TlsConfig;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let tls = TlsConfig {
ca_cert_file: Some("/path/to/ca.pem".to_string()),
cert_file: Some("/path/to/client-cert.pem".to_string()),
key_file: Some("/path/to/client-key.pem".to_string()),
..Default::default()
};
let client = KubemqClient::builder()
.host("kubemq.example.com")
.port(50000)
.tls_config(tls)
.build()
.await?;
let info = client.ping().await?;
println!("mTLS connected. Server version: {}", info.version);
client.close().await?;
Ok(())
}
```
```ruby title="mtls_connect.rb"
require 'kubemq'
tls = KubeMQ::TLSConfig.new(
enabled: true,
cert_file: '/path/to/client-cert.pem',
key_file: '/path/to/client-key.pem',
ca_file: '/path/to/ca.pem'
)
client = KubeMQ::PubSubClient.new(
address: 'kubemq.example.com:50000',
client_id: 'mtls-client',
tls: tls
)
info = client.ping
puts "mTLS connected: host=#{info.host}, version=#{info.version}"
client.close
```
```elixir title="mtls_connect.exs"
{:ok, client} =
KubeMQ.Client.start_link(
address: "kubemq.example.com:50000",
client_id: "mtls-client",
tls: [
cacertfile: "/path/to/ca.pem",
certfile: "/path/to/client-cert.pem",
keyfile: "/path/to/client-key.pem",
verify: :verify_peer
]
)
{:ok, info} = KubeMQ.Client.ping(client)
IO.puts("mTLS connected: version=#{info.version}")
KubeMQ.Client.close(client)
```
### When to Use mTLS [#when-to-use-mtls]
| Scenario | TLS | mTLS |
| -------------------------- | ---------- | ----------- |
| Encrypt traffic in transit | Yes | Yes |
| Verify server identity | Yes | Yes |
| Verify client identity | No | Yes |
| Zero-trust network | — | Recommended |
| Multi-tenant deployment | — | Recommended |
| Internal trusted network | Sufficient | Optional |
## Pattern-Specific Notes [#pattern-specific-notes]
TLS and mTLS configuration is **identical for Events, Events Store, Queues, and RPC**. The secure connection is established once at client creation and applies to all operations performed through that client. You do not need separate TLS configuration per pattern.
## Troubleshooting [#troubleshooting]
Verify the CA certificate matches the server's certificate issuer:
```bash
openssl verify -CAfile ca-cert.pem server-cert.pem
```
Common causes: expired certificates, wrong CA file, or intermediate CA missing from the chain.
Verify the client certificate and key are a matching pair:
```bash
openssl x509 -noout -modulus -in client-cert.pem | openssl md5
openssl rsa -noout -modulus -in client-key.pem | openssl md5
```
Both commands should output the same MD5 hash. If they differ, the cert and key do not match.
TLS typically uses a different port than plaintext. Confirm the server port in your deployment configuration. The default TLS port varies by deployment method.
## Next Steps [#next-steps]
# Error Handling Patterns (/learn/guides/error-handling)
Retries and dead-lettering build on KubeMQ's delivery semantics. Review [Delivery Guarantees](/learn/concepts/delivery-guarantees) in Fundamentals to understand at-least-once delivery and acknowledgement before designing your error-handling strategy.
## Error Categories [#error-categories]
KubeMQ errors fall into four categories. Handling differs by category, not by messaging pattern.
| Category | Cause | Example | Recovery |
| ----------------- | --------------------------------------------------- | ---------------------------------------------- | ------------------------------- |
| **Validation** | Invalid input before the message reaches the server | Empty channel name, body + metadata both empty | Fix the input — do not retry |
| **Connection** | Network or server unavailable | DNS failure, server restart, TLS mismatch | Reconnect with backoff |
| **Timeout** | Operation exceeded its deadline | RPC request timeout, queue poll timeout | Retry or increase timeout |
| **Authorization** | Missing or invalid credentials | Bad auth token, expired certificate | Refresh credentials, then retry |
## Connection Error Handling [#connection-error-handling]
Detect connection failures and attempt reconnection. All SDKs expose connection state or error callbacks.
```go title="connection_error.go"
package main
import (
"context"
"log"
"time"
"github.com/kubemq-io/kubemq-go/v2"
)
func connectWithRetry(ctx context.Context) *kubemq.Client {
var client *kubemq.Client
var err error
backoff := time.Second
for {
client, err = kubemq.NewClient(ctx,
kubemq.WithAddress("localhost", 50000),
kubemq.WithClientId("resilient-client"),
)
if err == nil {
if _, pingErr := client.Ping(ctx); pingErr == nil {
log.Println("Connected to KubeMQ")
return client
}
client.Close()
}
log.Printf("Connection failed: %v — retrying in %v", err, backoff)
time.Sleep(backoff)
if backoff < 30*time.Second {
backoff *= 2
}
}
}
```
```python title="connection_error.py"
import time
from kubemq.pubsub import Client as PubSubClient
def connect_with_retry(address: str) -> PubSubClient:
backoff = 1.0
while True:
try:
client = PubSubClient(
address=address,
client_id="resilient-client",
)
client.ping()
print("Connected to KubeMQ")
return client
except Exception as e:
print(f"Connection failed: {e} — retrying in {backoff}s")
time.sleep(backoff)
backoff = min(backoff * 2, 30)
```
```javascript title="connection_error.js"
const { KubeMQClient } = require("kubemq-js");
async function connectWithRetry(address) {
let backoff = 1000;
while (true) {
try {
const client = new KubeMQClient({
address,
clientId: "resilient-client",
});
await client.ping();
console.log("Connected to KubeMQ");
return client;
} catch (err) {
console.error(`Connection failed: ${err.message} — retrying in ${backoff}ms`);
await new Promise((r) => setTimeout(r, backoff));
backoff = Math.min(backoff * 2, 30000);
}
}
}
```
```java title="ConnectionError.java"
PubSubClient connectWithRetry(String address) throws InterruptedException {
long backoff = 1000;
while (true) {
try {
PubSubClient client = PubSubClient.builder()
.address(address)
.clientId("resilient-client")
.build();
client.ping();
System.out.println("Connected to KubeMQ");
return client;
} catch (Exception e) {
System.err.printf("Connection failed: %s — retrying in %dms%n",
e.getMessage(), backoff);
Thread.sleep(backoff);
backoff = Math.min(backoff * 2, 30000);
}
}
}
```
```csharp title="ConnectionError.cs"
async Task ConnectWithRetryAsync(string address)
{
var backoff = TimeSpan.FromSeconds(1);
while (true)
{
try
{
var client = new KubeMQClient(new KubeMQClientOptions
{
Address = address,
ClientId = "resilient-client",
});
await client.ConnectAsync();
await client.PingAsync();
Console.WriteLine("Connected to KubeMQ");
return client;
}
catch (Exception ex)
{
Console.WriteLine($"Connection failed: {ex.Message} — retrying in {backoff}");
await Task.Delay(backoff);
if (backoff < TimeSpan.FromSeconds(30))
backoff *= 2;
}
}
}
```
```kotlin title="ConnectionError.kt"
import io.kubemq.sdk.pubsub.PubSubClient
import kotlinx.coroutines.delay
suspend fun connectWithRetry(address: String): PubSubClient {
var backoff = 1000L
while (true) {
try {
val client = PubSubClient(address)
client.ping()
println("Connected to KubeMQ")
return client
} catch (e: Exception) {
println("Connection failed: ${e.message} — retrying in ${backoff}ms")
delay(backoff)
backoff = minOf(backoff * 2, 30000)
}
}
}
```
```cpp title="connection_error.cpp"
#include
#include
#include
#include
kubemq::PubSubClient connectWithRetry(const std::string& address) {
int backoff = 1000;
while (true) {
try {
kubemq::PubSubClient client(address);
client.ping();
std::cout << "Connected to KubeMQ" << std::endl;
return client;
} catch (const std::exception& e) {
std::cerr << "Connection failed: " << e.what()
<< " — retrying in " << backoff << "ms" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(backoff));
backoff = std::min(backoff * 2, 30000);
}
}
}
```
```rust title="connection_error.rs"
use kubemq::prelude::*;
use kubemq::RetryPolicy;
use std::time::Duration;
async fn connect_with_retry(host: &str, port: u16) -> KubemqClient {
let mut backoff = Duration::from_secs(1);
loop {
// The builder applies its own retry policy on transient failures;
// check_connection verifies the connection before returning.
let result = KubemqClient::builder()
.host(host)
.port(port)
.client_id("resilient-client")
.check_connection(true)
.retry_policy(RetryPolicy {
max_retries: 3,
initial_backoff: Duration::from_millis(100),
max_backoff: Duration::from_secs(10),
multiplier: 2.0,
..Default::default()
})
.build()
.await;
match result {
Ok(client) => {
println!("Connected to KubeMQ");
return client;
}
Err(e) => {
println!("Connection failed: {e} — retrying in {backoff:?}");
tokio::time::sleep(backoff).await;
backoff = std::cmp::min(backoff * 2, Duration::from_secs(30));
}
}
}
}
```
```ruby title="connection_error.rb"
require 'kubemq'
def connect_with_retry(address)
backoff = 1.0
loop do
begin
client = KubeMQ::PubSubClient.new(
address: address,
client_id: 'resilient-client'
)
client.ping
puts 'Connected to KubeMQ'
return client
rescue KubeMQ::Error, StandardError => e
puts "Connection failed: #{e.message} — retrying in #{backoff}s"
sleep backoff
backoff = [backoff * 2, 30].min
end
end
end
```
```elixir title="connection_error.exs"
# KubeMQ.Client.start_link/1 returns {:ok, client} or {:error, reason}.
# Retry with exponential backoff until the connection succeeds.
defmodule Resilient do
def connect_with_retry(address, backoff \\ 1_000) do
case KubeMQ.Client.start_link(address: address, client_id: "resilient-client") do
{:ok, client} ->
IO.puts("Connected to KubeMQ")
client
{:error, reason} ->
IO.puts("Connection failed: #{inspect(reason)} — retrying in #{backoff}ms")
Process.sleep(backoff)
connect_with_retry(address, min(backoff * 2, 30_000))
end
end
end
```
## Retry with Backoff [#retry-with-backoff]
Wrap send operations with exponential backoff and a maximum retry count to handle transient failures without overwhelming the server.
*A message moves from received to processing; on failure it backs off and is requeued for redelivery, and once retries are exhausted it lands in the dead-letter queue.*
```go title="retry_backoff.go"
func sendWithRetry(ctx context.Context, client *kubemq.Client, event *kubemq.Event, maxRetries int) error {
backoff := 100 * time.Millisecond
for attempt := 0; attempt <= maxRetries; attempt++ {
err := client.SendEvent(ctx, event)
if err == nil {
return nil
}
if attempt == maxRetries {
return fmt.Errorf("failed after %d retries: %w", maxRetries, err)
}
log.Printf("Attempt %d failed: %v — retrying in %v", attempt+1, err, backoff)
time.Sleep(backoff)
backoff *= 2
}
return nil
}
```
```python title="retry_backoff.py"
import time
def send_with_retry(client, event, max_retries=3):
backoff = 0.1
for attempt in range(max_retries + 1):
try:
client.send_event(event)
return
except Exception as e:
if attempt == max_retries:
raise RuntimeError(f"Failed after {max_retries} retries") from e
print(f"Attempt {attempt + 1} failed: {e} — retrying in {backoff}s")
time.sleep(backoff)
backoff *= 2
```
```javascript title="retry_backoff.js"
async function sendWithRetry(client, event, maxRetries = 3) {
let backoff = 100;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
await client.sendEvent(event);
return;
} catch (err) {
if (attempt === maxRetries) {
throw new Error(`Failed after ${maxRetries} retries: ${err.message}`);
}
console.warn(`Attempt ${attempt + 1} failed: ${err.message} — retrying in ${backoff}ms`);
await new Promise((r) => setTimeout(r, backoff));
backoff *= 2;
}
}
}
```
```java title="RetryBackoff.java"
void sendWithRetry(PubSubClient client, EventMessage event, int maxRetries)
throws Exception {
long backoff = 100;
for (int attempt = 0; attempt <= maxRetries; attempt++) {
try {
client.sendEventsMessage(event);
return;
} catch (Exception e) {
if (attempt == maxRetries) {
throw new RuntimeException("Failed after " + maxRetries + " retries", e);
}
System.err.printf("Attempt %d failed: %s — retrying in %dms%n",
attempt + 1, e.getMessage(), backoff);
Thread.sleep(backoff);
backoff *= 2;
}
}
}
```
```csharp title="RetryBackoff.cs"
async Task SendWithRetryAsync(KubeMQClient client, EventMessage message, int maxRetries = 3)
{
var backoff = TimeSpan.FromMilliseconds(100);
for (int attempt = 0; attempt <= maxRetries; attempt++)
{
try
{
await client.SendEventAsync(message);
return;
}
catch (Exception ex)
{
if (attempt == maxRetries)
throw new InvalidOperationException($"Failed after {maxRetries} retries", ex);
Console.WriteLine($"Attempt {attempt + 1} failed: {ex.Message} — retrying in {backoff}");
await Task.Delay(backoff);
backoff *= 2;
}
}
}
```
```kotlin title="RetryBackoff.kt"
suspend fun sendWithRetry(client: PubSubClient, event: EventMessage, maxRetries: Int = 3) {
var backoff = 100L
for (attempt in 0..maxRetries) {
try {
client.sendEvent(event)
return
} catch (e: Exception) {
if (attempt == maxRetries) {
throw RuntimeException("Failed after $maxRetries retries", e)
}
println("Attempt ${attempt + 1} failed: ${e.message} — retrying in ${backoff}ms")
delay(backoff)
backoff *= 2
}
}
}
```
```cpp title="retry_backoff.cpp"
void sendWithRetry(kubemq::PubSubClient& client, kubemq::EventMessage& event, int maxRetries = 3) {
int backoff = 100;
for (int attempt = 0; attempt <= maxRetries; ++attempt) {
try {
client.sendEvent(event);
return;
} catch (const std::exception& e) {
if (attempt == maxRetries) {
throw std::runtime_error(
"Failed after " + std::to_string(maxRetries) + " retries: " + e.what());
}
std::cerr << "Attempt " << attempt + 1 << " failed: " << e.what()
<< " — retrying in " << backoff << "ms" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(backoff));
backoff *= 2;
}
}
}
```
```rust title="retry_backoff.rs"
use kubemq::prelude::*;
use kubemq::Event;
use std::time::Duration;
async fn send_with_retry(
client: &KubemqClient,
event: Event,
max_retries: u32,
) -> kubemq::Result<()> {
let mut backoff = Duration::from_millis(100);
for attempt in 0..=max_retries {
match client.send_event(event.clone()).await {
Ok(()) => return Ok(()),
Err(e) => {
if attempt == max_retries {
return Err(e);
}
println!("Attempt {} failed: {e} — retrying in {backoff:?}", attempt + 1);
tokio::time::sleep(backoff).await;
backoff *= 2;
}
}
}
Ok(())
}
```
```ruby title="retry_backoff.rb"
def send_with_retry(client, message, max_retries = 3)
backoff = 0.1
(0..max_retries).each do |attempt|
begin
client.send_event(message)
return
rescue KubeMQ::Error, StandardError => e
raise "Failed after #{max_retries} retries: #{e.message}" if attempt == max_retries
puts "Attempt #{attempt + 1} failed: #{e.message} — retrying in #{backoff}s"
sleep backoff
backoff *= 2
end
end
end
```
```elixir title="retry_backoff.exs"
# send_event/2 returns :ok or {:error, err}. Retry transient failures
# with exponential backoff, raising once retries are exhausted.
defmodule Retry do
def send_with_retry(client, event, max_retries \\ 3, backoff \\ 100, attempt \\ 0) do
case KubeMQ.Client.send_event(client, event) do
:ok ->
:ok
{:error, err} when attempt >= max_retries ->
raise "Failed after #{max_retries} retries: #{err.message}"
{:error, err} ->
IO.puts("Attempt #{attempt + 1} failed: #{err.message} — retrying in #{backoff}ms")
Process.sleep(backoff)
send_with_retry(client, event, max_retries, backoff * 2, attempt + 1)
end
end
end
```
## Graceful Shutdown [#graceful-shutdown]
Close client connections cleanly to flush pending messages and release server resources.
```go title="graceful_shutdown.go"
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/kubemq-io/kubemq-go/v2"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
client, err := kubemq.NewClient(ctx,
kubemq.WithAddress("localhost", 50000),
)
if err != nil {
log.Fatal(err)
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sig
log.Println("Shutting down...")
cancel()
client.Close()
os.Exit(0)
}()
log.Println("Running — press Ctrl+C to stop")
<-ctx.Done()
}
```
```python title="graceful_shutdown.py"
import signal
import sys
from kubemq.pubsub import Client as PubSubClient
client = PubSubClient(address="localhost:50000")
def shutdown(signum, frame):
print("Shutting down...")
client.close()
sys.exit(0)
signal.signal(signal.SIGINT, shutdown)
signal.signal(signal.SIGTERM, shutdown)
print("Running — press Ctrl+C to stop")
signal.pause()
```
```javascript title="graceful_shutdown.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000" });
async function shutdown() {
console.log("Shutting down...");
await client.close();
process.exit(0);
}
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
console.log("Running — press Ctrl+C to stop");
```
```java title="GracefulShutdown.java"
PubSubClient client = PubSubClient.builder()
.address("localhost:50000")
.clientId("shutdown-demo")
.build();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Shutting down...");
client.close();
}));
System.out.println("Running — press Ctrl+C to stop");
Thread.currentThread().join();
```
```csharp title="GracefulShutdown.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions
{
Address = "localhost:50000",
});
await client.ConnectAsync();
var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
Console.WriteLine("Shutting down...");
cts.Cancel();
};
Console.WriteLine("Running — press Ctrl+C to stop");
try { await Task.Delay(Timeout.Infinite, cts.Token); }
catch (OperationCanceledException) { }
```
```kotlin title="GracefulShutdown.kt"
val client = PubSubClient("localhost:50000")
Runtime.getRuntime().addShutdownHook(Thread {
println("Shutting down...")
client.close()
})
println("Running — press Ctrl+C to stop")
Thread.currentThread().join()
```
```cpp title="graceful_shutdown.cpp"
#include
#include
#include
#include
std::atomic running{true};
kubemq::PubSubClient* globalClient = nullptr;
void signalHandler(int) {
std::cout << "Shutting down..." << std::endl;
running = false;
if (globalClient) globalClient->close();
}
int main() {
kubemq::PubSubClient client("localhost:50000");
globalClient = &client;
std::signal(SIGINT, signalHandler);
std::signal(SIGTERM, signalHandler);
std::cout << "Running — press Ctrl+C to stop" << std::endl;
while (running) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
```
```rust title="graceful_shutdown.rs"
use kubemq::prelude::*;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
println!("Running — press Ctrl+C to stop");
// Wait for a shutdown signal, then close the client cleanly.
tokio::signal::ctrl_c().await.ok();
println!("Shutting down...");
// close() flushes pending work and cancels active subscriptions.
client.close().await?;
println!("Client closed — shutdown complete");
Ok(())
}
```
```ruby title="graceful_shutdown.rb"
require 'kubemq'
client = KubeMQ::PubSubClient.new(address: 'localhost:50000', client_id: 'shutdown-demo')
shutdown = proc do
puts 'Shutting down...'
client.close
exit 0
end
Signal.trap('INT', &shutdown)
Signal.trap('TERM', &shutdown)
puts 'Running — press Ctrl+C to stop'
sleep
```
```elixir title="graceful_shutdown.exs"
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "shutdown-demo")
# Trap exits so the process can close the client before terminating.
Process.flag(:trap_exit, true)
IO.puts("Running — press Ctrl+C to stop")
receive do
{:EXIT, _from, _reason} ->
IO.puts("Shutting down...")
KubeMQ.Client.close(client)
IO.puts("Client closed — shutdown complete")
end
```
## Error Code Reference [#error-code-reference]
Common error codes returned by the KubeMQ server across all patterns.
| Code | Category | Description |
| ---- | ------------- | -------------------------------------------------------------- |
| 100 | Validation | Message body and metadata are both empty |
| 107 | Validation | Channel name contains wildcard characters |
| 108 | Validation | Channel name contains whitespace |
| 119 | Validation | Channel name ends with a dot |
| 120 | Validation | Channel name is empty |
| 200 | Connection | Server unavailable or connection refused |
| 201 | Connection | Connection timeout exceeded |
| 300 | Timeout | Request timeout (RPC commands/queries) |
| 301 | Timeout | Queue poll wait timeout (not an error — no messages available) |
| 400 | Authorization | Authentication token missing or invalid |
| 401 | Authorization | Client not authorized for the requested channel |
Code 301 (queue poll timeout) is expected behavior when no messages are available. Do not treat it as a failure in your error handling logic.
# OpenTelemetry Integration (/learn/guides/opentelemetry)
## Overview [#overview]
KubeMQ supports OpenTelemetry for distributed tracing and metrics. Instrumenting your producers and consumers gives you end-to-end visibility across messaging boundaries — regardless of which pattern (Events, Events Store, Queues, or RPC) you use.
Tracing is how you observe message flow under load. See [Scaling & Flow](/learn/concepts/scaling-and-flow) in Fundamentals for the concepts behind throughput, backpressure, and consumer groups that these traces will surface.
*Producer and consumer spans flow through the OTel Collector to a tracing backend, giving end-to-end visibility across the KubeMQ message path.*
## Setup [#setup]
Configure an OpenTelemetry tracer and meter provider in your application before creating KubeMQ clients.
```go title="otel_setup.go"
package main
import (
"context"
"log"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
)
func initTracer(ctx context.Context) (*sdktrace.TracerProvider, error) {
exporter, err := otlptracegrpc.New(ctx,
otlptracegrpc.WithEndpoint("localhost:4317"),
otlptracegrpc.WithInsecure(),
)
if err != nil {
return nil, err
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName("order-service"),
)),
)
otel.SetTracerProvider(tp)
return tp, nil
}
```
```python title="otel_setup.py"
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
resource = Resource.create({"service.name": "order-service"})
provider = TracerProvider(resource=resource)
exporter = OTLPSpanExporter(endpoint="localhost:4317", insecure=True)
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("order-service")
```
```typescript title="otel_setup.ts"
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-grpc";
import { Resource } from "@opentelemetry/resources";
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
const provider = new NodeTracerProvider({
resource: new Resource({ [ATTR_SERVICE_NAME]: "order-service" }),
});
provider.addSpanProcessor(
new BatchSpanProcessor(
new OTLPTraceExporter({ url: "http://localhost:4317" })
)
);
provider.register();
const tracer = provider.getTracer("order-service");
```
```java title="OtelSetup.java"
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.semconv.ResourceAttributes;
Resource resource = Resource.getDefault()
.merge(Resource.create(
io.opentelemetry.api.common.Attributes.of(
ResourceAttributes.SERVICE_NAME, "order-service")));
OtlpGrpcSpanExporter exporter = OtlpGrpcSpanExporter.builder()
.setEndpoint("http://localhost:4317")
.build();
SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(exporter).build())
.setResource(resource)
.build();
OpenTelemetry otel = OpenTelemetrySdk.builder()
.setTracerProvider(tracerProvider)
.build();
Tracer tracer = otel.getTracer("order-service");
```
```csharp title="OtelSetup.cs"
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(ResourceBuilder.CreateDefault()
.AddService("order-service"))
.AddOtlpExporter(opts =>
{
opts.Endpoint = new Uri("http://localhost:4317");
})
.Build();
var tracer = tracerProvider.GetTracer("order-service");
```
```kotlin title="OtelSetup.kt"
import io.opentelemetry.api.OpenTelemetry
import io.opentelemetry.api.trace.Tracer
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter
import io.opentelemetry.sdk.OpenTelemetrySdk
import io.opentelemetry.sdk.resources.Resource
import io.opentelemetry.sdk.trace.SdkTracerProvider
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor
import io.opentelemetry.semconv.ResourceAttributes
val resource = Resource.getDefault()
.merge(Resource.create(
io.opentelemetry.api.common.Attributes.of(
ResourceAttributes.SERVICE_NAME, "order-service")))
val exporter = OtlpGrpcSpanExporter.builder()
.setEndpoint("http://localhost:4317")
.build()
val tracerProvider = SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(exporter).build())
.setResource(resource)
.build()
val otel: OpenTelemetry = OpenTelemetrySdk.builder()
.setTracerProvider(tracerProvider)
.build()
val tracer: Tracer = otel.getTracer("order-service")
```
```cpp title="otel_setup.cpp"
#include
#include
#include
#include
#include
namespace trace_sdk = opentelemetry::sdk::trace;
namespace otlp = opentelemetry::exporter::otlp;
namespace resource = opentelemetry::sdk::resource;
auto exporter = std::make_unique(
otlp::OtlpGrpcExporterOptions{"localhost:4317"});
auto processor = std::make_unique(
std::move(exporter));
auto provider = std::make_shared(
std::move(processor),
resource::Resource::Create({{"service.name", "order-service"}}));
opentelemetry::trace::Provider::SetTracerProvider(provider);
auto tracer = provider->GetTracer("order-service");
```
```rust title="otel_setup.rs"
use kubemq::prelude::*;
use opentelemetry::global;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::{trace::TracerProvider, Resource};
use opentelemetry::KeyValue;
// Register a global TracerProvider before building the client. Once a
// provider is registered globally, the KubeMQ Rust client automatically
// instruments its gRPC calls — no per-call wiring required.
let exporter = opentelemetry_otlp::SpanExporter::builder()
.with_tonic()
.with_endpoint("http://localhost:4317")
.build()?;
let provider = TracerProvider::builder()
.with_batch_exporter(exporter, opentelemetry_sdk::runtime::Tokio)
.with_resource(Resource::new(vec![
KeyValue::new("service.name", "order-service"),
]))
.build();
global::set_tracer_provider(provider);
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
```
```ruby title="otel_setup.rb"
require 'kubemq'
require 'opentelemetry/sdk'
require 'opentelemetry/exporter/otlp'
# Configure the global OpenTelemetry SDK before creating the client. With a
# provider configured, the KubeMQ Ruby client's gRPC calls are instrumented
# through the standard OpenTelemetry gRPC instrumentation.
OpenTelemetry::SDK.configure do |c|
c.service_name = 'order-service'
c.use_all
end
tracer = OpenTelemetry.tracer_provider.tracer('order-service')
client = KubeMQ::PubSubClient.new(
address: 'localhost:50000',
client_id: 'order-service'
)
```
```elixir title="otel_setup.exs"
# The KubeMQ Elixir client emits :telemetry events for every operation
# rather than OpenTelemetry spans directly. Bridge those telemetry events
# into OpenTelemetry with the opentelemetry_telemetry library, or attach a
# handler to forward measurements to your tracer.
:telemetry.attach_many(
"kubemq-otel-bridge",
[
[:kubemq, :client, :send_event, :start],
[:kubemq, :client, :send_event, :stop],
[:kubemq, :client, :send_event, :exception]
],
fn event, measurements, metadata, _config ->
[_, _, action, phase] = event
# Forward to your OpenTelemetry tracer here, e.g. via OpenTelemetry.Tracer.
IO.puts("[otel] #{action}:#{phase} #{inspect(metadata[:channel])}")
end,
nil
)
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-service")
```
The Elixir client exposes observability through Erlang/Elixir `:telemetry` events (`[:kubemq, :client, :send_event, :start | :stop | :exception]`, and equivalents for commands, queries, and queues) rather than emitting OpenTelemetry spans directly. Use [`opentelemetry_telemetry`](https://hex.pm/packages/opentelemetry_telemetry) to convert these into spans, or attach your own handler.
## Tracing Messaging Operations [#tracing-messaging-operations]
Wrap your publish and subscribe operations in spans to trace message flow across services. The pattern is the same for Events, Events Store, Queues, and RPC.
```go title="traced_publish.go"
tracer := otel.Tracer("order-service")
ctx, span := tracer.Start(ctx, "publish-order",
trace.WithAttributes(
attribute.String("messaging.system", "kubemq"),
attribute.String("messaging.destination", "order-events"),
attribute.String("messaging.operation", "publish"),
),
)
defer span.End()
err := client.SendEvent(ctx, kubemq.NewEvent().
SetChannel("order-events").
SetBody([]byte(`{"orderId":"ORD-500"}`)),
)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
```
```python title="traced_publish.py"
with tracer.start_as_current_span(
"publish-order",
attributes={
"messaging.system": "kubemq",
"messaging.destination": "order-events",
"messaging.operation": "publish",
},
) as span:
try:
client.send_event(
EventMessage(
channel="order-events",
body=b'{"orderId":"ORD-500"}',
)
)
except Exception as e:
span.record_exception(e)
span.set_status(StatusCode.ERROR, str(e))
raise
```
```typescript title="traced_publish.ts"
await tracer.startActiveSpan("publish-order", {
attributes: {
"messaging.system": "kubemq",
"messaging.destination": "order-events",
"messaging.operation": "publish",
},
}, async (span) => {
try {
await client.sendEvent({
channel: "order-events",
body: Buffer.from('{"orderId":"ORD-500"}'),
});
} catch (err) {
span.recordException(err);
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
throw err;
} finally {
span.end();
}
});
```
```java title="TracedPublish.java"
Span span = tracer.spanBuilder("publish-order")
.setAttribute("messaging.system", "kubemq")
.setAttribute("messaging.destination", "order-events")
.setAttribute("messaging.operation", "publish")
.startSpan();
try (Scope scope = span.makeCurrent()) {
client.sendEventsMessage(EventMessage.builder()
.channel("order-events")
.body("{\"orderId\":\"ORD-500\"}".getBytes())
.build());
} catch (Exception e) {
span.recordException(e);
span.setStatus(StatusCode.ERROR, e.getMessage());
throw e;
} finally {
span.end();
}
```
```csharp title="TracedPublish.cs"
using var span = tracer.StartActiveSpan("publish-order");
span.SetAttribute("messaging.system", "kubemq");
span.SetAttribute("messaging.destination", "order-events");
span.SetAttribute("messaging.operation", "publish");
try
{
await client.SendEventAsync(new EventMessage
{
Channel = "order-events",
Body = Encoding.UTF8.GetBytes("{\"orderId\":\"ORD-500\"}"),
});
}
catch (Exception ex)
{
span.RecordException(ex);
span.SetStatus(Status.Error.WithDescription(ex.Message));
throw;
}
```
```kotlin title="TracedPublish.kt"
val span = tracer.spanBuilder("publish-order")
.setAttribute("messaging.system", "kubemq")
.setAttribute("messaging.destination", "order-events")
.setAttribute("messaging.operation", "publish")
.startSpan()
try {
span.makeCurrent().use {
client.sendEvent(EventMessage(
channel = "order-events",
body = """{"orderId":"ORD-500"}""".toByteArray(),
))
}
} catch (e: Exception) {
span.recordException(e)
span.setStatus(StatusCode.ERROR, e.message ?: "unknown error")
throw e
} finally {
span.end()
}
```
```cpp title="traced_publish.cpp"
auto span = tracer->StartSpan("publish-order", {
{"messaging.system", "kubemq"},
{"messaging.destination", "order-events"},
{"messaging.operation", "publish"},
});
auto scope = tracer->WithActiveSpan(span);
try {
kubemq::EventMessage event;
event.channel = "order-events";
event.body = R"({"orderId":"ORD-500"})";
client.sendEvent(event);
} catch (const std::exception& e) {
span->AddEvent("exception", {{"exception.message", e.what()}});
span->SetStatus(opentelemetry::trace::StatusCode::kError, e.what());
throw;
}
span->End();
```
```rust title="traced_publish.rs"
use kubemq::EventBuilder;
use opentelemetry::trace::{Span, Status, Tracer};
use opentelemetry::{global, KeyValue};
let tracer = global::tracer("order-service");
let mut span = tracer.start("publish-order");
span.set_attribute(KeyValue::new("messaging.system", "kubemq"));
span.set_attribute(KeyValue::new("messaging.destination", "order-events"));
span.set_attribute(KeyValue::new("messaging.operation", "publish"));
let event = EventBuilder::new()
.channel("order-events")
.body(br#"{"orderId":"ORD-500"}"#.to_vec())
.build();
match client.send_event(event).await {
Ok(_) => {}
Err(e) => {
span.set_status(Status::error(e.to_string()));
span.record_error(&e);
}
}
span.end();
```
```ruby title="traced_publish.rb"
tracer.in_span(
'publish-order',
attributes: {
'messaging.system' => 'kubemq',
'messaging.destination' => 'order-events',
'messaging.operation' => 'publish'
}
) do |span|
begin
msg = KubeMQ::PubSub::EventMessage.new(
channel: 'order-events',
body: '{"orderId":"ORD-500"}'
)
client.send_event(msg)
rescue KubeMQ::Error => e
span.record_exception(e)
span.status = OpenTelemetry::Trace::Status.error(e.message)
raise
end
end
```
```elixir title="traced_publish.exs"
require OpenTelemetry.Tracer, as: Tracer
Tracer.with_span "publish-order" do
Tracer.set_attributes([
{"messaging.system", "kubemq"},
{"messaging.destination", "order-events"},
{"messaging.operation", "publish"}
])
event =
KubeMQ.Event.new(channel: "order-events", body: ~s({"orderId":"ORD-500"}))
case KubeMQ.Client.send_event(client, event) do
:ok ->
:ok
{:error, err} ->
Tracer.set_status(OpenTelemetry.status(:error, err.message))
end
end
```
## Metrics [#metrics]
Instrument your messaging clients with OpenTelemetry metrics to track throughput, latency, and error rates.
### Recommended Metrics [#recommended-metrics]
| Metric | Type | Description |
| ---------------------------- | --------- | --------------------------------------- |
| `messaging.publish.duration` | Histogram | Time to publish a message (ms) |
| `messaging.process.duration` | Histogram | Time to process a received message (ms) |
| `messaging.publish.messages` | Counter | Total messages published |
| `messaging.receive.messages` | Counter | Total messages received |
| `messaging.publish.errors` | Counter | Failed publish attempts |
### Attribute Conventions [#attribute-conventions]
Follow OpenTelemetry semantic conventions for messaging attributes:
| Attribute | Example | Description |
| ----------------------- | --------------------- | --------------------------- |
| `messaging.system` | `kubemq` | Messaging system identifier |
| `messaging.destination` | `order-events` | Channel name |
| `messaging.operation` | `publish` / `receive` | Operation type |
| `messaging.message.id` | `uuid` | Message identifier |
These conventions align with the [OpenTelemetry Semantic Conventions for Messaging](https://opentelemetry.io/docs/specs/semconv/messaging/). Following them ensures compatibility with observability platforms like Jaeger, Grafana Tempo, and Datadog.
## Next Steps [#next-steps]
# Getting Started with RPC (/learn/rpc/getting-started)
**Prerequisites:** KubeMQ server running on `localhost:50000` and your SDK installed. See [Getting Started](/deploy) for setup.
## What You Will Build [#what-you-will-build]
A command sender that creates an order and a query sender that retrieves order status — each paired with a responder that handles the request and returns a response.
## Steps [#steps]
### Install the SDK [#install-the-sdk]
```bash
go get github.com/kubemq-io/kubemq-go/v2
```
```bash
pip install kubemq
```
```bash
npm install kubemq-js
```
```xml
io.kubemq.sdk
kubemq-sdk-Java
2.1.1
```
```bash
dotnet add package KubeMQ.SDK.CSharp
```
```kotlin
implementation("io.kubemq.sdk:kubemq-sdk-kotlin:2.1.0")
```
```bash
vcpkg install kubemq
```
```toml
[dependencies]
kubemq = "1.0"
tokio = { version = "1", features = ["full"] }
```
```bash
gem install kubemq
```
```elixir
def deps do
[{:kubemq, "~> 1.0"}]
end
```
### Create a Command Responder [#create-a-command-responder]
Start the responder first. It subscribes to incoming commands on `orders.process`, processes them, and sends back an execution status.
```go title="command_responder.go"
package main
import (
"context"
"fmt"
"log"
"time"
"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()
sub, err := client.SubscribeToCommands(ctx, "orders.process", "",
kubemq.WithOnCommandReceive(func(cmd *kubemq.CommandReceive) {
fmt.Printf("Received command: %s\n", cmd.Body)
resp := kubemq.NewCommandReply().
SetRequestId(cmd.Id).
SetResponseTo(cmd.ResponseTo).
SetExecutedAt(time.Now())
_ = client.SendCommandResponse(ctx, resp)
}),
kubemq.WithOnError(func(err error) {
log.Println("Error:", err)
}),
)
if err != nil {
log.Fatal(err)
}
defer sub.Unsubscribe()
fmt.Println("Command responder listening on 'orders.process'...")
<-ctx.Done()
}
```
```python title="command_responder.py"
import time
from kubemq.cq import Client as CQClient
from kubemq.cq import CommandsSubscription, CommandReceived, CommandResponse, CancellationToken
def on_command(request: CommandReceived) -> None:
print(f"Received command: {request.body.decode('utf-8')}")
client.send_response_message(
CommandResponse(command_received=request, is_executed=True)
)
def on_error(err):
print(f"Error: {err}")
client = CQClient(address="localhost:50000")
cancel = CancellationToken()
client.subscribe_to_commands(
subscription=CommandsSubscription(
channel="orders.process",
on_receive_command_callback=on_command,
on_error_callback=on_error,
),
cancel=cancel,
)
print("Command responder listening on 'orders.process'...")
time.sleep(3600)
```
```javascript title="command_responder.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000" });
client.subscribeToCommands({
channel: "orders.process",
onCommand: (cmd) => {
console.log("Received command:", Buffer.from(cmd.body).toString());
client.sendCommandResponse({ requestId: cmd.id, isExecuted: true });
},
onError: (err) => console.error("Error:", err.message),
});
console.log("Command responder listening on 'orders.process'...");
```
```java title="CommandResponder.java"
CQClient client = CQClient.builder()
.address("localhost:50000")
.clientId("order-responder")
.build();
client.subscribeToCommands(CommandsSubscription.builder()
.channel("orders.process")
.onReceiveCommandCallback(cmd -> {
System.out.println("Received: " + new String(cmd.getBody()));
return CommandResponseMessage.builder()
.requestId(cmd.getId())
.isExecuted(true)
.build();
})
.onErrorCallback(err -> System.err.println("Error: " + err.getMessage()))
.build());
System.out.println("Command responder listening on 'orders.process'...");
Thread.sleep(3600000);
client.close();
```
```csharp title="CommandResponder.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
Console.WriteLine("Command responder listening on 'orders.process'...");
await foreach (var cmd in client.SubscribeToCommandsAsync(
new CommandsSubscription { Channel = "orders.process" }))
{
Console.WriteLine($"Received: {Encoding.UTF8.GetString(cmd.Body.Span)}");
await client.SendCommandResponseAsync(new CommandResponse
{
RequestId = cmd.Id,
IsExecuted = true
});
}
```
```kotlin title="CommandResponder.kt"
val client = CQClient("localhost:50000")
client.subscribeToCommands(
channel = "orders.process",
onCommand = { cmd ->
println("Received command: ${String(cmd.body)}")
client.sendCommandResponse(
requestId = cmd.id, isExecuted = true
)
},
onError = { err -> System.err.println("Error: ${err.message}") }
)
println("Command responder listening on 'orders.process'...")
Thread.sleep(3600000)
client.close()
```
```cpp title="command_responder.cpp"
#include
#include
#include
auto client = kubemq::CQClient("localhost:50000");
client.subscribeToCommands("orders.process", "",
[&client](const kubemq::CommandReceive& cmd) {
std::cout << "Received command: " << cmd.body << std::endl;
client.sendCommandResponse(cmd.id, true);
},
[](const std::string& err) {
std::cerr << "Error: " << err << std::endl;
}
);
std::cout << "Command responder listening on 'orders.process'..." << std::endl;
std::this_thread::sleep_for(std::chrono::hours(1));
```
```rust title="command_responder.rs"
use kubemq::prelude::*;
use kubemq::CommandReplyBuilder;
use std::time::Duration;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
let rc = client.clone();
let sub = client
.subscribe_to_commands(
"orders.process",
"",
move |cmd| {
let c = rc.clone();
Box::pin(async move {
println!("Received command: {}", String::from_utf8_lossy(&cmd.body));
let reply = CommandReplyBuilder::new()
.request_id(&cmd.id)
.response_to(&cmd.response_to)
.build();
tokio::spawn(async move {
let _ = c.send_command_response(reply).await;
});
})
},
None,
)
.await?;
println!("Command responder listening on 'orders.process'...");
tokio::signal::ctrl_c().await.ok();
sub.unsubscribe().await;
client.close().await?;
Ok(())
}
```
```ruby title="command_responder.rb"
require 'kubemq'
client = KubeMQ::CQClient.new(address: 'localhost:50000', client_id: 'order-responder')
cancel = KubeMQ::CancellationToken.new
sub = KubeMQ::CQ::CommandsSubscription.new(channel: 'orders.process')
client.subscribe_to_commands(sub, cancellation_token: cancel,
on_error: ->(e) { puts "Error: #{e.message}" }) do |cmd|
puts "Received command: #{cmd.body}"
response = KubeMQ::CQ::CommandResponseMessage.new(
request_id: cmd.id,
reply_channel: cmd.reply_channel,
executed: true
)
client.send_response(response)
end
puts "Command responder listening on 'orders.process'..."
cancel.wait
```
```elixir title="command_responder.exs"
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-responder")
{:ok, _sub} =
KubeMQ.Client.subscribe_to_commands(client, "orders.process",
on_command: fn cmd ->
IO.puts("Received command: #{cmd.body}")
KubeMQ.CommandReply.new(
request_id: cmd.id,
response_to: cmd.reply_channel,
executed: true
)
end,
on_error: fn err -> IO.puts("Error: #{err.message}") end
)
IO.puts("Command responder listening on 'orders.process'...")
Process.sleep(:infinity)
```
### Send a Command [#send-a-command]
In a separate terminal, send a command. The sender blocks until the responder replies or the timeout expires.
```go title="send_command.go"
ctx := context.Background()
client, err := kubemq.NewClient(ctx,
kubemq.WithAddress("localhost", 50000),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
resp, err := client.SendCommand(ctx, kubemq.NewCommand().
SetChannel("orders.process").
SetBody([]byte(`{"action":"create","orderId":"ORD-1234"}`)).
SetTimeout(10 * time.Second))
if err != nil {
log.Fatal(err)
}
log.Printf("Executed: %v", resp.Executed)
```
```python title="send_command.py"
from kubemq.cq import Client as CQClient
from kubemq.cq import CommandMessage
with CQClient(address="localhost:50000") as client:
response = client.send_command(
CommandMessage(
channel="orders.process",
body=b'{"action":"create","orderId":"ORD-1234"}',
timeout_in_seconds=10,
)
)
print(f"Executed: {response.is_executed}")
```
```javascript title="send_command.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000" });
const response = await client.sendCommand({
channel: "orders.process",
body: Buffer.from(JSON.stringify({ action: "create", orderId: "ORD-1234" })),
timeoutInSeconds: 10,
});
console.log("Executed:", response.isExecuted);
```
```java title="SendCommand.java"
CQClient client = CQClient.builder()
.address("localhost:50000")
.clientId("order-sender")
.build();
CommandResponseMessage response = client.sendCommandRequest(
CommandMessage.builder()
.channel("orders.process")
.body("{\"action\":\"create\",\"orderId\":\"ORD-1234\"}".getBytes())
.timeout(10000)
.build());
System.out.println("Executed: " + response.isExecuted());
client.close();
```
```csharp title="SendCommand.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
var response = await client.SendCommandAsync(new CommandMessage
{
Channel = "orders.process",
Body = Encoding.UTF8.GetBytes("{\"action\":\"create\",\"orderId\":\"ORD-1234\"}"),
Timeout = TimeSpan.FromSeconds(10)
});
Console.WriteLine($"Executed: {response.IsExecuted}");
```
```kotlin title="SendCommand.kt"
val client = CQClient("localhost:50000")
val response = client.sendCommand(CommandMessage(
channel = "orders.process",
body = """{"action":"create","orderId":"ORD-1234"}""".toByteArray(),
timeout = 10000
))
println("Executed: ${response.isExecuted}")
client.close()
```
```cpp title="send_command.cpp"
#include
#include
auto client = kubemq::CQClient("localhost:50000");
kubemq::CommandMessage cmd;
cmd.channel = "orders.process";
cmd.body = R"({"action":"create","orderId":"ORD-1234"})";
cmd.timeout = 10000;
auto response = client.sendCommand(cmd);
std::cout << "Executed: " << response.isExecuted << std::endl;
```
```rust title="send_command.rs"
use kubemq::prelude::*;
use kubemq::CommandBuilder;
use std::time::Duration;
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
let command = CommandBuilder::new()
.channel("orders.process")
.body(br#"{"action":"create","orderId":"ORD-1234"}"#.to_vec())
.timeout(Duration::from_secs(10))
.build();
let response = client.send_command(command).await?;
println!("Executed: {}", response.executed);
client.close().await?;
```
```ruby title="send_command.rb"
require 'kubemq'
client = KubeMQ::CQClient.new(address: 'localhost:50000', client_id: 'order-sender')
msg = KubeMQ::CQ::CommandMessage.new(
channel: 'orders.process',
timeout: 10,
body: '{"action":"create","orderId":"ORD-1234"}'
)
result = client.send_command(msg)
puts "Executed: #{result.executed}"
client.close
```
```elixir title="send_command.exs"
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-sender")
command =
KubeMQ.Command.new(
channel: "orders.process",
body: ~s({"action":"create","orderId":"ORD-1234"}),
timeout: 10_000
)
{:ok, response} = KubeMQ.Client.send_command(client, command)
IO.puts("Executed: #{response.executed}")
KubeMQ.Client.close(client)
```
**Expected output (sender):** `Executed: true`
**Expected output (responder):** `Received command: {"action":"create","orderId":"ORD-1234"}`
### Create a Query Responder [#create-a-query-responder]
Queries work like commands but the responder can include data in the response body. Set up a query responder on `orders.lookup`.
```go title="query_responder.go"
sub, err := client.SubscribeToQueries(ctx, "orders.lookup", "",
kubemq.WithOnQueryReceive(func(query *kubemq.QueryReceive) {
fmt.Printf("Query for: %s\n", query.Body)
resp := kubemq.NewQueryReply().
SetRequestId(query.Id).
SetResponseTo(query.ResponseTo).
SetBody([]byte(`{"orderId":"ORD-1234","status":"shipped","total":99.99}`)).
SetExecutedAt(time.Now())
_ = client.SendQueryResponse(ctx, resp)
}),
kubemq.WithOnError(func(err error) {
log.Println("Error:", err)
}),
)
```
```python title="query_responder.py"
from kubemq.cq import QueriesSubscription, QueryReceived, QueryResponse
def on_query(request: QueryReceived) -> None:
print(f"Query for: {request.body.decode('utf-8')}")
client.send_response_message(
QueryResponse(
query_received=request,
is_executed=True,
body=b'{"orderId":"ORD-1234","status":"shipped","total":99.99}',
)
)
client.subscribe_to_queries(
subscription=QueriesSubscription(
channel="orders.lookup",
on_receive_query_callback=on_query,
on_error_callback=on_error,
),
cancel=cancel,
)
```
```javascript title="query_responder.js"
client.subscribeToQueries({
channel: "orders.lookup",
onQuery: (query) => {
console.log("Query for:", Buffer.from(query.body).toString());
client.sendQueryResponse({
requestId: query.id,
isExecuted: true,
body: Buffer.from(
JSON.stringify({ orderId: "ORD-1234", status: "shipped", total: 99.99 })
),
});
},
onError: (err) => console.error("Error:", err.message),
});
```
```java title="QueryResponder.java"
client.subscribeToQueries(QueriesSubscription.builder()
.channel("orders.lookup")
.onReceiveQueryCallback(query -> {
System.out.println("Query for: " + new String(query.getBody()));
return QueryResponseMessage.builder()
.requestId(query.getId())
.isExecuted(true)
.body("{\"orderId\":\"ORD-1234\",\"status\":\"shipped\",\"total\":99.99}".getBytes())
.build();
})
.onErrorCallback(err -> System.err.println("Error: " + err.getMessage()))
.build());
```
```csharp title="QueryResponder.cs"
await foreach (var query in client.SubscribeToQueriesAsync(
new QueriesSubscription { Channel = "orders.lookup" }))
{
Console.WriteLine($"Query for: {Encoding.UTF8.GetString(query.Body.Span)}");
await client.SendQueryResponseAsync(new QueryResponse
{
RequestId = query.Id,
IsExecuted = true,
Body = Encoding.UTF8.GetBytes(
"{\"orderId\":\"ORD-1234\",\"status\":\"shipped\",\"total\":99.99}")
});
}
```
```kotlin title="QueryResponder.kt"
client.subscribeToQueries(
channel = "orders.lookup",
onQuery = { query ->
println("Query for: ${String(query.body)}")
client.sendQueryResponse(
requestId = query.id,
isExecuted = true,
body = """{"orderId":"ORD-1234","status":"shipped","total":99.99}""".toByteArray()
)
},
onError = { err -> System.err.println("Error: ${err.message}") }
)
```
```cpp title="query_responder.cpp"
client.subscribeToQueries("orders.lookup", "",
[&client](const kubemq::QueryReceive& query) {
std::cout << "Query for: " << query.body << std::endl;
client.sendQueryResponse(query.id, true,
R"({"orderId":"ORD-1234","status":"shipped","total":99.99})");
},
[](const std::string& err) {
std::cerr << "Error: " << err << std::endl;
}
);
```
```rust title="query_responder.rs"
use kubemq::QueryReplyBuilder;
let rc = client.clone();
let sub = client
.subscribe_to_queries(
"orders.lookup",
"",
move |query| {
let c = rc.clone();
Box::pin(async move {
println!("Query for: {}", String::from_utf8_lossy(&query.body));
let reply = QueryReplyBuilder::new()
.request_id(&query.id)
.response_to(&query.response_to)
.body(br#"{"orderId":"ORD-1234","status":"shipped","total":99.99}"#.to_vec())
.build();
tokio::spawn(async move {
let _ = c.send_query_response(reply).await;
});
})
},
None,
)
.await?;
```
```ruby title="query_responder.rb"
sub = KubeMQ::CQ::QueriesSubscription.new(channel: 'orders.lookup')
client.subscribe_to_queries(sub, cancellation_token: cancel,
on_error: ->(e) { puts "Error: #{e.message}" }) do |query|
puts "Query for: #{query.body}"
response = KubeMQ::CQ::QueryResponseMessage.new(
request_id: query.id,
reply_channel: query.reply_channel,
executed: true,
body: '{"orderId":"ORD-1234","status":"shipped","total":99.99}'
)
client.send_response(response)
end
```
```elixir title="query_responder.exs"
{:ok, _sub} =
KubeMQ.Client.subscribe_to_queries(client, "orders.lookup",
on_query: fn query ->
IO.puts("Query for: #{query.body}")
KubeMQ.QueryReply.new(
request_id: query.id,
response_to: query.reply_channel,
executed: true,
body: ~s({"orderId":"ORD-1234","status":"shipped","total":99.99})
)
end,
on_error: fn err -> IO.puts("Error: #{err.message}") end
)
```
### Send a Query [#send-a-query]
Send a query to retrieve order data. Unlike commands, the response body is preserved.
```go title="send_query.go"
resp, err := client.SendQuery(ctx, kubemq.NewQuery().
SetChannel("orders.lookup").
SetBody([]byte("ORD-1234")).
SetTimeout(10 * time.Second))
if err != nil {
log.Fatal(err)
}
log.Printf("Order data: %s", resp.Body)
```
```python title="send_query.py"
from kubemq.cq import Client as CQClient
from kubemq.cq import QueryMessage
with CQClient(address="localhost:50000") as client:
response = client.send_query(
QueryMessage(
channel="orders.lookup",
body=b"ORD-1234",
timeout_in_seconds=10,
)
)
print(f"Order data: {response.body.decode('utf-8')}")
```
```javascript title="send_query.js"
const response = await client.sendQuery({
channel: "orders.lookup",
body: Buffer.from("ORD-1234"),
timeoutInSeconds: 10,
});
console.log("Order data:", Buffer.from(response.body).toString());
```
```java title="SendQuery.java"
QueryResponseMessage response = client.sendQueryRequest(
QueryMessage.builder()
.channel("orders.lookup")
.body("ORD-1234".getBytes())
.timeout(10000)
.build());
System.out.println("Order data: " + new String(response.getBody()));
```
```csharp title="SendQuery.cs"
var response = await client.SendQueryAsync(new QueryMessage
{
Channel = "orders.lookup",
Body = Encoding.UTF8.GetBytes("ORD-1234"),
Timeout = TimeSpan.FromSeconds(10)
});
Console.WriteLine($"Order data: {Encoding.UTF8.GetString(response.Body.Span)}");
```
```kotlin title="SendQuery.kt"
val response = client.sendQuery(QueryMessage(
channel = "orders.lookup",
body = "ORD-1234".toByteArray(),
timeout = 10000
))
println("Order data: ${String(response.body)}")
```
```cpp title="send_query.cpp"
kubemq::QueryMessage query;
query.channel = "orders.lookup";
query.body = "ORD-1234";
query.timeout = 10000;
auto response = client.sendQuery(query);
std::cout << "Order data: " << response.body << std::endl;
```
```rust title="send_query.rs"
use kubemq::QueryBuilder;
use std::time::Duration;
let query = QueryBuilder::new()
.channel("orders.lookup")
.body(b"ORD-1234".to_vec())
.timeout(Duration::from_secs(10))
.build();
let response = client.send_query(query).await?;
println!("Order data: {}", String::from_utf8_lossy(&response.body));
```
```ruby title="send_query.rb"
msg = KubeMQ::CQ::QueryMessage.new(
channel: 'orders.lookup',
timeout: 10,
body: 'ORD-1234'
)
result = client.send_query(msg)
puts "Order data: #{result.body}"
```
```elixir title="send_query.exs"
query =
KubeMQ.Query.new(
channel: "orders.lookup",
body: "ORD-1234",
timeout: 10_000
)
{:ok, response} = KubeMQ.Client.send_query(client, query)
IO.puts("Order data: #{response.body}")
```
Unlike commands, query responses preserve the full response body and metadata. This makes queries ideal for data retrieval operations.
### Run the Example [#run-the-example]
1. Start the **responder** in one terminal (handles both commands and queries)
2. Run the **command sender** in a separate terminal
3. Run the **query sender** in a separate terminal
4. Observe the responses in each terminal
## What Just Happened [#what-just-happened]
1. The **responder** subscribed to both command and query channels
2. The **sender** sent a command — the responder processed it and returned `Executed: true` (response body stripped)
3. The **sender** sent a query — the responder returned the full order data in the response body (preserved)
## Commands vs Queries Summary [#commands-vs-queries-summary]
| Aspect | Command | Query |
| --------------------- | -------------------------- | ------------------------------ |
| **Response body** | Stripped (always `nil`) | Preserved |
| **Response metadata** | Stripped | Preserved |
| **CacheHit field** | Stripped | Preserved |
| **Use for** | Writes, mutations, actions | Reads, lookups, data retrieval |
## Next Steps [#next-steps]
# RPC — Commands & Queries (/learn/rpc)
Think of RPC like a phone call — you dial a number, ask a question, and wait on the line for an answer. If nobody picks up within a set time, you hang up and try again. KubeMQ RPC brings this synchronous request-reply model to messaging infrastructure.
KubeMQ implements RPC through two complementary operation types following the CQRS (Command Query Responsibility Segregation) principle: **Commands** for writes and **Queries** for reads.
**The concept it implements.** RPC is KubeMQ's realization of the [request/reply interaction style](/learn/concepts/interaction-styles) — the sender blocks on a single matched response. The timeout-and-retry behavior maps to the [delivery guarantees](/learn/concepts/delivery-guarantees) you choose at the application level: a request either gets exactly one answer or a timeout error.
## Commands vs Queries [#commands-vs-queries]
| Aspect | Commands | Queries |
| --------------------- | ------------------------------------------------ | ------------------------------------------------- |
| **Purpose** | State-changing operations (writes, mutations) | Read-only operations (data lookups) |
| **Response body** | Stripped — sender receives only execution status | Preserved — sender receives full response payload |
| **Response metadata** | Stripped | Preserved |
| **Caching** | Not supported | Supported via `CacheKey` / `CacheTTL` |
| **Use cases** | Order placement, device control, config changes | Data lookups, status checks, service reads |
Commands tell the system to **do something** and return only a success/failure indicator. Queries **ask for data** and return the full response body and metadata.
## How It Works [#how-it-works]
*Request/reply: the sender blocks while KubeMQ routes the request to a responder and delivers the single matched response back.*
The sender publishes a request to a named channel with a timeout. KubeMQ routes the request to a subscribed responder (or load-balances across a group of responders). The responder processes the request and sends a response back through KubeMQ. If no response arrives before the timeout expires, the sender receives a timeout error.
## Key Features [#key-features]
* **Synchronous request-reply** — sender blocks until a response arrives or timeout expires
* **Commands and Queries** — separate semantics for writes and reads following CQRS
* **Response caching** — server-side caching for queries with configurable TTL
* **Load balancing** — distribute requests across multiple responders using queue groups
* **Configurable timeouts** — per-request timeout in milliseconds
* **gRPC and REST** — use any transport protocol
## Quick Example [#quick-example]
```go title="send_command.go"
package main
import (
"context"
"log"
"time"
"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()
resp, err := client.SendCommand(ctx, kubemq.NewCommand().
SetChannel("orders.process").
SetBody([]byte(`{"action":"create","orderId":"ORD-1234"}`)).
SetTimeout(10 * time.Second))
if err != nil {
log.Fatal(err)
}
log.Printf("Command executed: %v", resp.Executed)
}
```
```python title="send_command.py"
from kubemq.cq import Client as CQClient
from kubemq.cq import CommandMessage
client = CQClient(address="localhost:50000")
response = client.send_command(
CommandMessage(
channel="orders.process",
body=b'{"action":"create","orderId":"ORD-1234"}',
timeout_in_seconds=10,
)
)
print(f"Command executed: {response.is_executed}")
client.close()
```
```javascript title="send_command.js"
const { KubeMQClient } = require("kubemq-js");
const client = new KubeMQClient({ address: "localhost:50000" });
const response = await client.sendCommand({
channel: "orders.process",
body: Buffer.from(JSON.stringify({ action: "create", orderId: "ORD-1234" })),
timeoutInSeconds: 10,
});
console.log("Command executed:", response.isExecuted);
```
```java title="SendCommand.java"
CQClient client = CQClient.builder()
.address("localhost:50000")
.clientId("order-service")
.build();
CommandResponseMessage response = client.sendCommandRequest(
CommandMessage.builder()
.channel("orders.process")
.body("{\"action\":\"create\",\"orderId\":\"ORD-1234\"}".getBytes())
.timeout(10000)
.build());
System.out.println("Executed: " + response.isExecuted());
client.close();
```
```csharp title="SendCommand.cs"
await using var client = new KubeMQClient(new KubeMQClientOptions());
await client.ConnectAsync();
var response = await client.SendCommandAsync(new CommandMessage
{
Channel = "orders.process",
Body = Encoding.UTF8.GetBytes("{\"action\":\"create\",\"orderId\":\"ORD-1234\"}"),
Timeout = TimeSpan.FromSeconds(10)
});
Console.WriteLine($"Executed: {response.IsExecuted}");
```
```kotlin title="SendCommand.kt"
val client = CQClient("localhost:50000")
val response = client.sendCommand(CommandMessage(
channel = "orders.process",
body = """{"action":"create","orderId":"ORD-1234"}""".toByteArray(),
timeout = 10000
))
println("Command executed: ${response.isExecuted}")
client.close()
```
```cpp title="send_command.cpp"
#include
#include
auto client = kubemq::CQClient("localhost:50000");
kubemq::CommandMessage cmd;
cmd.channel = "orders.process";
cmd.body = R"({"action":"create","orderId":"ORD-1234"})";
cmd.timeout = 10000;
auto response = client.sendCommand(cmd);
std::cout << "Command executed: " << response.isExecuted << std::endl;
```
```rust title="send_command.rs"
use kubemq::prelude::*;
use kubemq::CommandBuilder;
use std::time::Duration;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
let command = CommandBuilder::new()
.channel("orders.process")
.body(br#"{"action":"create","orderId":"ORD-1234"}"#.to_vec())
.timeout(Duration::from_secs(10))
.build();
let response = client.send_command(command).await?;
println!("Command executed: {}", response.executed);
client.close().await?;
Ok(())
}
```
```ruby title="send_command.rb"
require 'kubemq'
client = KubeMQ::CQClient.new(address: 'localhost:50000', client_id: 'order-service')
msg = KubeMQ::CQ::CommandMessage.new(
channel: 'orders.process',
body: '{"action":"create","orderId":"ORD-1234"}',
timeout: 10
)
result = client.send_command(msg)
puts "Command executed: #{result.executed}"
client.close
```
```elixir title="send_command.exs"
{:ok, client} =
KubeMQ.Client.start_link(address: "localhost:50000", client_id: "order-service")
command =
KubeMQ.Command.new(
channel: "orders.process",
body: ~s({"action":"create","orderId":"ORD-1234"}),
timeout: 10_000
)
case KubeMQ.Client.send_command(client, command) do
{:ok, response} -> IO.puts("Command executed: #{response.executed}")
{:error, err} -> IO.puts("Command failed: #{err.message}")
end
KubeMQ.Client.close(client)
```
## When to Use RPC [#when-to-use-rpc]
| Scenario | RPC | Events / Queues |
| ---------------------------- | -------------------- | ---------------------- |
| Service-to-service API calls | ✅ Best choice | Not suitable |
| Data lookups and reads | ✅ Queries | Possible but awkward |
| Write confirmations | ✅ Commands | Queues with ack |
| CQRS implementation | ✅ Commands + Queries | Events for projections |
| Fire-and-forget broadcasts | ❌ Blocks on response | ✅ Use Events |
| Reliable async processing | ❌ Blocks on response | ✅ Use Queues |
Need fire-and-forget delivery? Use [Events](/learn/events) for broadcasts or [Queues](/learn/queues) for reliable processing.
Commands and queries are also available via the [CloudEvents protocol](/connectors/cloudevents/how-to/commands-queries) — use any language with a CloudEvents SDK, no KubeMQ client library needed.
## Learn More [#learn-more]
# Commands & Queries Reference (/learn/rpc/reference)
## Request Model [#request-model]
Commands and queries share the same request structure. The `RequestTypeData` field determines whether the request is treated as a command or query.
## Response Model [#response-model]
## Command vs Query Response Differences [#command-vs-query-response-differences]
| Response Field | Command | Query |
| -------------- | ------------------------- | ---------------------- |
| `Body` | Always `nil` (stripped) | Preserved |
| `Metadata` | Always `""` (stripped) | Preserved |
| `CacheHit` | Always `false` (stripped) | Preserved |
| `ReplyChannel` | Always `""` (stripped) | Always `""` (stripped) |
| `Executed` | Preserved | Preserved |
| `Error` | Preserved | Preserved |
## Validation Rules [#validation-rules]
### Channel Name [#channel-name]
| Rule | Constraint | Error Code |
| --------------- | ------------------------- | ---------- |
| Required | Cannot be empty | 102 |
| No trailing dot | Cannot end with `.` | 119 |
| No whitespace | Cannot contain spaces | 108 |
| No wildcards | Cannot contain `*` or `>` | 107 |
Valid channel name regex: `^[^\s*>]+[^.]$`
### Client ID [#client-id]
| Rule | Constraint | Error Code |
| ------------ | ----------------------------- | ---------- |
| Required | Cannot be empty | 101 |
| Alphanumeric | Must match `^[a-zA-Z0-9_-]+$` | — |
### Request Content [#request-content]
At least one of `Body` or `Metadata` must be provided. If both are empty, the request is rejected with error code 115.
### Timeout [#timeout]
| Rule | Constraint | Error Code |
| -------- | ------------------------- | ---------- |
| Required | Must be greater than zero | 109 |
### Cache (Queries Only) [#cache-queries-only]
| Rule | Constraint | Error Code |
| ----------------- | -------------------------------------------- | ---------- |
| CacheTTL required | If `CacheKey` is set, `CacheTTL` must be > 0 | 116 |
## Subscription Model [#subscription-model]
### Consumer Groups [#consumer-groups]
When multiple responders specify the same `group` value on the same channel:
* Each request is delivered to exactly **one** member of the group (round-robin)
* When `group` is empty, every responder receives every request (fan-out)
* Groups are independent per channel
* There is no limit on the number of group members
See [Load Balancing](/learn/rpc/how-to/load-balancing) for examples.
## Caching Configuration [#caching-configuration]
KubeMQ provides server-side response caching for queries. When a query includes a `CacheKey` and `CacheTTL`:
1. KubeMQ checks the in-memory cache for an entry matching `CacheKey`
2. **Cache hit:** Returns the cached response with `CacheHit: true` (responder is not called)
3. **Cache miss:** Routes the query to a responder, caches the response, and returns it with `CacheHit: false`
| Setting | Value |
| ------------------ | -------------------------------------------------- |
| Storage | In-memory TTL cache |
| Default expiration | Per-entry, specified by `CacheTTL` in milliseconds |
| Cleanup interval | Every 10 seconds |
| Persistence | None — cache is cleared on server restart |
Commands do **not** support caching — the `CacheKey` and `CacheTTL` fields are ignored for command requests.
See [Query Caching](/learn/rpc/tutorials/query-caching) for a step-by-step tutorial.
## Transport Protocols [#transport-protocols]
### gRPC [#grpc]
| Method | Type | Description |
| ------------------------------------------------- | ------------- | -------------------------------- |
| `SendRequest(Request) → Response` | Unary | Send command or query |
| `SendResponse(Response) → Empty` | Unary | Send response back to requester |
| `SubscribeToRequests(Subscribe) → stream Request` | Server stream | Subscribe to commands or queries |
Default port: `50000`
### REST [#rest]
| Method | Path | Description |
| ------ | --------------------- | ------------------------------------------- |
| `POST` | `/send/request` | Send command or query |
| `POST` | `/send/response` | Send RPC response |
| `GET` | `/subscribe/requests` | WebSocket: subscribe to commands or queries |
Default port: `9090`
REST subscription query parameters:
| Parameter | Description | Example |
| ---------------- | ----------------------- | ---------------- |
| `client_id` | Client identifier | `my-responder` |
| `channel` | Channel name | `orders.process` |
| `group` | Load balancing group | `workers` |
| `subscribe_type` | `commands` or `queries` | `commands` |
## Internal Channel Mapping [#internal-channel-mapping]
| Pattern | Channel Prefix | Example |
| -------- | -------------- | ---------------------------- |
| Commands | `_COMMANDS_.` | `_COMMANDS_.orders.process` |
| Queries | `_QUERIES_.` | `_QUERIES_.inventory.lookup` |
## Middleware Chain [#middleware-chain]
### Command Sender [#command-sender]
```text
Request → Logging → Monitor → Metrics → broker request
```
### Query Sender [#query-sender]
```text
Request → Logging → Monitor → Cache → Metrics → broker request
```
### Receiver (Commands and Queries) [#receiver-commands-and-queries]
```text
broker queue-subscribe → Logging → reqCh delivery
```
## Error Codes [#error-codes]
### Input Validation [#input-validation]
| Code | Error | Description |
| ---- | ----------------- | ------------------------------------------------ |
| 101 | Invalid ClientID | ClientID is empty |
| 102 | Invalid Channel | Channel is empty |
| 107 | Invalid Channel | Channel contains wildcards (`*` or `>`) |
| 108 | Invalid Channel | Channel contains whitespace |
| 109 | Invalid Timeout | Timeout is zero or negative |
| 115 | Invalid Request | Both body and metadata are empty |
| 116 | Invalid CacheTTL | CacheKey is set but CacheTTL is zero or negative |
| 117 | Invalid RequestID | RequestID is empty (on response) |
| 119 | Invalid Channel | Channel ends with `.` |
### Runtime Errors [#runtime-errors]
| Code | Error | Description |
| ---- | ----------------------- | ------------------------------------------------ |
| 206 | Invalid Request Type | Request type is not Command or Query |
| 207 | Invalid Subscribe Type | Subscribe type is not Commands or Queries |
| 301 | Request Timeout | No reply received before timeout expired |
| 302 | Connection Unavailable | broker connection is down |
| 303 | Invalid Response Format | Reply data cannot be unmarshaled |
| 409 | Shutdown Mode | Server is shutting down, all operations rejected |
| 412 | Access Denied | Authorization denied for the resource |
## Delivery Semantics [#delivery-semantics]
| Aspect | Behavior |
| ------------------ | ----------------------------------------------------------------- |
| Delivery guarantee | **At-most-once** (request is sent once, no automatic retry) |
| Ordering | Requests are independent (no ordering guarantee between requests) |
| Timeout | Sender blocks until response arrives or timeout expires |
| Acknowledgment | Implicit — response is the acknowledgment |
## SDK Quick Reference [#sdk-quick-reference]
```go
// Send Command
client.SendCommand(ctx, kubemq.NewCommand().
SetChannel("ch").SetBody([]byte("data")).SetTimeout(10*time.Second))
// Send Query
client.SendQuery(ctx, kubemq.NewQuery().
SetChannel("ch").SetBody([]byte("data")).SetTimeout(10*time.Second))
// Send Query with Cache
client.SendQuery(ctx, kubemq.NewQuery().
SetChannel("ch").SetBody([]byte("data")).SetTimeout(10*time.Second).
SetCacheKey("key").SetCacheTTL(60*time.Second))
// Subscribe to Commands
client.SubscribeToCommands(ctx, "ch", "group",
kubemq.WithOnCommandReceive(handler),
kubemq.WithOnError(errHandler))
// Subscribe to Queries
client.SubscribeToQueries(ctx, "ch", "group",
kubemq.WithOnQueryReceive(handler),
kubemq.WithOnError(errHandler))
```
```python
# Send Command
client.send_command(CommandMessage(
channel="ch", body=b"data", timeout_in_seconds=10))
# Send Query
client.send_query(QueryMessage(
channel="ch", body=b"data", timeout_in_seconds=10))
# Send Query with Cache
client.send_query(QueryMessage(
channel="ch", body=b"data", timeout_in_seconds=10,
cache_key="key", cache_ttl_in_seconds=60))
# Subscribe to Commands
client.subscribe_to_commands(CommandsSubscription(
channel="ch", group="group",
on_receive_command_callback=handler,
on_error_callback=err_handler), cancel=cancel)
# Subscribe to Queries
client.subscribe_to_queries(QueriesSubscription(
channel="ch", group="group",
on_receive_query_callback=handler,
on_error_callback=err_handler), cancel=cancel)
```
```javascript
// Send Command
await client.sendCommand({
channel: "ch", body: Buffer.from("data"), timeoutInSeconds: 10 });
// Send Query
await client.sendQuery({
channel: "ch", body: Buffer.from("data"), timeoutInSeconds: 10 });
// Send Query with Cache
await client.sendQuery({
channel: "ch", body: Buffer.from("data"), timeoutInSeconds: 10,
cacheKey: "key", cacheTTL: 60000 });
// Subscribe to Commands
client.subscribeToCommands({
channel: "ch", group: "group",
onCommand: handler, onError: errHandler });
// Subscribe to Queries
client.subscribeToQueries({
channel: "ch", group: "group",
onQuery: handler, onError: errHandler });
```
```java
// Send Command
client.sendCommandRequest(CommandMessage.builder()
.channel("ch").body("data".getBytes()).timeout(10000).build());
// Send Query
client.sendQueryRequest(QueryMessage.builder()
.channel("ch").body("data".getBytes()).timeout(10000).build());
// Send Query with Cache
client.sendQueryRequest(QueryMessage.builder()
.channel("ch").body("data".getBytes()).timeout(10000)
.cacheKey("key").cacheTTL(60000).build());
// Subscribe to Commands
client.subscribeToCommands(CommandsSubscription.builder()
.channel("ch").group("group")
.onReceiveCommandCallback(handler)
.onErrorCallback(errHandler).build());
// Subscribe to Queries
client.subscribeToQueries(QueriesSubscription.builder()
.channel("ch").group("group")
.onReceiveQueryCallback(handler)
.onErrorCallback(errHandler).build());
```
```csharp
// Send Command
await client.SendCommandAsync(new CommandMessage {
Channel = "ch", Body = Encoding.UTF8.GetBytes("data"),
Timeout = TimeSpan.FromSeconds(10) });
// Send Query
await client.SendQueryAsync(new QueryMessage {
Channel = "ch", Body = Encoding.UTF8.GetBytes("data"),
Timeout = TimeSpan.FromSeconds(10) });
// Send Query with Cache
await client.SendQueryAsync(new QueryMessage {
Channel = "ch", Body = Encoding.UTF8.GetBytes("data"),
Timeout = TimeSpan.FromSeconds(10),
CacheKey = "key", CacheTTL = TimeSpan.FromSeconds(60) });
// Subscribe to Commands
await foreach (var cmd in client.SubscribeToCommandsAsync(
new CommandsSubscription { Channel = "ch", Group = "group" })) { }
// Subscribe to Queries
await foreach (var q in client.SubscribeToQueriesAsync(
new QueriesSubscription { Channel = "ch", Group = "group" })) { }
```
```kotlin
// Send Command
client.sendCommand(CommandMessage(
channel = "ch", body = "data".toByteArray(), timeout = 10000))
// Send Query
client.sendQuery(QueryMessage(
channel = "ch", body = "data".toByteArray(), timeout = 10000))
// Send Query with Cache
client.sendQuery(QueryMessage(
channel = "ch", body = "data".toByteArray(), timeout = 10000,
cacheKey = "key", cacheTTL = 60000))
// Subscribe to Commands
client.subscribeToCommands(
channel = "ch", group = "group",
onCommand = handler, onError = errHandler)
// Subscribe to Queries
client.subscribeToQueries(
channel = "ch", group = "group",
onQuery = handler, onError = errHandler)
```
```cpp
// Send Command
kubemq::CommandMessage cmd;
cmd.channel = "ch"; cmd.body = "data"; cmd.timeout = 10000;
client.sendCommand(cmd);
// Send Query
kubemq::QueryMessage query;
query.channel = "ch"; query.body = "data"; query.timeout = 10000;
client.sendQuery(query);
// Send Query with Cache
query.cacheKey = "key"; query.cacheTTL = 60000;
client.sendQuery(query);
// Subscribe to Commands
client.subscribeToCommands("ch", "group", handler, errHandler);
// Subscribe to Queries
client.subscribeToQueries("ch", "group", handler, errHandler);
```
```rust
// Send Command
let command = CommandBuilder::new()
.channel("ch").body(b"data".to_vec())
.timeout(Duration::from_secs(10)).build();
client.send_command(command).await?;
// Send Query
let query = QueryBuilder::new()
.channel("ch").body(b"data".to_vec())
.timeout(Duration::from_secs(10)).build();
client.send_query(query).await?;
// Send Query with Cache
let query = QueryBuilder::new()
.channel("ch").body(b"data".to_vec())
.timeout(Duration::from_secs(10))
.cache_key("key").cache_ttl(Duration::from_secs(60)).build();
client.send_query(query).await?;
// Subscribe to Commands
client.subscribe_to_commands("ch", "group", handler, None).await?;
// Subscribe to Queries
client.subscribe_to_queries("ch", "group", handler, None).await?;
```
```ruby
# Send Command
msg = KubeMQ::CQ::CommandMessage.new(
channel: "ch", body: "data", timeout: 10)
client.send_command(msg)
# Send Query
msg = KubeMQ::CQ::QueryMessage.new(
channel: "ch", body: "data", timeout: 10)
client.send_query(msg)
# Send Query with Cache
msg = KubeMQ::CQ::QueryMessage.new(
channel: "ch", body: "data", timeout: 10,
cache_key: "key", cache_ttl: 60)
client.send_query(msg)
# Subscribe to Commands
sub = KubeMQ::CQ::CommandsSubscription.new(channel: "ch", group: "group")
client.subscribe_to_commands(sub, cancellation_token: cancel,
on_error: err_handler) { |cmd| handler.call(cmd) }
# Subscribe to Queries
sub = KubeMQ::CQ::QueriesSubscription.new(channel: "ch", group: "group")
client.subscribe_to_queries(sub, cancellation_token: cancel,
on_error: err_handler) { |query| handler.call(query) }
```
```elixir
# Send Command
command = KubeMQ.Command.new(
channel: "ch", body: "data", timeout: 10_000)
KubeMQ.Client.send_command(client, command)
# Send Query
query = KubeMQ.Query.new(
channel: "ch", body: "data", timeout: 10_000)
KubeMQ.Client.send_query(client, query)
# Send Query with Cache
query = KubeMQ.Query.new(
channel: "ch", body: "data", timeout: 10_000,
cache_key: "key", cache_ttl: 60_000)
KubeMQ.Client.send_query(client, query)
# Subscribe to Commands
KubeMQ.Client.subscribe_to_commands(client, "ch",
group: "group", on_command: handler, on_error: err_handler)
# Subscribe to Queries
KubeMQ.Client.subscribe_to_queries(client, "ch",
group: "group", on_query: handler, on_error: err_handler)
```
## Related [#related]
* [Getting Started](/learn/rpc/getting-started) — send your first command and query
* [Configure Timeouts](/learn/rpc/how-to/timeout-configuration) — per-request timeouts and retries
* [Load Balancing](/learn/rpc/how-to/load-balancing) — distribute requests across responders
* [Events Reference](/learn/events/reference) — for the fire-and-forget pattern
* [Queues Reference](/learn/queues/reference) — for guaranteed delivery
# .NET Aspire (/integrations/aspire)
The KubeMQ .NET Aspire integration wires the [KubeMQ](https://kubemq.io) message broker into the [.NET Aspire](https://learn.microsoft.com/dotnet/aspire/) application model. It follows the standard Aspire two-package model: `KubeMQ.Aspire.Hosting` provisions a KubeMQ container in your AppHost, and `KubeMQ.Aspire.Client` configures an `IKubeMQClient` in each consuming service — complete with health checks, OpenTelemetry, and keyed dependency injection. The client is a **native gRPC SDK client** that connects to the broker on port `50000`; there is no connector to enable.
New to the idea? See [what is an integration](/integrations#what-an-integration-is) for how SDK-level integrations differ from server-side [connectors](/connectors).
## Why KubeMQ + .NET Aspire? [#why-kubemq--net-aspire]
* **Container auto-provisioning** — `AddKubeMQ("messaging")` in the AppHost runs a KubeMQ broker container with the gRPC, REST, and Dashboard endpoints already mapped
* **Zero-config connection strings** — `WithReference(messaging)` injects the broker address into each service as an Aspire connection string; `AddKubeMQClient("messaging")` reads it back automatically, so no host or port is hard-coded
* **Built-in health checks** — readiness and liveness checks are registered out of the box with `ready` and `live` tags, surfacing the SDK's connection state to the Aspire dashboard and Kubernetes probes
* **OpenTelemetry on by default** — the SDK's `KubeMQ.Sdk` tracing source and meter are registered automatically, so traces and metrics flow into the Aspire telemetry pipeline with no extra code
* **Keyed DI for multiple brokers** — `AddKeyedKubeMQClient` registers a distinct `IKubeMQClient` per named broker, resolved with `[FromKeyedServices(...)]`
## The two packages [#the-two-packages]
| Package | Project | Responsibility |
| ----------------------- | ------- | ------------------------------------------------------------------------- |
| `KubeMQ.Aspire.Hosting` | AppHost | Provision KubeMQ containers in the Aspire AppHost |
| `KubeMQ.Aspire.Client` | Service | Configure `IKubeMQClient` with health checks, OpenTelemetry, and keyed DI |
## Install [#install]
Add the hosting package to your **AppHost** project:
```bash
dotnet add package KubeMQ.Aspire.Hosting
```
Add the client package to each **service** project that talks to KubeMQ:
```bash
dotnet add package KubeMQ.Aspire.Client
```
## Quick start [#quick-start]
Provision the broker in the AppHost and reference it from a service. The connection string flows from the container resource into the service automatically.
```csharp title="AppHost/Program.cs"
var builder = DistributedApplication.CreateBuilder(args);
var kubemqKey = builder.AddParameter("kubemq-key", secret: true);
var messaging = builder.AddKubeMQ("messaging")
.WithEnvironment("KUBEMQ_LICENSE_KEY", kubemqKey)
.WithDataVolume();
builder.AddProject("webapi")
.WithReference(messaging)
.WaitFor(messaging);
builder.Build().Run();
```
```csharp title="MyWebApi/Program.cs"
var builder = WebApplication.CreateBuilder(args);
builder.AddKubeMQClient("messaging");
var app = builder.Build();
app.Run();
```
`AddKubeMQClient` registers `IKubeMQClient` as a singleton and resolves the broker address from the `"messaging"` connection string injected by `WithReference`. For the full walkthrough — parameters, secrets, and verifying the connection — see [Getting Started](/integrations/aspire/tutorials/getting-started).
## Architecture [#architecture]
The AppHost provisions the KubeMQ container and injects its address as a connection string into each referencing service. In the service, `AddKubeMQClient` reads that connection string, constructs an `IKubeMQClient` that speaks gRPC to the broker on port `50000`, and registers the health checks and OpenTelemetry instrumentation as side outputs into the Aspire pipeline.
*The AppHost provisions the broker container and injects its `host:port` address; the service resolves it by connection name, builds an `IKubeMQClient`, and gets health checks and telemetry for free.*
## What the integration provisions [#what-the-integration-provisions]
The hosting package provisions a real KubeMQ container; the client package layers Aspire conventions on top of the KubeMQ .NET SDK.
| Feature | Detail |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Container image** | `AddKubeMQ` runs `europe-docker.pkg.dev/kubemq/images/kubemq-next:latest` |
| **gRPC endpoint** | Target port `50000` (TCP) — the primary client connection |
| **REST endpoint** | Target port `9090` (HTTP) |
| **Dashboard endpoint** | Target port `8080` (HTTP) |
| **Persistent lifetime** | The container uses `ContainerLifetime.Persistent`, so it survives AppHost restarts |
| **Persistent storage** | `WithDataVolume()` binds a volume to `/store` for durable messages |
| **License key** | `WithEnvironment("KUBEMQ_LICENSE_KEY", parameter)` sets the [license key](/configure/reference/core#license) on the container from a secret parameter |
| **Image override** | `WithImageTag()` overrides the default image tag |
| **Health checks** | Readiness (`ready`) and liveness (`live`) checks reporting the SDK connection state |
| **OpenTelemetry** | Tracing source and meter `KubeMQ.Sdk` registered by default |
| **Keyed DI** | `AddKeyedKubeMQClient` for multiple named brokers in one service |
## Supported runtime [#supported-runtime]
| Requirement | Version |
| ------------------- | --------------------------------------------- |
| Language | C# (.NET) |
| .NET runtime | .NET 8.0 or .NET 9.0 |
| .NET Aspire | 9.0+ |
| `KubeMQ.SDK.CSharp` | 3.0.1 |
| KubeMQ broker | gRPC on `:50000` (always on — no enable flag) |
## Messaging patterns [#messaging-patterns]
Once `IKubeMQClient` is injected, it speaks the full KubeMQ messaging surface through the native SDK. The capability pages document the Aspire-specific wiring and link out to the core pattern docs for the send/receive semantics.
## Quick links [#quick-links]
**Requirements** — .NET 8.0 or .NET 9.0, .NET Aspire 9.0 or later, a KubeMQ license key passed as `KUBEMQ_LICENSE_KEY` (which license fits: [Plans compared](/licensing)), and Docker for local development with Aspire.
New to KubeMQ? Start with the [KubeMQ Getting Started guide](/deploy) for core concepts like Events, Queues, and RPC before wiring up Aspire.
# Celery (/integrations/celery)
[`kubemq-celery`](https://pypi.org/project/kubemq-celery/) is a KubeMQ transport and queue-peek result backend for [Celery](https://docs.celeryq.dev/) task queues. It lets you run Celery on KubeMQ with a one-line configuration change — `broker="kubemq://localhost:50000"` — making KubeMQ the only Kubernetes-native, in-cluster Celery broker. The transport plugs into Kombu (Celery's messaging layer) and registers the `kubemq://` URL scheme, so your existing tasks, workers, and tooling keep working unchanged.
New to the idea? See [what is an integration](/integrations#what-an-integration-is) for how SDK-level integrations differ from the server-side [connectors](/connectors).
## Supported versions [#supported-versions]
| Requirement | Supported versions |
| ------------- | ------------------------------------------ |
| Language | Python `>= 3.10` |
| Celery | `>= 5.4` |
| Kombu | `>= 5.4` |
| KubeMQ SDK | `kubemq >= 4.1.5` |
| KubeMQ broker | Reachable over native gRPC on port `50000` |
| Package | `kubemq-celery` `1.1.0` (MIT) |
## Why KubeMQ over Redis/RabbitMQ? [#why-kubemq-over-redisrabbitmq]
KubeMQ replaces visibility-timeout heuristics and broker plugins with native gRPC primitives, and runs as a first-class workload inside your Kubernetes cluster.
| | Redis | RabbitMQ | KubeMQ |
| ------------------------ | -------------------- | ----------------- | --------------------------- |
| **Acknowledgment** | Visibility timeout | Native AMQP ack | Native gRPC ack |
| **Delayed delivery** | Client-side polling | Plugin required | Native `delay_in_seconds` |
| **Kubernetes** | External StatefulSet | External + Erlang | K8s-native, auto-clustering |
| **Connection stability** | TCP reset under load | Stable | gRPC keep-alive |
| **Setup complexity** | Moderate | High | Low |
* **No visibility-timeout bugs** — messages are explicitly acknowledged or rejected over a gRPC stream, instead of relying on a timeout window that causes duplicates when set too low and stalls reprocessing when set too high.
* **Native delayed delivery** — `countdown` and `eta` map directly to KubeMQ's `delay_in_seconds` with zero polling overhead and no broker plugin.
* **Kubernetes-native** — an in-cluster broker with auto-clustering, gRPC keep-alive for long-lived connections, and KEDA-driven autoscaling, instead of an external StatefulSet or an Erlang-backed service.
## Install [#install]
Install from PyPI with `pip` or [uv](https://docs.astral.sh/uv/):
```bash
# pip
pip install kubemq-celery
# uv (recommended)
uv add kubemq-celery
```
Switching an existing app is a one-line change — `kubemq-celery` is a drop-in replacement for Redis or RabbitMQ:
```python title="tasks.py"
import kubemq_celery # registers the kubemq:// transport
from celery import Celery
app = Celery("myapp", broker="kubemq://localhost:50000")
@app.task
def add(x, y):
return x + y
```
`import kubemq_celery` must run before Celery resolves the broker URL — it registers the `kubemq://` scheme with Kombu. Without it, Celery raises an "unknown transport" error.
Start a worker and send a task:
```bash
celery -A tasks worker --loglevel=info
```
```python
from tasks import add
add.delay(4, 6)
```
For the full walkthrough — including a local Docker broker and the result backend — see [Getting Started](/integrations/celery/tutorials/getting-started).
## Features [#features]
| Feature | Description |
| ---------------------- | -------------------------------------------------------------------------------- |
| **One-line setup** | `broker="kubemq://host:50000"` — drop-in replacement for Redis/RabbitMQ |
| **Native ack/nack** | Messages are explicitly acknowledged over gRPC — no visibility-timeout bugs |
| **Delayed delivery** | `countdown` and `eta` map to KubeMQ's native `delay_in_seconds` (no polling) |
| **Per-message TTL** | `message_expiration` transport option for automatic message expiration |
| **Dead letter queue** | Built-in DLQ via `max_receive_count` + `dead_letter_queue` transport options |
| **Batch receive** | `max_batch_size` fetches multiple messages per gRPC call for higher throughput |
| **Queue-peek results** | Optional result backend using non-destructive peek — no external Redis/DB needed |
| **Full monitoring** | Flower, `celery inspect`, `celery control` — all work via KubeMQ Events fanout |
| **TLS + mTLS** | `kubemq+tls://` for encrypted gRPC connections, mTLS for mutual authentication |
| **Async transport** | `kubemq+async://` for native asyncio I/O with `--pool=asyncio` workers |
| **KEDA autoscaling** | Kubernetes-native broker with auto-clustering and KEDA-driven scaling |
| **Auto-registration** | `import kubemq_celery` registers the `kubemq://` URL scheme automatically |
## Architecture [#architecture]
A Celery worker talks to KubeMQ through Kombu's virtual transport layer. `kubemq-celery` implements a `Channel` that extends Kombu's `virtual.Channel` (with `supports_fanout = True`) and maps Kombu's storage primitives onto KubeMQ's gRPC API on port `50000`. Task messages travel over KubeMQ **Queues** (with native ack/nack and `delay_in_seconds`), while pidbox and monitoring traffic — Flower, `celery inspect`, `celery control` — use KubeMQ **Events** fanout. When the optional result backend is enabled, results are written as Queue messages and read back with a non-destructive peek, so multiple callers can fetch the same result without consuming it.
*A Celery worker speaks `kubemq://` through Kombu; tasks and peek-read results ride KubeMQ Queues, while pidbox and monitoring traffic fan out over KubeMQ Events.*
## Usage [#usage]
## Quick Links [#quick-links]
**Requirements** — Python `>= 3.10`, Celery `>= 5.4`, Kombu `>= 5.4`, and the `kubemq` SDK `>= 4.1.5`. Current version: `1.1.0`. You also need a reachable KubeMQ broker (Docker, Kubernetes, or standalone).
New to KubeMQ? Start with the [KubeMQ Getting Started guide](/deploy) for core concepts like Queues and Events before wiring up Celery.
# FastStream (/integrations/faststream)
[`kubemq-faststream`](https://github.com/kubemq-io/kubemq-faststream) is a KubeMQ
broker adapter for the [FastStream](https://github.com/airtai/faststream) async
messaging framework. It registers `KubeMQBroker` as a first-class FastStream broker, so
all five KubeMQ patterns — **Events**, **Events Store**, **Queues**, **Commands**, and
**Queries** — become ordinary `@broker.subscriber(...)` endpoints, fully wired into
FastStream's lifecycle, dependency injection, middleware, and testing infrastructure.
New to the idea? See [what is an integration](/integrations#what-an-integration-is)
for how SDK-level integrations differ from server-side [connectors](/connectors).
## Why FastStream + KubeMQ [#why-faststream--kubemq]
* **All five patterns as FastStream endpoints** — one keyword on the subscriber
(`events=`, `events_store=`, `queues=`, `commands=`, `queries=`) selects the pattern;
no per-pattern client wiring.
* **Idiomatic decorator API** — register handlers with `@broker.subscriber(...)` and
auto-publish results with `@broker.publisher(...)`, exactly like every other FastStream
broker.
* **Full FastStream pipeline** — parser, decoder, broker and subscriber middleware, and
FastDepends dependency injection run for every message.
* **In-memory testing** — `TestKubeMQBroker` routes published messages to matching
subscribers without a live broker, exercising the real parse/decode/middleware path.
* **Runs inside your web app** — drop the broker into a FastAPI, Starlette, Django, or
Flask process and consume KubeMQ messages on the same event loop.
## Installation [#installation]
```bash
uv add kubemq-faststream
```
```bash
pip install kubemq-faststream
```
**Requirements**: Python 3.11+ and a running [KubeMQ](https://kubemq.io/) broker.
| Requirement | Supported versions |
| ----------- | ------------------------- |
| Language | Python 3.11, 3.12, 3.13 |
| FastStream | >= 0.6.7, \< 0.7.0 |
| KubeMQ SDK | >= 4.1.5, \< 5 |
| Package | `kubemq-faststream` 0.1.0 |
Start a broker locally with Docker:
`kubemq-faststream` is a native gRPC SDK client: it talks to KubeMQ over the gRPC port
`50000`, the same transport the native SDKs use. It is **always on** — there is no
server-side connector to enable and no HTTP flag to set. Port `9090` is the shared HTTP
server (REST and the HTTP connectors) and is not used by FastStream.
## Architecture [#architecture]
When it connects, `KubeMQBroker` creates three KubeMQ SDK async clients — one per
transport family — each on its own gRPC channel and all sharing a single set of
connection settings (URL, client ID, auth token, TLS, message-size limits, keepalive).
Your subscriber keyword routes each `publish`, `request`, and handler registration to the
matching client.
*`KubeMQBroker` fans your handlers across three SDK clients, all reaching the KubeMQ broker over gRPC on `:50000`.*
A minimal app wires the broker into `FastStream`, registers a subscriber, and publishes
after startup:
```python title="app.py"
import asyncio
from faststream import FastStream
from kubemq_faststream import KubeMQBroker
broker = KubeMQBroker("kubemq://localhost:50000")
app = FastStream(broker)
@broker.subscriber(queues="orders")
async def handle_order(order: dict) -> None:
print(f"Processing order: {order}")
@app.after_startup
async def publish() -> None:
await broker.publish({"id": "ORD-001", "item": "Widget"}, queues="orders")
if __name__ == "__main__":
asyncio.run(app.run())
```
## Messaging patterns [#messaging-patterns]
Each KubeMQ pattern maps to a subscriber keyword. The pages below document the FastStream
API for each — the decorators, options, and `broker.publish`/`broker.request` calls — and
link to the underlying KubeMQ concept.
## Capabilities [#capabilities]
* **`KubeMQBroker` over native gRPC** — connect with `kubemq://host:50000` (or
`kubemq+tls://` for TLS) straight to the KubeMQ gRPC port.
* **`KubeMQRouter` composition** — group handlers into routers whose `prefix` propagates
to every channel.
* **`@broker.publisher` auto-publish** — stack on a subscriber to publish its return value
to another channel.
* **`AckPolicy` settlement** — choose how queue messages are acked, nacked, or rejected.
* **`StartPosition` replay** — replay Events Store streams from first, a sequence, or a
point in time.
* **Server-side query caching** — pass `cache_key` and `cache_ttl` on a query request.
* **Health check** — `await broker.ping()` verifies broker connectivity.
## Next steps [#next-steps]
New to KubeMQ? Start with the [KubeMQ Getting Started guide](/deploy) for
the core concepts behind these patterns.
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# KEDA (/integrations/keda)
The **KubeMQ KEDA external scaler** brings Kubernetes-native autoscaling to KubeMQ
queue consumers. It is a standalone gRPC service that reads the live `Waiting` message
count from a KubeMQ queue channel and exposes it to [KEDA](https://keda.sh) as a single
metric, so a `ScaledObject` can scale queue-consuming workloads — GPU inference workers,
batch processors, task consumers — up and down (and all the way to zero) on real backlog
rather than CPU or memory.
## What it is [#what-it-is]
KEDA is the Kubernetes Event-Driven Autoscaler. It scales workloads from external signals
through *scalers* — small gRPC services that implement KEDA's `ExternalScaler` interface.
The KubeMQ scaler is one such service: it answers KEDA's `IsActive` / `GetMetrics` calls by
querying the broker's `ListQueuesChannels` API and reporting the channel's `Outgoing.Waiting`
count.
Unlike the framework adapters in this section, KEDA is **not a messaging client your app
embeds** — it is an autoscaler that runs alongside your consumers. Your consumers connect to
KubeMQ with the [native gRPC SDK](/deploy) on port `50000` as usual; the scaler
observes the same queues over that API and tells KEDA how many replicas to run. The metric it
exposes is queue depth, so the underlying concept is [Queues](/learn/queues) — the scaler reads
the same `Waiting` count you would see when introspecting a queue channel.
## Why KEDA + KubeMQ [#why-keda--kubemq]
* **Queue-depth-driven autoscaling** — scale on the live `Waiting` count of a [queue](/learn/queues), not on CPU or memory.
* **Scale-to-zero** — drop a deployment to zero replicas when its queue is empty and scale back up the moment work arrives.
* **Never-fake-zero** — KubeMQ errors map to gRPC status codes so KEDA applies its `fallback` strategy on a broker outage instead of scaling a healthy workload to zero.
* **Push or poll** — `external` (poll) and `external-push` (long-lived stream) trigger types, the latter for faster scale-from-zero detection.
* **Lightweight** — a single Go service requesting just `50m` CPU and `64Mi` memory, hardened with a non-root, read-only-root-filesystem `securityContext`.
## Architecture [#architecture]
The scaler is a standalone gRPC `ExternalScaler` server (default port `9090`). The KEDA
operator calls it to read queue depth; the scaler in turn dials the KubeMQ broker's gRPC API
(`50000`), calls `ListQueuesChannels`, and reports the `Waiting` count so KEDA can scale the
target deployment.
*The KEDA operator reads queue depth from the scaler, which polls the KubeMQ broker and drives the target deployment's replica count.*
## The metric and the RPCs [#the-metric-and-the-rpcs]
The scaler exposes exactly one metric, `kubemq-queue-waiting`, whose value is the queue
channel's `Outgoing.Waiting` count. It implements the four RPCs of KEDA's `ExternalScaler`
service:
| RPC | Purpose |
| ---------------- | ----------------------------------------------------------------------------------------------------- |
| `IsActive` | Returns `true` when `Waiting > activationTargetWaiting` — the scale-from-zero gate. |
| `StreamIsActive` | Server-streaming. Pushes active status immediately, then re-polls every `5s`. Drives `external-push`. |
| `GetMetricSpec` | Returns the target value for `kubemq-queue-waiting`, set from `targetWaiting`. |
| `GetMetrics` | Returns the current `Waiting` count as the metric value. |
KEDA supports two trigger types against the same scaler — `external` (poll-based, default) and
`external-push` (a long-lived `StreamIsActive` stream for faster scale-from-zero). See
[Concepts](/integrations/keda/concepts) for the full model.
## Prerequisites [#prerequisites]
* **Kubernetes 1.27+** — required for the native gRPC liveness/readiness probes the scaler uses.
* **KEDA 2.10+** — installed in the cluster.
* **A KubeMQ broker** — reachable in-cluster on its gRPC port `50000` at the address you pass in `kubemqAddress`.
## Supported runtime [#supported-runtime]
The scaler is a standalone Go service, not a language SDK you embed — your consumers can be written in any language and connect to the broker over native gRPC as usual.
| Requirement | Version |
| ----------------------------------- | --------------------------------------------- |
| KEDA | 2.10+ |
| Kubernetes | 1.27+ |
| Scaler image | `kubemq/kubemq-keda-scaler:1.0.0` |
| `github.com/kubemq-io/kubemq-go/v2` | v2.0.3 |
| Go (to build from source) | 1.25+ |
| KubeMQ broker | gRPC on `:50000` (always on — no enable flag) |
## A ScaledObject at a glance [#a-scaledobject-at-a-glance]
A `ScaledObject` targets your consumer `Deployment` and points an `external` trigger at both the
scaler Service and your broker:
```yaml title="scaled-object-basic.yaml"
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: kubemq-queue-scaler
spec:
scaleTargetRef:
name: my-queue-consumer
pollingInterval: 15
cooldownPeriod: 60
minReplicaCount: 1
maxReplicaCount: 10
triggers:
- type: external
metadata:
scalerAddress: kubemq-keda-scaler.default.svc.cluster.local:9090
kubemqAddress: kubemq.default.svc.cluster.local:50000
queueName: my-queue
targetWaiting: "10"
```
## Explore [#explore]
New to integrations? See [what an integration is](/integrations#what-an-integration-is)
for the mental model, then the [Queues](/learn/queues) concept and the
[Getting Started guide](/deploy) for the core SDK your consumers use. The scaler
observes queues over native gRPC on port `50000` — it is not a [connector](/connectors).
# MassTransit (/integrations/masstransit)
[MassTransit](https://masstransit.io) is the open-source distributed-application framework for .NET. **MassTransit.KubeMQ** is a MassTransit *transport* that runs the bus over KubeMQ via gRPC: you register it the same way you would RabbitMQ or Azure Service Bus, and your existing consumers, sagas, and message contracts work unchanged on KubeMQ.
Because the transport plugs in below the MassTransit abstractions, adopting KubeMQ is a configuration change rather than a rewrite. Message contracts, `IConsumer` implementations, sagas, the middleware pipeline, serialization, retry/redelivery policies, the EF Core outbox, OpenTelemetry, and DI registration (`AddConsumer`, `AddSaga`) all behave identically — only where messages physically travel changes.
New to the idea? See [what is an integration](/integrations#what-an-integration-is) for how SDK-level integrations differ from the server-side [connectors](/connectors).
## Why MassTransit + KubeMQ [#why-masstransit--kubemq]
* **Drop-in transport swap** — change `UsingRabbitMq`, `UsingAzureServiceBus`, or `UsingAmazonSqs` to `UsingKubeMQ`; contracts and consumers stay the same.
* **Native request/response** — KubeMQ's CQ pattern provides built-in request-reply with no temporary reply queues (unlike RabbitMQ/SQS, which simulate it).
* **Fire-and-forget or durable-replayable publish** — `Publish()` maps to KubeMQ Events for fan-out, or to EventsStore for persistent, replayable pub/sub.
* **Built-in priority queues and consumer groups** — weighted priority channels and competing consumers without extra infrastructure.
* **Full observability** — W3C trace context is propagated via tags, and the bus integrates with ASP.NET Core health checks and a `MassTransit.KubeMQ` metrics meter.
## Install [#install]
```bash title="terminal"
dotnet add package MassTransit.KubeMQ
```
The transport targets `net8.0` and requires MassTransit `>= 8.5.0`.
## Supported versions [#supported-versions]
| Requirement | Supported versions |
| ------------- | ------------------------------------------ |
| Language | C# / .NET (`net8.0` target) |
| Runtime | .NET SDK `8.0+` |
| MassTransit | `>= 8.5.0` |
| KubeMQ broker | Reachable over native gRPC on port `50000` |
| Package | `MassTransit.KubeMQ` `1.0.0` |
The transport is a **native gRPC client** that connects to KubeMQ on port `50000`. It is not an HTTP connector, so there is no `CONNECTORS*_ENABLE` flag to set — exposing the gRPC port is all that is needed. KubeMQ channels are created automatically on first use; there is no exchange, binding, virtual host, or topic-subscription topology to provision.
## Architecture [#architecture]
Your application talks to MassTransit abstractions as usual. The transport layers KubeMQ onto an InMemory base bus (for the `IBusControl` lifecycle) plus a **KubeMQ rider** that owns the connections and receive transports. The rider bridges those abstractions to the broker over gRPC on port `50000`, where KubeMQ dispatches to its four native subsystems.
*The KubeMQ rider maps MassTransit's transport-agnostic operations onto native KubeMQ Queues, Events, EventsStore, and CQ over gRPC.*
## Pattern mapping [#pattern-mapping]
MassTransit's transport-agnostic verbs map to KubeMQ's native messaging patterns. The mapping determines delivery semantics and which KubeMQ subsystem backs each message.
| MassTransit verb | KubeMQ pattern | Delivery | Capability page |
| --------------------- | --------------------- | ------------------------------------------------- | ----------------------------------------------------------------------- |
| **Send** | Queues | Point-to-point (exactly one consumer) | [Queues](/integrations/masstransit/how-to/queues) |
| **Publish** | Events | Fan-out (all active subscribers, fire-and-forget) | [Events](/integrations/masstransit/how-to/events) |
| **Publish** (durable) | EventsStore | Fan-out with persistence and replay | [Events Store](/integrations/masstransit/how-to/events-store) |
| **Request/Response** | Commands/Queries (CQ) | Native request-reply | [Commands & Queries](/integrations/masstransit/how-to/commands-queries) |
## Capabilities [#capabilities]
## Next steps [#next-steps]
New to KubeMQ? Start with the [KubeMQ Getting Started guide](/deploy) for the core messaging concepts.
# NestJS (/integrations/nestjs)
[`@kubemq/nestjs-transport`](https://www.npmjs.com/package/@kubemq/nestjs-transport) is a
custom [NestJS](https://nestjs.com/) transport that integrates KubeMQ into the NestJS
microservices ecosystem. It surfaces all five KubeMQ messaging patterns — Commands, Queries,
Events, Events Store, and Queues — through idiomatic `@*Handler` decorators and a standard
`ClientProxy`, so a Nest app sends and handles KubeMQ messages with the same DI, modules, and
testing patterns it already uses for HTTP. It is built on the native
[`kubemq-js`](https://www.npmjs.com/package/kubemq-js) SDK and speaks gRPC directly to the broker
on port `50000`.
## Why KubeMQ + NestJS [#why-kubemq--nestjs]
* **Idiomatic decorators** — `@CommandHandler`, `@QueryHandler`, `@EventHandler`,
`@EventStoreHandler`, and `@QueueHandler` replace manual `@MessagePattern` / `@EventPattern`
metadata wiring; the right KubeMQ pattern is attached for you.
* **One transport, five patterns** — a single `KubeMQServer` strategy (inbound) and
`KubeMQClientProxy` (outbound) cover every pattern; the `KubeMQRecord` builder re-targets the
message type with `.asQuery()`, `.asEventStore()`, or `.asQueue()`.
* **Dynamic-module DI** — `forRoot` / `forRootAsync` / `register` / `registerAsync` /
`forFeature` / `forTest` register the connection and named clients through NestJS dependency
injection.
* **Distributed CQRS** — the [CQRS bridge](/integrations/nestjs/how-to/cqrs-bridge) routes `@nestjs/cqrs` `CommandBus`,
`QueryBus`, and `EventBus` traffic across services over KubeMQ channels.
* **TypeScript-first** — full type safety with an ESM + CJS dual build and per-pattern context
types.
* **Broker-free tests** — `MockKubeMQClient`, `MockKubeMQServer`, and `KubeMQModule.forTest()`
exercise services and handlers without a live broker.
## Installation [#installation]
```bash
npm install @kubemq/nestjs-transport kubemq-js
```
Most peer dependencies already ship with a typical NestJS project; install any that are missing:
```bash
npm install @nestjs/common @nestjs/core @nestjs/microservices rxjs reflect-metadata
```
Optional peer dependencies enable specific features — `@nestjs/terminus` for the health-check
indicator and `@nestjs/cqrs` for the [CQRS bridge](/integrations/nestjs/how-to/cqrs-bridge):
```bash
npm install @nestjs/terminus # health checks
npm install @nestjs/cqrs # CQRS bridge
```
**Prerequisites:** Node.js 20.11.0 or later and a running KubeMQ broker (default
`localhost:50000`). The transport is a native gRPC SDK client — there is **no connector flag to
enable**; the gRPC API on `50000` is always on. Start a local broker with Docker (gRPC on `50000`,
the shared HTTP server and dashboard on `9090`):
## Supported versions [#supported-versions]
| Requirement | Supported versions |
| ----------- | ---------------------------------------- |
| Language | TypeScript `5.5+` (ESM + CJS dual build) |
| Runtime | Node.js `>= 20.11.0` |
| NestJS | `10.x` or `11.x` |
| KubeMQ SDK | `kubemq-js` `^3.0.1` |
| Package | `@kubemq/nestjs-transport` `1.0.0` |
## Architecture [#architecture]
A KubeMQ-backed NestJS app is a
[hybrid application](https://docs.nestjs.com/faq/hybrid-application): the HTTP app stays as-is
while the KubeMQ transport is attached as a microservice. Inbound handlers run through the
`KubeMQServer` strategy passed to `app.connectMicroservice({ strategy })`; outbound clients are
`KubeMQClientProxy` instances registered with `KubeMQModule`. Both wrap a `kubemq-js` client and
speak gRPC to the broker on port `50000`.
*Decorated handlers and injected client proxies both wrap `kubemq-js` and reach the broker over native gRPC.*
## Capabilities [#capabilities]
The transport plugs into NestJS DI and dispatch. Each capability below documents the
integration's own API surface and links to the underlying KubeMQ concept rather than re-teaching
it.
| Capability | Surface | KubeMQ concept |
| ------------------ | ---------------------------------------------------- | ----------------------------------- |
| Commands / Queries | `@CommandHandler` / `@QueryHandler`, `client.send()` | [RPC](/learn/rpc) |
| Events | `@EventHandler`, `client.emit()` | [Events](/learn/events) |
| Events Store | `@EventStoreHandler`, `.asEventStore()` | [Events Store](/learn/events-store) |
| Queues | `@QueueHandler`, `.asQueue()`, manual ack | [Queues](/learn/queues) |
| Module DI | `forRoot` / `register` / `forFeature` / `forTest` | — |
| Distributed CQRS | `KubeMQCqrsModule` over `@nestjs/cqrs` buses | — |
## Next steps [#next-steps]
New to integrations? See [what an integration is](/integrations#what-an-integration-is) for
the mental model, or start with the [KubeMQ Getting Started guide](/deploy) for core
broker concepts. This transport speaks native gRPC on port `50000` — it is a direct SDK client,
not a [connector](/connectors).
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Ray Serve (/integrations/rayserve)
`kubemq-rayserve` is a Python package that plugs [KubeMQ](https://kubemq.io/) into
[Ray Serve](https://docs.ray.io/en/latest/serve/index.html) as a task backend. It provides
`KubeMQTaskProcessorAdapter` — the first non-Celery adapter for Ray Serve's
`TaskProcessorAdapter` framework — so a Ray Serve deployment can run **queue-based asynchronous**
and **blocking synchronous** ML inference, with KubeMQ acting as the message broker, the result
store, the autoscaling signal, and the progress event bus all at once.
The adapter is a native gRPC SDK client. It connects to a KubeMQ broker on port `50000` and is
always available — there is no connector to enable on the server. You install one package, point
it at a broker, and Ray Serve drives the rest of the lifecycle.
Ray Serve is an [integration](/integrations#what-an-integration-is): a client-side library that
embeds a KubeMQ SDK, distinct from the server-side [connectors](/connectors) (MCP, A2A,
CloudEvents) that run inside the broker.
## Why KubeMQ + Ray Serve [#why-kubemq--ray-serve]
* **One Kubernetes-native broker** — a single binary carries the task queue, the synchronous query
channel, the result store, and the progress event stream. No Erlang, Redis, or RabbitMQ to
operate alongside Ray.
* **Built-in sync inference** — `query_task_sync` gives blocking request-response inference that the
reference Celery adapter does not offer.
* **Built-in progress tracking** — `report_progress` streams real-time task progress over KubeMQ
Events; Celery requires custom signals.
* **Queue-peek result backend** — results live in KubeMQ itself, with no separate Redis or database
to provision.
* **Native autoscaling** — `kubemq_queue_depth_policy` scales Ray Serve replicas from live queue
depth, and the same depth drives [KEDA](/integrations/keda) for cluster-level scaling.
* **One-dependency setup** — only KubeMQ is required, versus a broker plus a separate result
backend.
## Install [#install]
```bash title="terminal"
uv pip install kubemq-rayserve
```
| Requirement | Version |
| ------------------------ | --------- |
| Python | >= 3.10 |
| Ray Serve (`ray[serve]`) | >= 2.50.0 |
| `kubemq` (Python SDK) | >= 4.1.5 |
| `pydantic` | >= 2.0 |
A running KubeMQ broker is required (default address `localhost:50000`). Start one locally with
Docker:
Port `50000` is KubeMQ's gRPC endpoint — the only port the adapter's SDK clients use. Port `9090`
is the shared HTTP server (REST and the AI-agent connectors); the dashboard runs separately on
port `8080`. The adapter and the `kubemq_queue_depth_policy` autoscaler both speak gRPC on `50000`.
## Architecture [#architecture]
A producer enqueues a serialized task onto a KubeMQ Queue. Inside the Ray Serve deployment, the
`KubeMQTaskProcessorAdapter` runs a consumer thread that polls the queue, dispatches each task to a
registered handler, and writes the result back into the queue-peek result backend. A parallel Query
channel serves blocking sync inference, and an Events channel carries progress updates — all over
the same gRPC connection to port `50000`.
*The adapter maps Ray Serve's task model onto three KubeMQ primitives — Queues, Queries, and Events — over one gRPC connection.*
The adapter never re-teaches KubeMQ messaging: async tasks ride [Queues](/learn/queues), sync
inference rides request-response [RPC](/learn/rpc) (Queries), and progress rides
[Events](/learn/events). Each capability page documents the adapter API and links to the underlying
concept.
## Capabilities [#capabilities]
`KubeMQTaskProcessorAdapter` exposes eight capabilities, grouped into three inference models plus
the operational features that surround them.
| Capability | What it does | KubeMQ primitive |
| ----------------- | ------------------------------------------------------------------ | --------------------------- |
| Async inference | Enqueue a task, poll the result backend for the outcome | [Queues](/learn/queues) |
| Sync inference | Blocking request-response inference via `query_task_sync` | [RPC](/learn/rpc) (Queries) |
| Progress tracking | Stream live `report_progress` updates to subscribers | [Events](/learn/events) |
| Cancellation | Soft-cancel a task — overwrite its result with `CANCELLED` | Queues |
| DLQ monitoring | `on_dlq` callback alerts on permanently failed tasks | Queues |
| Autoscaling | Scale replicas on queue depth (`kubemq_queue_depth_policy` / KEDA) | Queues |
| Result backend | Queue-peek result storage with purge-then-write and TTL | Queues |
| Metrics | An 8-metric dict (depth, in-flight, DLQ, counters, durations) | — |
## Metrics at a glance [#metrics-at-a-glance]
`get_metrics_sync()` returns a single dict with eight entries — three live gauges read from KubeMQ
on each call, plus in-memory counters and a histogram. See the
[metrics guide](/integrations/rayserve/how-to/metrics) for collection patterns and the
[API reference](/integrations/rayserve/reference/api#metrics) for the full schema.
| Metric | Type | Reports |
| ---------------------------------- | --------- | ----------------------------------------------------------- |
| `queue_depth` | Gauge | Waiting messages in the task queue (the autoscaling signal) |
| `in_flight` | Gauge | Tasks currently being processed |
| `dlq_depth` | Gauge | Waiting messages in the dead-letter queue |
| `tasks_enqueued_total` | Counter | Tasks enqueued since startup |
| `tasks_completed_total` | Counter | Completed counts by status (`SUCCESS` / `FAILURE`) |
| `task_processing_duration_seconds` | Histogram | `min` / `max` / `avg` / `count` of handler durations |
| `result_storage_retries_total` | Counter | Result-storage retry attempts |
| `consumer_poll_latency_seconds` | Gauge | Duration of the last queue poll |
## How it compares to the Celery adapter [#how-it-compares-to-the-celery-adapter]
Ray Serve's reference `TaskProcessorAdapter` is Celery-backed. KubeMQ collapses the broker, result
backend, and scaler into one component.
| Feature | kubemq-rayserve | CeleryTaskProcessorAdapter |
| ------------------ | ---------------------------- | ------------------------------------- |
| Message broker | KubeMQ (Kubernetes-native) | Redis / RabbitMQ |
| Sync inference | Built-in (`query_task_sync`) | Not available |
| Progress tracking | Built-in (`report_progress`) | Requires custom signals |
| Autoscaling policy | `kubemq_queue_depth_policy` | Manual HPA configuration |
| DLQ monitoring | `on_dlq` callback | Requires Celery signals + custom code |
| Result backend | Queue-peek (no extra infra) | Requires separate Redis / DB |
| Setup complexity | 1 dependency (KubeMQ) | 2+ dependencies (broker + backend) |
## Next steps [#next-steps]
New to KubeMQ? Start with the [KubeMQ Getting Started guide](/deploy) for core
concepts.
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Spring Boot (/integrations/spring-boot)
The KubeMQ Spring Boot Starter is a production-quality Spring Boot 3.x and Spring Cloud Stream integration for the [KubeMQ](https://kubemq.io) message broker. It brings KubeMQ into the Spring programming model through auto-configuration, a thread-safe `KubeMQTemplate` send API, and annotation-driven listeners — all built on the native KubeMQ Java SDK clients so your application speaks gRPC to the broker directly.
## Why Spring Boot + KubeMQ? [#why-spring-boot--kubemq]
* **Native Spring idioms** — auto-configuration, `@ConfigurationProperties` bound under `kubemq.*`, Spring Boot Actuator health contributors, and Micrometer metrics and observations
* **Annotation-driven listeners** — `@KubeMQEventListener`, `@KubeMQEventStoreListener`, `@KubeMQQueueListener`, `@KubeMQCommandHandler`, and `@KubeMQQueryHandler` turn beans into message consumers
* **`KubeMQTemplate` send API** — one injectable template covers all five messaging patterns (Events, Events Store, Queues, Commands, Queries) with sync, async, and fluent-builder variants
* **Kotlin support** — coroutine extensions, `Flow` adapters, and a configuration DSL via the Kotlin starter
* **Spring Cloud Stream binder** — bind Events, Events Store, and Queues through the Spring Cloud Stream programming model
* **First-class test harness** — `MockKubeMQServer`, TestContainers support, and a test starter for exercising producers and consumers without a live broker
## Requirements [#requirements]
The starter targets the JVM and a running **KubeMQ broker** reachable over native gRPC on port `50000`. Supported languages and versions:
| Requirement | Version |
| -------------------------- | ------------- |
| Java | 17+ |
| Kotlin (Kotlin starter) | JVM target 17 |
| Spring Boot | 3.2.0+ |
| Spring Cloud (binder BOM) | 2023.0.0 |
| KubeMQ Spring Boot Starter | 1.0.0 |
The Spring Cloud Stream binder pulls in the **Spring Cloud 2023.0.0** BOM; add it only when you use the binder.
## Installation [#installation]
Add the starter dependency — it aggregates the auto-configuration and the KubeMQ Java SDK:
```kotlin title="build.gradle.kts"
dependencies {
implementation("io.kubemq:kubemq-spring-boot-starter:1.0.0")
}
```
Then point the application at your broker. The properties are bound under `kubemq.*`:
```yaml title="application.yml"
kubemq:
address: localhost:50000
client-id: my-app
```
Inject `KubeMQTemplate` to send, and annotate a bean method to receive:
```java title="OrderService.java"
@Service
public class OrderService {
private final KubeMQTemplate template;
public OrderService(KubeMQTemplate template) {
this.template = template;
}
public void placeOrder(Order order) {
template.sendEvent("orders", order);
}
}
```
```java title="OrderConsumer.java"
@Component
public class OrderConsumer {
@KubeMQEventListener(channels = "orders")
public void onOrder(EventMessageReceived event) {
// process event
}
}
```
Start a local broker with Docker — the gRPC API the starter connects to listens on `50000`, and the shared HTTP/REST and dashboard endpoints on `9090`:
## Modules [#modules]
The project is a multi-module Gradle build. Add `kubemq-spring-boot-starter` to your project; the rest are pulled in transitively or added when you need Spring Cloud Stream, Kotlin, or testing support.
| Module | Description |
| ----------------------------------- | --------------------------------------------------------------------------- |
| `kubemq-spring-boot-autoconfigure` | Auto-configuration, `KubeMQTemplate`, listener annotations, health, metrics |
| `kubemq-spring-boot-starter` | Dependency aggregator — add this to your project |
| `kubemq-spring-cloud-stream-binder` | Spring Cloud Stream binder for Events, Events Store, and Queues |
| `kubemq-spring-boot-starter-kotlin` | Kotlin coroutine extensions, `Flow` adapters, and DSL |
| `kubemq-spring-boot-starter-test` | `MockKubeMQServer`, TestContainers, and test harness |
## Architecture [#architecture]
`KubeMQAutoConfiguration` wires the native KubeMQ Java SDK clients — `PubSubClient`, `QueuesClient`, and `CQClient` — from your `kubemq.*` properties. The `KubeMQTemplate` send API and the `@KubeMQ*Listener` / `@KubeMQ*Handler` beans both delegate to those clients, which speak gRPC to the broker on port `50000`. There is no connector to enable — the starter is a native SDK client that connects directly.
*Auto-configuration binds the three SDK clients from `kubemq.*` properties; the template and listener beans delegate to them over gRPC on port 50000.*
## Capabilities [#capabilities]
Each capability page documents the Spring API surface (`KubeMQTemplate` send methods and the `@KubeMQ*Listener` / `@KubeMQ*Handler` annotations) and links to the underlying KubeMQ pattern so you learn the concept once.
## Quick Links [#quick-links]
New to integrations? See [what an integration is](/integrations#what-an-integration-is) for the mental model, or start with the [KubeMQ Getting Started guide](/deploy) for core broker concepts. This starter speaks native gRPC on port `50000` — it is a direct SDK client, not a [connector](/connectors).
## Container command examples
```sh
docker run -d \
--pull always \
--platform linux/amd64 \
--name kubemq \
--hostname kubemq \
-p 127.0.0.1:50000:50000 \
-p 127.0.0.1:9090:9090 \
-e STORE_ENGINE=next \
-e STORE_NEXT_ACK_POLICY=strict \
-e STORE_STORE_PATH=/kubemq/store \
-e API_BIND_ADDRESS=0.0.0.0 \
-v kubemq-data:/kubemq/store \
europe-docker.pkg.dev/kubemq/images/kubemq-next:latest
```
# Watermill (/integrations/watermill)
[`kubemq-watermill`](https://github.com/kubemq-io/kubemq-watermill) is a production-ready
[Watermill](https://watermill.io/) pub/sub plugin for KubeMQ. It implements Watermill's
`message.Publisher` and `message.Subscriber` interfaces across three KubeMQ messaging
patterns — Events, EventsStore, and Queues — plus a native `CQPublisher` for Commands and
Queries (request-reply). Drop it into an existing Watermill application and your Router,
handlers, and middleware run unchanged on top of KubeMQ.
It is a **native gRPC client** built on the `kubemq-go/v2` SDK — not an HTTP connector.
If you need protocol bridging instead (REST, MCP, A2A, CloudEvents), see the
[Connectors](/connectors) overview. For the messaging model behind the patterns,
see the core docs: [Events](/learn/events), [Events Store](/learn/events-store),
[Queues](/learn/queues), and [RPC](/learn/rpc).
## Why Watermill on KubeMQ [#why-watermill-on-kubemq]
* **Three messaging patterns** — Events (fire-and-forget), EventsStore (persistent with
replay), and Queues (reliable with explicit ack/nack), each behind the same Watermill
`Publisher`/`Subscriber` interfaces.
* **Native CQPublisher** — wraps KubeMQ's Commands and Queries APIs directly for
low-latency request-reply, with execution confirmation and query caching.
* **Full Watermill compatibility** — works with the Watermill Router and the entire
standard middleware stack (Retry, Throttle, CorrelationID, Poison Queue, CircuitBreaker).
* **Ack/Nack bridged to KubeMQ** — Watermill `msg.Ack()`/`msg.Nack()` map to KubeMQ queue
settlement; a Nack returns the message to the queue for redelivery.
* **Built-in DLQ, OTel, and metrics** — native dead-lettering via `QueueMessagePolicy`,
W3C Trace Context propagation through KubeMQ Tags, and Watermill's Prometheus component.
* **Verified compatibility** — passes the full Watermill `pubsub/tests.TestPubSub` suite.
## Architecture [#architecture]
Your Watermill Router, Publisher, and Subscriber call the plugin, which uses
`kubemq-go/v2` to open a gRPC connection to the KubeMQ broker on port `50000`. There is no
HTTP connector and no server-side translation layer — the broker's gRPC server is always
on, so the plugin works as soon as a broker is reachable.
*The plugin maps Watermill's Publisher/Subscriber model onto KubeMQ patterns over the native gRPC SDK on port 50000.*
## Capabilities [#capabilities]
Each Publisher and Subscriber serves exactly one KubeMQ pattern, selected with the
`Pattern` field. Commands and Queries use the standalone `CQPublisher`.
## Pattern selection [#pattern-selection]
KubeMQ supports three messaging patterns. Each Publisher/Subscriber instance serves
exactly one — pick the one that matches your delivery and persistence needs:
| Pattern | Delivery | Ack/Nack | Persistence | Best for |
| --------------- | ------------- | -------------------- | --------------------------- | ---------------------------------------------- |
| **Events** | At-most-once | No (fire-and-forget) | No | Real-time notifications, metrics, logs |
| **EventsStore** | At-least-once | Offset auto-advance | Yes (replay from any point) | Event sourcing, audit trails, stream replay |
| **Queues** | At-least-once | Explicit ack/nack | Yes (until acked) | Task queues, job processing, reliable delivery |
For request-reply, reach for the native `CQPublisher` (single hop, lower latency) or
Watermill's `requestreply` component over Queues (middleware-compatible) — see
[Commands & Queries](/integrations/watermill/how-to/commands-queries).
## Supported runtime [#supported-runtime]
| Requirement | Version |
| ------------------------------------ | --------------------------------------------- |
| Go | 1.25+ |
| `github.com/ThreeDotsLabs/watermill` | v1.5.1 |
| `github.com/kubemq-io/kubemq-go/v2` | v2.0.3 |
| KubeMQ broker | gRPC on `:50000` (always on — no enable flag) |
Install the plugin with `go get`:
```bash
go get github.com/kubemq-io/watermill-kubemq
```
## Next steps [#next-steps]
New to KubeMQ? Start with the [What is an integration?](/integrations#what-an-integration-is)
mental model, then the [KubeMQ Getting Started guide](/deploy).
# Audit Logging (/operate/observability/audit)
KubeMQ records a built-in audit trail of security, control-plane, and data-plane error
events. Every audit event follows the [CloudEvents v1.0](https://cloudevents.io/)
specification, so the trail is interoperable with any CloudEvents-aware tooling, and it is
queryable through a REST API on the management API port (`:8080`).
## Overview [#overview]
Audit logging is **on by default**. Events are persisted to a local durable store on each
node and synchronized across cluster nodes over the cluster mesh, so every node holds the
full audit trail for the entire cluster. Each event is a CloudEvents v1.0 envelope carrying
a structured `data` payload that captures who did what, on which channel, over which
transport, and whether it succeeded.
Three kinds of events are recorded:
* **Control events** — security, connection lifecycle, and administrative operations
(authentication, authorization, client connect/disconnect, subscriptions, channel
create/delete, cluster membership, server lifecycle).
* **Data error events** — failures in message send and receive operations across the
patterns.
* **System error events** — infrastructure-level failures such as storage or broker errors.
## Configure it [#configure-it]
Audit logging has three settings: a master `enable` toggle, the retention window in hours,
and how often expired records are purged.
```yaml title="config.yaml"
audit:
enable: true # on by default
retentionHours: 720 # retain events for 30 days
cleanupIntervalMinutes: 60 # purge expired events hourly
```
```yaml title="values.yaml"
spec:
audit:
enable: true # on by default
retentionHours: 720 # retain events for 30 days
cleanupIntervalMinutes: 60 # purge expired events hourly
```
For the full settings table — types, defaults, valid values, and the Docker/Helm naming for
each key — see the [Observability settings reference](/configure/reference/observability).
## Event format [#event-format]
Each audit event is a CloudEvents v1.0 envelope. The envelope carries the standard
CloudEvents attributes; the audit-specific payload lives in `data`.
```json
{
"specversion": "1.0",
"id": "550e8400-e29b-41d4-a716-446655440000",
"source": "kubemq://my-cluster/node-1",
"type": "io.kubemq.audit.auth.success",
"time": "2026-03-26T12:34:56.789Z",
"datacontenttype": "application/json",
"data": {
"category": "control",
"subcategory": "success",
"client_id": "my-producer",
"source_ip": "10.0.0.5",
"transport": "grpc",
"channel": "orders",
"action": "auth.success",
"outcome": "success",
"metadata": {
"method": "SendEvent"
}
}
}
```
### Envelope fields [#envelope-fields]
| Field | Description |
| ----------------- | ---------------------------------------------- |
| `specversion` | Always `"1.0"`. |
| `id` | Unique UUID for each event. |
| `source` | `kubemq://{cluster_name}/{node_id}`. |
| `type` | `io.kubemq.audit.{event_type}`. |
| `time` | ISO 8601 timestamp with millisecond precision. |
| `datacontenttype` | Always `"application/json"`. |
### Data fields [#data-fields]
| Field | Type | Description |
| ---------------- | ------ | ----------------------------------------------- |
| `category` | string | Event category: `control`, `data`, or `system`. |
| `subcategory` | string | Sub-category (e.g. `success`, `error`). |
| `client_id` | string | Client identifier (if applicable). |
| `source_ip` | string | Client IP address (if applicable). |
| `transport` | string | Transport layer (`grpc`, `rest`). |
| `channel` | string | Channel name (if applicable). |
| `message_id` | string | Message, event, or request ID (if applicable). |
| `action` | string | Event type name (same as the `type` suffix). |
| `outcome` | string | `success` or `error`. |
| `error` | string | Error message (only when `outcome` is `error`). |
| `error_category` | string | Error classification (if applicable). |
| `metadata` | map | Additional key-value metadata. |
## Event catalog [#event-catalog]
### Control events [#control-events]
Control-plane events track security, connection lifecycle, and administrative operations.
These events carry `category: "control"`.
| Event type | Description |
| ---------------------- | -------------------------------------------------- |
| `server.started` | Server completed startup. |
| `server.stopped` | Server shutting down. |
| `server.ready` | Server ready to accept traffic. |
| `auth.success` | Authentication succeeded. |
| `auth.failure` | Authentication failed. |
| `authz.denied` | Authorization denied. |
| `client.connected` | Client established a connection. |
| `client.disconnected` | Client disconnected. |
| `client.connect_error` | Client connection failed. |
| `subscription.created` | Subscription established. |
| `subscription.deleted` | Subscription removed. |
| `subscription.error` | Subscription failed. |
| `channel.created` | Channel created (detected by the channel monitor). |
| `channel.deleted` | Channel deleted (detected by the channel monitor). |
| `stream.opened` | Bidirectional stream opened. |
| `stream.closed` | Bidirectional stream closed. |
| `cluster.node_joined` | Cluster node joined. |
| `cluster.node_left` | Cluster node left. |
A channel monitor watches for channels appearing and disappearing and emits
`channel.created` / `channel.deleted` control events accordingly.
### Data error events [#data-error-events]
Data-plane error events track failures in message send and receive operations. These events
carry `category: "data"`.
| Event type | Description |
| ------------------------- | ---------------------------- |
| `events.send_error` | Event publish failed. |
| `events_store.send_error` | Events Store publish failed. |
| `command.send_error` | Command send failed. |
| `query.send_error` | Query send failed. |
| `queue.send_error` | Queue message send failed. |
| `queue.batch_send_error` | Queue batch send failed. |
| `queue.receive_error` | Queue receive failed. |
### System error events [#system-error-events]
System-level errors from infrastructure components. These events carry
`category: "system"`.
| Event type | Description |
| ---------------------- | --------------------------- |
| `system.storage_error` | Persistent storage failure. |
| `system.broker_error` | Message broker error. |
## Retention & cleanup [#retention--cleanup]
Audit events are retained for the window set by `retentionHours` (default `720` hours = 30
days). A background cleanup runs at the interval set by `cleanupIntervalMinutes` (default
`60` minutes) and deletes every event older than the retention window. Both settings accept
a minimum of `1`. Tune `retentionHours` to your compliance window and lower
`cleanupIntervalMinutes` only if you need expired events purged more aggressively.
Retention applies per node, but because the trail is synchronized over the cluster mesh,
every node holds — and prunes — the same cluster-wide set of events.
## Query the audit log (REST) [#query-the-audit-log-rest]
The audit trail is queryable through the management API port (`:8080`). Two endpoints are
available: one to list matching events and one to aggregate them.
### List events [#list-events]
```text
GET /api/v1/audit
```
| Parameter | Type | Default | Description |
| ------------- | -------------- | ---------- | ------------------------------------------------- |
| `from` | RFC3339 string | 1 hour ago | Start time. |
| `to` | RFC3339 string | now | End time. |
| `category` | string | (all) | Filter by category (`control`, `data`, `system`). |
| `subcategory` | string | (all) | Filter by subcategory. |
| `event_type` | string | (all) | Filter by event type (e.g. `auth.success`). |
| `channel` | string | (all) | Filter by channel name. |
| `client_id` | string | (all) | Filter by client ID. |
| `limit` | int | 50 | Results per page (1–1000). |
| `offset` | int | 0 | Pagination offset. |
```bash
curl "http://localhost:8080/api/v1/audit?category=control&event_type=auth.failure&limit=10"
```
### Aggregate statistics [#aggregate-statistics]
```text
GET /api/v1/audit/stats
```
| Parameter | Type | Default | Description |
| ---------- | -------------- | ------------ | ------------------- |
| `from` | RFC3339 string | 1 hour ago | Start time. |
| `to` | RFC3339 string | now | End time. |
| `group_by` | string | `event_type` | Grouping dimension. |
```bash
curl "http://localhost:8080/api/v1/audit/stats?group_by=category&from=2026-03-25T00:00:00Z"
```
### Error responses [#error-responses]
| HTTP code | Error | Description |
| --------- | ---------------------- | ----------------------------------------------- |
| 404 | `ErrAuditDisabled` | Audit service is disabled or not initialized. |
| 400 | `ErrAuditInvalidParam` | Invalid query parameter (e.g. bad date format). |
| 500 | `ErrAuditQueryFailed` | Query failed. |
## Access control [#access-control]
When control-plane authentication is enabled, the audit query endpoints require at least the
**ReadOnly** role, like the rest of the management API. See the
[Management API](/operate/observability/api-reference) overview for the response envelope,
status codes, and access-control model.
## Feed a SIEM [#feed-a-siem]
The REST query API makes it straightforward to feed audit events into an external SIEM. Poll
`GET /api/v1/audit` on an interval, advancing the `from` / `to` window each pass, and forward
the returned CloudEvents records into Splunk, Elastic, or any log-management platform. Because
the trail is synchronized cluster-wide, you can poll a single node and still capture every
event from the cluster.
## Related [#related]
* [Observability settings reference](/configure/reference/observability) — the audit
configuration keys with their Docker and Helm naming, defaults, and valid values.
* [Management API](/operate/observability/api-reference) — the response envelope, status codes,
and access-control model shared by the audit query endpoints.
# Observability (/operate/observability)
KubeMQ reports on itself across several complementary surfaces. An always-on Prometheus
exporter, opt-in OpenTelemetry traces and metrics, structured JSON logs, a CloudEvents
audit trail, a built-in web dashboard, and an HTTP/WebSocket management API all expose
what the server is doing right now and what it has done. This section is the operator's
home for monitoring KubeMQ in production — how to scrape metrics, wire up tracing, read
the logs, query the audit log, and consume the management API.
Each surface answers a different question: Prometheus metrics give you the quantitative
time series, tracing shows you the path of a single message across patterns, logs and the
audit trail record discrete events, the dashboard renders the live picture, and the
management API is the programmatic interface behind it all.
## The observability surfaces [#the-observability-surfaces]
| Surface | What it gives you | Where it's served | Always-on? |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | ----------- |
| Prometheus metrics | Counters, gauges, and histograms for every messaging pattern, queues, RPC latency, cluster health, and the agent platform | `GET /metrics` (`:8080`) | Yes |
| OpenTelemetry tracing | Distributed traces and OTel metrics over OTLP to Jaeger, Grafana Tempo, or Datadog | OTLP export to an external collector | No (opt-in) |
| Structured logging | JSON log lines on stdout — levels, the field set, and trace correlation | stdout | Yes |
| Audit logging | A CloudEvents v1.0 trail of auth, lifecycle, and data-plane error events | `GET /api/v1/audit` (`:8080`) | Yes |
| Built-in dashboard | A live web view of channels, clients, queues, the patterns, cluster topology, and agents | `:8080` | Yes |
| Management API | The HTTP and WebSocket interface for health, stats, snapshots, audit query, and dashboard actions | `:8080` | Yes |
## Push vs pull [#push-vs-pull]
KubeMQ uses a **pull-first** model for metrics and a **push-first** model for traces, and
the two can run at the same time. Logs are written to stdout and captured by your runtime.
| Signal | Model | Consumer |
| --------------------- | ------------------------------------------------------ | ----------------------------------- |
| Prometheus metrics | Pull — Prometheus scrapes `GET /metrics` on demand | Prometheus / Grafana |
| Dashboard snapshots | Pull — the dashboard polls the snapshot endpoints | Built-in dashboard |
| OpenTelemetry traces | Push — the OTLP exporter pushes to a collector | Jaeger / Tempo / Datadog |
| OpenTelemetry metrics | Push — the meter provider exports periodically | OTLP-compatible metrics backend |
| Audit events | Pull — the REST query API | Operator / SIEM |
| Logs | Push — JSON written to stdout, captured by the runtime | Log aggregator (Loki, Splunk, etc.) |
The Prometheus exporter always runs — it also powers the built-in dashboard. OpenTelemetry
is opt-in and is enabled through the telemetry settings.
## Where each surface is served [#where-each-surface-is-served]
The management API port (`:8080`) is the same in-process port that serves the dashboard,
the metrics endpoint, the stats and snapshot endpoints, and the audit query API. When
control-plane auth is enabled, every endpoint below requires at least the **ReadOnly**
role.
| Surface | Endpoint | Access (control-plane auth on) |
| ------------------------ | -------------------------------------------------------------- | ------------------------------ |
| Prometheus scrape | `GET /metrics` (`:8080`) | ReadOnly+ |
| Dashboard snapshots | `GET /api/snapshot`, `GET /api/cluster-snapshot` | ReadOnly+ |
| Audit query | `GET /api/v1/audit`, `GET /api/v1/audit/stats` | ReadOnly+ |
| Channel and client stats | `GET /v1/stats/channels`, `GET /v1/stats/clients` | ReadOnly+ |
| Live message monitor | WebSocket `/api/monitor` | ReadOnly+ |
| Real-time cluster stream | WebSocket `/api/connection` | ReadOnly+ |
| Billing summary | `GET /billing` | ReadOnly+ |
| OTLP export | OTLP gRPC (`:4317`) or HTTP (`:4318`) to an external collector | Collector-side |
| Application logs | stdout (JSON) | — |
## Start here [#start-here]
## Configure it [#configure-it]
The raw configuration keys for telemetry, audit, and server-event notifications — with
their Docker and Helm naming, defaults, and valid values — live in the
[Observability settings reference](/configure/reference/observability). That page
is the source of truth for the settings; this section covers the concepts, how-to, and the
full management API.
# Structured Logging (/operate/observability/logging)
KubeMQ writes **structured JSON logs to stdout**. Every log line is a single JSON object, which
makes the output easy to capture and parse with any container log aggregator — Loki, Splunk,
Datadog, Fluentd, and others — with no extra log files or rotation to manage.
## Log format [#log-format]
Every log line is one JSON object on stdout:
```json
{
"level": "INFO",
"time": "2026-06-29T12:34:56.789Z",
"component": "grpc",
"caller": "grpc/grpc.go:144",
"msg": "starting gRPC server",
"host": "kubemq-node-1"
}
```
The field set:
| JSON key | Description |
| ----------- | --------------------------------------------------------------------------------------------------------------- |
| `msg` | The log message string. |
| `level` | The level in ALL-CAPS: `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`. |
| `time` | ISO 8601 timestamp with milliseconds. |
| `component` | The logger name (the KubeMQ component that emitted the line, e.g. `grpc`, `array`). |
| `caller` | The trimmed `file:line` source location. |
| `stack` | A stack trace — present on `ERROR` and above when configured. |
| `host` | The node hostname. |
| `trace_id` | Trace identifier — present only when [tracing](/operate/observability/tracing) is enabled and a span is active. |
| `span_id` | Span identifier — present only when tracing is enabled and a span is active. |
Components enrich their loggers with extra context fields (such as `client_id` or `channel`)
that appear as additional key/value pairs on the relevant lines.
## Log levels [#log-levels]
KubeMQ maps six application levels onto the JSON `level` field. `Info` is the default.
| Level | JSON `level` |
| ----- | ---------------- |
| Trace | `DEBUG` |
| Debug | `DEBUG` |
| Info | `INFO` (default) |
| Warn | `WARN` |
| Error | `ERROR` |
| Fatal | `FATAL` |
Trace and Debug both emit at the `DEBUG` JSON level. The numeric values used in configuration
are `0=Trace`, `1=Debug`, `2=Info`, `3=Warn`, `4=Error`, `5=Fatal`.
## Configure the level [#configure-the-level]
Set the log level at startup with the `log.level` config key (or its environment-variable
binding). The default is `2` (Info).
```yaml title="config.yaml"
log:
level: 2 # 0=Trace 1=Debug 2=Info 3=Warn 4=Error 5=Fatal
```
Or set it with an environment variable, which overrides the config-file value at startup:
```bash
LOGLEVEL=1 # Debug
```
```yaml title="values.yaml"
log:
level: 2 # 0=Trace 1=Debug 2=Info 3=Warn 4=Error 5=Fatal
```
## Change the level at runtime [#change-the-level-at-runtime]
The log level can be changed **without restarting the server**. The management API exposes a
`set_log_level` action on its unified request endpoint; a single call takes effect immediately
across every component, because all loggers share one level. See the
[Action Endpoint](/operate/observability/api-reference/actions) for how requests are sent to the
management API.
## Correlate logs with traces [#correlate-logs-with-traces]
When [OpenTelemetry tracing](/operate/observability/tracing) is enabled, log lines emitted during a
traced operation carry `trace_id` and `span_id` fields. This lets you pivot from a log line to
the matching trace (and back) in your backend — Jaeger, Grafana Tempo, Datadog, and others.
```json
{
"level": "ERROR",
"time": "2026-06-29T12:34:56.789Z",
"component": "array",
"caller": "array/events_sender.go:42",
"msg": "publish pub/sub event error",
"host": "kubemq-node-1",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"span_id": "00f067aa0ba902b7",
"error": "context deadline exceeded"
}
```
These two fields appear **only when tracing is on and a span is active** for the operation being
logged. With tracing disabled, the fields are simply absent and logging behaves exactly as
before. Correlation therefore requires OpenTelemetry — see the
[Distributed Tracing](/operate/observability/tracing) page to enable it.
## Ship logs [#ship-logs]
Because KubeMQ logs JSON to stdout, any log shipper that captures container stdout works without
extra configuration — **Loki**, **Splunk**, **Datadog**, and **Fluentd** all ingest the lines as
structured records.
To correlate logs and traces in Grafana, link a Loki datasource to a Tempo datasource:
1. Ship KubeMQ's JSON logs to Loki (for example via Promtail or the Grafana Agent).
2. In the Loki datasource settings, configure **Derived Fields** with a regex that extracts
`trace_id`, pointing it at the Tempo datasource.
3. Log lines from traced operations then show a clickable **Tempo** button that opens the trace
in the same time range.
For Datadog, the `trace_id` and `span_id` field names already match the fields Datadog expects
for log–trace correlation, once your log pipeline parses them from the JSON body.
## Related [#related]
# Prometheus Metrics (/operate/observability/metrics)
KubeMQ exposes an always-on Prometheus exporter that reports message counts, byte volumes,
client counts, queue health, RPC latency, cluster state, and agent-platform activity. It
needs no configuration — it is running the moment KubeMQ starts.
## Overview [#overview]
The Prometheus exporter is **always on**. The same in-process metrics also power the
built-in dashboard and its snapshot system, so the numbers
you scrape with Prometheus and the numbers you see in the dashboard come from one source.
Metrics are served in-process by the [management API](/operate/observability/api-reference) at
`GET /metrics` on the management API port (`:8080`) — the same port that serves health
probes, stats, and the dashboard. There is no separate listener and no extra setup; the
endpoint returns standard Prometheus text format.
Prometheus is the **pull** path and is always on. KubeMQ also supports an opt-in
**push** path — OpenTelemetry metrics over OTLP — covered on the
[Distributed Tracing](/operate/observability/tracing) page. The OTel `pending` instrument
(active in-flight messages) is exported only over OTLP; there is no equivalent Prometheus
series.
## Scraping KubeMQ [#scraping-kubemq]
Read the endpoint directly with `curl`:
```bash
curl http://localhost:8080/metrics
```
Point Prometheus at the same endpoint with a `scrape_config`:
```yaml title="prometheus.yml"
scrape_configs:
- job_name: kubemq
metrics_path: /metrics
static_configs:
- targets: ["kubemq:8080"]
```
## Labels [#labels]
Core messaging metrics carry a shared label set. The `type` and `side` label values are
determined by the messaging pattern.
| Label | Values | Description |
| ----------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `node` | host name | The KubeMQ node that recorded the metric. |
| `client_id` | client id | The connected client. **Aggregated away on store series** — the per-channel store collectors drop `client_id` at collect time, so queue, RPC-latency, and similar series carry only `node`, `type`, `side`, `channel`. |
| `type` | `events`, `events_store`, `commands`, `queries`, `queues` | The messaging pattern. |
| `side` | `send`, `receive` | Whether the metric is for the producing or consuming side of the channel. |
| `channel` | channel name | The message channel the metric belongs to. |
## Core messaging metrics [#core-messaging-metrics]
These collectors track message activity across all five patterns. They share the label set
above.
| Prometheus name | Type | Description |
| --------------------------- | ------- | ----------------------------------------- |
| `kubemq_messages_count` | Counter | Total messages sent/received per channel. |
| `kubemq_messages_volume` | Counter | Total byte volume per channel. |
| `kubemq_messages_last_seen` | Gauge | Unix timestamp (ms) of last activity. |
| `kubemq_messages_delayed` | Counter | Number of delayed queue messages. |
| `kubemq_messages_expired` | Counter | Total expired queue messages. |
| `kubemq_messages_waiting` | Gauge | Queue messages waiting for consumers. |
| `kubemq_clients_count` | Gauge | Connected client count per channel. |
| `kubemq_errors_count` | Counter | Total errors per channel. |
| `kubemq_messages_responses` | Counter | Total RPC responses per channel. |
## Queue health metrics [#queue-health-metrics]
These series give queue operators visibility into redelivery, dead-letter dispositions,
backlog age, and dwell time. They use the standard four-label set (`node`, `type`, `side`,
`channel`) — `client_id` is aggregated away — except where a row notes an extra label.
| Prometheus name | Type | Description |
| ----------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kubemq_queue_redelivery_total` | Counter | Total queue redeliveries per channel — a receive whose post-increment receive count is greater than one — attributed to the source queue channel on the `receive` side. Uses the standard four labels only (no extra label). |
| `kubemq_queue_dlq_total` | Counter | Total queue dead-letter dispositions per channel, attributed to the source channel on the `receive` side. Carries one **extra `reason` label**: `routed` (re-published to the configured dead-letter queue) or `dropped` (no DLQ configured or a marshal error — silent data loss made visible). The `reason` label is on `dlq_total` only, not on `redelivery_total`. |
| `kubemq_queue_backlog_age_seconds` | Gauge | Age (seconds) of the oldest undelivered message in the backlog, per channel (`queues`/`receive`). A live gauge recomputed each 5-second snapshot cycle; `0` when the backlog is empty or fully delivered, and `0` after a restart until the next cycle rebuilds it. |
| `kubemq_queue_dwell_seconds_sum` | Counter | Cumulative sum of per-message dwell times (seconds) on the `receive` side — the time from when a message entered the queue until it was delivered to a consumer. Survives restarts. Divide by `kubemq_queue_dwell_messages_total` for the average dwell. |
| `kubemq_queue_dwell_messages_total` | Counter | Cumulative count of messages whose dwell time was recorded. Survives restarts. The denominator for the average dwell time. |
## RPC latency metrics [#rpc-latency-metrics]
These series measure command and query round-trip latency on the `send` side. They use the
standard four-label set.
| Prometheus name | Type | Description |
| -------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kubemq_rpc_latency_seconds_sum` | Counter | Cumulative sum of RPC round-trip times (seconds) on the `send` side of a command or query channel — measured from request dispatch until the response is received. Survives restarts. Recorded only when a response is received (errored or timed-out requests with no response are excluded). Divide by `kubemq_rpc_latency_calls_total` for the average. |
| `kubemq_rpc_latency_calls_total` | Counter | Cumulative count of RPC calls whose round-trip latency was recorded (`type ∈ {commands, queries}`, `side = send`). Survives restarts. The denominator for the average RPC latency. |
**Cache-served queries are excluded.** The query cache short-circuits before the latency is
recorded, so these series measure real backend round-trips (cache misses), not local cache
lookups. Commands have no cache and are always recorded.
## Latency histograms [#latency-histograms]
Three histogram instruments expose latency **distributions** (so you can compute percentiles
with `histogram_quantile`), labeled by `node`, `type`, and `side`.
| Prometheus name | Type | Description |
| -------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kubemq_rpc_latency_histogram_seconds` | Histogram | RPC round-trip latency distribution (commands and queries, `send` side). Same gate as `kubemq_rpc_latency_seconds_sum` — recorded only when a response is received; cache-served queries are excluded. |
| `kubemq_queue_dwell_histogram_seconds` | Histogram | Queue dwell-time distribution (`queues`, `receive` side). Its population matches `kubemq_queue_dwell_messages_total`. |
| `kubemq_operation_duration_seconds` | Histogram | Per-operation send duration for patterns with no round-trip: `type ∈ {events, events_store, queues}` on the `send` side. Commands and queries use `kubemq_rpc_latency_histogram_seconds` for their percentile source. |
All three histograms share one bucket set (seconds), giving a consistent latency vocabulary
across `/metrics`:
```text
0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60
```
## Cluster & infra metrics [#cluster--infra-metrics]
These gauges expose node health, cluster role, and configured peer state, labeled by `node`
(and `role` where noted).
| Prometheus name | Type | Description |
| ------------------------------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kubemq_cluster_leader` | Gauge | `1` if this node is the cluster leader **or** a standalone node (both act as the authoritative message processor); `0` otherwise. |
| `kubemq_cluster_role` | Gauge | Info-gauge: emits `1` for the active `role` label only, `0` for the rest. `role ∈ {leader, follower, candidate, standalone}`. Filter with `kubemq_cluster_role == 1`. |
| `kubemq_cluster_ready` | Gauge | `1` when the node is ready to accept traffic; `0` during startup or unhealthy states. Matches `/ready`: a clustered node that cannot reach the cluster coordinator over its internal forwarding network also reports `0`. |
| `kubemq_cluster_healthy` | Gauge | `1` when the node is healthy. Distinct from ready — a node can be healthy but not yet ready. |
| `kubemq_cluster_state_seconds` | Gauge | Seconds since the last cluster state change. For clustered nodes: seconds since the last ready-settle (leadership election or follower sync). For standalone nodes: seconds since server startup. |
| `kubemq_cluster_peers` | Gauge | The configured bootstrap peer count, including self (minimum `1` for standalone). This is the configured bootstrap peer list, **not** live cluster membership — on a running cluster, live membership may differ during leader transitions. |
On a single-node (standalone) server, `kubemq_cluster_leader = 1`,
`kubemq_cluster_role{role="standalone"} = 1`, `kubemq_cluster_ready = 1` once ready, and
`kubemq_cluster_peers = 1`. On a multi-node cluster, exactly one node has
`kubemq_cluster_leader = 1` at any given time.
## Kafka connector metrics [#kafka-connector-metrics]
The [Kafka connector](/connectors/kafka) exports its own series. They count Kafka wire traffic
only — a record produced over Kafka and read back over gRPC appears once here and once in the
core messaging metrics.
| Prometheus name | Type | Labels | Description |
| ---------------------------------------- | ------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kubemq_kafka_connections` | Gauge | — | Open Kafka client connections on this node. |
| `kubemq_kafka_operations_total` | Counter | `operation` | Kafka requests served, by operation (`produce`, `fetch`, …). |
| `kubemq_kafka_operation_avg_latency_ms` | Gauge | `operation` | Average latency of those requests, in milliseconds. |
| `kubemq_kafka_messages_total` | Counter | `op` | Records produced and fetched (`op` is `produced` or `fetched`). |
| `kubemq_kafka_message_bytes_total` | Counter | `op` | Wire bytes produced and fetched. |
| `kubemq_kafka_produce_rejects_total` | Counter | `error_code` | Produce requests refused, by Kafka error code — for example `MESSAGE_TOO_LARGE` or `TOPIC_AUTHORIZATION_FAILED`. |
| `kubemq_kafka_consumer_group_lag` | Gauge | `group`, `topic`, `partition` | Log-end offset minus the group's committed offset. |
| `kubemq_kafka_share_group_lag` | Gauge | `group`, `topic`, `partition` | Records behind the log end for a [share group](/connectors/kafka/how-to/share-groups). |
| `kubemq_kafka_share_group_in_flight` | Gauge | `group`, `topic`, `partition` | Stored batches a share group has delivered and not yet had acknowledged — held by a consumer, or released and waiting to be delivered again. Counts batches, not records. |
| `kubemq_kafka_share_group_redelivered` | Gauge | `group`, `topic`, `partition` | Stored batches whose delivery count is 2 or more. |
| `kubemq_kafka_undecodable_records_total` | Counter | `path` | Records in a Kafka topic that could not be decoded and were skipped. Any value above zero deserves a look. |
```text
# Alert: a consumer group has fallen behind by more than 10k records on any partition
max by (group, topic) (kubemq_kafka_consumer_group_lag) > 10000
# Produce refusals per second, by reason
sum by (error_code) (rate(kubemq_kafka_produce_rejects_total[5m]))
```
## Agent-platform metrics [#agent-platform-metrics]
KubeMQ's [agent platform](/aiway) emits its own series for MCP tool calls and A2A agent
traffic. These use domain-specific labels rather than the core messaging label set.
| Prometheus name | Type | Labels | Description |
| -------------------------------------- | --------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------- |
| `kubemq_mcp_tool_calls_total` | Counter | `tool`, `status` | Total MCP tool calls. |
| `kubemq_mcp_tool_duration_seconds` | Histogram | `tool` | Duration of MCP tool calls (seconds). |
| `kubemq_a2a_requests_total` | Counter | `agent_id`, `method`, `status` | Total A2A requests routed to agents (any path — HTTP gateway and MCP bridge). |
| `kubemq_a2a_request_duration_seconds` | Histogram | `agent_id` | Duration of A2A requests routed to agents (any path — HTTP gateway and MCP bridge). |
| `kubemq_a2a_errors_total` | Counter | `agent_id`, `error_code` | Total A2A errors for requests routed to agents (any path — HTTP gateway and MCP bridge). |
| `kubemq_a2a_stream_events_total` | Counter | `agent_id` | Total A2A stream events delivered to SSE clients (receive side). |
| `kubemq_a2a_stream_outcomes_total` | Counter | `agent_id`, `outcome` | Total A2A streams by terminal `outcome` (`done`, `error`, `idle_timeout`, `canceled`) — exactly one per stream. |
| `kubemq_a2a_registry_operations_total` | Counter | `op`, `status` | Total agent registry operations (register, deregister, heartbeat, expire). |
| `kubemq_a2a_sse_streams_active` | Gauge | — | Current number of active A2A SSE streams. |
The MCP tool-call histogram (`kubemq_mcp_tool_duration_seconds`) uses the bucket set
`0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10`; the A2A request-duration histogram
(`kubemq_a2a_request_duration_seconds`) uses `0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60`.
**The `agent_id` label is bounded.** The first \~1000 distinct agent IDs each get their own
label value; every subsequent agent ID collapses into `agent_id="other"`. This is cardinality
protection — for exact per-agent leaderboards across the whole fleet, use the dashboard rather
than Prometheus.
**The `method` label is sanitized.** Each A2A method is checked against a fixed allowlist of
known methods; anything not in the list is recorded as `method="unknown"`. This keeps a
malformed or malicious request stream from exploding Prometheus label cardinality.
In a cluster, these counters are aggregated across all nodes, so the totals reflect the whole
deployment rather than a single replica.
## PromQL examples [#promql-examples]
```text
# RPC p99 latency (commands) — rolling 5-minute window
histogram_quantile(0.99,
rate(kubemq_rpc_latency_histogram_seconds_bucket{type="commands"}[5m])
)
# Queue dwell p95 across all nodes
histogram_quantile(0.95,
sum(rate(kubemq_queue_dwell_histogram_seconds_bucket[5m])) by (le)
)
# Alert: no leader exists across the cluster
sum(kubemq_cluster_leader) == 0
# Alert: a node has been not-ready for more than 60 seconds
kubemq_cluster_ready == 0 and kubemq_cluster_state_seconds > 60
```
## Grafana [#grafana]
Point Grafana at the Prometheus instance scraping KubeMQ and build dashboards on the series
above — message rates from `kubemq_messages_count`, queue health from the
`kubemq_queue_*` series, latency percentiles from the histogram buckets, and cluster state
from the `kubemq_cluster_*` gauges.
## Internal channels [#internal-channels]
Internal cluster channels are filtered out of the user-facing metrics, so they never appear
in the series above.
# Distributed Tracing (/operate/observability/tracing)
KubeMQ integrates with [OpenTelemetry](https://opentelemetry.io/) (OTel) for distributed
tracing and metrics export. It is **opt-in** — off by default and turned on with a single
`telemetry.enable` flag. When enabled, KubeMQ instruments every messaging operation (Events,
Events Store, Queues, Commands, Queries) with spans and exports them, along with a set of OTel
metric instruments, over the OTLP protocol to any compatible backend (Jaeger, Grafana Tempo,
Datadog, and others).
Tracing is **complementary** to the [always-on Prometheus exporter](/operate/observability/metrics).
Prometheus gives you a pull-based metric series for dashboards and alerting; OpenTelemetry adds
distributed traces with context propagation across services, plus a parallel push-based metric
stream over OTLP.
## Enable it [#enable-it]
Telemetry is controlled by the master `telemetry.enable` switch (off by default). Turn it on,
then tune the traces, metrics, and exporter sub-blocks as needed.
```yaml title="config.yaml"
telemetry:
enable: true
```
```yaml title="values.yaml"
telemetry:
enable: true
```
The full set of telemetry settings — service name, traces/metrics sub-blocks, exporter
options, and the Docker/Helm key and environment-variable mappings — lives in the
[Configuration reference](/configure/reference/observability). This page covers what
those settings do and what you get when telemetry is on.
## OTLP exporter [#otlp-exporter]
Traces and metrics are exported over OTLP to a collector or backend. The exporter is configured
under `telemetry.exporter`.
| Setting | Default | Description |
| ------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `protocol` | `grpc` | OTLP wire protocol — `grpc` (default endpoint `:4317`) or `http` (default endpoint `:4318`). |
| `endpoint` | `localhost:4317` | OTLP collector endpoint (`host:port`). |
| `insecure` | `true` | When `true`, the connection skips TLS. Set `false` to use TLS 1.2+ to the collector. |
| `compression` | `gzip` | Payload compression — `gzip` or `none`. |
| `timeout` | `10s` | Export request timeout (Go duration). |
| `headers` | `{}` | Custom headers sent with each export request (a `key/value` map). **`config.yaml`-only** — there is no environment-variable or CRD path for this field. |
| Protocol | Default endpoint | Notes |
| -------- | ---------------- | -------------------------------------------------- |
| `grpc` | `localhost:4317` | OTLP over gRPC. Supports TLS and gzip compression. |
| `http` | `localhost:4318` | OTLP over HTTP. Supports TLS and gzip compression. |
## Samplers [#samplers]
The sampler decides which traces are recorded. It is set with `telemetry.traces.sampler`; the
ratio-based samplers read `telemetry.traces.samplingRatio` (a fraction from `0.0` to `1.0`).
| Sampler | Description |
| ---------------- | ---------------------------------------------------------------------------------------------------- |
| `always_on` | Sample every trace. |
| `always_off` | Sample no traces. |
| `trace_id_ratio` | Sample a fraction of traces based on `samplingRatio` (e.g. `0.1` = 10% of traces). |
| `parent_based` | Use the parent span's sampling decision; falls back to `trace_id_ratio` for root spans. The default. |
## Environment variable overrides [#environment-variable-overrides]
Standard OTel environment variables are read after the config file loads and **override** the
file values. These are the recommended way to set exporter and sampler options from outside the
container.
| Environment variable | Overrides | Notes |
| -------------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `OTEL_SERVICE_NAME` | Service name | The OTLP `service.name` resource attribute. |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | Exporter endpoint | |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Exporter protocol | `grpc` or `http`. |
| `OTEL_EXPORTER_OTLP_INSECURE` | Exporter insecure | `"true"` / `"false"`. |
| `OTEL_EXPORTER_OTLP_COMPRESSION` | Exporter compression | `gzip` or `none`. |
| `OTEL_EXPORTER_OTLP_TIMEOUT` | Exporter timeout | Integer milliseconds (e.g. `"10000"`). |
| `OTEL_EXPORTER_OTLP_HEADERS` | Exporter headers | Comma-separated `key=value` pairs. |
| `OTEL_TRACES_SAMPLER` | Traces sampler | OTel sampler names: `always_on`, `always_off`, `traceidratio`, `parentbased_traceidratio`, `parentbased_always_on`, `parentbased_always_off`. |
| `OTEL_TRACES_SAMPLER_ARG` | Traces sampling ratio | Float string (e.g. `"0.1"`). |
KubeMQ also derives its own `TELEMETRY_*` environment variables from the config keys (for
example `TELEMETRY_ENABLE`, `TELEMETRY_EXPORTER_ENDPOINT`). Where both exist, **prefer the
standard `OTEL_*` variables** above — they are the conventional way to configure an OTel
exporter and are read after the KubeMQ-specific values.
## What gets traced [#what-gets-traced]
When tracing is on, every messaging pattern is instrumented. Each operation produces a span
whose name encodes the operation and channel.
| Span name | Span kind | Pattern |
| -------------------------------- | --------- | ---------------- |
| `process events.{channel}` | Consumer | Events |
| `process events-store.{channel}` | Consumer | Events Store |
| `process commands.{channel}` | Consumer | Commands |
| `process queries.{channel}` | Consumer | Queries |
| `process queues.{channel}` | Consumer | Queues (single) |
| `publish-batch queues.{channel}` | Consumer | Queues (batch) |
| `deliver queues.{channel}` | Producer | Queues (receive) |
In addition, the shared HTTP server applies automatic **transport-level tracing** to all
HTTP-based connectors (REST, A2A, MCP, and CloudEvents) under the service name `kubemq-http`.
When telemetry is enabled, each HTTP request handled by these connectors generates a span with
the standard HTTP attributes:
| Attribute | Description |
| ------------------ | ------------------------------ |
| `http.method` | HTTP method (GET, POST, etc.). |
| `http.route` | Matched route pattern. |
| `http.status_code` | Response status code. |
| `http.target` | Request path. |
The A2A and MCP connectors and the agent registry have **no application-level OTel
instrumentation** — they rely on this transport-level tracing for HTTP spans (method, route,
status, duration) and on [Prometheus metrics](/operate/observability/metrics) for per-operation
detail. Per-operation spans (which agent was invoked, tool execution time, JSON-RPC method)
are not currently traced.
## Span attributes [#span-attributes]
Every messaging span carries a standard set of attributes:
| Attribute | Description | Example |
| ------------------------------- | ------------------------------ | --------------------------------------------------------- |
| `messaging.system` | Always `kubemq`. | `kubemq` |
| `messaging.operation.type` | Operation type. | `process`, `receive` |
| `messaging.destination.name` | Channel name. | `orders` |
| `messaging.message.id` | Message, event, or request ID. | `abc123` |
| `messaging.client.id` | Client identifier. | `my-producer` |
| `messaging.kubemq.channel_type` | Channel type. | `events`, `events_store`, `commands`, `queries`, `queues` |
Queue spans add these extra attributes:
| Attribute | Description |
| ------------------------------------ | ---------------------------------------------------------------------- |
| `messaging.kubemq.expiration` | Message expiration (e.g. `30s`). |
| `messaging.kubemq.delay` | Message delay (e.g. `10s`). |
| `messaging.kubemq.max_receive` | Max receive count before a message is routed to the dead-letter queue. |
| `messaging.batch.message_count` | Number of messages in a batch. |
| `messaging.kubemq.batch_error_count` | Number of failed messages in a batch. |
| `messaging.kubemq.messages_received` | Messages received in a receive operation. |
| `messaging.kubemq.messages_expired` | Messages expired during a receive. |
## Context propagation [#context-propagation]
KubeMQ propagates trace context through message tags using the W3C **TraceContext** and
**Baggage** propagators:
1. **Inject** — when a message passes through the tracing middleware, the current trace context
is injected into the message's `Tags` map.
2. **Extract** — when the message arrives at the message broker, the trace headers are read back
out of the `Tags` map to link the consumer span to the producer.
This enables end-to-end tracing across **producer → the message broker → consumer**, even when
the producer and consumer use different SDKs.
## Error recording [#error-recording]
When a send or receive operation fails, the tracing middleware:
1. Records the error on the span.
2. Sets the span status to `Error`.
3. Increments the `messaging.kubemq.errors.count` metric (see below).
## OTel metrics [#otel-metrics]
In addition to traces, KubeMQ exports a set of OTel metric instruments over OTLP. These are a
parallel push-based path to the [pull-based Prometheus series](/operate/observability/metrics) and
are useful when your backend already ingests OTLP metrics (Mimir, Datadog, and others). All
instruments share the labels `node`, `type` (channel type), `side` (`send` / `receive`), and
`channel`.
| Instrument | Type | Unit | Description |
| ------------------------------------- | ------------- | ----- | ------------------------------ |
| `messaging.kubemq.messages.count` | Counter | — | Total messages processed. |
| `messaging.kubemq.messages.volume` | Counter | bytes | Total message volume in bytes. |
| `messaging.kubemq.errors.count` | Counter | — | Total errors. |
| `messaging.kubemq.messages.pending` | UpDownCounter | — | Pending messages. |
| `messaging.kubemq.messages.delayed` | UpDownCounter | — | Delayed queue messages. |
| `messaging.kubemq.messages.expired` | Counter | — | Expired messages. |
| `messaging.kubemq.messages.waiting` | UpDownCounter | — | Queue messages waiting. |
| `messaging.kubemq.clients.count` | UpDownCounter | — | Connected clients. |
| `messaging.kubemq.messages.last_seen` | Gauge | — | Last activity timestamp. |
| `messaging.kubemq.responses.count` | Counter | — | RPC responses. |
| `messaging.kubemq.operation.duration` | Histogram | s | Per-operation latency. |
| `messaging.kubemq.message.size` | Histogram | bytes | Message payload size. |
| `messaging.kubemq.queue.depth` | UpDownCounter | — | Queue depth per channel. |
The OTel `messaging.kubemq.operation.duration` histogram uses its **own** bucket boundaries
(in seconds), which are **distinct** from the Prometheus histogram buckets on the
[Metrics page](/operate/observability/metrics) — do not assume they match:
```text
0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10
```
## Export to a backend [#export-to-a-backend]
Point the exporter at any OTLP-compatible collector or backend. The example below runs Jaeger
locally and exports traces to it over OTLP gRPC.
```yaml title="docker-compose.yml"
services:
jaeger:
image: jaegertracing/all-in-one:latest
ports:
- "4317:4317" # OTLP gRPC
- "16686:16686" # Jaeger UI
environment:
- COLLECTOR_OTLP_ENABLED=true
```
```yaml title="config.yaml"
telemetry:
enable: true
serviceName: "kubemq-production"
traces:
enable: true
sampler: "parent_based"
samplingRatio: 0.1 # sample 10% of traces
metrics:
enable: true
exportInterval: "30s"
exporter:
protocol: "grpc"
endpoint: "jaeger:4317"
insecure: true
compression: "gzip"
```
The same exporter block works for **Grafana Tempo** and **Datadog** — point `endpoint` at the
relevant OTLP receiver, switch `protocol` to `http` if the backend expects OTLP/HTTP, and supply
any required auth headers via `OTEL_EXPORTER_OTLP_HEADERS`.
## Correlate with logs [#correlate-with-logs]
When tracing is on, KubeMQ adds `trace_id` and `span_id` fields to the log lines emitted during
a traced operation, so you can pivot between a log line and its trace in your backend. See
[Structured Logging](/operate/observability/logging) for the log field set and a Grafana
Loki ↔ Tempo derived-fields setup.
## Related [#related]
# C++ SDK (/sdks/cpp)
The KubeMQ C++ SDK provides a high-performance, type-safe C++17 client for all messaging patterns. It requires C++17 (GCC 9+, Clang 9+, MSVC 2019+), CMake 3.16+, gRPC v1.78+, and Protobuf v5.29+.
## Installation [#installation]
### vcpkg (Recommended) [#vcpkg-recommended]
```bash
vcpkg install grpc protobuf nlohmann-json
cmake -B build -S . \
-DCMAKE_TOOLCHAIN_FILE=[vcpkg-root]/scripts/buildsystems/vcpkg.cmake
cmake --build build --parallel
```
### CMake FetchContent [#cmake-fetchcontent]
```cmake title="CMakeLists.txt"
include(FetchContent)
FetchContent_Declare(
kubemq-cpp
GIT_REPOSITORY https://github.com/kubemq-io/kubemq-cpp.git
GIT_TAG v1.0.0
)
FetchContent_MakeAvailable(kubemq-cpp)
target_link_libraries(your_app PRIVATE kubemq_static)
```
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/cpp/tutorials/first-message) to connect a client and publish and receive your first message.
# C# SDK (/sdks/csharp)
The KubeMQ .NET SDK provides an async-first C# client for all messaging patterns with dependency injection support, auto-reconnection, and retry policies. It requires .NET 8.0 (LTS).
## Installation [#installation]
```bash
dotnet add package KubeMQ.SDK.CSharp
```
Or via PackageReference:
```xml title="csproj"
```
**Prerequisites:** .NET 8.0 (LTS), KubeMQ server v3.0+.
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/csharp/tutorials/first-message) to connect a client and publish and receive your first message.
# Elixir SDK (/sdks/elixir)
The KubeMQ Elixir SDK provides an OTP-native GenServer client for all messaging patterns. It requires Elixir 1.15+ and communicates with KubeMQ over gRPC.
## Installation [#installation]
Add `kubemq` to your `mix.exs` dependencies:
```elixir title="mix.exs"
defp deps do
[
{:kubemq, "~> 1.0"}
]
end
```
Then fetch:
```bash
mix deps.get
```
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/elixir/tutorials/first-message) to connect a client and publish and receive your first message.
# Go SDK (/sdks/go)
The KubeMQ Go SDK provides a high-performance gRPC client for all messaging patterns. It requires Go 1.25 or later and is compatible with KubeMQ server v2.2+.
## Installation [#installation]
```bash
go get github.com/kubemq-io/kubemq-go/v2
```
## Quick connect [#quick-connect]
```go
import "github.com/kubemq-io/kubemq-go/v2"
// Connect to a local KubeMQ server on the default gRPC port.
client, err := kubemq.NewClient(ctx, kubemq.WithAddress("localhost", 50000))
```
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/go/tutorials/first-message) to connect a client and publish and receive your first message.
# Java SDK (/sdks/java)
The KubeMQ Java SDK provides a type-safe client for all messaging patterns over gRPC transport with built-in TLS, authentication, and reconnection support. It requires Java 11+ (LTS releases 11, 17, and 21 are tested).
## Installation [#installation]
### Maven [#maven]
```xml title="pom.xml"
io.kubemq.sdk
kubemq-sdk-Java
3.1.1
```
### Gradle [#gradle]
```groovy title="build.gradle"
implementation 'io.kubemq.sdk:kubemq-sdk-Java:3.1.1'
```
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/java/tutorials/first-message) to connect a client and publish and receive your first message.
# Kotlin SDK (/sdks/kotlin)
The KubeMQ Kotlin SDK provides a coroutine-first client for all messaging patterns over gRPC transport with DSL builders, Flow-based subscriptions, TLS, authentication, and automatic reconnection. It requires Kotlin 2.0+ and JDK 11, 17, or 21.
## Installation [#installation]
### Gradle (Kotlin DSL) [#gradle-kotlin-dsl]
```kotlin title="build.gradle.kts"
dependencies {
implementation("io.kubemq.sdk:kubemq-sdk-kotlin:1.0.1")
}
```
Or use the BOM for version alignment:
```kotlin title="build.gradle.kts"
dependencies {
implementation(platform("io.kubemq.sdk:kubemq-sdk-kotlin-bom:1.0.1"))
implementation("io.kubemq.sdk:kubemq-sdk-kotlin")
}
```
### Maven [#maven]
```xml title="pom.xml"
io.kubemq.sdk
kubemq-sdk-kotlin
1.0.1
```
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/kotlin/tutorials/first-message) to connect a client and publish and receive your first message.
# Node.js SDK (/sdks/nodejs)
The KubeMQ Node.js SDK is a TypeScript-first client with auto-retry, structured error handling, and OpenTelemetry integration. It requires Node.js 20+ and communicates with KubeMQ over gRPC.
## Installation [#installation]
```bash
npm install kubemq-js
```
**Prerequisites:** Node.js 20+ (22, 24 also supported).
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/nodejs/tutorials/first-message) to connect a client and publish and receive your first message.
# Python SDK (/sdks/python)
The KubeMQ Python SDK provides async clients for all messaging patterns. It requires Python 3.9+ and communicates with KubeMQ over gRPC.
## Installation [#installation]
```bash
pip install kubemq
```
For optional features:
```bash
pip install kubemq[otel] # OpenTelemetry integration
```
## Quick connect [#quick-connect]
```python
from kubemq import AsyncPubSubClient
# Connect to a local KubeMQ server on the default gRPC port.
async with AsyncPubSubClient(address="localhost:50000") as client:
...
```
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/python/tutorials/first-message) to connect a client and publish and receive your first message.
# Rust SDK (/sdks/rust)
The KubeMQ Rust SDK provides an async gRPC client for all messaging patterns. It is built on Tokio and Tonic, supports all five KubeMQ patterns (Events, Events Store, Queues, Commands, Queries), and is compatible with KubeMQ server v2.2+.
## Installation [#installation]
```bash
cargo add kubemq
```
The SDK requires an async runtime. Add Tokio if you haven't already:
```bash
cargo add tokio --features full
```
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/rust/tutorials/first-message) to connect a client and publish and receive your first message.
# Ruby SDK (/sdks/ruby)
The KubeMQ Ruby SDK provides a thread-safe gRPC client for all messaging patterns. It requires Ruby 3.1 or later and is compatible with KubeMQ server v2.2+.
## Installation [#installation]
```bash
gem install kubemq
```
Or add to your `Gemfile`:
```ruby title="Gemfile"
gem 'kubemq'
```
## Next: send your first message [#next-send-your-first-message]
With the SDK installed, continue to the [first-message tutorial](/sdks/ruby/tutorials/first-message) to connect a client and publish and receive your first message.
# Authentication (/aiway/a2a/guides/authentication)
The A2A connector is guarded by the same JWT Bearer authentication as every other
KubeMQ connector. You authenticate to the **gateway** (`/a2a/*`) and the **registry**
(`/agents/*`) with an `Authorization: Bearer` header; KubeMQ verifies the token,
records who you are, and propagates your identity to the agent as
`X-KubeMQ-Caller-ID` — without ever forwarding your token downstream.
## Overview [#overview]
Authentication for A2A is the connector-wide model described in
[Auth & Security](/connectors/reference/auth-and-security), applied to two route
families:
* **Gateway** — `POST /a2a/` and the SSE stream endpoint route requests to
agents. A verified token identifies the caller; that identity becomes the agent's
`X-KubeMQ-Caller-ID`.
* **Registry** — `POST /agents/register`, `/agents/heartbeat`, `/agents/deregister`,
and `DELETE /agents/` are owned operations. The principal in your token
becomes the agent's `registered_by`, and only that principal may later modify or
delete it.
When server authentication is **disabled**, every caller is treated as the synthetic
`anonymous` principal and no token is required. When it is **enabled**, an unverified
or missing token is rejected — as a JSON-RPC `-32010` error on `/a2a/*`, or HTTP 401
on the REST registry endpoints.
A2A discovery is intentionally public: `GET /.well-known/agent-card.json` and any
per-agent `/.well-known/agent-card.json` path bypass authentication so a caller can
read an [agent card](/aiway/a2a/agent-cards) before it has a token.
## How it works [#how-it-works]
The token is verified once, at the shared auth middleware, before the request reaches
the gateway. The middleware attaches your claims (including `ClientID`) to the request;
the gateway uses that identity for registry ownership and stamps it onto the agent call
as `X-KubeMQ-Caller-ID`. The agent receives the caller's identity — never the raw
token.
*KubeMQ verifies the token at the edge and forwards the caller's identity — not the token — to the agent.*
The `Authorization` header is **stripped** before the gateway calls the agent — along
with `Cookie`, `Proxy-Authorization`, and other sensitive or hop-by-hop headers. Agents
must trust `X-KubeMQ-Caller-ID` for the caller's identity, not a forwarded token. If an
agent needs its own credential, register it with the agent's URL and let the agent
authenticate downstream itself.
## Authenticating gateway calls [#authenticating-gateway-calls]
Add an `Authorization: Bearer ` header to any `POST /a2a/` request. The
header carrying the token is consumed by KubeMQ; the rest of the request — including
any `X-*` headers — is forwarded to the agent. These snippets send a `message/send`
with a Bearer token; on success the agent echoes its `received_headers` and you can see
that `Authorization` is absent and `X-KubeMQ-Caller-ID` is present.
```bash
curl -X POST http://localhost:9090/a2a/echo-agent-01 \
-H "Authorization: Bearer $A2A_BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "Authenticated call"}]}
}
}'
```
```csharp
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "echo-agent-01";
var token = Environment.GetEnvironmentVariable("A2A_BEARER_TOKEN");
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Authenticated call" })
}
}
};
using var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"{KubeMqUrl}/a2a/{AgentId}")
{
Content = new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json")
};
request.Headers.Add("Authorization", $"Bearer {token}");
var resp = await client.SendAsync(request);
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
var received = data["result"]?["received_headers"];
Console.WriteLine($"Status: {(int)resp.StatusCode}");
Console.WriteLine($"Caller ID seen by agent: {received?["X-KubeMQ-Caller-ID"]?.GetValue()}");
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "echo-agent-01"
)
func main() {
token := os.Getenv("A2A_BEARER_TOKEN")
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Authenticated call"}},
},
},
}
data, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", kubemqURL+"/a2a/"+agentID, bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
received, _ := result["result"].(map[string]interface{})["received_headers"].(map[string]interface{})
fmt.Printf("Status: %d\n", resp.StatusCode)
fmt.Printf("Caller ID seen by agent: %v\n", received["X-KubeMQ-Caller-ID"])
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "echo-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var token = System.getenv("A2A_BEARER_TOKEN");
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/send",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Authenticated call")))
)
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token)
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
var received = data.path("result").path("received_headers");
System.out.println("Status: " + resp.statusCode());
System.out.println("Caller ID seen by agent: " + received.path("X-KubeMQ-Caller-ID").asText());
}
}
```
```python
import json
import os
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "echo-agent-01"
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "Authenticated call"}]},
},
}
token = os.environ["A2A_BEARER_TOKEN"]
async with httpx.AsyncClient() as client:
resp = await client.post(
f"{KUBEMQ_URL}/a2a/{AGENT_ID}",
json=payload,
headers={"Authorization": f"Bearer {token}"},
)
data = resp.json()
received = data.get("result", {}).get("received_headers", {})
print(f"Status: {resp.status_code}")
print(f"Caller ID seen by agent: {received.get('X-KubeMQ-Caller-ID')}")
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "echo-agent-01";
const token = process.env.A2A_BEARER_TOKEN;
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: {
message: { parts: [{ text: "Authenticated call" }] },
},
};
const resp = await fetch(`${KUBEMQ_URL}/a2a/${AGENT_ID}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(request),
});
const data = await resp.json();
const received = data.result?.received_headers || {};
console.log(`Status: ${resp.status}`);
console.log(`Caller ID seen by agent: ${received["x-kubemq-caller-id"]}`);
```
## Authenticating registry calls [#authenticating-registry-calls]
The registry uses the **same** `Authorization: Bearer` header. The difference is what
KubeMQ does with your identity: `POST /agents/register` records the token's principal
as the agent's `registered_by`, and ownership-protected operations
(`heartbeat`, `deregister`, `DELETE`) verify that the caller's principal matches.
```bash
curl -X POST http://localhost:9090/agents/register \
-H "Authorization: Bearer $A2A_BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"url": "http://echo-agent.internal:8000/",
"skill_tags": ["echo"]
}'
```
```csharp
const string KubeMqUrl = "http://localhost:9090";
var token = Environment.GetEnvironmentVariable("A2A_BEARER_TOKEN");
var card = new JsonObject
{
["agent_id"] = "echo-agent-01",
["name"] = "Echo Agent",
["url"] = "http://echo-agent.internal:8000/",
["skill_tags"] = new JsonArray("echo")
};
using var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"{KubeMqUrl}/agents/register")
{
Content = new StringContent(card.ToJsonString(), Encoding.UTF8, "application/json")
};
request.Headers.Add("Authorization", $"Bearer {token}");
var resp = await client.SendAsync(request);
var data = JsonNode.Parse(await resp.Content.ReadAsStringAsync())!;
Console.WriteLine($"registered_by: {data["registered_by"]?.GetValue()}");
```
```go
token := os.Getenv("A2A_BEARER_TOKEN")
card := map[string]interface{}{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"url": "http://echo-agent.internal:8000/",
"skill_tags": []string{"echo"},
}
data, _ := json.Marshal(card)
req, _ := http.NewRequest("POST", "http://localhost:9090/agents/register", bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
fmt.Printf("registered_by: %v\n", result["registered_by"])
```
```java
var token = System.getenv("A2A_BEARER_TOKEN");
var card = Map.of(
"agent_id", "echo-agent-01",
"name", "Echo Agent",
"url", "http://echo-agent.internal:8000/",
"skill_tags", List.of("echo")
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents/register"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token)
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(card)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
System.out.println("registered_by: " + data.path("registered_by").asText());
```
```python
token = os.environ["A2A_BEARER_TOKEN"]
card = {
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"url": "http://echo-agent.internal:8000/",
"skill_tags": ["echo"],
}
async with httpx.AsyncClient() as client:
resp = await client.post(
"http://localhost:9090/agents/register",
json=card,
headers={"Authorization": f"Bearer {token}"},
)
data = resp.json()
print(f"registered_by: {data.get('registered_by')}")
```
```typescript
const token = process.env.A2A_BEARER_TOKEN;
const card = {
agent_id: "echo-agent-01",
name: "Echo Agent",
url: "http://echo-agent.internal:8000/",
skill_tags: ["echo"],
};
const resp = await fetch(`${KUBEMQ_URL}/agents/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(card),
});
const data = await resp.json();
console.log(`registered_by: ${data.registered_by}`);
```
## Agent ownership [#agent-ownership]
When authentication is enabled, the registry enforces ownership so one principal cannot
hijack or delete another principal's agents.
* On `POST /agents/register`, the agent's `registered_by` is set automatically from the
token's principal — clients cannot spoof it in the body.
* `heartbeat`, `deregister`, and `DELETE /agents/` succeed only when the caller's
principal matches the agent's `registered_by`. A mismatch returns **403 Forbidden**
(ownership conflict).
* If an agent's `registered_by` is **blank** while auth is enabled, the ownership check
**fails closed** — no principal can modify or delete it. Re-register the agent with a
token to take ownership.
| Operation | Auth | Ownership check |
| ------------------------------------------------ | -------------------------- | --------------------------------------------------------- |
| `GET /.well-known/agent-card.json` | Public | — |
| `GET /agents`, `GET /agents/` | Bearer (when auth enabled) | None (read-only) |
| `POST /agents/register` | Bearer | Sets `registered_by`; rejects cross-principal re-register |
| `POST /agents/heartbeat` | Bearer | Caller must own the agent |
| `POST /agents/deregister`, `DELETE /agents/` | Bearer | Caller must own the agent |
| `POST /a2a/` (gateway) | Bearer | None (any authenticated caller may message any agent) |
## Caller identity reaches the agent [#caller-identity-reaches-the-agent]
Because the gateway strips `Authorization` before calling the agent, the agent learns
who is calling from the **`X-KubeMQ-Caller-ID`** header, which the virtual subscriber
always injects with the caller's `ClientID`. This holds regardless of which transport
originated the call (A2A HTTP, gRPC, REST, or the MCP bridge), so an agent can apply its
own per-caller logic without parsing tokens.
| Header | Set by | Visible to agent | Contains |
| ----------------------- | ------------------ | ----------------- | ---------------------------------- |
| `Authorization: Bearer` | Caller | **No** (stripped) | The caller's JWT |
| `X-KubeMQ-Caller-ID` | Virtual subscriber | **Yes** | The caller's `ClientID` (identity) |
When server authentication is disabled, the injected `X-KubeMQ-Caller-ID` reflects the
synthetic `anonymous` identity — agents that gate on caller identity should account for
this in non-secured deployments.
## Related [#related]
# Building Agents (/aiway/a2a/guides/building-agents)
An A2A agent is a **plain HTTP server** that speaks JSON-RPC 2.0. It runs anywhere,
needs no KubeMQ SDK, and joins the platform by registering its URL with the
[registry](/aiway/a2a/registry). The gateway's per-agent virtual subscriber
does all the broker work — your agent just answers HTTP POSTs.
## Overview [#overview]
A compliant agent has to do three things:
1. **Listen** on a URL, e.g. `http://localhost:18080/`.
2. **Answer** `POST` requests whose body is a JSON-RPC 2.0 request, returning a
JSON-RPC 2.0 response (or an SSE stream for `message/stream`).
3. **Register** its [agent card](/aiway/a2a/agent-cards) — including the
absolute `url` — with KubeMQ so the gateway can route to it.
That is the entire contract. Your agent never connects to the broker, never imports a
KubeMQ client, and never deals with protobuf. KubeMQ's virtual subscriber subscribes
to Queries on `_AGENTS_.agents/` on your behalf, POSTs each request to
your registered URL, and relays the reply back through the broker.
This replaces the previous SDK-based model. Agents no longer subscribe to
Queries through the gRPC SDK — the `AgentCard.URL` field is now **required** and must
be an absolute `http://` or `https://` URL. See [Migration](#migration-from-the-sdk-model).
## How it works [#how-it-works]
When a caller targets your agent, the request flows through the gateway and your
agent's virtual subscriber, which turns it into an ordinary HTTP POST to your server.
*Your agent is a plain HTTP server; the gateway's virtual subscriber bridges the broker to HTTP POST.*
The virtual subscriber always injects an `X-KubeMQ-Caller-ID` header carrying the
originating caller's identity, and forwards caller `X-*` headers (stripping
hop-by-hop and sensitive ones). Your agent reads them like any other HTTP header.
## Build the agent server [#build-the-agent-server]
The minimal agent is an HTTP server with one `POST /` handler that parses the
JSON-RPC body, processes it, and returns a JSON-RPC response with the same `id`. The
example below is an **echo agent** that starts its server, then registers its card
with KubeMQ.
Always start the HTTP server **before** registering. KubeMQ may route a request to
your agent the moment registration succeeds.
```csharp
using System.Text.Json;
using System.Text.Json.Nodes;
public static class Agent
{
private const string KubeMqUrl = "http://localhost:9090";
private const string AgentId = "echo-agent-01";
private const int AgentPort = 18080;
public static async Task RunAsync()
{
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.MapPost("/", async (HttpContext context) =>
{
var body = (await JsonSerializer.DeserializeAsync(context.Request.Body))!;
var response = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = body["id"]?.DeepClone(),
["result"] = new JsonObject { ["echo"] = body.DeepClone() }
};
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(response.ToJsonString());
});
app.Urls.Add($"http://0.0.0.0:{AgentPort}");
await app.StartAsync();
Console.WriteLine($"Agent listening on port {AgentPort}");
await RegisterAgentAsync();
await app.WaitForShutdownAsync();
}
private static async Task RegisterAgentAsync()
{
var card = new JsonObject
{
["agent_id"] = AgentId,
["name"] = "Echo Agent",
["description"] = "A simple echo agent for testing",
["version"] = "1.0.0",
["url"] = $"http://localhost:{AgentPort}/",
["skills"] = new JsonArray(new JsonObject
{
["id"] = "echo", ["name"] = "Echo",
["description"] = "Echoes back the received message",
["tags"] = new JsonArray("test", "echo")
}),
["defaultInputModes"] = new JsonArray("text"),
["defaultOutputModes"] = new JsonArray("text"),
["protocolVersions"] = new JsonArray("1.0")
};
using var client = new HttpClient();
var resp = await client.PostAsync(
$"{KubeMqUrl}/agents/register",
new StringContent(card.ToJsonString(), System.Text.Encoding.UTF8, "application/json"));
Console.WriteLine($"Registered: {(int)resp.StatusCode}");
var body = await resp.Content.ReadAsStringAsync();
Console.WriteLine(JsonSerializer.Serialize(JsonNode.Parse(body), new JsonSerializerOptions { WriteIndented = true }));
}
}
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"os/signal"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "echo-agent-01"
agentPort = 18080
)
func handler(w http.ResponseWriter, r *http.Request) {
var body map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp := map[string]interface{}{
"jsonrpc": "2.0",
"id": body["id"],
"result": map[string]interface{}{"echo": body},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func registerAgent() {
card := map[string]interface{}{
"agent_id": agentID,
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": fmt.Sprintf("http://localhost:%d/", agentPort),
"skills": []map[string]interface{}{
{
"id": "echo",
"name": "Echo",
"description": "Echoes back the received message",
"tags": []string{"test", "echo"},
},
},
"defaultInputModes": []string{"text"},
"defaultOutputModes": []string{"text"},
"protocolVersions": []string{"1.0"},
}
data, _ := json.Marshal(card)
resp, err := http.Post(kubemqURL+"/agents/register", "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Registration failed: %v\n", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Registered: %d\n", resp.StatusCode)
var pretty bytes.Buffer
json.Indent(&pretty, body, "", " ")
fmt.Println(pretty.String())
}
func main() {
http.HandleFunc("/", handler)
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", agentPort))
if err != nil {
fmt.Fprintf(os.Stderr, "Listen failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Agent listening on port %d\n", agentPort)
go http.Serve(ln, nil)
registerAgent()
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
fmt.Println("\nShutting down")
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
public class Agent {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "echo-agent-01";
static final int AGENT_PORT = 18080;
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(AGENT_PORT), 0);
server.createContext("/", exchange -> {
if (!"POST".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(405, -1);
return;
}
var body = MAPPER.readTree(exchange.getRequestBody());
var response = MAPPER.createObjectNode();
response.put("jsonrpc", "2.0");
response.set("id", body.get("id"));
response.putObject("result").set("echo", body);
byte[] out = MAPPER.writeValueAsBytes(response);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, out.length);
try (OutputStream os = exchange.getResponseBody()) { os.write(out); }
});
server.start();
System.out.println("Agent listening on port " + AGENT_PORT);
var card = Map.of(
"agent_id", AGENT_ID,
"name", "Echo Agent",
"description", "A simple echo agent for testing",
"version", "1.0.0",
"url", "http://localhost:" + AGENT_PORT + "/",
"skills", List.of(Map.of(
"id", "echo", "name", "Echo",
"description", "Echoes back the received message",
"tags", List.of("test", "echo")
)),
"defaultInputModes", List.of("text"),
"defaultOutputModes", List.of("text"),
"protocolVersions", List.of("1.0")
);
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents/register"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(card)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("Registered: " + resp.statusCode());
System.out.println(MAPPER.writerWithDefaultPrettyPrinter()
.writeValueAsString(MAPPER.readTree(resp.body())));
Thread.currentThread().join();
}
}
```
```python
"""Echo agent that registers with KubeMQ."""
import asyncio
import json
import signal
import httpx
from aiohttp import web
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "echo-agent-01"
AGENT_PORT = 18080
async def handle_request(request: web.Request) -> web.Response:
body = await request.json()
return web.json_response({
"jsonrpc": "2.0",
"id": body.get("id"),
"result": {"echo": body},
})
async def register_agent() -> None:
card = {
"agent_id": AGENT_ID,
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": f"http://localhost:{AGENT_PORT}/",
"skills": [
{
"id": "echo",
"name": "Echo",
"description": "Echoes back the received message",
"tags": ["test", "echo"],
}
],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"],
}
async with httpx.AsyncClient() as client:
resp = await client.post(f"{KUBEMQ_URL}/agents/register", json=card)
print(f"Registered: {resp.status_code}")
print(json.dumps(resp.json(), indent=2))
async def main() -> None:
app = web.Application()
app.router.add_post("/", handle_request)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "0.0.0.0", AGENT_PORT)
await site.start()
print(f"Agent listening on port {AGENT_PORT}")
await register_agent()
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, stop.set)
await stop.wait()
await runner.cleanup()
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
import express from "express";
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "echo-agent-01";
const AGENT_PORT = 18080;
const app = express();
app.use(express.json());
app.post("/", (req, res) => {
const body = req.body;
console.log("Received request:", JSON.stringify(body));
res.json({
jsonrpc: "2.0",
id: body.id,
result: { echo: body },
});
});
app.listen(AGENT_PORT, async () => {
console.log(`Agent listening on port ${AGENT_PORT}`);
const card = {
agent_id: AGENT_ID,
name: "Echo Agent",
description: "A simple echo agent for testing",
version: "1.0.0",
url: `http://localhost:${AGENT_PORT}/`,
skills: [
{
id: "echo",
name: "Echo",
description: "Echoes back the received message",
tags: ["test", "echo"],
},
],
defaultInputModes: ["text"],
defaultOutputModes: ["text"],
protocolVersions: ["1.0"],
};
const resp = await fetch(`${KUBEMQ_URL}/agents/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(card),
});
const data = await resp.json();
console.log("Registered:", JSON.stringify(data, null, 2));
});
```
You can register the same way with plain curl — useful for a sidecar agent or a
language not shown above:
```bash
curl -X POST http://localhost:9090/agents/register \
-H "Content-Type: application/json" \
-d '{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"description": "A simple echo agent for testing",
"version": "1.0.0",
"url": "http://localhost:18080/",
"skills": [{"id": "echo", "name": "Echo", "tags": ["test", "echo"]}],
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"protocolVersions": ["1.0"]
}'
```
## Handle streaming (message/stream) [#handle-streaming-messagestream]
If your agent produces incremental output, support the `message/stream` method.
Inspect the request's `method`; when it is `message/stream`, respond with
`Content-Type: text/event-stream` and write SSE events instead of a single JSON body.
Each event uses an `event:` name and a JSON `data:` line, and the stream ends with a
terminal `task.done` (or `task.error`) event.
```text
event: task.status
data: {"type": "status_update", "payload": {"status": "working", "progress": 1, "total": 5}}
event: task.done
data: {"type": "done", "payload": {"final_result": "completed"}}
```
The handler below extends the echo agent: it emits five `task.status` events, then a
`task.done`, for `message/stream` requests, and falls back to a plain JSON-RPC reply
for everything else.
```csharp
app.MapPost("/", async (HttpContext context) =>
{
var body = (await JsonSerializer.DeserializeAsync(context.Request.Body))!;
var method = body["method"]?.GetValue() ?? "";
if (method == "message/stream")
{
context.Response.ContentType = "text/event-stream";
context.Response.Headers.CacheControl = "no-cache";
for (int i = 1; i <= 5; i++)
{
var ev = JsonSerializer.Serialize(new { type = "status_update", payload = new { status = "working", progress = i, total = 5 } });
await context.Response.WriteAsync($"event: task.status\ndata: {ev}\n\n");
await context.Response.Body.FlushAsync();
await Task.Delay(500);
}
var done = JsonSerializer.Serialize(new { type = "done", payload = new { final_result = "completed", event_count = 5 } });
await context.Response.WriteAsync($"event: task.done\ndata: {done}\n\n");
await context.Response.Body.FlushAsync();
return;
}
var response = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = body["id"]?.DeepClone(),
["result"] = new JsonObject { ["echo"] = body.DeepClone() }
};
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(response.ToJsonString());
});
```
```go
func handleStream(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming not supported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
for i := 1; i <= 5; i++ {
event, _ := json.Marshal(map[string]interface{}{
"type": "status_update",
"payload": map[string]interface{}{
"status": "working", "progress": i, "total": 5,
},
})
fmt.Fprintf(w, "event: task.status\ndata: %s\n\n", event)
flusher.Flush()
time.Sleep(500 * time.Millisecond)
}
done, _ := json.Marshal(map[string]interface{}{
"type": "done",
"payload": map[string]interface{}{"final_result": "completed", "event_count": 5},
})
fmt.Fprintf(w, "event: task.done\ndata: %s\n\n", done)
flusher.Flush()
}
func handler(w http.ResponseWriter, r *http.Request) {
var body map[string]interface{}
json.NewDecoder(r.Body).Decode(&body)
if method, _ := body["method"].(string); method == "message/stream" {
handleStream(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"jsonrpc": "2.0",
"id": body["id"],
"result": map[string]interface{}{"echo": body},
})
}
```
```java
server.createContext("/", exchange -> {
if (!"POST".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(405, -1);
return;
}
var body = MAPPER.readTree(exchange.getRequestBody());
var method = body.path("method").asText("");
if ("message/stream".equals(method)) {
exchange.getResponseHeaders().set("Content-Type", "text/event-stream");
exchange.getResponseHeaders().set("Cache-Control", "no-cache");
exchange.sendResponseHeaders(200, 0);
try (OutputStream os = exchange.getResponseBody()) {
for (int i = 1; i <= 5; i++) {
var event = MAPPER.writeValueAsString(Map.of(
"type", "status_update",
"payload", Map.of("status", "working", "progress", i, "total", 5)
));
os.write(("event: task.status\ndata: " + event + "\n\n").getBytes());
os.flush();
try { Thread.sleep(500); } catch (InterruptedException ie) { break; }
}
var done = MAPPER.writeValueAsString(Map.of(
"type", "done",
"payload", Map.of("final_result", "completed", "event_count", 5)
));
os.write(("event: task.done\ndata: " + done + "\n\n").getBytes());
os.flush();
}
return;
}
var response = MAPPER.createObjectNode();
response.put("jsonrpc", "2.0");
response.set("id", body.get("id"));
response.putObject("result").set("echo", body);
byte[] out = MAPPER.writeValueAsBytes(response);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, out.length);
try (OutputStream os = exchange.getResponseBody()) { os.write(out); }
});
```
```python
async def handle_stream(request: web.Request) -> web.StreamResponse:
resp = web.StreamResponse(
status=200,
headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"},
)
await resp.prepare(request)
for i in range(1, 6):
event = json.dumps({"type": "status_update", "payload": {"status": "working", "progress": i, "total": 5}})
await resp.write(f"event: task.status\ndata: {event}\n\n".encode())
await asyncio.sleep(0.5)
done = json.dumps({"type": "done", "payload": {"final_result": "completed", "event_count": 5}})
await resp.write(f"event: task.done\ndata: {done}\n\n".encode())
await resp.write_eof()
return resp
async def handle_request(request: web.Request) -> web.Response:
body = await request.json()
method = body.get("method", "")
if method == "message/stream":
return await handle_stream(request)
return web.json_response({"jsonrpc": "2.0", "id": body.get("id"), "result": {"echo": body}})
```
```typescript
app.post("/", async (req, res) => {
if (req.body.method === "message/stream") {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.flushHeaders();
for (let i = 1; i <= 5; i++) {
const event = {
type: "status_update",
payload: { status: "working", progress: i, total: 5 },
};
res.write(`event: task.status\ndata: ${JSON.stringify(event)}\n\n`);
await new Promise((r) => setTimeout(r, 500));
}
const done = { type: "done", payload: { final_result: "completed", event_count: 5 } };
res.write(`event: task.done\ndata: ${JSON.stringify(done)}\n\n`);
res.end();
} else {
res.json({ jsonrpc: "2.0", id: req.body.id, result: { echo: req.body } });
}
});
```
The gateway maps your SSE event names to caller-facing envelopes: `task.status`,
`task.artifact`, `task.done`, and `task.error`. See
[SSE behavior](/aiway/a2a/guides/sse-behavior) for the full wire format,
keepalive, and cancel-on-disconnect rules.
## Agent lifecycle [#agent-lifecycle]
Beyond serving requests, an agent manages its presence in the registry:
| Stage | Endpoint | When |
| ---------- | ------------------------- | ----------------------------------------------------- |
| Register | `POST /agents/register` | After the HTTP server is listening, on startup. |
| Heartbeat | `POST /agents/heartbeat` | Every 30–60s to refresh `last_seen` and beat the TTL. |
| Deregister | `POST /agents/deregister` | On graceful shutdown, before stopping the server. |
If an agent stops sending heartbeats, the registry expires it after
`AgentTTLSeconds` (default 300) and tears down its virtual subscriber. Refresh
liveness with a periodic heartbeat:
```bash
curl -X POST http://localhost:9090/agents/heartbeat \
-H "Content-Type: application/json" \
-d '{"agent_id": "echo-agent-01"}'
```
On shutdown, deregister first so callers stop being routed to the agent, then drain
in-flight requests and stop the server:
```bash
curl -X POST http://localhost:9090/agents/deregister \
-H "Content-Type: application/json" \
-d '{"agent_id": "echo-agent-01"}'
```
When authentication is enabled, only the principal that registered an agent can
heartbeat or deregister it. See [Authentication](/aiway/a2a/guides/authentication).
## Migration from the SDK model [#migration-from-the-sdk-model]
Earlier KubeMQ versions required receiving agents to use the gRPC SDK to subscribe to
Queries on `_AGENTS_.agents/`. That path is gone — replaced by the
virtual-subscriber architecture, where agents are plain HTTP servers.
**What changed:**
* Agents no longer connect to KubeMQ via the gRPC SDK to receive tasks, and no longer
call `SubscribeToQueries()` on agent channels.
* The `AgentCard.URL` field is now **required** and must be an absolute `http://` or
`https://` URL. Relative paths (e.g. `/a2a/`) are rejected.
* The old default URL auto-assignment (`/a2a/` when `url` was empty) has
been removed.
**To migrate an existing agent:**
1. Deploy it as a standard HTTP server that accepts `POST` requests with
`Content-Type: application/json`.
2. Implement a JSON-RPC 2.0 handler at the root URL (or any path).
3. Update registration to include the full absolute URL, e.g.
`"url": "http://my-agent:8080/"`.
4. Remove all KubeMQ SDK dependencies from the agent.
5. For streaming agents, implement SSE responses for `message/stream`.
The **caller side is unchanged** — callers can keep using any KubeMQ transport (gRPC,
REST, the A2A HTTP gateway, or the MCP bridge) to reach agents.
## Related [#related]
# Concurrency & Limits (/aiway/a2a/guides/concurrency)
The A2A gateway protects itself and your agents with three hard limits: a **per-agent
concurrency cap**, a **response-size cap**, and **timeout capping**. Each is enforced by
the agent's virtual subscriber, returns a predictable error when crossed, and is tunable
through [`A2aConfig`](/aiway/a2a/configuration). This guide explains the
behavior of each limit and shows how to observe it from a client.
## Overview [#overview]
Every registered agent runs behind a **virtual subscriber** — the bridge that turns an
inbound JSON-RPC request into an outbound HTTP POST to the agent's URL. That subscriber is
where the limits live, so they apply **per agent**, not per client. Multiple callers
hitting the same `agent_id` share the same budget.
| Limit | Config field | Default | What happens when exceeded |
| ----------------------------- | --------------------------------------------- | ------------------ | ---------------------------------------------------------------------------- |
| Concurrent in-flight requests | `AgentMaxConcurrency` | `100` | Overflow request rejected immediately — `Executed: false`, JSON-RPC `-32603` |
| Agent response body size | `AgentMaxResponseBytes` | `10485760` (10 MB) | Response dropped — `Executed: false`, JSON-RPC `-32603` |
| Per-request timeout | `DefaultTimeoutSeconds` / `MaxTimeoutSeconds` | `300` / `3600` | Capped silently, or `-32001` (agent timeout) on expiry |
All three surface as **transport errors** (`Executed: false`) — the request never reached
your agent's business logic, so a retry is generally safe. See
[Error handling](/aiway/a2a/error-handling) for the transport-vs-application
distinction.
## Per-agent concurrency limit [#per-agent-concurrency-limit]
Each agent's virtual subscriber holds a buffered-channel **semaphore** sized to
`AgentMaxConcurrency` (default **100**). The count covers **both** synchronous
(`message/send`) and streaming (`message/stream`) requests in flight at the same time.
| Request # | Behavior |
| --------- | ---------------------------------------------------------------------- |
| 1–100 | A handler is spawned and the request is proxied to the agent |
| 101+ | Immediately rejected — no goroutine spawned, the agent is never called |
When the semaphore is full, the overflow request comes back as a JSON-RPC `-32603` error:
```json
{
"jsonrpc": "2.0",
"id": 101,
"error": {
"code": -32603,
"message": "internal error: concurrency limit exceeded"
}
}
```
At the transport layer this is recorded as `Executed: false` with the reason
`server busy: concurrency limit reached`. Because the request was never processed,
retrying after a short backoff is safe.
The limit is **per agent**, not per client. To raise headroom for a busy agent, increase
`AgentMaxConcurrency` in [configuration](/aiway/a2a/configuration) — or run more
agent instances behind distinct `agent_id`s and route across them.
### Observe the limit [#observe-the-limit]
Fire more than `AgentMaxConcurrency` requests at one agent simultaneously and at least one
comes back with `-32603`. The snippets below send **101** concurrent `message/send`
requests and count how many were rejected.
```bash
# Fire 101 requests in parallel; at least one returns -32603 "concurrency limit exceeded".
for i in $(seq 1 101); do
curl -s -X POST http://localhost:9090/a2a/concurrency-agent-01 \
-H "Content-Type: application/json" \
-d "{\"jsonrpc\":\"2.0\",\"id\":$i,\"method\":\"message/send\",\"params\":{\"message\":{\"parts\":[{\"text\":\"Request #$i\"}]}}}" &
done | grep -c -- -32603
wait
# => prints the number of requests rejected by the concurrency limit (>= 1)
```
```csharp
using System.Text;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "concurrency-agent-01";
const int NumRequests = 101;
async Task SendRequest(HttpClient httpClient, int requestId)
{
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = requestId,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = $"Request #{requestId}" })
}
}
};
var resp = await httpClient.PostAsync(
$"{KubeMqUrl}/a2a/{AgentId}",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
return JsonNode.Parse(await resp.Content.ReadAsStringAsync());
}
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
Console.WriteLine($"Sending {NumRequests} concurrent requests (limit is 100)...");
var tasks = Enumerable.Range(1, NumRequests)
.Select(i => SendRequest(client, i))
.ToArray();
var results = await Task.WhenAll(tasks);
int successes = 0, concurrencyErrors = 0, otherErrors = 0;
foreach (var r in results)
{
if (r?["result"] != null)
successes++;
else if (r?["error"]?["code"]?.GetValue() == -32603)
concurrencyErrors++;
else
otherErrors++;
}
Console.WriteLine($" Successes: {successes}");
Console.WriteLine($" Concurrency errors: {concurrencyErrors} (code -32603)");
Console.WriteLine($" Other errors: {otherErrors}");
if (concurrencyErrors >= 1)
Console.WriteLine($"\nConcurrency limit enforced — {concurrencyErrors} request(s) rejected!");
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "concurrency-agent-01"
numRequests = 101
)
type result struct {
data map[string]interface{}
err error
}
func sendRequest(id int, client *http.Client, wg *sync.WaitGroup, results chan<- result) {
defer wg.Done()
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": id,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": fmt.Sprintf("Request #%d", id)}},
},
},
}
data, _ := json.Marshal(payload)
resp, err := client.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(data))
if err != nil {
results <- result{err: err}
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var r map[string]interface{}
json.Unmarshal(body, &r)
results <- result{data: r}
}
func main() {
fmt.Printf("Sending %d concurrent requests (limit is 100)...\n", numRequests)
client := &http.Client{Timeout: 30 * time.Second}
results := make(chan result, numRequests)
var wg sync.WaitGroup
for i := 1; i <= numRequests; i++ {
wg.Add(1)
go sendRequest(i, client, &wg, results)
}
wg.Wait()
close(results)
successes, concurrencyErrors, otherErrors := 0, 0, 0
for r := range results {
if r.err != nil {
otherErrors++
} else if _, ok := r.data["result"]; ok {
successes++
} else if e, ok := r.data["error"].(map[string]interface{}); ok {
if code, _ := e["code"].(float64); int(code) == -32603 {
concurrencyErrors++
} else {
otherErrors++
}
}
}
fmt.Printf(" Successes: %d\n", successes)
fmt.Printf(" Concurrency errors: %d (code -32603)\n", concurrencyErrors)
fmt.Printf(" Other errors: %d\n", otherErrors)
if concurrencyErrors >= 1 {
fmt.Printf("\nConcurrency limit enforced — %d request(s) rejected!\n", concurrencyErrors)
}
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "concurrency-agent-01";
static final int NUM_REQUESTS = 101;
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(30))
.build();
System.out.println("Sending " + NUM_REQUESTS + " concurrent requests (limit is 100)...");
List>> futures = new ArrayList<>();
for (int i = 1; i <= NUM_REQUESTS; i++) {
var payload = Map.of(
"jsonrpc", "2.0",
"id", i,
"method", "message/send",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Request #" + i)))
)
);
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(30))
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
futures.add(client.sendAsync(req, HttpResponse.BodyHandlers.ofString()));
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
int successes = 0, concurrencyErrors = 0, otherErrors = 0;
for (var future : futures) {
var data = MAPPER.readTree(future.get().body());
if (data.has("result")) {
successes++;
} else if (data.has("error")) {
if (data.path("error").path("code").asInt() == -32603) concurrencyErrors++;
else otherErrors++;
}
}
System.out.println(" Successes: " + successes);
System.out.println(" Concurrency errors: " + concurrencyErrors + " (code -32603)");
System.out.println(" Other errors: " + otherErrors);
if (concurrencyErrors >= 1)
System.out.println("\nConcurrency limit enforced — " + concurrencyErrors + " request(s) rejected!");
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "concurrency-agent-01"
NUM_REQUESTS = 101
async def send_request(client: httpx.AsyncClient, request_id: int) -> dict:
payload = {
"jsonrpc": "2.0",
"id": request_id,
"method": "message/send",
"params": {
"message": {"parts": [{"text": f"Request #{request_id}"}]},
},
}
resp = await client.post(f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload)
return resp.json()
async def main() -> None:
limits = httpx.Limits(max_connections=200)
async with httpx.AsyncClient(timeout=30, limits=limits) as client:
print(f"Sending {NUM_REQUESTS} concurrent requests (limit is 100)...")
tasks = [send_request(client, i) for i in range(1, NUM_REQUESTS + 1)]
results = await asyncio.gather(*tasks)
successes = sum(1 for r in results if "result" in r)
concurrency_errors = sum(1 for r in results if r.get("error", {}).get("code") == -32603)
other_errors = len(results) - successes - concurrency_errors
print(f" Successes: {successes}")
print(f" Concurrency errors: {concurrency_errors} (code -32603)")
print(f" Other errors: {other_errors}")
assert concurrency_errors >= 1, "Expected at least 1 concurrency limit error"
print(f"\nConcurrency limit enforced — {concurrency_errors} request(s) rejected!")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "concurrency-agent-01";
const NUM_REQUESTS = 101;
async function sendRequest(id: number): Promise<{ ok: boolean; errorCode?: number }> {
const request = {
jsonrpc: "2.0",
id,
method: "message/send",
params: { message: { parts: [{ text: `Request ${id}` }] } },
};
const resp = await fetch(`${KUBEMQ_URL}/a2a/${AGENT_ID}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const data = await resp.json();
if (data.error) {
return { ok: false, errorCode: data.error.code };
}
return { ok: true };
}
async function main() {
console.log(`Sending ${NUM_REQUESTS} concurrent requests (limit is 100)...`);
const promises = Array.from({ length: NUM_REQUESTS }, (_, i) => sendRequest(i + 1));
const results = await Promise.all(promises);
const succeeded = results.filter((r) => r.ok).length;
const rejected = results.filter((r) => r.errorCode === -32603).length;
const otherErrors = results.length - succeeded - rejected;
console.log(` Succeeded: ${succeeded} (expect <=100)`);
console.log(` Rejected -32603: ${rejected} (expect >=1)`);
console.log(` Other errors: ${otherErrors}`);
if (rejected > 0) {
console.log(`\nConcurrency limit enforced correctly.`);
}
}
main().catch(console.error);
```
## Response-size limit [#response-size-limit]
The gateway caps the agent's HTTP response body at `AgentMaxResponseBytes` (default
**10 MB**). When an agent returns more than that — for a synchronous reply, or for a single
SSE event's accumulated data lines on a stream — the gateway aborts the relay to protect
itself from memory exhaustion and returns `-32603`:
```json
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32603,
"message": "internal error: response too large"
}
}
```
At the transport layer this is `Executed: false` with the reason
`agent response too large`. Unlike a timeout, retrying the **same** request will fail
identically — the agent is producing an oversized body. Fix it by paginating the agent's
output, streaming the result via [`message/stream`](/aiway/a2a/streaming), or
raising `AgentMaxResponseBytes` if the payload is legitimately large.
### Observe the limit [#observe-the-limit-1]
Target an agent that returns more than 10 MB and inspect the `error` object.
```bash
curl -s -X POST http://localhost:9090/a2a/oversize-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {"message": {"parts": [{"text": "Give me a large response"}]}}
}'
# => {"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"internal error: response too large"}}
```
```csharp
using System.Text;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "oversize-agent-01";
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Give me a large response" })
}
}
};
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
Console.WriteLine("Requesting oversized response (>10MB)...");
var resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/{AgentId}",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
var body = await resp.Content.ReadAsStringAsync();
var data = JsonNode.Parse(body)!;
if (data["error"] != null)
{
var error = data["error"]!;
Console.WriteLine($"Error code: {error["code"]}");
Console.WriteLine($"Error message: {error["message"]}");
Console.WriteLine("\nResponse size limit enforced!");
}
else
{
Console.WriteLine($"Status: {(int)resp.StatusCode}");
Console.WriteLine("Note: Response was accepted (check AgentMaxResponseBytes)");
}
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "oversize-agent-01"
)
func main() {
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Give me a large response"}},
},
},
}
data, _ := json.Marshal(payload)
fmt.Println("Requesting oversized response (>10MB)...")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
if errorObj, ok := result["error"].(map[string]interface{}); ok {
code, _ := errorObj["code"].(float64)
msg, _ := errorObj["message"].(string)
fmt.Printf("Error code: %.0f\n", code)
fmt.Printf("Error message: %s\n", msg)
fmt.Println("\nResponse size limit enforced!")
} else {
fmt.Printf("Status: %d\n", resp.StatusCode)
fmt.Println("Note: Response was accepted (check AgentMaxResponseBytes)")
}
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "oversize-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/send",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Give me a large response")))
)
);
var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(30))
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
System.out.println("Requesting oversized response (>10MB)...");
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
var data = MAPPER.readTree(resp.body());
if (data.has("error")) {
var error = data.path("error");
System.out.println("Error code: " + error.path("code").asInt());
System.out.println("Error message: " + error.path("message").asText());
System.out.println("\nResponse size limit enforced!");
} else {
System.out.println("Status: " + resp.statusCode());
System.out.println("Note: Response was accepted (check AgentMaxResponseBytes)");
}
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "oversize-agent-01"
async def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {"parts": [{"text": "Give me a large response"}]},
},
}
async with httpx.AsyncClient(timeout=30) as client:
print("Requesting oversized response (>10MB)...")
resp = await client.post(f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload)
data = resp.json()
if "error" in data:
error = data["error"]
print(f"Error code: {error.get('code')}")
print(f"Error message: {error.get('message')}")
print("\nResponse size limit enforced!")
else:
print(f"Status: {resp.status_code}")
print("Note: Response was accepted (check AgentMaxResponseBytes)")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "oversize-agent-01";
async function main() {
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: {
message: { parts: [{ text: "Give me a large response" }] },
},
};
console.log("Requesting oversized response (>10MB)...");
const resp = await fetch(`${KUBEMQ_URL}/a2a/${AGENT_ID}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
const data = await resp.json();
if (data.error) {
console.log(`Error code: ${data.error.code}`);
console.log(`Error message: ${data.error.message}`);
console.log("\nResponse size limit enforced!");
} else {
console.log("Unexpected: got success response. Response may have been under the limit.");
}
}
main().catch(console.error);
```
## Timeout capping [#timeout-capping]
Each call carries a deadline. When a client sets `params.configuration.timeout` (in
seconds), the gateway clamps it to the configured window before proxying to the agent:
* If no timeout is supplied, the server applies `DefaultTimeoutSeconds` (**300s**).
* Any value above `MaxTimeoutSeconds` (**3600s**) is **silently reduced** to that ceiling.
* When the deadline passes before the agent replies, the call returns
[`-32001` (agent timeout)](/aiway/a2a/error-handling).
| `params.configuration.timeout` | Effective deadline |
| ------------------------------ | ------------------------------------- |
| not set | `DefaultTimeoutSeconds` (300s) |
| `30` | 30s |
| `3600` | 3600s |
| `99999` | 3600s (capped to `MaxTimeoutSeconds`) |
A **gateway buffer** of \~10 seconds (`GatewayTimeoutBuffer`) is added on top of the
effective deadline before the gateway times out its proxy request, so the gateway never
gives up before the agent's own deadline. Give your HTTP client a slightly longer timeout
than the value you request (a 15s pad is typical) so the client does not abort before the
gateway returns the `-32001` envelope.
## Monitoring [#monitoring]
Concurrency and limit pressure are visible in the Prometheus metrics exported on port 8080
— see [Observability](/connectors/concepts/observability).
| Metric | What it tells you |
| ------------------------------- | ---------------------------------------------------------------------------------- |
| `kubemq_a2a_requests_total` | Total requests per agent and method — rising rejections track concurrency pressure |
| `kubemq_a2a_errors_total` | Error count per agent — `-32603` spikes signal a saturated agent |
| `kubemq_a2a_sse_streams_active` | Active SSE streams per agent (each counts against the concurrency budget) |
## Related [#related]
# SSE Behavior (/aiway/a2a/guides/sse-behavior)
A2A streaming rides on **Server-Sent Events (SSE)**: the gateway proxies a long-lived
`text/event-stream` response from the agent back to the caller. This guide is the
ground-truth reference for *how that stream behaves on the wire* — the exact event
names, the JSON envelope each event carries, the keepalive cadence, when the gateway
closes a stream, and what happens when the caller hangs up.
For the task-level walkthrough of *using* streaming, see
[Streaming (SSE)](/aiway/a2a/streaming). This page focuses on protocol details
you need when writing or debugging an SSE client.
## Overview [#overview]
A stream is opened either by `POST /a2a/:agent_id` with `method: "message/stream"`, or by
`GET /a2a/:agent_id/stream`. In both cases the gateway responds with
`Content-Type: text/event-stream` and relays events the agent emits, framed in the
standard SSE format, until a terminal event arrives or the stream is torn down.
The gateway is a transparent relay: the agent produces the events, KubeMQ's per-agent
**virtual subscriber** bridges them from the agent's HTTP SSE connection onto a temporary
Events channel (`_AGENTS_.stream/`), and the A2A connector replays them to
the caller. The caller only ever sees a normal SSE stream.
## How it works [#how-it-works]
The diagram below traces a single streaming request through the gateway and virtual
subscriber and back to the caller's SSE reader.
*The gateway and virtual subscriber relay the agent's SSE events to the caller; a `task.done` or `task.error` envelope ends the stream.*
## Wire format [#wire-format]
Each SSE message is an `event:` line and a `data:` line, terminated by a blank line. The
`data:` payload is a single-line JSON envelope:
```text
event: task.status
data: {"stream_id":"...","type":"status_update","payload":{"status":"working","progress":3,"total":10}}
```
Multi-line JSON is not used — every envelope is serialized to one line so it fits a single
`data:` field. Responses carry `Content-Type: text/event-stream`.
## Event types [#event-types]
The agent's envelope `type` maps to a named SSE `event`. `task.done` and `task.error` are
**terminal** — after either, stop reading; the gateway closes the connection and the
`kubemq_a2a_sse_streams_active` gauge decrements.
| SSE event | Envelope `type` | Meaning | Terminal |
| --------------- | --------------- | ----------------------------------------------- | -------- |
| `task.status` | `status_update` | Progress update (`status`, `progress`, `total`) | No |
| `task.artifact` | `artifact` | Intermediate artifact delivery | No |
| `task.done` | `done` | Successful completion | Yes |
| `task.error` | `error` | Failure (carries `code` and `message`) | Yes |
| `message` | (default) | Any envelope without a recognized type | No |
Example payloads:
```json
{"type": "status_update", "payload": {"status": "working", "progress": 3, "total": 10}}
{"type": "artifact", "payload": {"name": "result.json", "data": {"key": "value"}}}
{"type": "done", "payload": {"final_result": "completed", "event_count": 10}}
{"type": "error", "payload": {"code": -32001, "message": "agent timeout"}}
```
## Keepalive comments [#keepalive-comments]
To keep proxies and load balancers from dropping an idle connection, the gateway emits an
SSE **comment** line every 30 seconds (`sseKeepaliveInterval`):
```text
: keepalive
```
Comment lines start with `:`, carry no `event:` or `data:` line, and are not stream events.
Standard SSE client libraries ignore them automatically. If you parse the stream by hand,
skip any line beginning with `:`.
## Idle timeout [#idle-timeout]
If no events flow for `MaxSSEIdleSeconds` (default **300s**, set on `A2aConfig`), the
gateway closes the stream. Before closing it sends a terminal `task.error` with code
`-32001` and message `"stream idle timeout"`, then issues a best-effort cancel to the
agent. Agents handling long-running work should emit periodic `task.status` events to keep
the stream alive.
The idle timer measures time *between events*, not total stream duration. A stream can run
indefinitely as long as the agent keeps emitting events (including `task.status`
heartbeats) more often than `MaxSSEIdleSeconds`.
## Client disconnect and cancellation [#client-disconnect-and-cancellation]
When the caller disconnects from an open stream, the gateway detects it and propagates the
cancellation to the agent rather than leaking the upstream connection:
1. The gateway detects the closed caller connection.
2. It sends a Query to the agent's virtual subscriber on `_AGENTS_.agents/`
with `a2a_method: "stream_cancel"` and the `stream_id` (10s timeout).
3. The virtual subscriber cancels its SSE relay goroutine, closing the HTTP SSE connection
to the agent.
4. `kubemq_a2a_sse_streams_active` decrements.
This means closing your SSE reader is a real cancellation signal — the agent is told to
stop, freeing its work and the agent's concurrency slot.
## Reconnection [#reconnection]
A2A streams are **not resumable**. There is no event ID and no `Last-Event-ID` support — a
dropped stream cannot be resumed from where it stopped, and any undelivered events are lost.
To recover, start a fresh stream.
Do not rely on automatic SSE reconnection to continue a task. Because there is no replay,
a reconnect starts a brand-new request. For long-running work, make the agent idempotent
and correlate retries with `context_id`.
For resilience across reconnects:
* Reuse `context_id` so the agent can correlate the new stream with the original request.
* Make agent-side processing idempotent.
* Where supported, check task status before re-streaming so you do not duplicate work.
## Concurrent streams [#concurrent-streams]
Multiple SSE streams can be open at once:
* Multiple streams to the **same agent** are allowed; each one counts against that agent's
`AgentMaxConcurrency` limit (default 100).
* Streams to **different agents** are fully independent.
* `kubemq_a2a_sse_streams_active` tracks all active streams.
## Consuming the stream [#consuming-the-stream]
Read the stream line by line, track the most recent `event:`, parse each `data:` line as
JSON, and stop when you see `task.done` or `task.error`. The snippets below read a
`message/stream` response end to end.
```bash
curl -N -X POST http://localhost:9090/a2a/stream-agent-01 \
-H 'Content-Type: application/json' \
-H 'Accept: text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": { "message": { "parts": [{ "text": "Stream me some updates" }] } }
}'
```
```csharp
using System.Text;
using System.Text.Json;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "stream-agent-01";
var payload = new
{
jsonrpc = "2.0",
id = 1,
method = "message/stream",
@params = new { message = new { parts = new[] { new { text = "Stream me some updates" } } } }
};
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };
var request = new HttpRequestMessage(HttpMethod.Post, $"{KubeMqUrl}/a2a/{AgentId}")
{
Content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json")
};
request.Headers.Add("Accept", "text/event-stream");
Console.WriteLine("Connecting to SSE stream...");
using var resp = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
using var stream = await resp.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
string? eventType = null;
int eventCount = 0;
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
if (line == null) break;
if (line.StartsWith("event: "))
eventType = line[7..];
else if (line.StartsWith("data: ") && eventType != null)
{
eventCount++;
var data = line[6..];
Console.WriteLine($"[{eventType}] {data}");
if (eventType is "task.done" or "task.error")
break;
}
else if (line.Length == 0)
eventType = null;
}
Console.WriteLine($"\nReceived {eventCount} events");
```
```go
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "stream-agent-01"
)
func main() {
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Stream me some updates"}},
},
},
}
data, err := json.Marshal(payload)
if err != nil {
fmt.Fprintf(os.Stderr, "Marshal failed: %v\n", err)
os.Exit(1)
}
req, err := http.NewRequest(http.MethodPost, kubemqURL+"/a2a/"+agentID, bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Request build failed: %v\n", err)
os.Exit(1)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "text/event-stream")
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
fmt.Println("Connecting to SSE stream...")
eventCount := 0
eventType := ""
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "event: ") {
eventType = strings.TrimPrefix(line, "event: ")
} else if strings.HasPrefix(line, "data: ") {
eventCount++
dataStr := strings.TrimPrefix(line, "data: ")
fmt.Printf("[%s] %s\n", eventType, dataStr)
if eventType == "task.done" || eventType == "task.error" {
break
}
}
}
fmt.Printf("\nReceived %d events\n", eventCount)
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "stream-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/stream",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Stream me some updates")))
)
);
var client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(60))
.build();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.header("Accept", "text/event-stream")
.timeout(Duration.ofSeconds(60))
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
System.out.println("Connecting to SSE stream...");
var resp = client.send(req, HttpResponse.BodyHandlers.ofLines());
int eventCount = 0;
String currentEvent = null;
for (var it = resp.body().iterator(); it.hasNext(); ) {
String line = it.next();
if (line.startsWith("event: ")) {
currentEvent = line.substring(7).trim();
} else if (line.startsWith("data: ")) {
eventCount++;
String data = line.substring(6);
System.out.println("[" + currentEvent + "] " + data);
if ("task.done".equals(currentEvent) || "task.error".equals(currentEvent)) {
break;
}
}
}
System.out.println("\nReceived " + eventCount + " events");
}
}
```
```python
import asyncio
import json
import httpx
from httpx_sse import aconnect_sse
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "stream-agent-01"
async def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": {
"message": {"parts": [{"text": "Stream me some updates"}]},
},
}
async with httpx.AsyncClient(timeout=60) as client:
print("Connecting to SSE stream...")
async with aconnect_sse(
client,
"POST",
f"{KUBEMQ_URL}/a2a/{AGENT_ID}",
json=payload,
headers={"Accept": "text/event-stream"},
) as event_source:
event_count = 0
async for event in event_source.aiter_sse():
event_count += 1
data = json.loads(event.data)
print(f"[{event.event}] {json.dumps(data)}")
if event.event in ("task.done", "task.error"):
break
print(f"\nReceived {event_count} events")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "stream-agent-01";
async function main() {
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/stream",
params: { message: { parts: [{ text: "Stream me some updates" }] } },
};
const resp = await fetch(`${KUBEMQ_URL}/a2a/${AGENT_ID}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(request),
});
const reader = resp.body!.getReader();
const decoder = new TextDecoder();
let eventCount = 0;
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const frames = buffer.split("\n\n");
buffer = frames.pop() ?? "";
for (const frame of frames) {
if (!frame.trim()) continue;
let eventType = "";
let eventData = "";
for (const line of frame.split("\n")) {
if (line.startsWith("event: ")) eventType = line.slice(7).trim();
else if (line.startsWith("data: ")) eventData = line.slice(6).trim();
}
if (!eventType) continue;
eventCount++;
const payload = JSON.parse(eventData);
console.log(`[${eventType}] ${JSON.stringify(payload)}`);
if (eventType === "task.done" || eventType === "task.error") {
console.log(`\nStream complete. Total events: ${eventCount}`);
reader.cancel();
return;
}
}
}
}
main().catch(console.error);
```
Always break on `task.done` or `task.error`. Closing the reader after a terminal event is
how the gateway and agent learn the stream is finished — and, mid-stream, how a caller
cancels the agent's work (see [Client disconnect and cancellation](#client-disconnect-and-cancellation)).
## Related [#related]
# Multi-Agent Gateway (/aiway/a2a/scenarios/multi-agent-gateway)
This scenario stands up **three independent agents** — echo, translate, and summarize —
behind a single A2A gateway, then drives them from one client: discover the right agent
by **skill tag**, and dispatch a `message/send` to it by **`agent_id`**. It ties together
the [registry](/aiway/a2a/registry) and
[synchronous messaging](/aiway/a2a/sync-messaging).
## The setup [#the-setup]
Each agent is a plain HTTP server registered by URL — no KubeMQ SDK runs on any of them.
The gateway keeps one [virtual subscriber](/aiway/a2a/architecture) per agent,
so a caller reaches any agent through the same `POST /a2a/{agent_id}` surface. Callers
never address an agent's HTTP URL directly; they address its `agent_id` and the gateway
routes the request.
*One gateway fronts many agents; the client discovers by skill tag and routes by `agent_id`.*
## Step 1 — Register the agents [#step-1--register-the-agents]
Each agent registers its own [agent card](/aiway/a2a/agent-cards) with a unique
`agent_id`, its HTTP `url`, and a `skills` list. The `tags` on each skill are what make the
agent discoverable later. Agents that share a capability (here, `translate` and `summarize`
both carry the `nlp` tag) can be found together.
```bash
# Register three agents with distinct skills.
# (Each agent process registers itself on start; shown here as explicit calls.)
curl -X POST http://localhost:9090/agents/register \
-H "Content-Type: application/json" \
-d '{
"agent_id": "echo-agent-01",
"name": "Echo Agent",
"url": "http://localhost:18081/",
"skills": [{"id": "echo", "name": "Echo", "tags": ["echo"]}]
}'
curl -X POST http://localhost:9090/agents/register \
-H "Content-Type: application/json" \
-d '{
"agent_id": "translate-agent-01",
"name": "Translate Agent",
"url": "http://localhost:18082/",
"skills": [{"id": "translate", "name": "Translate", "tags": ["translate", "nlp"]}]
}'
curl -X POST http://localhost:9090/agents/register \
-H "Content-Type: application/json" \
-d '{
"agent_id": "summarize-agent-01",
"name": "Summarize Agent",
"url": "http://localhost:18083/",
"skills": [{"id": "summarize", "name": "Summarize", "tags": ["summarize", "nlp"]}]
}'
```
```csharp
using System.Text;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
using var client = new HttpClient();
var agents = new[]
{
("echo-agent-01", "Echo Agent", 18081, "echo", new[] { "echo" }),
("translate-agent-01", "Translate Agent", 18082, "translate", new[] { "translate", "nlp" }),
("summarize-agent-01", "Summarize Agent", 18083, "summarize", new[] { "summarize", "nlp" }),
};
foreach (var (id, name, port, skillId, tags) in agents)
{
var card = new JsonObject
{
["agent_id"] = id,
["name"] = name,
["url"] = $"http://localhost:{port}/",
["skills"] = new JsonArray(new JsonObject
{
["id"] = skillId,
["name"] = skillId,
["tags"] = new JsonArray(tags.Select(t => (JsonNode)t!).ToArray())
})
};
var resp = await client.PostAsync(
$"{KubeMqUrl}/agents/register",
new StringContent(card.ToJsonString(), Encoding.UTF8, "application/json"));
Console.WriteLine($"Registered {id}: {(int)resp.StatusCode}");
}
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
const kubemqURL = "http://localhost:9090"
func main() {
agents := []map[string]interface{}{
{
"agent_id": "echo-agent-01", "name": "Echo Agent",
"url": "http://localhost:18081/",
"skills": []map[string]interface{}{{"id": "echo", "name": "Echo", "tags": []string{"echo"}}},
},
{
"agent_id": "translate-agent-01", "name": "Translate Agent",
"url": "http://localhost:18082/",
"skills": []map[string]interface{}{{"id": "translate", "name": "Translate", "tags": []string{"translate", "nlp"}}},
},
{
"agent_id": "summarize-agent-01", "name": "Summarize Agent",
"url": "http://localhost:18083/",
"skills": []map[string]interface{}{{"id": "summarize", "name": "Summarize", "tags": []string{"summarize", "nlp"}}},
},
}
for _, card := range agents {
data, _ := json.Marshal(card)
resp, err := http.Post(kubemqURL+"/agents/register", "application/json", bytes.NewReader(data))
if err != nil {
fmt.Printf("Register %v failed: %v\n", card["agent_id"], err)
continue
}
resp.Body.Close()
fmt.Printf("Registered %v: %d\n", card["agent_id"], resp.StatusCode)
}
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var client = HttpClient.newHttpClient();
var agents = List.of(
Map.of("agent_id", "echo-agent-01", "name", "Echo Agent",
"url", "http://localhost:18081/",
"skills", List.of(Map.of("id", "echo", "name", "Echo", "tags", List.of("echo")))),
Map.of("agent_id", "translate-agent-01", "name", "Translate Agent",
"url", "http://localhost:18082/",
"skills", List.of(Map.of("id", "translate", "name", "Translate", "tags", List.of("translate", "nlp")))),
Map.of("agent_id", "summarize-agent-01", "name", "Summarize Agent",
"url", "http://localhost:18083/",
"skills", List.of(Map.of("id", "summarize", "name", "Summarize", "tags", List.of("summarize", "nlp"))))
);
for (var card : agents) {
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents/register"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(card)))
.build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("Registered " + card.get("agent_id") + ": " + resp.statusCode());
}
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
AGENTS = [
{"agent_id": "echo-agent-01", "name": "Echo Agent", "url": "http://localhost:18081/",
"skills": [{"id": "echo", "name": "Echo", "tags": ["echo"]}]},
{"agent_id": "translate-agent-01", "name": "Translate Agent", "url": "http://localhost:18082/",
"skills": [{"id": "translate", "name": "Translate", "tags": ["translate", "nlp"]}]},
{"agent_id": "summarize-agent-01", "name": "Summarize Agent", "url": "http://localhost:18083/",
"skills": [{"id": "summarize", "name": "Summarize", "tags": ["summarize", "nlp"]}]},
]
async def main() -> None:
async with httpx.AsyncClient() as client:
for card in AGENTS:
resp = await client.post(f"{KUBEMQ_URL}/agents/register", json=card)
print(f"Registered {card['agent_id']}: {resp.status_code}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENTS = [
{ agent_id: "echo-agent-01", name: "Echo Agent", url: "http://localhost:18081/",
skills: [{ id: "echo", name: "Echo", tags: ["echo"] }] },
{ agent_id: "translate-agent-01", name: "Translate Agent", url: "http://localhost:18082/",
skills: [{ id: "translate", name: "Translate", tags: ["translate", "nlp"] }] },
{ agent_id: "summarize-agent-01", name: "Summarize Agent", url: "http://localhost:18083/",
skills: [{ id: "summarize", name: "Summarize", tags: ["summarize", "nlp"] }] },
];
async function main() {
for (const card of AGENTS) {
const resp = await fetch(`${KUBEMQ_URL}/agents/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(card),
});
console.log(`Registered ${card.agent_id}: ${resp.status}`);
}
}
main().catch(console.error);
```
## Step 2 — Discover agents by skill [#step-2--discover-agents-by-skill]
The router doesn't hardcode `agent_id`s — it asks the registry which agents have a needed
skill. `GET /agents?skill_tags=...` returns only agents whose skills carry **all** of the
requested tags (comma-separated). Filtering `nlp` returns both the translate and summarize
agents; filtering `echo` returns just one.
```bash
# Agents that can do NLP work
curl "http://localhost:9090/agents?skill_tags=nlp"
# Agents that can echo
curl "http://localhost:9090/agents?skill_tags=echo"
```
```csharp
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
using var client = new HttpClient();
async Task> Discover(string tag)
{
var resp = await client.GetAsync($"{KubeMqUrl}/agents?skill_tags={tag}");
var root = JsonNode.Parse(await resp.Content.ReadAsStringAsync())!;
var agents = root is JsonArray arr ? arr : root["agents"]!.AsArray();
return agents.Select(a => a!["agent_id"]!.GetValue()).ToList();
}
Console.WriteLine($"nlp: [{string.Join(", ", await Discover("nlp"))}]");
Console.WriteLine($"echo: [{string.Join(", ", await Discover("echo"))}]");
```
```go
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
const kubemqURL = "http://localhost:9090"
func discover(tag string) []string {
resp, err := http.Get(kubemqURL + "/agents?skill_tags=" + tag)
if err != nil {
return nil
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var wrapper map[string]interface{}
json.Unmarshal(body, &wrapper)
agents, _ := wrapper["agents"].([]interface{})
ids := make([]string, 0, len(agents))
for _, a := range agents {
ids = append(ids, a.(map[string]interface{})["agent_id"].(string))
}
return ids
}
func main() {
fmt.Printf("nlp: %v\n", discover("nlp"))
fmt.Printf("echo: %v\n", discover("echo"))
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final ObjectMapper MAPPER = new ObjectMapper();
static final HttpClient CLIENT = HttpClient.newHttpClient();
static List discover(String tag) throws Exception {
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/agents?skill_tags=" + tag))
.GET().build();
var resp = CLIENT.send(req, HttpResponse.BodyHandlers.ofString());
var root = MAPPER.readTree(resp.body());
var agents = root.isArray() ? root : root.get("agents");
var ids = new ArrayList();
for (var agent : agents) ids.add(agent.get("agent_id").asText());
return ids;
}
public static void main(String[] args) throws Exception {
System.out.println("nlp: " + discover("nlp"));
System.out.println("echo: " + discover("echo"));
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
async def discover(client: httpx.AsyncClient, tag: str) -> list[str]:
resp = await client.get(f"{KUBEMQ_URL}/agents", params={"skill_tags": tag})
data = resp.json()
agents = data.get("agents", data) if isinstance(data, dict) else data
return [a["agent_id"] for a in agents]
async def main() -> None:
async with httpx.AsyncClient() as client:
print(f"nlp: {await discover(client, 'nlp')}")
print(f"echo: {await discover(client, 'echo')}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
async function discover(tag: string): Promise {
const resp = await fetch(`${KUBEMQ_URL}/agents?skill_tags=${tag}`);
const data = await resp.json();
const agents = Array.isArray(data) ? data : (data.agents || []);
return agents.map((a: { agent_id: string }) => a.agent_id);
}
async function main() {
console.log("nlp: ", await discover("nlp"));
console.log("echo:", await discover("echo"));
}
main().catch(console.error);
```
## Step 3 — Route a request by agent\_id [#step-3--route-a-request-by-agent_id]
Once the router has picked an agent, it sends a normal
[`message/send`](/aiway/a2a/sync-messaging) to `POST /a2a/{agent_id}`. The same
client can fan a workload across agents by choosing a different `agent_id` per call — the
gateway routes each request to the matching agent's virtual subscriber.
```bash
# Route to the translate agent
curl -X POST http://localhost:9090/a2a/translate-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {"message": {"parts": [{"text": "Translate: hello"}]}}
}'
# Route to the summarize agent
curl -X POST http://localhost:9090/a2a/summarize-agent-01 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "message/send",
"params": {"message": {"parts": [{"text": "Summarize this report..."}]}}
}'
```
```csharp
using System.Text;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
using var client = new HttpClient();
async Task RouteTo(string agentId, string text)
{
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/send",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = text })
}
}
};
var resp = await client.PostAsync(
$"{KubeMqUrl}/a2a/{agentId}",
new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json"));
Console.WriteLine($"{agentId} -> {(int)resp.StatusCode}");
}
await RouteTo("translate-agent-01", "Translate: hello");
await RouteTo("summarize-agent-01", "Summarize this report...");
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
const kubemqURL = "http://localhost:9090"
func routeTo(agentID, text string) {
payload := map[string]interface{}{
"jsonrpc": "2.0", "id": 1, "method": "message/send",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": text}},
},
},
}
data, _ := json.Marshal(payload)
resp, err := http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(data))
if err != nil {
fmt.Printf("%s -> error: %v\n", agentID, err)
return
}
defer resp.Body.Close()
fmt.Printf("%s -> %d\n", agentID, resp.StatusCode)
}
func main() {
routeTo("translate-agent-01", "Translate: hello")
routeTo("summarize-agent-01", "Summarize this report...")
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final ObjectMapper MAPPER = new ObjectMapper();
static final HttpClient CLIENT = HttpClient.newHttpClient();
static void routeTo(String agentId, String text) throws Exception {
var payload = Map.of(
"jsonrpc", "2.0", "id", 1, "method", "message/send",
"params", Map.of("message", Map.of("parts", List.of(Map.of("text", text))))
);
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + agentId))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
var resp = CLIENT.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(agentId + " -> " + resp.statusCode());
}
public static void main(String[] args) throws Exception {
routeTo("translate-agent-01", "Translate: hello");
routeTo("summarize-agent-01", "Summarize this report...");
}
}
```
```python
import asyncio
import httpx
KUBEMQ_URL = "http://localhost:9090"
async def route_to(client: httpx.AsyncClient, agent_id: str, text: str) -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {"message": {"parts": [{"text": text}]}},
}
resp = await client.post(f"{KUBEMQ_URL}/a2a/{agent_id}", json=payload)
print(f"{agent_id} -> {resp.status_code}")
async def main() -> None:
async with httpx.AsyncClient() as client:
await route_to(client, "translate-agent-01", "Translate: hello")
await route_to(client, "summarize-agent-01", "Summarize this report...")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
async function routeTo(agentId: string, text: string) {
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/send",
params: { message: { parts: [{ text }] } },
};
const resp = await fetch(`${KUBEMQ_URL}/a2a/${agentId}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
console.log(`${agentId} -> ${resp.status}`);
}
async function main() {
await routeTo("translate-agent-01", "Translate: hello");
await routeTo("summarize-agent-01", "Summarize this report...");
}
main().catch(console.error);
```
## How routing works [#how-routing-works]
The gateway is a thin router, not a load balancer — `agent_id` selects exactly one agent.
* **Addressing.** The `{agent_id}` path segment names the target. The gateway validates it
against the registry, then issues a Query on `_AGENTS_.agents/`, which only
that agent's virtual subscriber consumes.
* **Discovery vs. routing.** Skill tags are a **discovery** convenience for picking an
`agent_id`; they never auto-route. The caller (or its own routing logic) decides which
`agent_id` to send to.
* **Isolation.** Each agent has its own [concurrency cap](/aiway/a2a/guides/concurrency)
(`AgentMaxConcurrency`, default 100) and its own liveness/TTL — one busy or expired agent
does not affect the others.
* **Scaling out.** Want two interchangeable translators? Register them under different
`agent_id`s with the same `translate` tag, then let your router pick between the matches
returned by `GET /agents?skill_tags=translate`.
Skill-tag filtering matches agents that carry **all** requested tags, and the filter runs
in memory after the registry fetch. To group agents for discovery, give them a shared tag
(like `nlp` above) in addition to their specific skill.
## Related [#related]
# Streaming Task Pipeline (/aiway/a2a/scenarios/streaming-task-pipeline)
This scenario streams a **long-running agent task** end to end. A single client opens a
`message/stream` request, the gateway relays the agent's progress as Server-Sent Events,
and the client consumes a sequence of **`task.*` envelopes** — interim `task.status`
updates, one or more `task.artifact` results, and a terminal `task.done`. It builds on
[streaming (SSE)](/aiway/a2a/streaming) and the per-agent
[virtual subscriber](/aiway/a2a/architecture).
## The setup [#the-setup]
The agent is a plain HTTP server registered by URL — no KubeMQ SDK runs on it. When the
client `POST`s a `message/stream` request to `/a2a/{agent_id}`, the gateway opens an SSE
relay through the agent's virtual subscriber: it sends a Query carrying the stream
channel, the agent streams SSE events back, and the gateway relays each one to the caller
as a `task.*` event. The client reads the stream until it sees the terminal `task.done`
(or `task.error`), and **cancelling is just disconnecting** — when the caller's connection
drops, the gateway sends a `stream_cancel` query to the agent and tears the relay down.
*The gateway relays the agent's SSE task events back to the caller and cancels the agent when the caller disconnects.*
## The task envelopes [#the-task-envelopes]
Each SSE frame names an event type and carries a JSON envelope. The agent emits four
envelope kinds; the gateway maps them to these SSE event names:
| SSE event | Envelope `type` | Meaning |
| --------------- | --------------- | ---------------------------------------------------- |
| `task.status` | `status_update` | Interim progress (`status`, `progress`, `total`) |
| `task.artifact` | `artifact` | A produced result (`name`, `data`) |
| `task.done` | `done` | Terminal success (`final_result`) — stream closes |
| `task.error` | `error` | Terminal failure (`code`, `message`) — stream closes |
The wire frame for a status update looks like this:
```text
event: task.status
data: {"stream_id":"","type":"status_update","payload":{"status":"working","progress":1,"total":3}}
```
A comment keepalive (`: keepalive`) arrives every 30 seconds on an otherwise idle stream,
and the stream closes on the first `task.done` or `task.error`.
## Step 1 — Open the stream [#step-1--open-the-stream]
Send a `message/stream` JSON-RPC request to the agent. The gateway responds with
`Content-Type: text/event-stream` and begins relaying the agent's `task.*` events. Pass
`Accept: text/event-stream` and read the response body line by line.
```bash
# -N disables curl buffering so events print as they arrive.
curl -N -X POST http://localhost:9090/a2a/task-events-agent-01 \
-H 'Content-Type: application/json' \
-H 'Accept: text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": {"message": {"parts": [{"text": "Show me all event types"}]}}
}'
```
```csharp
using System.Text;
using System.Text.Json.Nodes;
const string KubeMqUrl = "http://localhost:9090";
const string AgentId = "task-events-agent-01";
var payload = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = 1,
["method"] = "message/stream",
["params"] = new JsonObject
{
["message"] = new JsonObject
{
["parts"] = new JsonArray(new JsonObject { ["text"] = "Show me all event types" })
}
}
};
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };
var request = new HttpRequestMessage(HttpMethod.Post, $"{KubeMqUrl}/a2a/{AgentId}")
{
Content = new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json")
};
Console.WriteLine("Connecting to SSE stream...");
using var resp = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
using var stream = await resp.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
// ...continue reading events in Step 2
```
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
const (
kubemqURL = "http://localhost:9090"
agentID = "task-events-agent-01"
)
func main() {
payload := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": map[string]interface{}{
"message": map[string]interface{}{
"parts": []map[string]interface{}{{"text": "Show me all event types"}},
},
},
}
data, _ := json.Marshal(payload)
resp, err := http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(data))
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()
fmt.Println("Connecting to SSE stream...")
// ...continue reading events in Step 2
}
```
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
public class Client {
static final String KUBEMQ_URL = "http://localhost:9090";
static final String AGENT_ID = "task-events-agent-01";
static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws Exception {
var payload = Map.of(
"jsonrpc", "2.0",
"id", 1,
"method", "message/stream",
"params", Map.of(
"message", Map.of("parts", List.of(Map.of("text", "Show me all event types")))
)
);
var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(60)).build();
var req = HttpRequest.newBuilder()
.uri(URI.create(KUBEMQ_URL + "/a2a/" + AGENT_ID))
.header("Content-Type", "application/json")
.header("Accept", "text/event-stream")
.timeout(Duration.ofSeconds(60))
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(payload)))
.build();
System.out.println("Connecting to SSE stream...");
var resp = client.send(req, HttpResponse.BodyHandlers.ofLines());
// ...continue reading events in Step 2
}
}
```
```python
"""Stream a long-running task and consume its task.* envelopes."""
import asyncio
import json
from collections import Counter
import httpx
from httpx_sse import aconnect_sse
KUBEMQ_URL = "http://localhost:9090"
AGENT_ID = "task-events-agent-01"
async def main() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "message/stream",
"params": {"message": {"parts": [{"text": "Show me all event types"}]}},
}
async with httpx.AsyncClient(timeout=60) as client:
print("Connecting to SSE stream...")
async with aconnect_sse(
client, "POST", f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload
) as event_source:
... # consume events in Step 2
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
const KUBEMQ_URL = "http://localhost:9090";
const AGENT_ID = "task-events-agent-01";
async function main() {
const request = {
jsonrpc: "2.0",
id: 1,
method: "message/stream",
params: { message: { parts: [{ text: "Send me task events" }] } },
};
const resp = await fetch(`${KUBEMQ_URL}/a2a/${AGENT_ID}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(request),
});
const reader = resp.body!.getReader();
// ...continue reading events in Step 2
}
main().catch(console.error);
```
## Step 2 — Consume the task.\* envelopes [#step-2--consume-the-task-envelopes]
Read the stream frame by frame, dispatch on the SSE event name, and pull the result out of
`payload.payload`. Keep a count of each event type for a summary, and **break on the
terminal envelope** (`task.done` or `task.error`) — that frame closes the stream.
```text
event: task.status
data: {"stream_id":"...","type":"status_update","payload":{"status":"working","progress":1,"total":3}}
event: task.status
data: {"stream_id":"...","type":"status_update","payload":{"status":"working","progress":2,"total":3}}
event: task.artifact
data: {"stream_id":"...","type":"artifact","payload":{"name":"result.json","data":{"key":"value"}}}
event: task.done
data: {"stream_id":"...","type":"done","payload":{"final_result":"completed"}}
```
```csharp
var eventTypes = new Dictionary();
string? eventType = null;
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
if (line == null) break;
if (line.StartsWith("event: "))
eventType = line[7..];
else if (line.StartsWith("data: ") && eventType != null)
{
eventTypes[eventType] = eventTypes.GetValueOrDefault(eventType) + 1;
var data = JsonNode.Parse(line[6..])!;
if (eventType == "task.status")
{
var p = data["payload"]!["payload"]!;
Console.WriteLine($" [STATUS] progress={p["progress"]}/{p["total"]}");
}
else if (eventType == "task.artifact")
Console.WriteLine($" [ARTIFACT] name={data["payload"]!["payload"]!["name"]}");
else if (eventType == "task.done")
Console.WriteLine($" [DONE] result={data["payload"]!["payload"]!["final_result"]}");
else if (eventType == "task.error")
Console.WriteLine($" [ERROR] {data["payload"]!["payload"]}");
if (eventType is "task.done" or "task.error")
break;
}
else if (line.Length == 0)
eventType = null;
}
Console.WriteLine($"\n--- Event Summary ---");
foreach (var (et, count) in eventTypes.OrderBy(kv => kv.Key))
Console.WriteLine($" {et}: {count}");
Console.WriteLine($" Total: {eventTypes.Values.Sum()}");
```
```go
scanner := bufio.NewScanner(resp.Body)
eventType := ""
counts := map[string]int{}
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "event: ") {
eventType = strings.TrimPrefix(line, "event: ")
} else if strings.HasPrefix(line, "data: ") {
counts[eventType]++
dataStr := strings.TrimPrefix(line, "data: ")
var d map[string]interface{}
json.Unmarshal([]byte(dataStr), &d)
payload, _ := d["payload"].(map[string]interface{})
inner, _ := payload["payload"].(map[string]interface{})
if inner == nil {
inner = payload
}
switch eventType {
case "task.status":
fmt.Printf(" [STATUS] progress=%.0f/%.0f\n", inner["progress"], inner["total"])
case "task.artifact":
fmt.Printf(" [ARTIFACT] name=%v\n", inner["name"])
case "task.done":
fmt.Printf(" [DONE] result=%v\n", inner["final_result"])
case "task.error":
fmt.Printf(" [ERROR] %v\n", inner)
}
if eventType == "task.done" || eventType == "task.error" {
break
}
}
}
```
```java
Map eventTypes = new LinkedHashMap<>();
String currentEvent = null;
for (var it = resp.body().iterator(); it.hasNext(); ) {
String line = it.next();
if (line.startsWith("event: ")) {
currentEvent = line.substring(7).trim();
} else if (line.startsWith("data: ") && currentEvent != null) {
var data = MAPPER.readTree(line.substring(6));
eventTypes.merge(currentEvent, 1, Integer::sum);
var inner = data.path("payload").path("payload");
switch (currentEvent) {
case "task.status" ->
System.out.println(" [STATUS] progress=" + inner.path("progress") + "/" + inner.path("total"));
case "task.artifact" ->
System.out.println(" [ARTIFACT] name=" + inner.path("name").asText());
case "task.done" ->
System.out.println(" [DONE] result=" + inner.path("final_result").asText());
case "task.error" ->
System.out.println(" [ERROR] " + inner);
}
if ("task.done".equals(currentEvent) || "task.error".equals(currentEvent)) break;
}
}
```
```python
event_types: Counter[str] = Counter()
async for event in event_source.aiter_sse():
data = json.loads(event.data)
event_types[event.event] += 1
if event.event == "task.status":
inner = data["payload"]["payload"]
print(f" [STATUS] progress={inner['progress']}/{inner['total']}")
elif event.event == "task.artifact":
inner = data["payload"]["payload"]
print(f" [ARTIFACT] name={inner['name']}")
elif event.event == "task.done":
inner = data["payload"]["payload"]
print(f" [DONE] result={inner['final_result']}")
elif event.event == "task.error":
print(f" [ERROR] {data['payload']['payload']}")
if event.event in ("task.done", "task.error"):
break
print(f"\n--- Event Summary ---")
for event_type, count in sorted(event_types.items()):
print(f" {event_type}: {count}")
print(f" Total: {sum(event_types.values())}")
```
```typescript
function parseSSE(chunk: string): Array<{ event: string; data: string }> {
const events: Array<{ event: string; data: string }> = [];
let currentEvent = "";
let currentData = "";
for (const line of chunk.split("\n")) {
if (line.startsWith("event: ")) {
currentEvent = line.slice(7).trim();
} else if (line.startsWith("data: ")) {
currentData = line.slice(6).trim();
} else if (line === "" && currentEvent) {
events.push({ event: currentEvent, data: currentData });
currentEvent = "";
currentData = "";
}
}
return events;
}
const decoder = new TextDecoder();
const counts: Record = {};
while (true) {
const { done, value } = await reader.read();
if (done) break;
const events = parseSSE(decoder.decode(value, { stream: true }));
for (const evt of events) {
counts[evt.event] = (counts[evt.event] || 0) + 1;
const payload = JSON.parse(evt.data);
const inner = payload.payload?.payload ?? payload.payload;
switch (evt.event) {
case "task.status":
console.log(`[STATUS] progress=${inner.progress}/${inner.total} status=${inner.status}`);
break;
case "task.artifact":
console.log(`[ARTIFACT] name=${inner.name} data=${JSON.stringify(inner.data)}`);
break;
case "task.done":
console.log(`[DONE] result=${inner.final_result}`);
break;
case "task.error":
console.log(`[ERROR] ${inner.message}`);
break;
}
if (evt.event === "task.done" || evt.event === "task.error") {
console.log("\n=== Event Summary ===");
for (const [type, count] of Object.entries(counts)) {
console.log(` ${type}: ${count}`);
}
reader.cancel();
return;
}
}
}
```
A complete run prints the interim status, the artifact, the terminal result, and a summary:
```text
Connecting to SSE stream...
[STATUS] progress=1/3
[STATUS] progress=2/3
[ARTIFACT] name=result.json
[DONE] result=completed
--- Event Summary ---
task.artifact: 1
task.done: 1
task.status: 2
Total: 4
```
## Step 3 — Cancel by disconnecting [#step-3--cancel-by-disconnecting]
There is no explicit "cancel" RPC for the caller — **cancelling a streaming task is just
closing the connection**. When the client stops reading and disconnects before the terminal
envelope, the gateway detects the dropped connection and sends a `stream_cancel` query to
the agent's virtual subscriber (on `_AGENTS_.agents/{agent_id}`, with the `stream_id` and a
10-second timeout). The virtual subscriber closes its HTTP SSE connection to the agent and
tears down the relay, so the agent stops doing work.
```bash
# Read only the first events, then Ctrl-C (or pipe through head) to disconnect.
# The gateway sends stream_cancel to the agent on disconnect.
curl -N -X POST http://localhost:9090/a2a/slow-stream-agent-01 \
-H 'Content-Type: application/json' \
-H 'Accept: text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"message/stream",
"params":{"message":{"parts":[{"text":"I will disconnect early"}]}}}' \
| head -n 6
```
```go
// Break out of the read loop early and close the body — the gateway
// detects the disconnect and cancels the agent's stream.
resp, _ := http.Post(kubemqURL+"/a2a/"+agentID, "application/json", bytes.NewReader(data))
count := 0
eventType := ""
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "event: ") {
eventType = strings.TrimPrefix(line, "event: ")
} else if strings.HasPrefix(line, "data: ") {
count++
var d map[string]interface{}
json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &d)
p, _ := d["payload"].(map[string]interface{})
fmt.Printf(" Event %d: [%s] progress=%.0f\n", count, eventType, p["progress"])
if count >= maxEvents {
fmt.Printf("\nDisconnecting after %d events...\n", maxEvents)
break
}
}
}
resp.Body.Close() // closing the connection triggers stream_cancel
fmt.Println("KubeMQ will detect the disconnect and clean up the stream.")
```
```python
"""Disconnect from the SSE stream after a couple of events to cancel the task."""
MAX_EVENTS = 2
async with httpx.AsyncClient(timeout=30) as client:
async with aconnect_sse(
client, "POST", f"{KUBEMQ_URL}/a2a/{AGENT_ID}", json=payload
) as event_source:
count = 0
async for event in event_source.aiter_sse():
count += 1
data = json.loads(event.data)
print(f" Event {count}: [{event.event}] progress={data['payload'].get('progress')}")
if count >= MAX_EVENTS:
print(f"\nDisconnecting after {MAX_EVENTS} events...")
break # leaving the context closes the connection -> stream_cancel
print("Client disconnected.")
print("KubeMQ will detect the disconnect and clean up the stream.")
```
The gateway also closes the stream on its own when the idle timer fires
(`MaxSSEIdleSeconds`, default 300s): it emits a `task.error` with code `-32001` and message
`"stream idle timeout"`, then best-effort cancels the agent. See
[SSE behavior](/aiway/a2a/guides/sse-behavior) for the full wire-level rules.
## Related [#related]
# Endpoints (/aiway/mcp/reference/endpoints)
The MCP connector exposes a single HTTP path, `/mcp`, on the shared HTTP server (port 9090). All tool discovery and invocation flow through it as JSON-RPC 2.0 over the Streamable HTTP transport.
The connector is **enabled by default** — start kubemq-server and `/mcp` is live; no `=true` flag is needed. To disable it, set `CONNECTORSMCP_ENABLE=false` (see [Shared HTTP server](/connectors/concepts/shared-http-server#enable-model-on-by-default) for the enable model and the irregular var name).
## HTTP endpoints [#http-endpoints]
| Method | Path | Description |
| ------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST` | `/mcp` | JSON-RPC 2.0 request handler — a single request or a JSON array (batch). Carries `initialize`, `ping`, `tools/list`, `tools/call`, and notifications. |
| `GET` | `/mcp` | SSE keepalive stream. Holds an event-stream connection open; clients that prefer a long-lived channel use it alongside the stateless `POST`. |
Both routes pass through origin validation; `POST /mcp` additionally runs the per-route timeout middleware.
## JSON-RPC methods [#json-rpc-methods]
`POST /mcp` accepts the following methods:
| Method | Type | Description |
| --------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `initialize` | Request | Start a session and negotiate capabilities. Returns `protocolVersion`, `capabilities`, `serverInfo`, and `_meta.sessionId`. |
| `notifications/initialized` | Notification | Client confirms initialization is complete. No `id` field; the server replies `200 OK` with body `{"jsonrpc":"2.0","result":null,"id":null}`. |
| `ping` | Request | Health check. Returns an empty result `{}`. |
| `tools/list` | Request | Discover the available tools with their `inputSchema` (11 core tools, plus 4 agent-bridge tools when the agent registry is available). |
| `tools/call` | Request | Invoke a tool by name with its `arguments`. |
The full tool catalog and per-tool arguments live in [Tools reference](/aiway/mcp/reference/tools-reference). For the JSON-RPC and tool-level error model, see [Error codes](/aiway/mcp/reference/error-codes).
## Headers [#headers]
| Header | Direction | Description |
| ---------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `Content-Type` | Request | Must be `application/json`. |
| `MCP-Session-Id` | Both | Session identifier. The server sets it in the `initialize` response (`_meta.sessionId`); the client echoes it on every subsequent request. |
| `MCP-Protocol-Version` | Response | Negotiated protocol version — always `2025-11-25`. |
| `Authorization` | Request | `Bearer ` when JWT auth is enabled. See [Authentication](/aiway/mcp/guides/authentication). |
## Request shape [#request-shape]
A JSON-RPC 2.0 request carries an `id` so the client can correlate the response:
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "",
"params": { }
}
```
* `jsonrpc` — must be `"2.0"`.
* `id` — request identifier; the response echoes this value.
* `method` — one of the JSON-RPC methods above.
* `params` — method-specific parameters (object). Optional when the method takes no arguments, such as `ping`.
## Notification shape [#notification-shape]
Notifications omit the `id` field. The server processes them but returns no JSON-RPC result body:
```json
{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
```
In a batch (`POST` with a JSON array), notification entries are executed but produce no response entry.
## initialize response [#initialize-response]
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-11-25",
"capabilities": {
"tools": { "listChanged": false },
"resources": null,
"prompts": null
},
"serverInfo": {
"name": "kubemq",
"version": ""
},
"_meta": {
"sessionId": ""
}
}
}
```
Save `result._meta.sessionId` and send it back as the `MCP-Session-Id` header on every later request. See [Session management](/aiway/mcp/guides/session-management) for the full lifecycle.
## HTTP status codes [#http-status-codes]
| Status | Meaning |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `200` | Success — covers successful results, notifications (body `{"jsonrpc":"2.0","result":null,"id":null}`), and JSON-RPC error responses. A protocol error — including an auth failure (code `-32010`) — still returns `200` with an `error` object in the body, never `401`. See [Error codes](/aiway/mcp/reference/error-codes). |
## Endpoint signatures [#endpoint-signatures]
The following `curl` calls cover every method on the endpoint.
```bash
# initialize — start a session, capture _meta.sessionId
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": { "name": "curl", "version": "1.0.0" }
}
}'
# notifications/initialized — confirm; server replies 200 with {"jsonrpc":"2.0","result":null,"id":null}
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-H "MCP-Session-Id: " \
-d '{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}'
# ping — health check, returns an empty result {}
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-H "MCP-Session-Id: " \
-d '{ "jsonrpc": "2.0", "id": 2, "method": "ping" }'
# tools/list — discover tools and their inputSchema
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-H "MCP-Session-Id: " \
-d '{ "jsonrpc": "2.0", "id": 3, "method": "tools/list" }'
# tools/call — invoke a tool by name
curl -X POST http://localhost:9090/mcp \
-H "Content-Type: application/json" \
-H "MCP-Session-Id: " \
-d '{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "queue_send",
"arguments": { "channel": "my-queue", "body": "Hello from MCP" }
}
}'
# GET /mcp — open the SSE keepalive stream
curl -N http://localhost:9090/mcp \
-H "Accept: text/event-stream" \
-H "MCP-Session-Id: "
```
## Related [#related]
# Error Codes (/aiway/mcp/reference/error-codes)
The MCP connector surfaces failures across three layers: **JSON-RPC protocol errors** (in the response `error` field), **tool-execution errors** (in a normal `result` with `isError: true`), and **HTTP status codes** from the shared HTTP server. This page is the authoritative catalog of every code. For task-focused guidance on detecting and recovering from these layers in client code, see the [Error Handling guide](/aiway/mcp/guides/error-handling).
## The three error layers [#the-three-error-layers]
A single failed `tools/call` can fail at exactly one of three levels. Check them in order — protocol first, then tool result, then transport — because a higher-layer failure short-circuits the lower layers.
| Layer | Where it appears | Example cause |
| ----------------------- | --------------------------- | ------------------------------------------------------------ |
| JSON-RPC protocol error | `error` field (no `result`) | Malformed JSON, unknown method, missing params, auth failure |
| Tool-execution error | `result.isError: true` | Reserved channel, agent not found, command timeout |
| HTTP status | HTTP response status line | Broker not ready (503), gateway timeout (504) |
## JSON-RPC protocol error codes [#json-rpc-protocol-error-codes]
Protocol-level errors mean the request itself was malformed or could not be dispatched. They are returned in the `error` field — there is **no** `result` field. The HTTP status is still `200` (per JSON-RPC convention); the failure is encoded in the body.
| Code | Constant | Name | Trigger |
| -------- | ----------------------- | ---------------------- | ---------------------------------------------------------------------------------------------- |
| `-32700` | `JSONRPCParseError` | Parse Error | Malformed JSON body, or wrong `Content-Type` (e.g. `text/plain` instead of `application/json`) |
| `-32600` | `JSONRPCInvalidRequest` | Invalid Request | Empty `method` field, or `jsonrpc` version is not `"2.0"` |
| `-32601` | `JSONRPCMethodNotFound` | Method Not Found | Unknown method name (e.g. `tools/unknown`) |
| `-32602` | `JSONRPCInvalidParams` | Invalid Params | `params` is not an object, or a required tool argument is missing |
| `-32603` | `JSONRPCInternalError` | Internal Error | Unexpected server-side failure while dispatching the request |
| `-32010` | `jsonrpcAuthError` | Authentication Failure | Bearer token missing or invalid on the JSON-RPC endpoint (`/mcp`) |
`-32700` through `-32603` are the standard JSON-RPC 2.0 reserved codes. `-32010` is a KubeMQ server-defined code shared by the JSON-RPC endpoints (`/mcp`, `/a2a`).
### Error response format [#error-response-format]
```json
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32601,
"message": "Method not found"
}
}
```
A parse error that occurs before the request `id` can be read returns `"id": null`:
```json
{
"jsonrpc": "2.0",
"id": null,
"error": {
"code": -32700,
"message": "Parse error"
}
}
```
### Authentication failures (-32010) [#authentication-failures--32010]
When JWT auth is enabled and a request to `/mcp` carries a missing or invalid `Authorization: Bearer` token, the connector returns the JSON-RPC auth code `-32010` with HTTP status `200` — **not** HTTP `401`:
```json
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32010,
"message": "authentication required"
}
}
```
The `-32010` code applies only to JSON-RPC endpoints (`/mcp`, `/a2a`). Standard HTTP/REST endpoints return HTTP `401` for the same auth failure. See [Auth & security](/connectors/reference/auth-and-security) for the shared auth model.
## Tool-execution errors (`isError`) [#tool-execution-errors-iserror]
Tool-level errors are **not** JSON-RPC errors. The request was valid JSON-RPC and was dispatched successfully, but the underlying messaging operation failed. The response carries a normal `result` field with `isError: true`; the human-readable cause is in `result.content[].text`.
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [{ "type": "text", "text": "Agent 'nonexistent' not found" }],
"isError": true
}
}
```
This is why robust clients **check for `error` first, then `result.isError`** — a successful protocol response can still describe a failed tool operation.
### Common tool-execution errors [#common-tool-execution-errors]
| Error | Affected tools | Example message |
| -------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------- |
| Reserved channel rejection | `queue_send`, `events_publish`, `events_store_publish`, `command_send`, `query_send` | `"Channel '_AGENTS_reserved' uses a reserved prefix"` |
| Non-existent agent | `agent_info`, `agent_send`, `agent_query` | `"Agent 'nonexistent' not found"` |
| Timeout exceeded | `command_send`, `query_send`, `agent_send`, `agent_query` | `"Command timed out: no subscriber on channel 'ch' within 10s"` |
| No subscriber available | `command_send`, `query_send` | `"Command timed out: no subscriber on channel 'ch' within 10s"` |
| Non-existent channel | `channel_info` | `"Channel 'nonexistent' of type 'queues' not found"` |
Reserved-channel rejection comes from the shared `_AGENTS_.` prefix guard — see [Channel resolution](/aiway/mcp/guides/channel-resolution).
## HTTP status codes [#http-status-codes]
For a well-formed request, the connector returns HTTP `200` even when the body contains a JSON-RPC error. Other statuses originate from the shared HTTP server layer (middleware chain) before or around tool dispatch.
| Status | Meaning | When |
| ------ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `200` | OK | All JSON-RPC responses, including error responses and notifications (e.g. `notifications/initialized`, which returns body `{"jsonrpc":"2.0","result":null,"id":null}`) |
| `503` | Service Unavailable | The broker is not ready; the traffic gate rejects the request |
| `504` | Gateway Timeout | The request deadline elapsed before a response was committed |
HTTP `200` is returned even for JSON-RPC error responses. The error is encoded in the JSON body, not the HTTP status line — always parse the body before treating a `200` as success.
## Resolution order [#resolution-order]
When handling a response, evaluate the layers top-down:
1. **Inspect the HTTP status.** A `503` means the broker is not ready (retry with backoff); a `504` means the request timed out.
2. **Check for `error`.** A present `error` field is a JSON-RPC protocol failure — fix the request (or token for `-32010`). Do not look for `result`.
3. **Check `result.isError`.** If `true`, the tool ran but the operation failed; read the cause from `result.content[0].text`.
4. **Otherwise the call succeeded** — the payload is in `result.content`.
## Related [#related]
# Tools Reference (/aiway/mcp/reference/tools-reference)
The authoritative catalog of every tool the MCP connector exposes through `tools/call`: 11 core messaging tools plus 4 agent-bridge tools. For each tool you get its arguments, defaults, JSON Schema, a ready-to-run curl request, and the response shape.
## Overview [#overview]
The MCP connector advertises **15 tools** in its `tools/list` response and runs them through the single `POST /mcp` endpoint on the [shared HTTP server](/connectors/concepts/shared-http-server) (port `9090`, protocol version `2025-11-25`). The 11 core tools are always registered; the 4 agent-bridge tools appear only when the [A2A agent registry](/aiway/a2a) is present.
This page is the canonical argument and schema reference. The per-tool pages under [Tools](/aiway/mcp/tools) carry the same operations with examples in all nine languages. For the wire-level request/response forms see [Endpoints](/aiway/mcp/reference/endpoints); for the failure codes see [Error codes](/aiway/mcp/reference/error-codes).
## Tool summary [#tool-summary]
| # | Tool | Category | Required args | Optional args |
| -- | -------------------------- | --------------- | ------------------------- | --------------------------------------------------------------------------------------------------- |
| 1 | `queue_send` | Queue | `channel`, `body` | `metadata`, `tags`, `delay_seconds`, `expiration_seconds`, `max_receive_count`, `dead_letter_queue` |
| 2 | `queue_receive` | Queue | `channel`, `max_messages` | `wait_timeout_seconds` |
| 3 | `queue_peek` | Queue | `channel`, `max_messages` | *(none)* |
| 4 | `events_publish` | Events | `channel`, `body` | `metadata`, `tags` |
| 5 | `events_store_publish` | Events | `channel`, `body` | `metadata`, `tags` |
| 6 | `events_store_read` | Events | `channel`, `max_messages` | `from_sequence`, `from_time` |
| 7 | `events_store_read_latest` | Events | `channel` | `count` |
| 8 | `command_send` | Command / Query | `channel`, `body` | `timeout_seconds`, `metadata`, `tags` |
| 9 | `query_send` | Command / Query | `channel`, `body` | `timeout_seconds`, `metadata`, `tags` |
| 10 | `channel_list` | Channel | *(none)* | `type`, `pattern` |
| 11 | `channel_info` | Channel | `channel`, `type` | *(none)* |
| 12 | `agent_list` | Agent bridge | *(none)* | `skill_tags` |
| 13 | `agent_info` | Agent bridge | `agent_id` | *(none)* |
| 14 | `agent_send` | Agent bridge | `agent_id`, `message` | `blocking`, `context_id`, `timeout_seconds` |
| 15 | `agent_query` | Agent bridge | `agent_id`, `method` | `params` |
## Calling convention [#calling-convention]
Every tool is invoked the same way: a `tools/call` JSON-RPC request naming the tool and passing its `arguments` object. Only `name` and `arguments` change between tools.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "",
"arguments": { }
}
}'
```
Every successful `tools/call` returns a result with a `content` array of typed blocks — KubeMQ uses `text` blocks carrying the operation result as a string (often a JSON string). A tool-level failure sets `isError: true` in the same envelope; the JSON-RPC response itself still succeeds with HTTP `200`.
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [{ "type": "text", "text": "..." }],
"isError": false
}
}
```
A `channel` that starts with the reserved prefix `_AGENTS_.` is rejected — see [Channel resolution](/aiway/mcp/guides/channel-resolution). Missing required arguments return a `-32602` Invalid Params JSON-RPC error, not an `isError` result.
## Queue tools [#queue-tools]
Durable, point-to-point queue messaging. See [Queue tools](/aiway/mcp/tools/queues) for language examples.
### queue\_send [#queue_send]
Send a message to a queue channel.
| Argument | Type | Required | Default | Description |
| -------------------- | ------- | -------- | ------- | ------------------------------------------------------------------------- |
| `channel` | string | Yes | — | Target queue channel. Must not start with the reserved prefix `_AGENTS_.` |
| `body` | string | Yes | — | Message body content |
| `metadata` | string | No | `""` | Optional message metadata string |
| `tags` | object | No | `{}` | Key-value tags for message classification |
| `delay_seconds` | integer | No | `0` | Delay before the message becomes visible. `0` = immediately available |
| `expiration_seconds` | integer | No | `0` | TTL in seconds. `0` = no expiration |
| `max_receive_count` | integer | No | `0` | Max receives before dead-letter. `0` = unlimited |
| `dead_letter_queue` | string | No | `""` | Dead-letter queue channel name |
```json
{
"type": "object",
"required": ["channel", "body"],
"properties": {
"channel": { "type": "string" },
"body": { "type": "string" },
"metadata": { "type": "string", "default": "" },
"tags": { "type": "object", "additionalProperties": { "type": "string" }, "default": {} },
"delay_seconds": { "type": "integer", "minimum": 0, "default": 0 },
"expiration_seconds": { "type": "integer", "minimum": 0, "default": 0 },
"max_receive_count": { "type": "integer", "minimum": 0, "default": 0 },
"dead_letter_queue": { "type": "string", "default": "" }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "queue_send",
"arguments": {
"channel": "example-queue",
"body": "Hello from MCP",
"metadata": "example-metadata",
"tags": { "env": "dev", "source": "mcp-example" }
}
}
}'
```
**Response** — a confirmation message in a single text block:
```json
{
"content": [{ "type": "text", "text": "Message sent successfully to queue 'example-queue'" }],
"isError": false
}
```
**Errors:** reserved channel → `isError: true`; missing `channel`/`body` → `-32602`.
### queue\_receive [#queue_receive]
Receive and consume messages from a queue channel. This is a destructive read — returned messages are removed from the queue.
| Argument | Type | Required | Default | Description |
| ---------------------- | ------- | -------- | ------- | ------------------------------------------------ |
| `channel` | string | Yes | — | Source queue channel |
| `max_messages` | integer | Yes | `1` | Max messages to receive in a single call (1–100) |
| `wait_timeout_seconds` | integer | No | `5` | Long-poll wait time in seconds (1–60) |
```json
{
"type": "object",
"required": ["channel", "max_messages"],
"properties": {
"channel": { "type": "string" },
"max_messages": { "type": "integer", "minimum": 1, "maximum": 100, "default": 1 },
"wait_timeout_seconds": { "type": "integer", "minimum": 1, "maximum": 60, "default": 5 }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "queue_receive",
"arguments": { "channel": "example-queue", "max_messages": 5 }
}
}'
```
**Response** — a JSON array of received messages, serialized as the text payload:
```json
{
"content": [{ "type": "text", "text": "[{\"body\":\"Hello from MCP\",\"metadata\":\"example-metadata\",\"tags\":{\"env\":\"dev\",\"source\":\"mcp-example\"}}]" }],
"isError": false
}
```
**Errors:** reserved channel → `isError: true`; a non-existent channel returns an empty result (no error).
### queue\_peek [#queue_peek]
Peek at messages without consuming them — a non-destructive read; messages stay in the queue.
| Argument | Type | Required | Default | Description |
| -------------- | ------- | -------- | ------- | ---------------------------------------------- |
| `channel` | string | Yes | — | Source queue channel |
| `max_messages` | integer | Yes | `1` | Max messages to peek without consuming (1–100) |
```json
{
"type": "object",
"required": ["channel", "max_messages"],
"properties": {
"channel": { "type": "string" },
"max_messages": { "type": "integer", "minimum": 1, "maximum": 100, "default": 1 }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "queue_peek",
"arguments": { "channel": "example-queue", "max_messages": 5 }
}
}'
```
**Response** — same shape as `queue_receive`, but the messages remain in the queue:
```json
{
"content": [{ "type": "text", "text": "[{\"body\":\"Hello from MCP\",\"metadata\":\"example-metadata\",\"tags\":{\"env\":\"dev\"}}]" }],
"isError": false
}
```
**Errors:** reserved channel → `isError: true`; a non-existent channel returns an empty result (no error).
## Events tools [#events-tools]
Pub/sub and the persistent events store. See [Events tools](/aiway/mcp/tools/events) for language examples.
### events\_publish [#events_publish]
Publish an ephemeral event (fire-and-forget; no persistence).
| Argument | Type | Required | Default | Description |
| ---------- | ------ | -------- | ------- | --------------------------------------- |
| `channel` | string | Yes | — | Target events channel |
| `body` | string | Yes | — | Event body content |
| `metadata` | string | No | `""` | Optional event metadata string |
| `tags` | object | No | `{}` | Key-value tags for event classification |
```json
{
"type": "object",
"required": ["channel", "body"],
"properties": {
"channel": { "type": "string" },
"body": { "type": "string" },
"metadata": { "type": "string", "default": "" },
"tags": { "type": "object", "additionalProperties": { "type": "string" }, "default": {} }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "events_publish",
"arguments": {
"channel": "example-events",
"body": "Event data",
"metadata": "event-meta",
"tags": { "source": "mcp-example" }
}
}
}'
```
**Response:**
```json
{
"content": [{ "type": "text", "text": "Event published successfully to channel 'example-events'" }],
"isError": false
}
```
**Errors:** reserved channel → `isError: true`; missing `channel`/`body` → `-32602`.
### events\_store\_publish [#events_store_publish]
Publish a persistent event to the events store. Stored events receive a monotonic sequence number.
| Argument | Type | Required | Default | Description |
| ---------- | ------ | -------- | ------- | --------------------------------------- |
| `channel` | string | Yes | — | Target events-store channel |
| `body` | string | Yes | — | Event body content to store |
| `metadata` | string | No | `""` | Optional event metadata string |
| `tags` | object | No | `{}` | Key-value tags for event classification |
```json
{
"type": "object",
"required": ["channel", "body"],
"properties": {
"channel": { "type": "string" },
"body": { "type": "string" },
"metadata": { "type": "string", "default": "" },
"tags": { "type": "object", "additionalProperties": { "type": "string" }, "default": {} }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 6,
"method": "tools/call",
"params": {
"name": "events_store_publish",
"arguments": {
"channel": "example-events-store",
"body": "Stored event data",
"metadata": "store-meta",
"tags": { "source": "mcp-example" }
}
}
}'
```
**Response:**
```json
{
"content": [{ "type": "text", "text": "Event published successfully to events store channel 'example-events-store'" }],
"isError": false
}
```
**Errors:** reserved channel → `isError: true`; missing `channel`/`body` → `-32602`.
### events\_store\_read [#events_store_read]
Read stored events starting from a sequence number or a timestamp.
| Argument | Type | Required | Default | Description |
| --------------- | ------- | -------- | ------- | --------------------------------------------------------------------------- |
| `channel` | string | Yes | — | Source events-store channel |
| `from_sequence` | integer | No | — | Start from this sequence number. Mutually exclusive with `from_time` |
| `from_time` | string | No | — | Start from this ISO 8601 timestamp. Mutually exclusive with `from_sequence` |
| `max_messages` | integer | Yes | — | Maximum number of messages to return (1–100) |
`from_sequence` and `from_time` are mutually exclusive — supply at most one.
```json
{
"type": "object",
"required": ["channel", "max_messages"],
"properties": {
"channel": { "type": "string" },
"from_sequence": { "type": "integer", "minimum": 1 },
"from_time": { "type": "string", "format": "date-time" },
"max_messages": { "type": "integer", "minimum": 1, "maximum": 100 }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "events_store_read",
"arguments": { "channel": "example-events-store", "from_sequence": 1, "max_messages": 10 }
}
}'
```
**Response** — a JSON array of stored events, each with its `sequence` and `timestamp`:
```json
{
"content": [{ "type": "text", "text": "[{\"body\":\"Stored event data\",\"metadata\":\"store-meta\",\"sequence\":1,\"timestamp\":\"2026-06-08T12:00:00Z\"}]" }],
"isError": false
}
```
**Errors:** reserved channel → `isError: true`; a non-existent channel returns an empty result; missing `channel` → `-32602`.
### events\_store\_read\_latest [#events_store_read_latest]
Read the N most recent stored events.
| Argument | Type | Required | Default | Description |
| --------- | ------- | -------- | ------- | -------------------------------------- |
| `channel` | string | Yes | — | Source events-store channel |
| `count` | integer | No | `1` | Number of most recent events to return |
```json
{
"type": "object",
"required": ["channel"],
"properties": {
"channel": { "type": "string" },
"count": { "type": "integer", "minimum": 1, "default": 1 }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 8,
"method": "tools/call",
"params": {
"name": "events_store_read_latest",
"arguments": { "channel": "example-events-store", "count": 3 }
}
}'
```
**Response** — the most recent events, newest first:
```json
{
"content": [{ "type": "text", "text": "[{\"body\":\"Stored event 3\",\"sequence\":3},{\"body\":\"Stored event 2\",\"sequence\":2},{\"body\":\"Stored event 1\",\"sequence\":1}]" }],
"isError": false
}
```
**Errors:** reserved channel → `isError: true`; a non-existent channel returns an empty result; missing `channel` → `-32602`.
## Command & query tools [#command--query-tools]
Synchronous request/reply. See [Command & query tools](/aiway/mcp/tools/commands-queries) for language examples.
### command\_send [#command_send]
Send a command and wait for acknowledgment from a subscriber.
| Argument | Type | Required | Default | Description |
| ----------------- | ------- | -------- | ------- | ------------------------------------------- |
| `channel` | string | Yes | — | Target command channel |
| `body` | string | Yes | — | Command body content |
| `timeout_seconds` | integer | No | `10` | Timeout in seconds waiting for the response |
| `metadata` | string | No | `""` | Optional command metadata string |
| `tags` | object | No | `{}` | Key-value tags for command classification |
```json
{
"type": "object",
"required": ["channel", "body"],
"properties": {
"channel": { "type": "string" },
"body": { "type": "string" },
"timeout_seconds": { "type": "integer", "minimum": 1, "default": 10 },
"metadata": { "type": "string", "default": "" },
"tags": { "type": "object", "additionalProperties": { "type": "string" }, "default": {} }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 9,
"method": "tools/call",
"params": {
"name": "command_send",
"arguments": {
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10,
"metadata": "cmd-meta",
"tags": { "action": "process" }
}
}
}'
```
**Response (success):**
```json
{
"content": [{ "type": "text", "text": "Command executed successfully on channel 'example-commands'" }],
"isError": false
}
```
**Errors:** reserved channel, no subscriber (timeout), or subscriber rejection → `isError: true`; missing `channel`/`body` → `-32602`.
### query\_send [#query_send]
Send a query and receive a data response from a subscriber.
| Argument | Type | Required | Default | Description |
| ----------------- | ------- | -------- | ------- | ------------------------------------------- |
| `channel` | string | Yes | — | Target query channel |
| `body` | string | Yes | — | Query body content |
| `timeout_seconds` | integer | No | `30` | Timeout in seconds waiting for the response |
| `metadata` | string | No | `""` | Optional query metadata string |
| `tags` | object | No | `{}` | Key-value tags for query classification |
```json
{
"type": "object",
"required": ["channel", "body"],
"properties": {
"channel": { "type": "string" },
"body": { "type": "string" },
"timeout_seconds": { "type": "integer", "minimum": 1, "default": 30 },
"metadata": { "type": "string", "default": "" },
"tags": { "type": "object", "additionalProperties": { "type": "string" }, "default": {} }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 10,
"method": "tools/call",
"params": {
"name": "query_send",
"arguments": {
"channel": "example-queries",
"body": "get-data",
"timeout_seconds": 30,
"metadata": "qry-meta",
"tags": { "action": "lookup" }
}
}
}'
```
**Response (success)** — the subscriber's reply payload as the text block:
```json
{
"content": [{ "type": "text", "text": "{\"data\":\"query response payload from subscriber\"}" }],
"isError": false
}
```
**Errors:** reserved channel, no subscriber (timeout), or subscriber rejection → `isError: true`; missing `channel`/`body` → `-32602`.
## Channel tools [#channel-tools]
Discovery and inspection of channels. See [Channel tools](/aiway/mcp/tools/channel-management) for language examples.
### channel\_list [#channel_list]
List channels, optionally filtered by type or name pattern. An empty list is a normal successful result.
| Argument | Type | Required | Default | Description |
| --------- | ------ | -------- | ------- | ---------------------------------------------------------------------------------- |
| `type` | string | No | — | Filter by channel type (`queues`, `events`, `events_store`, `commands`, `queries`) |
| `pattern` | string | No | — | Filter by channel name pattern or prefix |
```json
{
"type": "object",
"required": [],
"properties": {
"type": { "type": "string" },
"pattern": { "type": "string" }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 11,
"method": "tools/call",
"params": {
"name": "channel_list",
"arguments": {}
}
}'
```
**Response** — a JSON array of channel descriptors:
```json
{
"content": [{ "type": "text", "text": "[{\"name\":\"example-queue\",\"type\":\"queues\",\"is_active\":true},{\"name\":\"example-events\",\"type\":\"events\",\"is_active\":true}]" }],
"isError": false
}
```
**Errors:** invalid arguments → `-32602`. No tool-specific failures otherwise.
### channel\_info [#channel_info]
Get metadata for a specific channel.
| Argument | Type | Required | Default | Description |
| --------- | ------ | -------- | ------- | ------------------------------------------------------------------------ |
| `channel` | string | Yes | — | Channel name |
| `type` | string | Yes | — | Channel type (`queues`, `events`, `events_store`, `commands`, `queries`) |
```json
{
"type": "object",
"required": ["channel", "type"],
"properties": {
"channel": { "type": "string" },
"type": { "type": "string" }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 12,
"method": "tools/call",
"params": {
"name": "channel_info",
"arguments": { "channel": "example-queue", "type": "queues" }
}
}'
```
**Response (success)** — channel metadata with traffic counters:
```json
{
"content": [{ "type": "text", "text": "{\"name\":\"example-queue\",\"type\":\"queues\",\"is_active\":true,\"incoming\":5,\"outgoing\":3}" }],
"isError": false
}
```
**Errors:** non-existent channel → `isError: true`.
## Agent-bridge tools [#agent-bridge-tools]
These 4 tools appear in `tools/list` **only when the A2A agent registry is present**. They turn an MCP client into an A2A caller. See [Agent-bridge tools](/aiway/mcp/tools/agent-bridge) for language examples and the [A2A connector](/aiway/a2a) for the agent model.
### agent\_list [#agent_list]
List registered agents, optionally filtered by skill tags. An empty list is a normal successful result.
| Argument | Type | Required | Default | Description |
| ------------ | --------------- | -------- | ------- | --------------------------- |
| `skill_tags` | array of string | No | — | Filter agents by skill tags |
```json
{
"type": "object",
"required": [],
"properties": {
"skill_tags": { "type": "array", "items": { "type": "string" } }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 13,
"method": "tools/call",
"params": {
"name": "agent_list",
"arguments": {}
}
}'
```
**Response** — a JSON array of agents with their skills:
```json
{
"content": [{ "type": "text", "text": "[{\"agent_id\":\"echo-01\",\"name\":\"Echo Agent 01\",\"skills\":[{\"id\":\"echo\",\"name\":\"Echo\",\"tags\":[\"test\",\"echo\"]}]}]" }],
"isError": false
}
```
**Errors:** invalid arguments → `-32602`. No tool-specific failures otherwise.
### agent\_info [#agent_info]
Get detailed metadata for a specific agent.
| Argument | Type | Required | Default | Description |
| ---------- | ------ | -------- | ------- | --------------------------- |
| `agent_id` | string | Yes | — | Agent identifier to look up |
```json
{
"type": "object",
"required": ["agent_id"],
"properties": {
"agent_id": { "type": "string" }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 14,
"method": "tools/call",
"params": {
"name": "agent_info",
"arguments": { "agent_id": "echo-01" }
}
}'
```
**Response (success)** — the agent's card, including its registered HTTP `url` and skills:
```json
{
"content": [{ "type": "text", "text": "{\"agent_id\":\"echo-01\",\"name\":\"Echo Agent 01\",\"description\":\"echo agent\",\"version\":\"1.0.0\",\"url\":\"http://localhost:18080/\",\"skills\":[{\"id\":\"echo\",\"name\":\"Echo\",\"tags\":[\"test\",\"echo\"]}]}" }],
"isError": false
}
```
**Errors:** non-existent agent → `isError: true`.
### agent\_send [#agent_send]
Send a message to an agent. The connector builds a `message/send` envelope and forwards it over the broker as a Query to `_AGENTS_.agents/`.
| Argument | Type | Required | Default | Description |
| ----------------- | ------- | -------- | ------- | ----------------------------------------------------------------- |
| `agent_id` | string | Yes | — | Target agent identifier |
| `message` | string | Yes | — | Message content to send to the agent |
| `blocking` | boolean | No | `true` | Wait for the agent response if `true`; fire-and-forget if `false` |
| `context_id` | string | No | — | Conversation context ID for multi-turn interactions |
| `timeout_seconds` | integer | No | — | Timeout in seconds. The server adds a +10s `GatewayTimeoutBuffer` |
```json
{
"type": "object",
"required": ["agent_id", "message"],
"properties": {
"agent_id": { "type": "string" },
"message": { "type": "string" },
"blocking": { "type": "boolean", "default": true },
"context_id": { "type": "string" },
"timeout_seconds": { "type": "integer", "minimum": 1 }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 15,
"method": "tools/call",
"params": {
"name": "agent_send",
"arguments": { "agent_id": "echo-01", "message": "hello from MCP" }
}
}'
```
**Response (success)** — the agent's reply payload as the text block:
```json
{
"content": [{ "type": "text", "text": "{\"echo\":{\"method\":\"message/send\",\"params\":{\"message\":\"hello from MCP\"}},\"received_headers\":{}}" }],
"isError": false
}
```
**Errors:** non-existent agent or timeout exceeded → `isError: true`.
### agent\_query [#agent_query]
Query an agent with a specific JSON-RPC method.
| Argument | Type | Required | Default | Description |
| ---------- | ------ | -------- | ------- | ------------------------------------------------------------------------ |
| `agent_id` | string | Yes | — | Target agent identifier |
| `method` | string | Yes | — | Query method to invoke (`tasks/get`, `tasks/cancel`, or a custom method) |
| `params` | object | No | — | Method-specific parameters |
```json
{
"type": "object",
"required": ["agent_id", "method"],
"properties": {
"agent_id": { "type": "string" },
"method": { "type": "string" },
"params": { "type": "object" }
}
}
```
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 16,
"method": "tools/call",
"params": {
"name": "agent_query",
"arguments": { "agent_id": "echo-01", "method": "tasks/get" }
}
}'
```
**Response (success):**
```json
{
"content": [{ "type": "text", "text": "{\"echo\":{\"method\":\"tasks/get\",\"params\":{}},\"received_headers\":{}}" }],
"isError": false
}
```
**Errors:** non-existent agent or timeout exceeded → `isError: true`.
## Related [#related]
# Authentication (/aiway/mcp/guides/authentication)
The MCP connector is guarded by the same JWT Bearer authentication as every other
KubeMQ connector. You authenticate to `POST /mcp` with an `Authorization: Bearer`
header; KubeMQ verifies the token, attaches your identity claims, and lets the tool
call through. This guide shows how to attach that header through each MCP SDK's
transport — the place an SDK client differs from a raw `curl` call — plus how MCP
reports auth failures and validates request origins.
## Overview [#overview]
Authentication for MCP is the connector-wide model described in
[Auth & Security](/connectors/reference/auth-and-security), applied to the single MCP
endpoint:
* **Endpoint** — `POST /mcp` (and the `GET /mcp` keepalive stream) carry every
JSON-RPC method: `initialize`, `tools/list`, `tools/call`, and `ping`. A verified
token identifies the caller; that `ClientID` flows through to the broker and, for the
[agent-bridge tools](/aiway/mcp/tools/agent-bridge), to the agent as
`X-KubeMQ-Caller-ID`.
When server authentication is **disabled** (the default for local development), every
caller is treated as the synthetic `anonymous` principal and no token is required. When
it is **enabled**, a missing or unverified token is rejected as a JSON-RPC `-32010`
error.
Authentication is **disabled by default** so MCP works out of the box for local
development. Enable it before exposing the endpoint beyond a trusted network — see
[Production recommendations](#production-recommendations).
## How it works [#how-it-works]
The token is verified once, at the shared auth middleware, before the request reaches
the MCP connector. The middleware extracts the `Bearer` token from the `Authorization`
header, verifies it against KubeMQ's authentication singleton, and attaches the caller's
claims (including `ClientID`) to the request context. The connector then resolves the
tool to a KubeMQ operation under that identity.
*KubeMQ verifies the Bearer token at the edge, then runs the tool call under the caller's identity.*
## Attaching the token [#attaching-the-token]
Every MCP request must carry an `Authorization: Bearer ` header when server auth is
enabled. With raw JSON-RPC the header goes straight onto the HTTP request; with an MCP
SDK you attach it through the **streamable-HTTP transport** so the header rides on every
call in the session — the `initialize` handshake, `tools/list`, and each `tools/call`.
These snippets store the token in the `KUBEMQ_MCP_AUTH_TOKEN` environment variable —
the same variable the KubeMQ MCP examples use — and send it on a `tools/list` request.
```bash
curl -X POST http://localhost:9090/mcp \
-H "Authorization: Bearer $KUBEMQ_MCP_AUTH_TOKEN" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
```csharp
using ModelContextProtocol.Client;
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var token = Environment.GetEnvironmentVariable("KUBEMQ_MCP_AUTH_TOKEN");
var transport = new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = new Uri($"{url}/mcp"),
AdditionalHeaders = new Dictionary
{
["Authorization"] = $"Bearer {token}",
},
});
await using var client = await McpClientFactory.CreateAsync(transport);
var tools = await client.ListToolsAsync();
Console.WriteLine($"Tools: {tools.Count}");
```
```go
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/client/transport"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
token := os.Getenv("KUBEMQ_MCP_AUTH_TOKEN")
c, err := client.NewStreamableHttpClient(url+"/mcp",
transport.WithHTTPHeaders(map[string]string{
"Authorization": "Bearer " + token,
}),
)
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
if _, err := c.Initialize(ctx, mcp.InitializeRequest{}); err != nil {
log.Fatal(err)
}
tools, err := c.ListTools(ctx, mcp.ListToolsRequest{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Tools: %d\n", len(tools.Tools))
}
```
```java
import io.modelcontextprotocol.sdk.McpClient;
import io.modelcontextprotocol.sdk.client.transport.HttpClientStreamableHttpTransport;
public class Auth {
public static void main(String[] args) {
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
String token = System.getenv("KUBEMQ_MCP_AUTH_TOKEN");
var transport = HttpClientStreamableHttpTransport.builder(url)
.endpoint("/mcp")
.httpRequestCustomizer((builder, method, endpoint, body, context) ->
builder.header("Authorization", "Bearer " + token))
.build();
var client = McpClient.sync(transport).build();
client.initialize();
var tools = client.listTools();
System.out.println("Tools: " + tools.tools().size());
client.closeGracefully();
}
}
```
```kotlin
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport
import io.ktor.client.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.sse.*
import io.ktor.client.request.*
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val token = System.getenv("KUBEMQ_MCP_AUTH_TOKEN")
val httpClient = HttpClient {
install(SSE)
defaultRequest { header("Authorization", "Bearer $token") }
}
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val tools = client.listTools()
println("Tools: ${tools?.tools?.size}")
}
```
```python
import asyncio
import os
import httpx2
from mcp.client.streamable_http import streamable_http_client
from mcp import ClientSession
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
TOKEN = os.environ.get("KUBEMQ_MCP_AUTH_TOKEN")
async def main():
headers = {"Authorization": f"Bearer {TOKEN}"} if TOKEN else {}
async with httpx2.AsyncClient(headers=headers) as http_client:
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp", http_client=http_client) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
print(f"Tools: {len(tools.tools)}")
if __name__ == "__main__":
asyncio.run(main())
```
```ruby
require "mcp"
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
token = ENV["KUBEMQ_MCP_AUTH_TOKEN"]
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new(
"#{url}/mcp",
headers: { "Authorization" => "Bearer #{token}" }
),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
tools = client.list_tools
puts "Tools: #{tools.size}"
client.close
```
```rust
use rmcp::transport::streamable_http::StreamableHttpClientTransport;
use rmcp::transport::streamable_http::client::StreamableHttpClientTransportConfig;
use rmcp::service::RunService;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let token = std::env::var("KUBEMQ_MCP_AUTH_TOKEN").unwrap_or_default();
let http = reqwest::Client::builder()
.default_headers({
let mut h = reqwest::header::HeaderMap::new();
h.insert(
reqwest::header::AUTHORIZATION,
format!("Bearer {token}").parse()?,
);
h
})
.build()?;
let transport = StreamableHttpClientTransport::with_client(
http,
StreamableHttpClientTransportConfig::with_uri(format!("{url}/mcp")),
);
let client = ().serve(transport).await?;
let tools = client.list_all_tools().await?;
println!("Tools: {}", tools.len());
Ok(())
}
```
```swift
import Foundation
import MCP
@main
struct Auth {
static func main() async throws {
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let token = ProcessInfo.processInfo.environment["KUBEMQ_MCP_AUTH_TOKEN"] ?? ""
let transport = HTTPClientTransport(
endpoint: URL(string: "\(url)/mcp")!,
streaming: true,
requestModifier: { request in
var modified = request
modified.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
return modified
}
)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let (tools, _) = try await client.listTools()
print("Tools: \(tools.count)")
}
}
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
const token = process.env.KUBEMQ_MCP_AUTH_TOKEN;
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`),
{
requestInit: {
headers: { Authorization: `Bearer ${token}` },
},
}
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
const tools = await client.listTools();
console.log(`Tools: ${tools.tools.length}`);
await client.close();
```
The token is set on the **transport**, not on a single request, so it is sent with the
`initialize` handshake and every subsequent `tools/call` in the session. Set
`KUBEMQ_MCP_AUTH_TOKEN` in your environment rather than hard-coding the JWT in source.
## How auth failures are reported [#how-auth-failures-are-reported]
MCP is a JSON-RPC endpoint, so authentication errors come back as a JSON-RPC error
object — not an HTTP 401. The HTTP status stays `200`; the failure is encoded in the
`error` field with code `-32010`.
```json
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32010,
"message": "Authentication failed"
}
}
```
| Condition | Result |
| -------------------------------------- | ----------------------------------------- |
| Auth disabled (default) | Request runs as the `anonymous` principal |
| Auth enabled, valid token | Request runs as the token's `ClientID` |
| Auth enabled, missing or invalid token | JSON-RPC error **`-32010`** |
`-32010` is distinct from the standard JSON-RPC codes (`-32700` … `-32603`) and from
tool-level errors, which return a normal result with `isError: true`. A `-32010` is an
**authentication** failure, never a tool failure. The full code list is in the
[error codes reference](/aiway/mcp/reference/error-codes).
## Origin validation [#origin-validation]
Beyond the shared HTTP server's CORS and origin middleware, MCP applies its **own**
origin check (`validateOrigin`) against `McpConfig.TrustedOrigins`. This guards the
endpoint against DNS-rebinding and cross-site requests from untrusted browser pages.
| `TrustedOrigins` value | Behavior |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `auto` (default) | Matches localhost variants — `localhost`, `127.0.0.1`, `::1`, `[::1]`, `0.0.0.0` — plus the server's bind address |
| `*` | Allows all origins |
| *(custom list)* | Allows exactly the listed origins |
An **empty `Origin` header** — which non-browser clients such as `curl`, the MCP SDKs,
and server-to-server calls send — is **always allowed**. Only browser callers, which set
an `Origin`, are screened. Configure the list with `CONNECTORSMCP_TRUSTED_ORIGINS` (see
[Configuration](/aiway/mcp/configuration)); for example, to allow a single web
app:
```bash title="env.sh"
export CONNECTORSMCP_TRUSTED_ORIGINS=https://app.example.com
```
A rejected origin is refused before the JSON-RPC method runs.
## Production recommendations [#production-recommendations]
Authentication is off by default for convenience; turn it on before the endpoint is
reachable from anywhere untrusted.
* **Enable authentication** in any non-local deployment and require a Bearer token on
every MCP call.
* **Use TLS** (`https://`) for all production MCP endpoints — see
[Auth & Security → TLS and mTLS](/connectors/reference/auth-and-security#tls-and-mtls).
* **Prefer short-lived, rotated tokens** to limit the blast radius of a leaked JWT.
* **Restrict `TrustedOrigins`** to the exact web origins that need browser access instead
of leaving `auto` or `*` in place.
* **Restrict network access** to the endpoint with firewall rules or Kubernetes network
policies as defense in depth.
## Related [#related]
# Channel Resolution (/aiway/mcp/guides/channel-resolution)
Every KubeMQ MCP tool acts on a **channel** — the addressable destination a message is
sent to or read from. This guide explains how channels are named, the five channel types
each tool family targets, the single reserved prefix you must avoid, and how a model
discovers channels at runtime before it acts.
## Overview [#overview]
A channel is just a string. There is no registry to provision and no create step: a
channel comes into existence the first time a tool references it, and disappears from
discovery when it no longer carries traffic. This makes the MCP surface
self-describing — a model can name a channel on the fly (`orders.us-west`), and the same
name resolves consistently across every tool that uses it.
Each tool argument named `channel` is resolved against one of the five KubeMQ messaging
patterns. The tool you call determines the pattern; the channel string determines the
destination within it.
## How tools map to channels [#how-tools-map-to-channels]
There is no separate "channel resolution" step in the protocol — the **tool name selects
the channel type**, and the `channel` argument names the destination. The model never has
to declare a type alongside a send; calling `queue_send` *is* the declaration that the
channel is a queue.
*The tool family selects the channel type; the `channel` argument names the destination.*
## Channel naming [#channel-naming]
* Channels are arbitrary strings — for example `my-app.orders`, `notifications`, or
`user-events`.
* Channels are **created implicitly on first use**. There is no explicit creation step.
* **Convention:** use dot-separated hierarchical names to organize a namespace, such as
`orders.us-west` or `events.user.signup`.
Because channels are created on demand, a typo creates a new (empty) channel rather than
raising an error. Use [`channel_list`](#discovering-channels) to confirm a channel exists
and carries traffic before relying on it.
## Channel types [#channel-types]
Each channel belongs to exactly one of five types — one per messaging pattern — and each
type is served by a specific set of tools:
| Type | Description | Associated tools |
| -------------- | ------------------------------------------ | ----------------------------------------------------------------------- |
| `queues` | Point-to-point durable queue channels | `queue_send`, `queue_receive`, `queue_peek` |
| `events` | Ephemeral fire-and-forget pub/sub channels | `events_publish` |
| `events_store` | Persistent pub/sub channels with replay | `events_store_publish`, `events_store_read`, `events_store_read_latest` |
| `commands` | Request/reply command channels | `command_send` |
| `queries` | Request/reply query channels | `query_send` |
The same string can name distinct channels under different types — `orders` as a queue and
`orders` as an events channel are unrelated. That is why `channel_info` requires both the
`channel` name **and** the `type`.
Only `queues` and `events_store` channels are backed by broker monitoring, so
`channel_list` and `channel_info` report live message statistics for them. The ephemeral
types (`events`, `commands`, `queries`) exist only while subscribers are connected and are
returned as type descriptions rather than per-channel stats.
## Reserved prefix [#reserved-prefix]
One prefix is reserved by the broker for the agent bridge and **cannot be targeted by the
direct messaging tools**.
| Prefix | Purpose | Restriction |
| ----------- | ----------------------------------- | -------------------------------------- |
| `_AGENTS_.` | Agent-bridge internal communication | Rejected by all direct messaging tools |
A channel is reserved when its name begins with the literal prefix `_AGENTS_.` (the
trailing dot is part of the prefix). Passing such a channel to `queue_send`,
`events_publish`, `events_store_publish`, `command_send`, or `query_send` returns a tool
error (`isError: true`) at the tool layer — the message is never published.
To reach an agent, use the agent-bridge tools `agent_send` and `agent_query` instead of
addressing `_AGENTS_.*` channels directly. The bridge manages the reserved channels on
your behalf — see [Agent-bridge tools](/aiway/mcp/tools/agent-bridge).
## Discovering channels [#discovering-channels]
Two read-only tools let a model explore the namespace at runtime instead of hard-coding
channel names: `channel_list` enumerates channels (optionally filtered), and
`channel_info` returns metadata for one channel.
### Listing and filtering [#listing-and-filtering]
`channel_list` returns every known channel, or a subset filtered by `type`, by a name
`pattern`, or both. The `pattern` filter is a **prefix match** — `"example-"` matches
`example-queue` and `example-events` but not `my-example`. With no arguments it returns
all channels.
```bash
# List all channels (no filter)
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'MCP-Protocol-Version: 2025-11-25' \
-d '{
"jsonrpc": "2.0",
"id": 11,
"method": "tools/call",
"params": {
"name": "channel_list",
"arguments": {}
}
}'
# Filter by type: "arguments": { "type": "queues" }
# Filter by prefix: "arguments": { "pattern": "example-" }
```
```go
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "channel_list",
Arguments: map[string]any{},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
```
```python
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# List all channels (no filter)
result = await session.call_tool("channel_list", {})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
# To filter by type, use: {"type": "queues"}
# To filter by pattern, use: {"pattern": "example-"}
```
```typescript
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
// List all channels (no filter)
const result = await client.callTool({
name: "channel_list",
arguments: {},
});
console.log(JSON.stringify(result, null, 2));
// To filter by type: { type: "queues" }
// To filter by pattern: { pattern: "example-" }
await client.close();
```
```java
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
// List all channels (no filter)
var result = client.callTool(new CallToolRequest(
"channel_list",
Map.of()
));
System.out.println(result);
// To filter by type: Map.of("type", "queues")
// To filter by pattern: Map.of("pattern", "example-")
client.closeGracefully();
```
```csharp
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("channel_list", new Dictionary());
Console.WriteLine($"Result: {result}");
```
```kotlin
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("channel_list", emptyMap())
println("Result: $result")
client.close()
httpClient.close()
```
```ruby
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("channel_list", {})
puts "Result: #{result}"
client.close
```
```rust
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("channel_list", json!({})).await?;
println!("Result: {result:#?}");
```
```swift
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("channel_list", arguments: [:])
print("Result: \(result)")
```
A successful `channel_list` returns a JSON array in the standard `content[]`/`isError`
envelope. An empty array (`[]`) is a normal result, not an error:
```json
{
"jsonrpc": "2.0",
"id": 11,
"result": {
"content": [
{
"type": "text",
"text": "[{\"name\":\"example-queue\",\"type\":\"queues\",\"is_active\":true},{\"name\":\"example-events\",\"type\":\"events\",\"is_active\":true}]"
}
],
"isError": false
}
}
```
### Inspecting one channel [#inspecting-one-channel]
`channel_info` confirms a single channel's type and live state. Both the `channel` name and
its `type` are required — the type scopes the lookup to the correct messaging pattern.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'MCP-Protocol-Version: 2025-11-25' \
-d '{
"jsonrpc": "2.0",
"id": 12,
"method": "tools/call",
"params": {
"name": "channel_info",
"arguments": {
"channel": "example-queue",
"type": "queues"
}
}
}'
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "channel_info",
Arguments: map[string]any{
"channel": "example-queue",
"type": "queues",
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
```
```python
result = await session.call_tool("channel_info", {
"channel": "example-queue",
"type": "queues",
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```typescript
const result = await client.callTool({
name: "channel_info",
arguments: {
channel: "example-queue",
type: "queues",
},
});
console.log(JSON.stringify(result, null, 2));
```
```java
var result = client.callTool(new CallToolRequest(
"channel_info",
Map.of(
"channel", "example-queue",
"type", "queues"
)
));
System.out.println(result);
```
```csharp
var result = await client.CallToolAsync("channel_info", new Dictionary
{
["channel"] = "example-queue",
["type"] = "queues",
});
Console.WriteLine($"Result: {result}");
```
```kotlin
val result = client.callTool("channel_info", mapOf(
"channel" to "example-queue",
"type" to "queues"
))
println("Result: $result")
```
```ruby
result = client.call_tool("channel_info", {
"channel" => "example-queue",
"type" => "queues",
})
puts "Result: #{result}"
```
```rust
let result = client.call_tool("channel_info", json!({
"channel": "example-queue",
"type": "queues"
})).await?;
println!("Result: {result:#?}");
```
```swift
let result = try await client.callTool("channel_info", arguments: [
"channel": "example-queue",
"type": "queues",
])
print("Result: \(result)")
```
For `queues` and `events_store` channels the result includes live `incoming`/`outgoing`
message counts; for the ephemeral types it returns the channel's type and active state:
```json
{
"jsonrpc": "2.0",
"id": 12,
"result": {
"content": [
{
"type": "text",
"text": "{\"name\":\"example-queue\",\"type\":\"queues\",\"is_active\":true,\"incoming\":5,\"outgoing\":3}"
}
],
"isError": false
}
}
```
## Resolution failures [#resolution-failures]
| Condition | Result |
| --------------------------------------------------------------- | ------------------------------------------ |
| Channel name begins with `_AGENTS_.` on a direct messaging tool | Tool error — `isError: true` |
| Invalid `type` value (not one of the five) | JSON-RPC `-32602` Invalid Params |
| `channel_info` missing `channel` or `type` | JSON-RPC `-32602` Invalid Params |
| `channel_list` with a pattern that matches nothing | Successful result with an empty array `[]` |
For the full JSON-RPC error catalog, see
[Error codes](/aiway/mcp/reference/error-codes).
## Related [#related]
# Client Setup (/aiway/mcp/guides/client-setup)
The MCP connector speaks the [Model Context Protocol](/aiway/mcp) (version `2025-11-25`) as JSON-RPC 2.0 over the **Streamable HTTP transport** at `POST /mcp`. Any compliant MCP client — Claude Desktop, an official MCP SDK, or a hand-rolled JSON-RPC caller — connects the same way: point it at the endpoint, run the `initialize` handshake, and start calling tools. This guide covers each path in depth. For the 5-minute quick start, see [Getting started](/aiway/mcp/getting-started).
## Overview [#overview]
Every MCP client connects to a single URL and goes through the same three-step lifecycle before any tool call:
1. **`initialize`** — negotiate the protocol version and open a session.
2. **`notifications/initialized`** — acknowledge the handshake.
3. **`tools/list` / `tools/call`** — discover and invoke tools.
The official SDKs and Claude Desktop perform steps 1 and 2 automatically and track the [session ID](/aiway/mcp/guides/session-management) for you. With raw `curl` you drive each step yourself.
## How it works [#how-it-works]
The Streamable HTTP transport carries every JSON-RPC message as a standalone `POST /mcp`. The server returns an `MCP-Session-Id` on `initialize`, and the client echoes it on all subsequent requests. A separate `GET /mcp` opens a stateless keepalive stream that emits a `: keepalive` comment every 30 seconds.
*One session, established once, carries every later request via the `MCP-Session-Id` header.*
## Claude Desktop [#claude-desktop]
Claude Desktop's configuration file lists local (stdio) servers that it starts itself; it does not connect to an HTTP address. Add KubeMQ through `mcp-remote`, a local bridge that `npx` runs and that speaks Streamable HTTP to KubeMQ. Open `claude_desktop_config.json` (Claude Desktop → Settings → Developer → Edit Config), add the entry, then quit and restart Claude Desktop.
```json title="claude_desktop_config.json"
{
"mcpServers": {
"kubemq": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:9090/mcp"]
}
}
}
```
On restart, Claude Desktop starts the bridge, which runs the `initialize` handshake, discovers all 15 KubeMQ [tools](/aiway/mcp/tools), and exposes them in the conversation. The bridge needs Node.js, which provides `npx`.
### Cursor and other HTTP hosts [#cursor-and-other-http-hosts]
Hosts that connect over HTTP take the endpoint directly. For Cursor, add it to `~/.cursor/mcp.json`:
```json title="~/.cursor/mcp.json"
{
"mcpServers": {
"kubemq": {
"url": "http://localhost:9090/mcp"
}
}
}
```
The `url` must include the `/mcp` path — it is the only required field for an unauthenticated server.
### Authenticated servers [#authenticated-servers]
If the [shared HTTP server](/connectors/concepts/shared-http-server) has JWT auth enabled, every request needs a Bearer token. For Claude Desktop, pass the header to the bridge:
```json title="claude_desktop_config.json"
{
"mcpServers": {
"kubemq": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://kubemq.example.com/mcp", "--header", "Authorization:${KUBEMQ_AUTH}"],
"env": {
"KUBEMQ_AUTH": "Bearer YOUR_TOKEN"
}
}
}
}
```
Replace:
* `YOUR_TOKEN` — the JWT issued for this host by whoever runs your KubeMQ authentication.
Keep spaces out of `args`: Claude Desktop on Windows does not escape them, so the space in `Bearer YOUR_TOKEN` goes in `env`.
For Cursor and other HTTP hosts, add a `headers` object:
```json title="~/.cursor/mcp.json"
{
"mcpServers": {
"kubemq": {
"url": "https://kubemq.example.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_TOKEN"
}
}
}
}
```
Use `https://` for any remote endpoint. See [Authentication](/aiway/mcp/guides/authentication) for how the connector validates the token and returns `-32010` on failure.
The MCP connector also validates the request `Origin` against `McpConfig.TrustedOrigins` (default `["auto"]`, which matches `localhost`, `127.0.0.1`, `::1`, `[::1]`, `0.0.0.0`, and the server's bind address). When connecting from a remote host or a custom origin, add it to the trusted-origins list in [Configuration](/aiway/mcp/configuration) or origin validation will reject the connection.
## Generic JSON-RPC client [#generic-json-rpc-client]
Any HTTP client can speak MCP directly — no SDK required. You manage the handshake, the `MCP-Session-Id` header, and request IDs yourself. This is the lowest-level path and mirrors exactly what an SDK does internally.
### Open a session with `initialize` [#open-a-session-with-initialize]
`POST` an `initialize` request announcing the protocol version (`2025-11-25`) and your client identity:
```bash title="terminal"
curl -i -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": { "name": "my-agent", "version": "1.0.0" }
}
}'
```
Capture the session ID from `result._meta.sessionId` in the body — it is also returned in the `MCP-Session-Id` response header (use `-i` to see headers):
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-11-25",
"capabilities": { "tools": {} },
"serverInfo": { "name": "kubemq", "version": "..." },
"_meta": { "sessionId": "" }
}
}
```
### Acknowledge with `notifications/initialized` [#acknowledge-with-notificationsinitialized]
Send the `notifications/initialized` notification, carrying the session ID. It has no `id`, so the server replies with HTTP `200 OK` and body `{"jsonrpc":"2.0","result":null,"id":null}`:
```bash title="terminal"
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: ' \
-d '{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}'
```
### Call tools with the session header [#call-tools-with-the-session-header]
Every later request — `tools/list`, `tools/call`, `ping` — includes the `MCP-Session-Id` header:
```bash title="terminal"
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: ' \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "queue_send",
"arguments": { "channel": "my-queue", "body": "Hello from MCP" }
}
}'
```
### Required headers [#required-headers]
| Header | Direction | When | Description |
| ---------------------- | --------- | ------------------ | ----------------------------------------------- |
| `Content-Type` | Request | Always | Must be `application/json`. |
| `MCP-Session-Id` | Request | After `initialize` | The session ID returned by the handshake. |
| `MCP-Session-Id` | Response | Always | Echoed back by the server. |
| `MCP-Protocol-Version` | Response | Always | The protocol version, `2025-11-25`. |
| `Authorization` | Request | When auth is on | `Bearer ` for authenticated servers. |
A stateless `GET /mcp` opens an SSE keepalive stream that emits a `: keepalive` comment every 30 seconds and carries no MCP messages — it only keeps an idle connection alive and closes when the client disconnects. See [Session management](/aiway/mcp/guides/session-management) for the full lifecycle and batching.
## Official MCP SDKs [#official-mcp-sdks]
Each official MCP SDK wraps the Streamable HTTP transport: it performs the `initialize` handshake, sends `notifications/initialized`, and tracks the session ID automatically — you construct the transport with the endpoint URL and call tools. All examples read `KUBEMQ_MCP_URL` (default `http://localhost:9090`) and append `/mcp`.
```bash
# Raw JSON-RPC: initialize, then call a tool with the returned session ID.
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: ' \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "queue_send",
"arguments": {
"channel": "example-queue",
"body": "Hello from MCP",
"metadata": "example-metadata",
"tags": { "env": "dev", "source": "mcp-example" }
}
}
}'
```
```go
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "queue_send",
Arguments: map[string]any{
"channel": "example-queue",
"body": "Hello from Go MCP",
"metadata": "example-metadata",
"tags": map[string]any{"env": "dev", "source": "mcp-example"},
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Tool: queue_send")
fmt.Printf("Result: %+v\n", result)
}
```
```python
import asyncio
import os
from mcp.client.streamable_http import streamable_http_client
from mcp import ClientSession
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
async def main():
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool("queue_send", {
"channel": "example-queue",
"body": "Hello from Python MCP",
"metadata": "example-metadata",
"tags": {"env": "dev", "source": "mcp-example"},
})
print(f"Tool: queue_send")
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
if __name__ == "__main__":
asyncio.run(main())
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
async function main() {
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
const result = await client.callTool({
name: "queue_send",
arguments: {
channel: "example-queue",
body: "Hello from TypeScript MCP",
metadata: "example-metadata",
tags: { env: "dev", source: "mcp-example" },
},
});
console.log(JSON.stringify(result, null, 2));
await client.close();
}
main().catch(console.error);
```
```java
import io.modelcontextprotocol.sdk.McpClient;
import io.modelcontextprotocol.sdk.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import java.util.Map;
public class QueueSend {
public static void main(String[] args) {
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
var result = client.callTool(new CallToolRequest(
"queue_send",
Map.of(
"channel", "example-queue",
"body", "Hello from Java MCP",
"metadata", "example-metadata",
"tags", Map.of("env", "dev", "source", "mcp-example")
)
));
System.out.println(result);
client.closeGracefully();
}
}
```
```csharp
using ModelContextProtocol.Client;
class QueueSend
{
static async Task Main(string[] args)
{
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("queue_send", new Dictionary
{
["channel"] = "example-queue",
["body"] = "Hello from C# MCP",
["metadata"] = "example-metadata",
["tags"] = new Dictionary { ["env"] = "dev", ["source"] = "mcp-example" },
});
Console.WriteLine($"Tool: queue_send");
Console.WriteLine($"Result: {result}");
}
}
```
```kotlin
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport
import io.ktor.client.*
import io.ktor.client.plugins.sse.*
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("queue_send", mapOf(
"channel" to "example-queue",
"body" to "Hello from Kotlin MCP",
"metadata" to "example-metadata",
"tags" to mapOf("env" to "dev", "source" to "mcp-example")
))
println("Tool: queue_send")
println("Result: $result")
client.close()
httpClient.close()
}
```
```ruby
require "mcp"
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("queue_send", {
"channel" => "example-queue",
"body" => "Hello from Ruby MCP",
"metadata" => "example-metadata",
"tags" => { "env" => "dev", "source" => "mcp-example" },
})
puts "Tool: queue_send"
puts "Result: #{result}"
client.close
```
```rust
use rmcp::transport::streamable_http::StreamableHttpClientTransport;
use rmcp::service::RunService;
use serde_json::json;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("queue_send", json!({
"channel": "example-queue",
"body": "Hello from Rust MCP",
"metadata": "example-metadata",
"tags": {"env": "dev", "source": "mcp-example"}
})).await?;
println!("Tool: queue_send");
println!("Result: {result:#?}");
Ok(())
}
```
```swift
import Foundation
import MCP
@main
struct QueueSend {
static func main() async throws {
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("queue_send", arguments: [
"channel": "example-queue",
"body": "Hello from Swift MCP",
"metadata": "example-metadata",
"tags": ["env": "dev", "source": "mcp-example"],
])
print("Tool: queue_send")
print("Result: \(result)")
}
}
```
For an authenticated server, pass the JWT through the SDK's transport options (an `Authorization: Bearer ` header) — the same mechanism Claude Desktop uses. The standard environment variables are `KUBEMQ_MCP_URL`, `KUBEMQ_MCP_TIMEOUT` (client-side HTTP timeout, default `30`s), and `KUBEMQ_MCP_AUTH_TOKEN`.
## Related [#related]
# Error Handling (/aiway/mcp/guides/error-handling)
A `tools/call` can fail in three structurally different ways, and each one shows up
in a different part of the response. A client that treats them as one bucket will
either crash on a recoverable failure or silently swallow a malformed request. This
guide shows how to detect each layer and branch on them in the right order; for the
exhaustive list of codes and messages, see the
[Error codes reference](/aiway/mcp/reference/error-codes).
## Overview [#overview]
When you call a tool over `/mcp`, the request passes through three checkpoints
before you get a result back:
1. **HTTP / auth layer** — the shared HTTP server validates the origin and the
`Authorization` header *before* any JSON-RPC is parsed. Failures here surface as
the JSON-RPC auth error `-32010` (the body still parses as JSON-RPC).
2. **JSON-RPC protocol layer** — the connector parses the envelope and resolves the
method. A malformed body, an unknown method, or bad params produce a JSON-RPC
`error` object **with no `result`**.
3. **Tool execution layer** — the envelope was valid and a tool ran, but the
operation failed (reserved channel, missing agent, timeout). The response is a
normal `result` carrying `isError: true`.
The decisive split is between layers 2 and 3: a **protocol error** means the tool
never ran, so retrying the same request fails identically — the fix is to correct
the request. A **tool error** means a valid request ran and failed for an
operational reason, which may be transient (a timeout) and worth retrying.
Every JSON-RPC response — success *or* error — comes back as **HTTP 200**. The
outcome is encoded in the JSON body, not the status line. Do not branch on the HTTP
status code for JSON-RPC calls.
## How it works [#how-it-works]
Branch on the layers in a fixed order so a recoverable tool failure is never
mistaken for a protocol failure, and vice versa.
*A `tools/call` clears three checkpoints; each failure surfaces in a different field, so inspect them in order.*
## Layer 1 — HTTP and auth [#layer-1--http-and-auth]
Authentication and origin checks run in the shared HTTP server, ahead of JSON-RPC
parsing. When JWT auth is enabled and the `Authorization: Bearer` header is missing
or invalid, the `/mcp` endpoint returns the JSON-RPC auth error `-32010` — the
response is still valid JSON-RPC, so you read it the same way as any other error
object:
```json title="Auth failure (-32010)"
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32010,
"message": "authentication failed"
}
}
```
Origin validation can also reject the request before a tool runs. Auth and origin
behavior are shared across all connectors and documented once in
[Auth & security](/connectors/reference/auth-and-security); the MCP-specific
`validateOrigin`/`TrustedOrigins` rules are covered in
[Authentication](/aiway/mcp/guides/authentication).
## Layer 2 — JSON-RPC protocol errors [#layer-2--json-rpc-protocol-errors]
Protocol errors mean the envelope itself was rejected: malformed JSON, the wrong
`Content-Type`, an unknown method, or invalid params. They appear in the `error`
field and there is **no `result`** field at all.
```json title="Protocol error (-32601)"
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32601,
"message": "Method not found"
}
}
```
| Code | Trigger |
| -------- | ---------------------------------------------------------------------------------------------- |
| `-32700` | Malformed JSON body, or wrong `Content-Type` (e.g. `text/plain` instead of `application/json`) |
| `-32600` | Empty `method` field, or `jsonrpc` is not `"2.0"` |
| `-32601` | Unknown method name (e.g. `tools/unknown`) |
| `-32602` | `params` is not an object, or required tool arguments are missing |
Retrying an identical request after a protocol error fails the same way — correct
the request instead of retrying. The full catalog, with response examples for each
code, lives in the [Error codes reference](/aiway/mcp/reference/error-codes).
## Layer 3 — tool execution errors [#layer-3--tool-execution-errors]
A tool error means the envelope was valid and a tool was invoked, but the operation
failed. The response is structurally a **success** — HTTP 200, a populated
`result` — with `isError: true` and a human-readable cause in
`result.content[].text`. A client that only checks the `error` field treats this as
a successful call, so always inspect `result.isError` as a second step.
```json title="Tool error (result.isError)"
{
"jsonrpc": "2.0",
"id": 9,
"result": {
"content": [{ "type": "text", "text": "Command timed out: no subscriber on channel 'example-commands' within 10s" }],
"isError": true
}
}
```
Common tool-level failures and the tools that raise them:
| Failure | Affected tools |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------ |
| Reserved-channel rejection (channel starts with `_AGENTS_.`) | `queue_send`, `events_publish`, `events_store_publish`, `command_send`, `query_send` |
| Non-existent agent | `agent_info`, `agent_send`, `agent_query` |
| Timeout exceeded / no subscriber | `command_send`, `query_send`, `agent_send`, `agent_query` |
| Non-existent channel | `channel_info` |
Channels beginning with `_AGENTS_.` are reserved for the agent bridge, so any
publish or request tool targeting one is rejected at the tool layer. To reach an
agent, use the [agent-bridge tools](/aiway/mcp/tools/agent-bridge)
(`agent_send`, `agent_query`) instead.
## Handling timeouts [#handling-timeouts]
The synchronous tools — `command_send`, `query_send`, `agent_send`, `agent_query` —
block until a responder replies or the timeout elapses. When no responder is
listening, the call does **not** raise a protocol error; it returns a normal result
with `isError: true` and a timeout message. Detect a timeout by reading
`result.isError`, not by catching a transport exception.
* The per-call timeout is the `timeout_seconds` argument (default 10 for commands,
30 for queries, 60 for the agent-bridge tools), capped at **300**.
* The connector also enforces a server-side `ToolTimeoutSeconds` ceiling
(default **300**) — see [Configuration](/aiway/mcp/configuration).
* A timeout may be transient (the responder was briefly absent). It is one of the
few tool errors that is reasonable to **retry** with backoff — unlike a
reserved-channel or invalid-params error, which will fail identically.
## Detecting both layers in code [#detecting-both-layers-in-code]
Branch in a fixed order: check the `error` field first, then `result.isError`. The
example below calls `command_send` (which surfaces a timeout as a tool error) and
inspects the result. Each snippet assumes an initialized MCP session — for the
connect-and-initialize handshake, see
[Client setup](/aiway/mcp/guides/client-setup).
```bash
# The JSON-RPC envelope always returns HTTP 200. Inspect the body:
# .error -> protocol error (no .result)
# .result.isError -> tool execution error
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 9,
"method": "tools/call",
"params": {
"name": "command_send",
"arguments": {
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10
}
}
}'
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "command_send",
Arguments: map[string]any{
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10,
},
},
})
if err != nil {
// Layer 1/2: transport or JSON-RPC protocol error — the tool never ran.
log.Fatal(err)
}
// Layer 3: a valid call that failed at the tool layer (e.g. timeout).
if result.IsError {
fmt.Printf("tool error: %+v\n", result.Content)
return
}
fmt.Printf("Result: %+v\n", result)
```
```python
result = await session.call_tool("command_send", {
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10,
})
# Layer 3: tool execution error (timeout, reserved channel, ...).
# Layer 1/2 protocol errors raise an exception before reaching here.
if result.isError:
print(f"tool error: {result.content[0].text}")
else:
print(f"Result: {result.content[0].text}")
```
```typescript
const result = await client.callTool({
name: "command_send",
arguments: {
channel: "example-commands",
body: "do-work",
timeout_seconds: 10,
},
});
// Layer 3: inspect isError before trusting the content.
if (result.isError) {
console.error("tool error:", result.content);
} else {
console.log(JSON.stringify(result, null, 2));
}
```
```java
var result = client.callTool(new CallToolRequest(
"command_send",
Map.of(
"channel", "example-commands",
"body", "do-work",
"timeout_seconds", 10
)
));
// Layer 3: a valid call that failed at the tool layer.
if (Boolean.TRUE.equals(result.isError())) {
System.out.println("tool error: " + result.content());
} else {
System.out.println(result);
}
```
```csharp
var result = await client.CallToolAsync("command_send", new Dictionary
{
["channel"] = "example-commands",
["body"] = "do-work",
["timeout_seconds"] = 10,
});
// Layer 3: tool execution error (e.g. timeout).
if (result.IsError)
{
Console.WriteLine($"tool error: {result.Content}");
}
else
{
Console.WriteLine($"Result: {result}");
}
```
```kotlin
val result = client.callTool("command_send", mapOf(
"channel" to "example-commands",
"body" to "do-work",
"timeout_seconds" to 10
))
// Layer 3: inspect isError before using the content.
if (result.isError == true) {
println("tool error: ${result.content}")
} else {
println("Result: $result")
}
```
```ruby
result = client.call_tool("command_send", {
"channel" => "example-commands",
"body" => "do-work",
"timeout_seconds" => 10,
})
# Layer 3: tool execution error (e.g. timeout).
if result.is_error
puts "tool error: #{result.content}"
else
puts "Result: #{result}"
end
```
```rust
let result = client.call_tool("command_send", json!({
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10
})).await?;
// Layer 3: a valid call that failed at the tool layer.
if result.is_error.unwrap_or(false) {
eprintln!("tool error: {:#?}", result.content);
} else {
println!("Result: {result:#?}");
}
```
```swift
let result = try await client.callTool("command_send", arguments: [
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10,
])
// Layer 3: inspect isError before trusting the content.
if result.isError == true {
print("tool error: \(result.content)")
} else {
print("Result: \(result)")
}
```
A timeout is reported through `result.isError`, **not** as a JSON-RPC error and
**not** as a non-200 HTTP status. Code that only catches transport exceptions or
checks the status code will silently treat a timed-out command as a success.
## Best practices [#best-practices]
1. **Check `error` first, then `result.isError`.** A protocol error has no
`result`; a tool error is structurally a success with `isError: true`.
2. **Do not branch on the HTTP status for JSON-RPC calls** — every response is
HTTP 200 (auth/origin rejections excepted, which return `-32010` in the body).
3. **Retry only transient tool errors** (timeouts, no-subscriber). Protocol errors
and reserved-channel/invalid-params errors fail identically on retry — fix the
request instead.
4. **Log the full response** when debugging, not just the field you branched on.
## Related [#related]
# Session Management (/aiway/mcp/guides/session-management)
Every MCP interaction with the KubeMQ connector runs inside a **session**. The session is opened by an `initialize` handshake, identified by an `MCP-Session-Id` header, and reused across every tool call until the client disconnects.
## Overview [#overview]
The MCP connector speaks JSON-RPC 2.0 over the shared HTTP server on port 9090. A single endpoint — `POST /mcp` — handles `initialize`, `tools/list`, `tools/call`, and `ping`. A companion `GET /mcp` endpoint provides an SSE keepalive stream.
A session is **server-managed**: the server issues a session ID during `initialize`, and the client echoes it on every subsequent request. Multiple tool calls share one session, and each session keeps its own request context. You rarely build the handshake by hand — every official MCP SDK performs it for you when you connect. This page shows both: the raw protocol so you understand what travels on the wire, and the SDK call that establishes the session for you.
The session model is part of the [shared HTTP server](/connectors/concepts/shared-http-server). For who may open a session and how auth applies, see [Auth & security](/connectors/reference/auth-and-security).
## How it works [#how-it-works]
The handshake is three steps: the client sends `initialize`, the server returns its capabilities plus a session ID, and the client acknowledges with a `notifications/initialized` notification. After that, every request carries the `MCP-Session-Id` header.
*The initialize handshake opens a session; the session ID is replayed on each later request.*
## The handshake [#the-handshake]
### Step 1 — initialize [#step-1--initialize]
Send an `initialize` request with the protocol version, your capabilities, and `clientInfo`:
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": { "name": "my-agent", "version": "1.0.0" }
}
}
```
### Step 2 — receive the session ID [#step-2--receive-the-session-id]
The server responds with its `protocolVersion`, `capabilities`, `serverInfo`, and the session ID under `result._meta.sessionId`:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-11-25",
"capabilities": { "tools": { "listChanged": false } },
"serverInfo": { "name": "kubemq", "version": "" },
"_meta": { "sessionId": "abc123-def456" }
}
}
```
The session ID is also returned in the `MCP-Session-Id` response header, alongside `MCP-Protocol-Version: 2025-11-25`.
### Step 3 — send the initialized notification [#step-3--send-the-initialized-notification]
Acknowledge with a `notifications/initialized` notification. A notification has **no `id` field** and the server returns **HTTP 200** with body `{"jsonrpc":"2.0","result":null,"id":null}`:
```json
{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
```
## Establishing a session [#establishing-a-session]
Below, `curl` walks the raw three-step handshake; the SDK tabs perform the same handshake transparently when you connect, then reuse the session for every tool call.
```bash
# 1. initialize — capture the session ID from the MCP-Session-Id response header
curl -i -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"my-agent","version":"1.0.0"}}}'
# 2. acknowledge — replay the session ID; server returns 200 with {"jsonrpc":"2.0","result":null,"id":null}
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: abc123-def456' \
-d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
# 3. call a tool inside the session
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: abc123-def456' \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"queue_send","arguments":{"channel":"example-queue","body":"Hello"}}}'
```
```csharp
using ModelContextProtocol.Client;
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
// CreateAsync runs the initialize handshake and holds the session for reuse.
await using var client = await McpClientFactory.CreateAsync(transport);
// Every later call rides the same session.
var result = await client.CallToolAsync("queue_send", new Dictionary
{
["channel"] = "example-queue",
["body"] = "Hello from C# MCP",
});
Console.WriteLine($"Result: {result}");
```
```go
package main
import (
"context"
"log"
"os"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
// Start performs the initialize handshake and binds the session.
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
// The same session is reused for every CallTool.
_, err = c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "queue_send",
Arguments: map[string]any{"channel": "example-queue", "body": "Hello from Go MCP"},
},
})
if err != nil {
log.Fatal(err)
}
}
```
```java
import io.modelcontextprotocol.sdk.McpClient;
import io.modelcontextprotocol.sdk.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import java.util.Map;
public class Session {
public static void main(String[] args) {
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
// initialize() performs the handshake and opens the session.
client.initialize();
// The client reuses the session for each call.
var result = client.callTool(new CallToolRequest(
"queue_send",
Map.of("channel", "example-queue", "body", "Hello from Java MCP")
));
System.out.println(result);
client.closeGracefully();
}
}
```
```kotlin
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport
import io.ktor.client.*
import io.ktor.client.plugins.sse.*
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin", version = "1.0.0"))
// connect() runs the initialize handshake and holds the session.
client.connect(transport)
client.callTool("queue_send", mapOf("channel" to "example-queue", "body" to "Hello from Kotlin MCP"))
client.close()
httpClient.close()
}
```
```python
import asyncio
import os
from mcp.client.streamable_http import streamable_http_client
from mcp import ClientSession
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
async def main():
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
# initialize() performs the 3-step handshake and stores the session ID.
await session.initialize()
# Every call_tool on this session replays the same MCP-Session-Id.
result = await session.call_tool("queue_send", {
"channel": "example-queue",
"body": "Hello from Python MCP",
})
print(f"IsError: {result.isError}")
if __name__ == "__main__":
asyncio.run(main())
```
```ruby
require "mcp"
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby",
version: "1.0.0"
)
# initialize_handshake performs the handshake and opens the session.
client.initialize_handshake
# The session is reused for each call_tool.
result = client.call_tool("queue_send", {
"channel" => "example-queue",
"body" => "Hello from Ruby MCP",
})
puts "Result: #{result}"
client.close
```
```rust
use rmcp::transport::streamable_http::StreamableHttpClientTransport;
use rmcp::service::RunService;
use serde_json::json;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
// serve() runs the initialize handshake and binds the session.
let client = ().serve(transport).await?;
// The client reuses the session for each call.
let _ = client.call_tool("queue_send", json!({
"channel": "example-queue",
"body": "Hello from Rust MCP"
})).await?;
Ok(())
}
```
```swift
import Foundation
import MCP
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift", version: "1.0.0")
// connect() performs the initialize handshake and opens the session.
try await client.connect(transport: transport)
// The session is reused for each callTool.
let result = try await client.callTool("queue_send", arguments: [
"channel": "example-queue",
"body": "Hello from Swift MCP",
])
print("Result: \(result)")
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
const transport = new StreamableHTTPClientTransport(new URL(`${KUBEMQ_MCP_URL}/mcp`));
const client = new Client({ name: "kubemq-mcp-ts", version: "1.0.0" });
// connect() runs the initialize handshake and holds the session for reuse.
await client.connect(transport);
// Every callTool on this client rides the same session.
const result = await client.callTool({
name: "queue_send",
arguments: { channel: "example-queue", body: "Hello from TypeScript MCP" },
});
console.log(JSON.stringify(result, null, 2));
await client.close();
```
## Session headers [#session-headers]
| Header | Direction | Required | Description |
| ---------------------- | --------- | ------------------ | ------------------------------------------------- |
| `Content-Type` | Request | Always | Must be `application/json` |
| `MCP-Session-Id` | Request | After `initialize` | Session identifier from the `initialize` response |
| `MCP-Session-Id` | Response | Always | Echoed back by the server |
| `MCP-Protocol-Version` | Response | Always | Protocol version `2025-11-25` |
## Session lifecycle [#session-lifecycle]
* Sessions are **server-managed** — the server mints the session ID during `initialize`.
* **Multiple tool calls share one session**; each maintains its own request context.
* A session persists until the client disconnects or a server-side inactivity timeout occurs.
* Reusing the connection (and the `MCP-Session-Id`) avoids re-running the handshake on every call.
## Batch requests [#batch-requests]
`POST /mcp` accepts a **JSON array** of JSON-RPC requests and processes each one **sequentially**. Requests carrying an `id` produce a response entry; notifications (no `id`) are executed but produce no entry. Send the batch with the same `MCP-Session-Id` as any single request.
```bash
# Two tool calls in a single batched POST — one response entry per id.
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'MCP-Session-Id: abc123-def456' \
-d '[
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"queue_send","arguments":{"channel":"a","body":"one"}}},
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"queue_send","arguments":{"channel":"b","body":"two"}}}
]'
```
```python
# SDKs typically issue calls individually over one session rather than
# constructing a raw JSON-RPC array. The session is reused for each call:
await session.call_tool("queue_send", {"channel": "a", "body": "one"})
await session.call_tool("queue_send", {"channel": "b", "body": "two"})
```
```typescript
// SDKs reuse the open session per call; the connector batches at the HTTP
// layer when a raw JSON-RPC array is posted.
await client.callTool({ name: "queue_send", arguments: { channel: "a", body: "one" } });
await client.callTool({ name: "queue_send", arguments: { channel: "b", body: "two" } });
```
## Keepalive stream — GET /mcp [#keepalive-stream--get-mcp]
`GET /mcp` opens an SSE stream that emits a `: keepalive` comment every **30 seconds**. It is a **stateless keepalive only** — no MCP messages travel over it, and the stream closes when the client disconnects. Use it to hold a long-lived connection open through intermediaries; all real work still goes through `POST /mcp`.
```bash
# Hold an SSE keepalive open (a ": keepalive" comment arrives every 30s)
curl -N http://localhost:9090/mcp
```
## Related [#related]
# Agent-bridge tools (/aiway/mcp/tools/agent-bridge)
The four **agent-bridge tools** turn an MCP client into an [A2A](/aiway/a2a)
caller: it can list registered agents, read an agent's card, and send messages or
forward JSON-RPC methods to an agent — all without leaving the Model Context Protocol.
## Overview [#overview]
The MCP connector exposes 15 tools. Eleven are core messaging tools that always
reach the broker directly. The remaining four — `agent_list`, `agent_info`,
`agent_send`, and `agent_query` — are **bridge tools**: they forward to the A2A
[agent registry](/aiway/a2a) instead of to a messaging channel.
| Tool | Purpose | Required arguments | Optional arguments |
| ------------- | ------------------------------------- | --------------------- | -------------------------------------------------------------------------------------- |
| `agent_list` | List registered agents | (none) | `skill_tags` (array of strings) |
| `agent_info` | Get an agent's details | `agent_id` | (none) |
| `agent_send` | Send a message to an agent via A2A | `agent_id`, `message` | `blocking` (default `true`), `timeout_seconds` (default `60`, max `300`), `context_id` |
| `agent_query` | Forward a JSON-RPC method to an agent | `agent_id`, `method` | `params` (object), `timeout_seconds` (default `60`, max `300`) |
The bridge tools appear in `tools/list` **only when the A2A agent registry is
injected** into the MCP connector. If the A2A connector is not running, an MCP
client sees only the 11 core tools. See [Tools overview](/aiway/mcp/tools).
## How it works [#how-it-works]
`agent_send` builds an A2A `message/send` JSON-RPC envelope and forwards it over a
Query to `_AGENTS_.agents/`, where the agent's
[virtual subscriber](/aiway/a2a) delivers it as an HTTP POST. `agent_query`
forwards an arbitrary JSON-RPC method to the same destination. Both add the gateway
timeout buffer on top of the caller's `timeout_seconds`.
*Bridge tools route discovery to the registry and messages to the agent's internal channel, which a virtual subscriber delivers over HTTP.*
## agent\_list [#agent_list]
Lists every registered agent. Pass `skill_tags` to filter agents whose
[agent card](/aiway/a2a/agent-cards) advertises matching skill tags.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 13,
"method": "tools/call",
"params": {
"name": "agent_list",
"arguments": {}
}
}'
```
```go
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "agent_list",
Arguments: map[string]any{},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Tool: agent_list")
fmt.Printf("Result: %+v\n", result)
```
```python
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# List all agents (no filter)
result = await session.call_tool("agent_list", {})
print(f"Tool: agent_list")
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
# To filter by skill tags, use: {"skill_tags": ["echo"]}
```
```typescript
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
// List all agents (no filter)
const result = await client.callTool({
name: "agent_list",
arguments: {},
});
console.log(JSON.stringify(result, null, 2));
// To filter by skill tags: { skill_tags: ["echo"] }
await client.close();
```
```java
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
// List all agents (no filter)
var result = client.callTool(new CallToolRequest(
"agent_list",
Map.of()
));
System.out.println(result);
// To filter by skill tags: Map.of("skill_tags", List.of("echo"))
client.closeGracefully();
```
```csharp
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("agent_list", new Dictionary());
Console.WriteLine($"Tool: agent_list");
Console.WriteLine($"Result: {result}");
```
```kotlin
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("agent_list", emptyMap())
println("Tool: agent_list")
println("Result: $result")
client.close()
httpClient.close()
```
```ruby
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("agent_list", {})
puts "Tool: agent_list"
puts "Result: #{result}"
client.close
```
```rust
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("agent_list", json!({})).await?;
println!("Tool: agent_list");
println!("Result: {result:#?}");
```
```swift
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("agent_list", arguments: [:])
print("Tool: agent_list")
print("Result: \(result)")
```
The result text is a JSON array of agent summaries:
```json
{
"jsonrpc": "2.0",
"id": 13,
"result": {
"content": [{ "type": "text", "text": "[{\"agent_id\":\"echo-01\",\"name\":\"Echo Agent 01\",\"skills\":[{\"id\":\"echo\",\"name\":\"Echo\",\"tags\":[\"test\",\"echo\"]}]}]" }],
"isError": false
}
}
```
## agent\_info [#agent_info]
Returns the full [agent card](/aiway/a2a/agent-cards) for one agent —
name, description, version, URL, and skills.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 14,
"method": "tools/call",
"params": {
"name": "agent_info",
"arguments": { "agent_id": "example-agent" }
}
}'
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "agent_info",
Arguments: map[string]any{
"agent_id": "example-agent",
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Tool: agent_info")
fmt.Printf("Result: %+v\n", result)
```
```python
result = await session.call_tool("agent_info", {
"agent_id": "example-agent",
})
print(f"Tool: agent_info")
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```typescript
const result = await client.callTool({
name: "agent_info",
arguments: {
agent_id: "example-agent",
},
});
console.log(JSON.stringify(result, null, 2));
```
```java
var result = client.callTool(new CallToolRequest(
"agent_info",
Map.of("agent_id", "example-agent")
));
System.out.println(result);
```
```csharp
var result = await client.CallToolAsync("agent_info", new Dictionary
{
["agent_id"] = "example-agent",
});
Console.WriteLine($"Tool: agent_info");
Console.WriteLine($"Result: {result}");
```
```kotlin
val result = client.callTool("agent_info", mapOf(
"agent_id" to "example-agent"
))
println("Tool: agent_info")
println("Result: $result")
```
```ruby
result = client.call_tool("agent_info", {
"agent_id" => "example-agent",
})
puts "Tool: agent_info"
puts "Result: #{result}"
```
```rust
let result = client.call_tool("agent_info", json!({
"agent_id": "example-agent"
})).await?;
println!("Tool: agent_info");
println!("Result: {result:#?}");
```
```swift
let result = try await client.callTool("agent_info", arguments: [
"agent_id": "example-agent",
])
print("Tool: agent_info")
print("Result: \(result)")
```
A successful call returns the agent card as a JSON string; an unknown `agent_id`
returns `isError: true` with `Agent 'example-agent' not found`:
```json
{
"jsonrpc": "2.0",
"id": 14,
"result": {
"content": [{ "type": "text", "text": "{\"agent_id\":\"example-agent\",\"name\":\"Example Agent\",\"description\":\"example agent\",\"version\":\"1.0.0\"}" }],
"isError": false
}
}
```
## agent\_send [#agent_send]
Sends a message to an agent. The bridge wraps it in an A2A `message/send` envelope.
By default the call is **blocking** — it waits up to `timeout_seconds` for the
agent's reply. Pass `blocking: false` for fire-and-forget, or `context_id` to thread
the message into an existing conversation.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 15,
"method": "tools/call",
"params": {
"name": "agent_send",
"arguments": { "agent_id": "example-agent", "message": "hello from MCP" }
}
}'
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "agent_send",
Arguments: map[string]any{
"agent_id": "example-agent",
"message": "hello",
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Tool: agent_send")
fmt.Printf("Result: %+v\n", result)
```
```python
result = await session.call_tool("agent_send", {
"agent_id": "example-agent",
"message": "hello from MCP",
})
print(f"Tool: agent_send")
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```typescript
const result = await client.callTool({
name: "agent_send",
arguments: {
agent_id: "example-agent",
message: "hello from MCP",
},
});
console.log(JSON.stringify(result, null, 2));
```
```java
var result = client.callTool(new CallToolRequest(
"agent_send",
Map.of(
"agent_id", "example-agent",
"message", "hello from MCP"
)
));
System.out.println(result);
```
```csharp
var result = await client.CallToolAsync("agent_send", new Dictionary
{
["agent_id"] = "example-agent",
["message"] = "hello",
});
Console.WriteLine($"Tool: agent_send");
Console.WriteLine($"Result: {result}");
```
```kotlin
val result = client.callTool("agent_send", mapOf(
"agent_id" to "example-agent",
"message" to "hello"
))
println("Tool: agent_send")
println("Result: $result")
```
```ruby
result = client.call_tool("agent_send", {
"agent_id" => "example-agent",
"message" => "hello from MCP",
})
puts "Tool: agent_send"
puts "Result: #{result}"
```
```rust
let result = client.call_tool("agent_send", json!({
"agent_id": "example-agent",
"message": "hello from MCP"
})).await?;
println!("Tool: agent_send");
println!("Result: {result:#?}");
```
```swift
let result = try await client.callTool("agent_send", arguments: [
"agent_id": "example-agent",
"message": "hello",
])
print("Tool: agent_send")
print("Result: \(result)")
```
The agent's reply is returned in the `content` text. If the agent is not registered,
the call returns `isError: true`:
```json
{
"jsonrpc": "2.0",
"id": 15,
"result": {
"content": [{ "type": "text", "text": "{\"echo\":{\"method\":\"message/send\",\"params\":{\"message\":\"hello from MCP\"}},\"received_headers\":{}}" }],
"isError": false
}
}
```
## agent\_query [#agent_query]
Forwards an arbitrary JSON-RPC `method` to an agent — useful for A2A methods beyond
`message/send`, such as `tasks/get`. Pass a `params` object to supply method
arguments.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 16,
"method": "tools/call",
"params": {
"name": "agent_query",
"arguments": { "agent_id": "example-agent", "method": "tasks/get" }
}
}'
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "agent_query",
Arguments: map[string]any{
"agent_id": "example-agent",
"method": "tasks/get",
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Tool: agent_query")
fmt.Printf("Result: %+v\n", result)
```
```python
result = await session.call_tool("agent_query", {
"agent_id": "example-agent",
"method": "tasks/get",
})
print(f"Tool: agent_query")
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```typescript
const result = await client.callTool({
name: "agent_query",
arguments: {
agent_id: "example-agent",
method: "tasks/get",
},
});
console.log(JSON.stringify(result, null, 2));
```
```java
var result = client.callTool(new CallToolRequest(
"agent_query",
Map.of(
"agent_id", "example-agent",
"method", "tasks/get"
)
));
System.out.println(result);
```
```csharp
var result = await client.CallToolAsync("agent_query", new Dictionary
{
["agent_id"] = "example-agent",
["method"] = "tasks/get",
});
Console.WriteLine($"Tool: agent_query");
Console.WriteLine($"Result: {result}");
```
```kotlin
val result = client.callTool("agent_query", mapOf(
"agent_id" to "example-agent",
"method" to "tasks/get"
))
println("Tool: agent_query")
println("Result: $result")
```
```ruby
result = client.call_tool("agent_query", {
"agent_id" => "example-agent",
"method" => "tasks/get",
})
puts "Tool: agent_query"
puts "Result: #{result}"
```
```rust
let result = client.call_tool("agent_query", json!({
"agent_id": "example-agent",
"method": "tasks/get"
})).await?;
println!("Tool: agent_query");
println!("Result: {result:#?}");
```
```swift
let result = try await client.callTool("agent_query", arguments: [
"agent_id": "example-agent",
"method": "tasks/get",
])
print("Tool: agent_query")
print("Result: \(result)")
```
```json
{
"jsonrpc": "2.0",
"id": 16,
"result": {
"content": [{ "type": "text", "text": "{\"echo\":{\"method\":\"tasks/get\",\"params\":{}},\"received_headers\":{}}" }],
"isError": false
}
}
```
## Errors [#errors]
A missing or unknown `agent_id` returns a tool-level error — `isError: true` with the
message in the `content` block — not a JSON-RPC protocol error:
```json
{
"jsonrpc": "2.0",
"id": 15,
"result": {
"content": [{ "type": "text", "text": "Agent 'example-agent' not found" }],
"isError": true
}
}
```
The bridge applies the gateway timeout buffer on top of the caller's
`timeout_seconds` (default `60`, max `300`). See
[Error handling](/aiway/mcp/guides/error-handling) for the three failure
layers and [Error codes](/aiway/mcp/reference/error-codes) for the catalog.
## Related [#related]
# Channel Management Tools (/aiway/mcp/tools/channel-management)
The channel-management tools let an AI model **discover what messaging surfaces exist**
on a KubeMQ server before it sends, publishes, or queries anything. `channel_list`
enumerates channels (optionally filtered), and `channel_info` returns live metadata for
one channel.
## Overview [#overview]
Most MCP tools act on a channel you already know — `queue_send` needs a queue name,
`events_publish` needs an events channel. The two **read-only** channel-management tools
close that gap: they let the model explore the broker's namespace and confirm a channel's
type and activity before acting on it.
| Tool | Purpose | Required arguments |
| -------------- | ---------------------------------------------------------- | ------------------ |
| `channel_list` | List channels, optionally filtered by type or name pattern | *(none)* |
| `channel_info` | Return metadata for one specific channel | `channel`, `type` |
A **channel type** is one of `queues`, `events`, `events_store`, `commands`, or
`queries` — the five KubeMQ messaging patterns. Both tools accept the type to scope the
lookup. Reserved channels (those under the `_AGENTS_.` prefix used by the agent bridge)
are internal and are not addressable through these tools.
Both tools are **read-only discovery operations** — they never create, delete, or modify
a channel. Channels in KubeMQ are created implicitly on first use, so `channel_list`
reflects channels that already carry traffic.
## channel\_list [#channel_list]
List all channels on the server, or narrow the result by channel `type`, by a name
`pattern`, or both. With no arguments it returns every known channel.
### Input schema [#input-schema]
```json
{
"type": "object",
"required": [],
"properties": {
"type": {
"type": "string",
"description": "Filter by channel type (queues, events, events_store, commands, queries)."
},
"pattern": {
"type": "string",
"description": "Filter by channel name pattern or prefix."
}
}
}
```
| Argument | Type | Required | Default | Description |
| --------- | ------ | -------- | ------- | --------------------------------------------------------------------------------- |
| `type` | string | no | — | Filter by channel type: `queues`, `events`, `events_store`, `commands`, `queries` |
| `pattern` | string | no | — | Filter by channel name pattern or prefix |
### Output [#output]
The tool result wraps a JSON **array** of channel summaries in the standard MCP
`content[]`/`isError` envelope. Each element carries the channel `name`, `type`, and
`is_active` flag.
```json
{
"jsonrpc": "2.0",
"id": 11,
"result": {
"content": [
{
"type": "text",
"text": "[{\"name\":\"example-queue\",\"type\":\"queues\",\"is_active\":true},{\"name\":\"example-events\",\"type\":\"events\",\"is_active\":true}]"
}
],
"isError": false
}
}
```
An empty list (`[]`) is a normal successful result, not an error.
### Usage [#usage]
```bash
# List all channels (no filter)
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'MCP-Protocol-Version: 2025-11-25' \
-d '{
"jsonrpc": "2.0",
"id": 11,
"method": "tools/call",
"params": {
"name": "channel_list",
"arguments": {}
}
}'
# Filter by type
# "arguments": { "type": "queues" }
# Filter by name pattern
# "arguments": { "pattern": "example-" }
```
```go
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "channel_list",
Arguments: map[string]any{},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
```
```python
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# List all channels (no filter)
result = await session.call_tool("channel_list", {})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
# To filter by type, use: {"type": "queues"}
# To filter by pattern, use: {"pattern": "example-"}
```
```typescript
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
// List all channels (no filter)
const result = await client.callTool({
name: "channel_list",
arguments: {},
});
console.log(JSON.stringify(result, null, 2));
// To filter by type: { type: "queues" }
// To filter by pattern: { pattern: "example-" }
await client.close();
```
```java
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
// List all channels (no filter)
var result = client.callTool(new CallToolRequest(
"channel_list",
Map.of()
));
System.out.println(result);
// To filter by type: Map.of("type", "queues")
// To filter by pattern: Map.of("pattern", "example-")
client.closeGracefully();
```
```csharp
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("channel_list", new Dictionary());
Console.WriteLine($"Result: {result}");
```
```kotlin
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("channel_list", emptyMap())
println("Result: $result")
client.close()
httpClient.close()
```
```ruby
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("channel_list", {})
puts "Result: #{result}"
client.close
```
```rust
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("channel_list", json!({})).await?;
println!("Result: {result:#?}");
```
```swift
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("channel_list", arguments: [:])
print("Result: \(result)")
```
## channel\_info [#channel_info]
Return metadata for a single channel. Both `channel` (the name) and `type` are required —
the type scopes the lookup to the right messaging pattern.
### Input schema [#input-schema-1]
```json
{
"type": "object",
"required": ["channel", "type"],
"properties": {
"channel": {
"type": "string",
"description": "Channel name to get information for."
},
"type": {
"type": "string",
"description": "Channel type (queues, events, events_store, commands, queries)."
}
}
}
```
| Argument | Type | Required | Default | Description |
| --------- | ------ | -------- | ------- | ----------------------------------------------------------------------- |
| `channel` | string | yes | — | Channel name to inspect |
| `type` | string | yes | — | Channel type: `queues`, `events`, `events_store`, `commands`, `queries` |
### Output [#output-1]
The result wraps a single JSON **object** describing the channel. Alongside `name`,
`type`, and `is_active`, queue-style channels report live `incoming`/`outgoing` message
counts.
```json
{
"jsonrpc": "2.0",
"id": 12,
"result": {
"content": [
{
"type": "text",
"text": "{\"name\":\"example-queue\",\"type\":\"queues\",\"is_active\":true,\"incoming\":5,\"outgoing\":3}"
}
],
"isError": false
}
}
```
Requesting a channel that does not exist returns a tool error (`isError: true`) rather
than a transport-level failure.
### Usage [#usage-1]
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'MCP-Protocol-Version: 2025-11-25' \
-d '{
"jsonrpc": "2.0",
"id": 12,
"method": "tools/call",
"params": {
"name": "channel_info",
"arguments": {
"channel": "example-queue",
"type": "queues"
}
}
}'
```
```go
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "channel_info",
Arguments: map[string]any{
"channel": "example-queue",
"type": "queues",
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
```
```python
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool("channel_info", {
"channel": "example-queue",
"type": "queues",
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```typescript
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
const result = await client.callTool({
name: "channel_info",
arguments: {
channel: "example-queue",
type: "queues",
},
});
console.log(JSON.stringify(result, null, 2));
await client.close();
```
```java
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
var result = client.callTool(new CallToolRequest(
"channel_info",
Map.of(
"channel", "example-queue",
"type", "queues"
)
));
System.out.println(result);
client.closeGracefully();
```
```csharp
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("channel_info", new Dictionary
{
["channel"] = "example-queue",
["type"] = "queues",
});
Console.WriteLine($"Result: {result}");
```
```kotlin
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("channel_info", mapOf(
"channel" to "example-queue",
"type" to "queues"
))
println("Result: $result")
client.close()
httpClient.close()
```
```ruby
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("channel_info", {
"channel" => "example-queue",
"type" => "queues",
})
puts "Result: #{result}"
client.close
```
```rust
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("channel_info", json!({
"channel": "example-queue",
"type": "queues"
})).await?;
println!("Result: {result:#?}");
```
```swift
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("channel_info", arguments: [
"channel": "example-queue",
"type": "queues",
])
print("Result: \(result)")
```
## Error handling [#error-handling]
| Condition | Result |
| ---------------------------------------- | ------------------------------------------ |
| Invalid or malformed arguments | JSON-RPC `-32602` Invalid Params |
| `channel_info` on a non-existent channel | Tool error — `isError: true` in the result |
| `channel_list` with no matches | Successful result with an empty array `[]` |
`channel_list` has no tool-specific failures: an empty list is a normal, successful
response. For the full JSON-RPC error catalog, see
[Error codes](/aiway/mcp/reference/error-codes).
## Related [#related]
# Command & Query Tools (/aiway/mcp/tools/commands-queries)
The `command_send` and `query_send` tools let an MCP client make **synchronous
request/reply** calls into KubeMQ. A command triggers an action and waits for an
acknowledgement; a query asks for data and waits for a response payload.
## Overview [#overview]
Both tools are part of the [11 core messaging tools](/aiway/mcp/tools) —
they are always available at `/mcp`, no agent registry required. Each maps to one
KubeMQ Request/Reply operation:
* **`command_send`** — sends a command to a channel and blocks until a responder
acknowledges it (success or error). Use it for *mutating* actions where you only
need to know whether the work was accepted.
* **`query_send`** — sends a query to a channel and blocks until a responder returns
a payload. Use it for *read* operations that produce data the model needs back.
Both are synchronous: the connector holds the `tools/call` open until the responder
replies or the timeout elapses. They require an **active subscriber** on the target
channel — with no responder, the call times out and returns an error result.
## How it works [#how-it-works]
The connector translates the tool call into a native KubeMQ command or query, routes
it to a responder over the [Array](/connectors), waits for the reply, and hands
the result back inside the `tools/call` response.
*Both tools hold the `tools/call` open for the round trip; a query returns data, a command returns an acknowledgement.*
## Input schema [#input-schema]
Both tools share the same core arguments. The only difference is the default timeout.
| Argument | Type | Required | Default | Description |
| ----------------- | ------- | -------- | ----------------------------- | ------------------------------------------------------------------ |
| `channel` | string | yes | — | Target channel. Cannot start with the reserved `_AGENTS_.` prefix. |
| `body` | string | yes | — | Request payload sent to the responder. |
| `metadata` | string | no | — | Optional metadata string carried alongside the body. |
| `tags` | object | no | — | Optional string key/value tags attached to the request. |
| `timeout_seconds` | integer | no | `10` (command) · `30` (query) | Seconds to wait for a reply. Maximum **300**. |
`timeout_seconds` is capped at **300** for both tools. The connector also adds a
small gateway buffer on top of the caller-specified timeout. See
[Configuration](/aiway/mcp/configuration) for `ToolTimeoutSeconds`.
## Output schema [#output-schema]
Both tools return the standard `tools/call` result with a `content` array of `text`
blocks. `command_send` returns an acknowledgement string; `query_send` returns the
responder's payload (often JSON) as text.
A successful command:
```json
{
"jsonrpc": "2.0",
"id": 9,
"result": {
"content": [{ "type": "text", "text": "Command executed successfully on channel 'example-commands'" }],
"isError": false
}
}
```
A successful query:
```json
{
"jsonrpc": "2.0",
"id": 10,
"result": {
"content": [{ "type": "text", "text": "{\"data\":\"query response payload from subscriber\"}" }],
"isError": false
}
}
```
When no responder is listening, the call returns `isError: true` with a timeout
message — the JSON-RPC envelope itself still succeeds:
```json
{
"jsonrpc": "2.0",
"id": 9,
"result": {
"content": [{ "type": "text", "text": "Command timed out: no subscriber on channel 'example-commands' within 10s" }],
"isError": true
}
}
```
A timeout is reported through `isError`, not as a JSON-RPC error. See
[Error handling](/aiway/mcp/guides/error-handling) for the three failure
layers.
## command\_send [#command_send]
Send a command and wait for an acknowledgement.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 9,
"method": "tools/call",
"params": {
"name": "command_send",
"arguments": {
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10,
"metadata": "cmd-meta",
"tags": { "action": "process" }
}
}
}'
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "command_send",
Arguments: map[string]any{
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10,
"metadata": "cmd-meta",
"tags": map[string]any{"action": "process"},
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Tool: command_send")
fmt.Printf("Result: %+v\n", result)
```
```python
result = await session.call_tool("command_send", {
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10,
"metadata": "cmd-meta",
"tags": {"action": "process"},
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```typescript
const result = await client.callTool({
name: "command_send",
arguments: {
channel: "example-commands",
body: "do-work",
timeout_seconds: 10,
metadata: "cmd-meta",
tags: { action: "process" },
},
});
console.log(JSON.stringify(result, null, 2));
```
```java
var result = client.callTool(new CallToolRequest(
"command_send",
Map.of(
"channel", "example-commands",
"body", "do-work",
"timeout_seconds", 10,
"metadata", "cmd-meta",
"tags", Map.of("action", "process")
)
));
System.out.println(result);
```
```csharp
var result = await client.CallToolAsync("command_send", new Dictionary
{
["channel"] = "example-commands",
["body"] = "do-work",
["timeout_seconds"] = 10,
["metadata"] = "cmd-meta",
["tags"] = new Dictionary { ["action"] = "process" },
});
Console.WriteLine($"Result: {result}");
```
```kotlin
val result = client.callTool("command_send", mapOf(
"channel" to "example-commands",
"body" to "do-work",
"timeout_seconds" to 10
))
println("Result: $result")
```
```ruby
result = client.call_tool("command_send", {
"channel" => "example-commands",
"body" => "do-work",
"timeout_seconds" => 10,
})
puts "Result: #{result}"
```
```rust
let result = client.call_tool("command_send", json!({
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10,
"metadata": "cmd-meta",
"tags": {"action": "process"}
})).await?;
println!("Result: {result:#?}");
```
```swift
let result = try await client.callTool("command_send", arguments: [
"channel": "example-commands",
"body": "do-work",
"timeout_seconds": 10,
])
print("Result: \(result)")
```
## query\_send [#query_send]
Send a query and wait for a response payload.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 10,
"method": "tools/call",
"params": {
"name": "query_send",
"arguments": {
"channel": "example-queries",
"body": "get-data",
"timeout_seconds": 30,
"metadata": "qry-meta",
"tags": { "action": "lookup" }
}
}
}'
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "query_send",
Arguments: map[string]any{
"channel": "example-queries",
"body": "get-data",
"timeout_seconds": 30,
"metadata": "qry-meta",
"tags": map[string]any{"action": "lookup"},
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Tool: query_send")
fmt.Printf("Result: %+v\n", result)
```
```python
result = await session.call_tool("query_send", {
"channel": "example-queries",
"body": "get-data",
"timeout_seconds": 30,
"metadata": "qry-meta",
"tags": {"action": "lookup"},
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```typescript
const result = await client.callTool({
name: "query_send",
arguments: {
channel: "example-queries",
body: "get-data",
timeout_seconds: 30,
metadata: "qry-meta",
tags: { action: "lookup" },
},
});
console.log(JSON.stringify(result, null, 2));
```
```java
var result = client.callTool(new CallToolRequest(
"query_send",
Map.of(
"channel", "example-queries",
"body", "get-data",
"timeout_seconds", 30,
"metadata", "qry-meta",
"tags", Map.of("action", "lookup")
)
));
System.out.println(result);
```
```csharp
var result = await client.CallToolAsync("query_send", new Dictionary
{
["channel"] = "example-queries",
["body"] = "get-data",
["timeout_seconds"] = 30,
["metadata"] = "qry-meta",
["tags"] = new Dictionary { ["action"] = "lookup" },
});
Console.WriteLine($"Result: {result}");
```
```kotlin
val result = client.callTool("query_send", mapOf(
"channel" to "example-queries",
"body" to "get-data",
"timeout_seconds" to 30
))
println("Result: $result")
```
```ruby
result = client.call_tool("query_send", {
"channel" => "example-queries",
"body" => "get-data",
"timeout_seconds" => 30,
})
puts "Result: #{result}"
```
```rust
let result = client.call_tool("query_send", json!({
"channel": "example-queries",
"body": "get-data",
"timeout_seconds": 30,
"metadata": "qry-meta",
"tags": {"action": "lookup"}
})).await?;
println!("Result: {result:#?}");
```
```swift
let result = try await client.callTool("query_send", arguments: [
"channel": "example-queries",
"body": "get-data",
"timeout_seconds": 30,
])
print("Result: \(result)")
```
The snippets above assume an initialized MCP session (`client` / `session`). For the
full connect-and-initialize handshake in each language, see
[Client setup](/aiway/mcp/guides/client-setup).
## Related [#related]
# Events Tools (/aiway/mcp/tools/events)
The events tools let an AI model publish events to KubeMQ and read them back from the
events store, all over the Model Context Protocol. They cover both the **fire-and-forget**
pub/sub pattern and the **persistent, replayable** events store.
## Overview [#overview]
The MCP connector exposes four events tools, split across two delivery models:
* **`events_publish`** — fire-and-forget pub/sub. The event is delivered to whatever
subscribers are live at that instant and is **not stored**; if no one is listening,
it is lost.
* **`events_store_publish`** — persistent publish. The event is appended to the events
store with a sequence number and can be re-read later.
* **`events_store_read`** — read stored events starting from a sequence number or a
timestamp.
* **`events_store_read_latest`** — return the most recent N stored events.
Use `events_publish` for live notifications where missed messages are acceptable, and
the events-store tools when a model needs durable history it can replay — for example,
reading recent events to build context before acting.
## How it works [#how-it-works]
Every tool is a `tools/call` JSON-RPC request. The connector translates the call into
a native KubeMQ events or events-store operation over the [Array](/connectors),
then returns the result in the standard `content[]` envelope.
*Ephemeral events fan out to live subscribers; events-store events are appended with a sequence number and read back on demand.*
## events\_publish [#events_publish]
Publish a fire-and-forget event to an events channel. The call returns as soon as the
event is accepted — there is no stored copy and no per-subscriber acknowledgement.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "events_publish",
"arguments": {
"channel": "example-events",
"body": "Event data",
"metadata": "event-meta",
"tags": {"source": "mcp-example"}
}
}
}'
```
```csharp
using ModelContextProtocol.Client;
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("events_publish", new Dictionary
{
["channel"] = "example-events",
["body"] = "Event data",
["metadata"] = "event-meta",
["tags"] = new Dictionary { ["source"] = "mcp-example" },
});
Console.WriteLine($"Result: {result}");
```
```go
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "events_publish",
Arguments: map[string]any{
"channel": "example-events",
"body": "Event data",
"metadata": "event-meta",
"tags": map[string]any{"source": "mcp-example"},
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
```
```java
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
var result = client.callTool(new CallToolRequest(
"events_publish",
Map.of(
"channel", "example-events",
"body", "Event data",
"metadata", "event-meta",
"tags", Map.of("source", "mcp-example")
)
));
System.out.println(result);
client.closeGracefully();
```
```kotlin
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("events_publish", mapOf(
"channel" to "example-events",
"body" to "Event data"
))
println("Result: $result")
client.close()
httpClient.close()
```
```python
import asyncio
import os
from mcp.client.streamable_http import streamable_http_client
from mcp import ClientSession
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
async def main():
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool("events_publish", {
"channel": "example-events",
"body": "Event data",
"metadata": "event-meta",
"tags": {"source": "mcp-example"},
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
if __name__ == "__main__":
asyncio.run(main())
```
```ruby
require "mcp"
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("events_publish", {
"channel" => "example-events",
"body" => "Event data",
})
puts "Result: #{result}"
client.close
```
```rust
use rmcp::transport::streamable_http::StreamableHttpClientTransport;
use rmcp::service::RunService;
use serde_json::json;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("events_publish", json!({
"channel": "example-events",
"body": "Event data",
"metadata": "event-meta",
"tags": {"source": "mcp-example"}
})).await?;
println!("Result: {result:#?}");
Ok(())
}
```
```swift
import Foundation
import MCP
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("events_publish", arguments: [
"channel": "example-events",
"body": "Event data",
])
print("Result: \(result)")
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
const result = await client.callTool({
name: "events_publish",
arguments: {
channel: "example-events",
body: "Event data",
metadata: "event-meta",
tags: { source: "mcp-example" },
},
});
console.log(JSON.stringify(result, null, 2));
await client.close();
```
A successful publish returns a confirmation message in the standard envelope:
```json
{
"jsonrpc": "2.0",
"id": 5,
"result": {
"content": [{ "type": "text", "text": "Event published successfully to channel 'example-events'" }],
"isError": false
}
}
```
## events\_store\_publish [#events_store_publish]
Publish a **persistent** event. The event is appended to the events store, assigned a
sequence number, and remains available for re-reading by later `events_store_read` and
`events_store_read_latest` calls.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 6,
"method": "tools/call",
"params": {
"name": "events_store_publish",
"arguments": {
"channel": "example-events-store",
"body": "Stored event data",
"metadata": "store-meta",
"tags": {"source": "mcp-example"}
}
}
}'
```
```csharp
var result = await client.CallToolAsync("events_store_publish", new Dictionary
{
["channel"] = "example-events-store",
["body"] = "Stored event data",
["metadata"] = "store-meta",
["tags"] = new Dictionary { ["source"] = "mcp-example" },
});
Console.WriteLine($"Result: {result}");
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "events_store_publish",
Arguments: map[string]any{
"channel": "example-events-store",
"body": "Stored event data",
"metadata": "store-meta",
"tags": map[string]any{"source": "mcp-example"},
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
```
```java
var result = client.callTool(new CallToolRequest(
"events_store_publish",
Map.of(
"channel", "example-events-store",
"body", "Stored event data",
"metadata", "store-meta",
"tags", Map.of("source", "mcp-example")
)
));
System.out.println(result);
```
```kotlin
val result = client.callTool("events_store_publish", mapOf(
"channel" to "example-events-store",
"body" to "Stored event"
))
println("Result: $result")
```
```python
result = await session.call_tool("events_store_publish", {
"channel": "example-events-store",
"body": "Stored event data",
"metadata": "store-meta",
"tags": {"source": "mcp-example"},
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```ruby
result = client.call_tool("events_store_publish", {
"channel" => "example-events-store",
"body" => "Stored event",
})
puts "Result: #{result}"
```
```rust
let result = client.call_tool("events_store_publish", json!({
"channel": "example-events-store",
"body": "Stored event data",
"metadata": "store-meta",
"tags": {"source": "mcp-example"}
})).await?;
println!("Result: {result:#?}");
```
```swift
let result = try await client.callTool("events_store_publish", arguments: [
"channel": "example-events-store",
"body": "Stored event",
])
print("Result: \(result)")
```
```typescript
const result = await client.callTool({
name: "events_store_publish",
arguments: {
channel: "example-events-store",
body: "Stored event data",
metadata: "store-meta",
tags: { source: "mcp-example" },
},
});
console.log(JSON.stringify(result, null, 2));
```
```json
{
"jsonrpc": "2.0",
"id": 6,
"result": {
"content": [{ "type": "text", "text": "Event published successfully to events store channel 'example-events-store'" }],
"isError": false
}
}
```
## events\_store\_read [#events_store_read]
Read stored events starting from a position. Provide `from_sequence` to start at a
sequence number, or `from_time` to start at an RFC 3339 timestamp, and cap the result
with `max_messages`.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "events_store_read",
"arguments": {
"channel": "example-events-store",
"from_sequence": 1,
"max_messages": 10
}
}
}'
```
```csharp
var result = await client.CallToolAsync("events_store_read", new Dictionary
{
["channel"] = "example-events-store",
["from_sequence"] = 1,
["max_messages"] = 10,
});
Console.WriteLine($"Result: {result}");
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "events_store_read",
Arguments: map[string]any{
"channel": "example-events-store",
"from_sequence": 1,
"max_messages": 10,
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
```
```java
var result = client.callTool(new CallToolRequest(
"events_store_read",
Map.of(
"channel", "example-events-store",
"from_sequence", 1,
"max_messages", 10
)
));
System.out.println(result);
```
```kotlin
val result = client.callTool("events_store_read", mapOf(
"channel" to "example-events-store",
"from_sequence" to 1,
"max_messages" to 10
))
println("Result: $result")
```
```python
result = await session.call_tool("events_store_read", {
"channel": "example-events-store",
"from_sequence": 1,
"max_messages": 10,
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```ruby
result = client.call_tool("events_store_read", {
"channel" => "example-events-store",
"from_sequence" => 1,
"max_messages" => 10,
})
puts "Result: #{result}"
```
```rust
let result = client.call_tool("events_store_read", json!({
"channel": "example-events-store",
"from_sequence": 1,
"max_messages": 10
})).await?;
println!("Result: {result:#?}");
```
```swift
let result = try await client.callTool("events_store_read", arguments: [
"channel": "example-events-store",
"from_sequence": 1,
"max_messages": 10,
])
print("Result: \(result)")
```
```typescript
const result = await client.callTool({
name: "events_store_read",
arguments: {
channel: "example-events-store",
from_sequence: 1,
max_messages: 10,
},
});
console.log(JSON.stringify(result, null, 2));
```
The result text is a JSON array of stored events, each carrying its `body`, `metadata`,
`sequence`, and `timestamp`:
```json
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"content": [{ "type": "text", "text": "[{\"body\":\"Stored event data\",\"metadata\":\"store-meta\",\"sequence\":1,\"timestamp\":\"2026-04-06T12:00:00Z\"}]" }],
"isError": false
}
}
```
## events\_store\_read\_latest [#events_store_read_latest]
Return the most recent events from the store. Set `count` to choose how many to read
back, newest first.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 8,
"method": "tools/call",
"params": {
"name": "events_store_read_latest",
"arguments": {
"channel": "example-events-store",
"count": 3
}
}
}'
```
```csharp
var result = await client.CallToolAsync("events_store_read_latest", new Dictionary
{
["channel"] = "example-events-store",
["count"] = 3,
});
Console.WriteLine($"Result: {result}");
```
```go
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "events_store_read_latest",
Arguments: map[string]any{
"channel": "example-events-store",
"count": 3,
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
```
```java
var result = client.callTool(new CallToolRequest(
"events_store_read_latest",
Map.of(
"channel", "example-events-store",
"count", 3
)
));
System.out.println(result);
```
```kotlin
val result = client.callTool("events_store_read_latest", mapOf(
"channel" to "example-events-store",
"count" to 3
))
println("Result: $result")
```
```python
result = await session.call_tool("events_store_read_latest", {
"channel": "example-events-store",
"count": 3,
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
```
```ruby
result = client.call_tool("events_store_read_latest", {
"channel" => "example-events-store",
"count" => 3,
})
puts "Result: #{result}"
```
```rust
let result = client.call_tool("events_store_read_latest", json!({
"channel": "example-events-store",
"count": 3
})).await?;
println!("Result: {result:#?}");
```
```swift
let result = try await client.callTool("events_store_read_latest", arguments: [
"channel": "example-events-store",
"count": 3,
])
print("Result: \(result)")
```
```typescript
const result = await client.callTool({
name: "events_store_read_latest",
arguments: {
channel: "example-events-store",
count: 3,
},
});
console.log(JSON.stringify(result, null, 2));
```
```json
{
"jsonrpc": "2.0",
"id": 8,
"result": {
"content": [{ "type": "text", "text": "[{\"body\":\"Stored event 3\",\"sequence\":3},{\"body\":\"Stored event 2\",\"sequence\":2},{\"body\":\"Stored event 1\",\"sequence\":1}]" }],
"isError": false
}
}
```
## Parameters [#parameters]
### events\_publish [#events_publish-1]
| Argument | Type | Required | Default | Description |
| ---------- | ------ | -------- | ------- | ----------------------------------------------- |
| `channel` | string | yes | — | Events channel to publish to. |
| `body` | string | yes | — | Event payload. |
| `metadata` | string | no | — | Optional metadata string attached to the event. |
| `tags` | object | no | — | Optional key/value string tags. |
### events\_store\_publish [#events_store_publish-1]
| Argument | Type | Required | Default | Description |
| ---------- | ------ | -------- | ------- | ----------------------------------------------- |
| `channel` | string | yes | — | Events store channel to append to. |
| `body` | string | yes | — | Event payload. |
| `metadata` | string | no | — | Optional metadata string attached to the event. |
| `tags` | object | no | — | Optional key/value string tags. |
### events\_store\_read [#events_store_read-1]
| Argument | Type | Required | Default | Description |
| --------------- | ------ | -------- | ------- | ----------------------------------------- |
| `channel` | string | yes | — | Events store channel to read from. |
| `max_messages` | number | yes | — | Maximum number of events to return. |
| `from_sequence` | number | no | — | Start reading at this sequence number. |
| `from_time` | string | no | — | Start reading at this RFC 3339 timestamp. |
### events\_store\_read\_latest [#events_store_read_latest-1]
| Argument | Type | Required | Default | Description |
| --------- | ------ | -------- | ------- | --------------------------------------------------- |
| `channel` | string | yes | — | Events store channel to read from. |
| `count` | number | no | `10` | Number of most-recent events to return (max `100`). |
Channel names beginning with the reserved `_AGENTS_.` prefix are rejected — see
[Channel resolution](/aiway/mcp/guides/channel-resolution).
## Response [#response]
Publish tools return a single text confirmation in the `content[]` envelope. Read tools
return a text block whose `text` is a JSON array of stored events. A failed call sets
`isError: true` and carries the message in the same block — see
[Error handling](/aiway/mcp/guides/error-handling) for the three failure
layers.
## Related [#related]
# Tools Overview (/aiway/mcp/tools)
KubeMQ exposes its messaging operations to AI models as **MCP tools**. A client
discovers them with `tools/list` and invokes them with `tools/call` — there is no
KubeMQ-specific client library involved, just the Model Context Protocol.
## Overview [#overview]
The MCP connector publishes **15 tools** in two families:
* **11 core messaging tools** — always available. They cover queues, events, the
events store, commands/queries, and channel discovery.
* **4 agent-bridge tools** — available only when the [A2A agent registry](/aiway/a2a)
is present. They let an MCP client discover and message registered agents,
bridging MCP to the A2A gateway.
Every tool maps onto a single KubeMQ messaging operation. The model calls the tool
by name with a JSON arguments object; the connector translates it into a native
KubeMQ call over the [Array](/connectors) and returns the result.
## How it works [#how-it-works]
The connector advertises each tool through `tools/list`, then routes each
`tools/call` to the matching KubeMQ operation. Core tools reach the broker
directly; bridge tools forward through the agent registry to an external agent.
*One MCP connector fans out to core messaging tools and, when the registry is present, agent-bridge tools.*
## Core messaging tools [#core-messaging-tools]
These 11 tools are registered unconditionally — start kubemq-server and they are
live at `/mcp`.
| Category | Tools | Page |
| ------------------ | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| Queues | `queue_send`, `queue_receive`, `queue_peek` | [Queue tools](/aiway/mcp/tools/queues) |
| Events | `events_publish`, `events_store_publish`, `events_store_read`, `events_store_read_latest` | [Events tools](/aiway/mcp/tools/events) |
| Commands & Queries | `command_send`, `query_send` | [Command & query tools](/aiway/mcp/tools/commands-queries) |
| Channels | `channel_list`, `channel_info` | [Channel tools](/aiway/mcp/tools/channel-management) |
## Agent-bridge tools [#agent-bridge-tools]
These 4 tools appear in `tools/list` **only when the A2A agent registry is
injected** into the MCP connector. They turn an MCP client into an A2A caller:
`agent_send` builds a `message/send` envelope and forwards it over Query to
`_AGENTS_.agents/`, while `agent_query` forwards an arbitrary JSON-RPC
method to the agent.
| Category | Tools | Page |
| ------------ | ------------------------------------------------------- | --------------------------------------------------- |
| Agent bridge | `agent_list`, `agent_info`, `agent_send`, `agent_query` | [Agent-bridge tools](/aiway/mcp/tools/agent-bridge) |
The bridge connects MCP to the [A2A connector](/aiway/a2a). If A2A is not
running, only the 11 core tools are listed.
## Calling a tool [#calling-a-tool]
Every tool is invoked the same way — a `tools/call` JSON-RPC request naming the
tool and passing its `arguments` object. The skeleton below works for any of the 15
tools; only `name` and `arguments` change.
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "queue_send",
"arguments": {
"channel": "example-queue",
"body": "Hello from MCP"
}
}
}'
```
List the available tools and their input schemas first with `tools/list` — see
[Endpoints](/aiway/mcp/reference/endpoints). The per-tool pages document
each tool's arguments and provide ready-to-run examples in all nine languages.
## Response shape [#response-shape]
`tools/call` always returns a result with a `content` array. Each entry is a typed
block — KubeMQ uses `text` blocks carrying the operation result as a JSON string.
A successful call:
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [{ "type": "text", "text": "Message sent successfully to queue 'example-queue'" }],
"isError": false
}
}
```
A failed call sets `isError: true` and carries the error message in the same
`content` block — the JSON-RPC envelope itself still succeeds:
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [{ "type": "text", "text": "error: channel name uses reserved prefix '_AGENTS_.'" }],
"isError": true
}
}
```
`isError` is **not** a protocol failure. A malformed JSON-RPC request (missing
`name`, bad params) returns a JSON-RPC error instead — see
[Error handling](/aiway/mcp/guides/error-handling) for the three failure
layers and [Error codes](/aiway/mcp/reference/error-codes) for the catalog.
## Related [#related]
# Queue Tools (/aiway/mcp/tools/queues)
The queue tools expose KubeMQ's durable, point-to-point queue messaging as MCP tools, so an AI model can enqueue work, consume it, and inspect a backlog without removing it.
## Overview [#overview]
KubeMQ's [queue messaging](/learn/queues) is a durable, at-least-once, single-consumer channel: a message is held until exactly one consumer receives it. The MCP connector surfaces three queue operations as tools, all invoked through the standard `tools/call` method against the single `POST /mcp` endpoint on the [shared HTTP server](/connectors/concepts/shared-http-server) (port `9090`). Channels are created automatically on first use.
| Tool | Operation | Idempotent |
| --------------- | ------------------------------------------------------------- | ---------- |
| `queue_send` | Enqueue a message for durable, single-consumer delivery | No |
| `queue_receive` | Receive and consume messages (destructive read) | No |
| `queue_peek` | Inspect messages without removing them (non-destructive read) | Yes |
The MCP connector is **enabled by default** — start kubemq-server and `/mcp` is live. To disable it, set `CONNECTORSMCP_ENABLE=false`. See [Configuration](/aiway/mcp/configuration) for details.
## How it works [#how-it-works]
A `tools/call` request flows through the MCP connector, which translates the tool arguments into a native KubeMQ queue operation against the broker.
*An AI model sends and receives queue messages through the MCP connector, which bridges to the KubeMQ broker.*
A `channel` that starts with the reserved prefix `_AGENTS_.` is rejected with a `-32602` Invalid Params error. See [Channel resolution](/aiway/mcp/guides/channel-resolution).
## queue\_send [#queue_send]
> Send a message to a KubeMQ queue channel. Use for reliable, persistent messaging with at-least-once delivery. Each call enqueues a new message (not idempotent).
The channel is created automatically if it does not exist. Optional policy fields delay visibility (`delay_seconds`), set a time-to-live (`expiration_seconds`), and route poison messages to a dead-letter queue (`max_receive_count` plus `dead_letter_queue`). Both `channel` and `body` are required — omitting either returns a `-32602` Invalid Params error.
### Input schema [#input-schema]
| Argument | Type | Required | Default | Description |
| -------------------- | ------- | -------- | ------- | ----------------------------------------------------------------------- |
| `channel` | string | Yes | — | Queue channel name. Must not start with the reserved prefix `_AGENTS_.` |
| `body` | string | Yes | — | Message body (string) |
| `metadata` | string | No | `""` | Optional metadata |
| `tags` | object | No | `{}` | Optional key-value tags (string values) |
| `delay_seconds` | integer | No | `0` | Delay delivery by N seconds (`0` = immediately visible) |
| `expiration_seconds` | integer | No | `0` | Message expiry in seconds (`0` = no expiration) |
| `max_receive_count` | integer | No | `0` | Max receive attempts before dead-letter (`0` = unlimited) |
| `dead_letter_queue` | string | No | `""` | Dead-letter queue channel name |
### Usage [#usage]
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "queue_send",
"arguments": {
"channel": "example-queue",
"body": "Hello from MCP",
"metadata": "example-metadata",
"tags": { "env": "dev", "source": "mcp-example" }
}
}
}'
```
```csharp
using ModelContextProtocol.Client;
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("queue_send", new Dictionary
{
["channel"] = "example-queue",
["body"] = "Hello from C# MCP",
["metadata"] = "example-metadata",
["tags"] = new Dictionary { ["env"] = "dev", ["source"] = "mcp-example" },
});
Console.WriteLine($"Result: {result}");
```
```go
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "queue_send",
Arguments: map[string]any{
"channel": "example-queue",
"body": "Hello from Go MCP",
"metadata": "example-metadata",
"tags": map[string]any{"env": "dev", "source": "mcp-example"},
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
}
```
```java
import io.modelcontextprotocol.sdk.McpClient;
import io.modelcontextprotocol.sdk.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import java.util.Map;
public class QueueSend {
public static void main(String[] args) {
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
var result = client.callTool(new CallToolRequest(
"queue_send",
Map.of(
"channel", "example-queue",
"body", "Hello from Java MCP",
"metadata", "example-metadata",
"tags", Map.of("env", "dev", "source", "mcp-example")
)
));
System.out.println(result);
client.closeGracefully();
}
}
```
```kotlin
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport
import io.ktor.client.*
import io.ktor.client.plugins.sse.*
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("queue_send", mapOf(
"channel" to "example-queue",
"body" to "Hello from Kotlin MCP",
"metadata" to "example-metadata",
"tags" to mapOf("env" to "dev", "source" to "mcp-example")
))
println("Result: $result")
client.close()
httpClient.close()
}
```
```python
import asyncio
import os
from mcp.client.streamable_http import streamable_http_client
from mcp import ClientSession
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
async def main():
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool("queue_send", {
"channel": "example-queue",
"body": "Hello from Python MCP",
"metadata": "example-metadata",
"tags": {"env": "dev", "source": "mcp-example"},
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
if __name__ == "__main__":
asyncio.run(main())
```
```ruby
require "mcp"
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("queue_send", {
"channel" => "example-queue",
"body" => "Hello from Ruby MCP",
"metadata" => "example-metadata",
"tags" => { "env" => "dev", "source" => "mcp-example" },
})
puts "Result: #{result}"
client.close
```
```rust
use rmcp::transport::streamable_http::StreamableHttpClientTransport;
use rmcp::service::RunService;
use serde_json::json;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("queue_send", json!({
"channel": "example-queue",
"body": "Hello from Rust MCP",
"metadata": "example-metadata",
"tags": {"env": "dev", "source": "mcp-example"}
})).await?;
println!("Result: {result:#?}");
Ok(())
}
```
```swift
import Foundation
import MCP
@main
struct QueueSend {
static func main() async throws {
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("queue_send", arguments: [
"channel": "example-queue",
"body": "Hello from Swift MCP",
"metadata": "example-metadata",
"tags": ["env": "dev", "source": "mcp-example"],
])
print("Result: \(result)")
}
}
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
async function main() {
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
const result = await client.callTool({
name: "queue_send",
arguments: {
channel: "example-queue",
body: "Hello from TypeScript MCP",
metadata: "example-metadata",
tags: { env: "dev", source: "mcp-example" },
},
});
console.log(JSON.stringify(result, null, 2));
await client.close();
}
main().catch(console.error);
```
### Response [#response]
The tool result wraps a JSON string in the standard MCP `content[]` / `isError` envelope. The text payload reports the enqueue result:
```json
{
"content": [
{
"type": "text",
"text": "{\"message_id\":\"a1b2c3...\",\"sent_at\":\"2026-06-08T10:00:00Z\",\"is_error\":false}"
}
],
"isError": false
}
```
## queue\_receive [#queue_receive]
> Receive messages from a KubeMQ queue channel. Messages are auto-acknowledged on receipt (destructive read). Not idempotent — failed processing requires re-enqueue.
This is a destructive read: returned messages are removed from the queue, so each message is delivered to exactly one consumer. Set `max_messages` to drain a batch (clamped to the `1–100` range), and `wait_timeout_seconds` to long-poll for messages that have not yet arrived. Receiving from a non-existent channel is not an error — it returns an empty `messages` array. Because the read is not idempotent, do not blindly retry: a retry may consume *additional* messages rather than re-fetch the same ones.
### Input schema [#input-schema-1]
| Argument | Type | Required | Default | Description |
| ---------------------- | ------- | -------- | ------- | -------------------------------------------- |
| `channel` | string | Yes | — | Queue channel name |
| `max_messages` | integer | Yes | `1` | Max messages to receive (clamped to `1–100`) |
| `wait_timeout_seconds` | integer | No | `5` | Long-poll wait timeout in seconds (`1–60`) |
### Usage [#usage-1]
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "queue_receive",
"arguments": {
"channel": "example-queue",
"max_messages": 5
}
}
}'
```
```csharp
using ModelContextProtocol.Client;
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("queue_receive", new Dictionary
{
["channel"] = "example-queue",
["max_messages"] = 5,
});
Console.WriteLine($"Result: {result}");
```
```go
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "queue_receive",
Arguments: map[string]any{
"channel": "example-queue",
"max_messages": 5,
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
}
```
```java
import io.modelcontextprotocol.sdk.McpClient;
import io.modelcontextprotocol.sdk.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import java.util.Map;
public class QueueReceive {
public static void main(String[] args) {
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
var result = client.callTool(new CallToolRequest(
"queue_receive",
Map.of(
"channel", "example-queue",
"max_messages", 5
)
));
System.out.println(result);
client.closeGracefully();
}
}
```
```kotlin
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport
import io.ktor.client.*
import io.ktor.client.plugins.sse.*
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("queue_receive", mapOf(
"channel" to "example-queue",
"max_messages" to 5
))
println("Result: $result")
client.close()
httpClient.close()
}
```
```python
import asyncio
import os
from mcp.client.streamable_http import streamable_http_client
from mcp import ClientSession
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
async def main():
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool("queue_receive", {
"channel": "example-queue",
"max_messages": 5,
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
if __name__ == "__main__":
asyncio.run(main())
```
```ruby
require "mcp"
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("queue_receive", {
"channel" => "example-queue",
"max_messages" => 5,
})
puts "Result: #{result}"
client.close
```
```rust
use rmcp::transport::streamable_http::StreamableHttpClientTransport;
use rmcp::service::RunService;
use serde_json::json;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("queue_receive", json!({
"channel": "example-queue",
"max_messages": 5
})).await?;
println!("Result: {result:#?}");
Ok(())
}
```
```swift
import Foundation
import MCP
@main
struct QueueReceive {
static func main() async throws {
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("queue_receive", arguments: [
"channel": "example-queue",
"max_messages": 5,
])
print("Result: \(result)")
}
}
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
async function main() {
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
const result = await client.callTool({
name: "queue_receive",
arguments: {
channel: "example-queue",
max_messages: 5,
},
});
console.log(JSON.stringify(result, null, 2));
await client.close();
}
main().catch(console.error);
```
### Response [#response-1]
The text payload is a JSON object holding the received messages and a count. Each message carries its `id`, `channel`, `body`, `metadata`, and (when present) `timestamp`, `sequence`, and `tags`:
```json
{
"content": [
{
"type": "text",
"text": "{\"messages\":[{\"id\":\"...\",\"channel\":\"example-queue\",\"body\":\"Hello from MCP\",\"metadata\":\"example-metadata\",\"tags\":{\"env\":\"dev\",\"source\":\"mcp-example\"}}],\"messages_count\":1,\"is_error\":false}"
}
],
"isError": false
}
```
## queue\_peek [#queue_peek]
> Peek at messages in a KubeMQ queue without removing them. Idempotent — does not modify queue state.
Peek is a non-destructive, idempotent read: inspected messages remain in the queue and can still be consumed later by `queue_receive`. Use it for monitoring, debugging, or letting an agent reason about pending work before deciding to consume it. Set `max_messages` to control how many messages to inspect (clamped to `1–100`). As with receive, peeking a non-existent channel returns an empty result rather than an error.
### Input schema [#input-schema-2]
| Argument | Type | Required | Default | Description |
| -------------- | ------- | -------- | ------- | ----------------------------------------- |
| `channel` | string | Yes | — | Queue channel name |
| `max_messages` | integer | Yes | `1` | Max messages to peek (clamped to `1–100`) |
### Usage [#usage-2]
```bash
curl -X POST http://localhost:9090/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "queue_peek",
"arguments": {
"channel": "example-queue",
"max_messages": 5
}
}
}'
```
```csharp
using ModelContextProtocol.Client;
var url = Environment.GetEnvironmentVariable("KUBEMQ_MCP_URL") ?? "http://localhost:9090";
var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri($"{url}/mcp") });
await using var client = await McpClientFactory.CreateAsync(transport);
var result = await client.CallToolAsync("queue_peek", new Dictionary
{
["channel"] = "example-queue",
["max_messages"] = 5,
});
Console.WriteLine($"Result: {result}");
```
```go
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/mcp"
)
func main() {
url := os.Getenv("KUBEMQ_MCP_URL")
if url == "" {
url = "http://localhost:9090"
}
c, err := client.NewStreamableHttpClient(url + "/mcp")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx := context.Background()
if err := c.Start(ctx); err != nil {
log.Fatal(err)
}
result, err := c.CallTool(ctx, mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: "queue_peek",
Arguments: map[string]any{
"channel": "example-queue",
"max_messages": 5,
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Result: %+v\n", result)
}
```
```java
import io.modelcontextprotocol.sdk.McpClient;
import io.modelcontextprotocol.sdk.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import java.util.Map;
public class QueuePeek {
public static void main(String[] args) {
String url = System.getenv().getOrDefault("KUBEMQ_MCP_URL", "http://localhost:9090");
var transport = HttpClientStreamableHttpTransport.builder(url).endpoint("/mcp").build();
var client = McpClient.sync(transport).build();
client.initialize();
var result = client.callTool(new CallToolRequest(
"queue_peek",
Map.of(
"channel", "example-queue",
"max_messages", 5
)
));
System.out.println(result);
client.closeGracefully();
}
}
```
```kotlin
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.client.Client
import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport
import io.ktor.client.*
import io.ktor.client.plugins.sse.*
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val url = System.getenv("KUBEMQ_MCP_URL") ?: "http://localhost:9090"
val httpClient = HttpClient { install(SSE) }
val transport = StreamableHttpClientTransport(client = httpClient, url = "$url/mcp")
val client = Client(clientInfo = Implementation(name = "kubemq-mcp-kotlin-example", version = "1.0.0"))
client.connect(transport)
val result = client.callTool("queue_peek", mapOf(
"channel" to "example-queue",
"max_messages" to 5
))
println("Result: $result")
client.close()
httpClient.close()
}
```
```python
import asyncio
import os
from mcp.client.streamable_http import streamable_http_client
from mcp import ClientSession
KUBEMQ_MCP_URL = os.environ.get("KUBEMQ_MCP_URL", "http://localhost:9090")
async def main():
async with streamable_http_client(f"{KUBEMQ_MCP_URL}/mcp") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool("queue_peek", {
"channel": "example-queue",
"max_messages": 5,
})
print(f"IsError: {result.isError}")
for content in result.content:
print(f"Result: {content.text}")
if __name__ == "__main__":
asyncio.run(main())
```
```ruby
require "mcp"
url = ENV.fetch("KUBEMQ_MCP_URL", "http://localhost:9090")
client = MCP::Client.new(
transport: MCP::Transport::StreamableHTTP.new("#{url}/mcp"),
name: "kubemq-mcp-ruby-example",
version: "1.0.0"
)
client.initialize_handshake
result = client.call_tool("queue_peek", {
"channel" => "example-queue",
"max_messages" => 5,
})
puts "Result: #{result}"
client.close
```
```rust
use rmcp::transport::streamable_http::StreamableHttpClientTransport;
use rmcp::service::RunService;
use serde_json::json;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::var("KUBEMQ_MCP_URL")
.unwrap_or_else(|_| "http://localhost:9090".to_string());
let transport = StreamableHttpClientTransport::from_uri(format!("{url}/mcp"))?;
let client = ().serve(transport).await?;
let result = client.call_tool("queue_peek", json!({
"channel": "example-queue",
"max_messages": 5
})).await?;
println!("Result: {result:#?}");
Ok(())
}
```
```swift
import Foundation
import MCP
@main
struct QueuePeek {
static func main() async throws {
let url = ProcessInfo.processInfo.environment["KUBEMQ_MCP_URL"] ?? "http://localhost:9090"
let transport = HTTPClientTransport(endpoint: URL(string: "\(url)/mcp")!, streaming: true)
let client = Client(name: "kubemq-mcp-swift-example", version: "1.0.0")
try await client.connect(transport: transport)
let result = try await client.callTool("queue_peek", arguments: [
"channel": "example-queue",
"max_messages": 5,
])
print("Result: \(result)")
}
}
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const KUBEMQ_MCP_URL = process.env.KUBEMQ_MCP_URL || "http://localhost:9090";
async function main() {
const transport = new StreamableHTTPClientTransport(
new URL(`${KUBEMQ_MCP_URL}/mcp`)
);
const client = new Client({ name: "kubemq-mcp-ts-example", version: "1.0.0" });
await client.connect(transport);
const result = await client.callTool({
name: "queue_peek",
arguments: {
channel: "example-queue",
max_messages: 5,
},
});
console.log(JSON.stringify(result, null, 2));
await client.close();
}
main().catch(console.error);
```
### Response [#response-2]
Same envelope as `queue_receive`, but the messages stay in the queue. Peeked messages omit `tags` and report `messages_count`:
```json
{
"content": [
{
"type": "text",
"text": "{\"messages\":[{\"id\":\"...\",\"channel\":\"example-queue\",\"body\":\"Hello from MCP\",\"metadata\":\"example-metadata\"}],\"messages_count\":1}"
}
],
"isError": false
}
```
## Receive vs peek [#receive-vs-peek]
| Behavior | `queue_receive` | `queue_peek` |
| ------------------------------- | ----------------------------------- | --------------------- |
| Removes messages from the queue | Yes | No |
| Idempotent | No | Yes |
| Long-poll wait | `wait_timeout_seconds` (default 5s) | Fixed 1s internally |
| Typical use | Processing work items | Monitoring, debugging |
## Related [#related]
# Addressing (/connectors/amqp/concepts/addressing)
The terminus address is the single most client-load-bearing fact about the KubeMQ AMQP 1.0
connector: it tells the connector **which KubeMQ pattern and channel** a link talks to. This
guide is the practical playbook for the `/` grammar — always use explicit
prefixes — plus channel validation, longest-prefix matching, dynamic and anonymous addresses,
and the absence of vhosts.
For the address validation rules in table form, see
[Address mapping](/connectors/amqp/reference/address-mapping).
## Where the address goes [#where-the-address-goes]
AMQP 1.0 has no exchanges or routing keys. You choose the destination by setting a terminus
address on the link — and *where* it goes depends on the link role:
| You are… | The address goes in… |
| ------------------------------------------ | -------------------------------------------------------- |
| a **receiver** (you consume) | the link **source** address |
| a **sender** to a fixed node (you produce) | the link **target** address |
| an **anonymous sender** | `properties.to` on **each message** (the target is null) |
## The grammar — always use explicit prefixes [#the-grammar--always-use-explicit-prefixes]
```text
address := [ "/" ] pattern "/" channel # leading "/" is optional: queues/x ≡ /queues/x
| bare # no recognized prefix → JMS hint, else DefaultPattern
| "/responses/" RequestID # RPC reply token (reply path only; server-receiver only)
| # source.dynamic / target.dynamic → _amqp10.tmp..
pattern := "queues" | "events" | "events-store" | "commands" | "queries"
```
| Terminus address | KubeMQ pattern | Channel |
| ---------------------------- | -------------------------------------------------------------------------------- | ---------------------- |
| `queues/` | queues | `` |
| `events/` | events | `` |
| `events-store/` | events-store | `` |
| `commands/` | commands | `` |
| `queries/` | queries | `` |
| `responses/` | responses (synthetic; RPC reply path only) | the opaque reply token |
| bare (no prefix, no `/`) | JMS node-capability hint (`queue`→queues, `topic`→events), else `DefaultPattern` | the bare string |
| null target on a sender | anonymous — routed per-message by `properties.to` | (per message) |
| anything else containing `/` | **error** → `DETACH(amqp:not-found, "unknown address prefix")` | — |
The leading slash is optional and stripped: `queues/orders` ≡ `/queues/orders`. The prefix is
**stripped, never prepended** — the resolved channel (`orders`) is what the broker sees, so it
always passes the underlying channel validation.
**Always emit the explicit `/` prefix.** It makes the destination
deterministic and self-documenting: `queues/orders`, `events/telemetry`,
`events-store/audit`, `commands/provision`, `queries/lookup`. Do not rely on bare addressing
in fresh application code (see below).
## Longest-prefix matching [#longest-prefix-matching]
The connector matches prefixes **longest-first**: `events-store/` is tested **before**
`events/`. So `events-store/audit` resolves to the **events-store** pattern with channel
`audit` — it is never mis-read as the **events** pattern with channel `store/audit`. You never
need to escape or disambiguate; just write the full prefix. The full matching order is
`events-store → queues → events → commands → queries → responses`.
## Bare addressing — a Qpid-JMS migration convenience only [#bare-addressing--a-qpid-jms-migration-convenience-only]
A bare address (no recognized prefix and no `/`) is resolved **non-deterministically**:
1. If the terminus carries a JMS **node-capability hint**, it selects the pattern: `queue` →
queues, `topic` → events.
2. Otherwise the connector's configured **`DefaultPattern`** applies (default `queues`).
This exists so a **migrating Qpid-JMS / ActiveMQ app** can point at KubeMQ by changing only the
connection string and the destination name — a JMS `Queue("orders")` carries the `queue`
capability and lands on `queues/orders` without an explicit prefix.
Bare addressing is **non-deterministic and config-dependent**: the same bare name resolves
differently depending on the client's capability hint and the broker's `DefaultPattern`. Treat
it as a migration aid, not a design choice. For any fresh code, **use the explicit prefix** so
the destination is unambiguous and survives a `DefaultPattern` change. A bare value that still
contains a `/` is treated as an **unknown prefix**, not a bare channel →
`DETACH(amqp:not-found, "unknown address prefix")`.
## Channel validation — stricter than the native layer [#channel-validation--stricter-than-the-native-layer]
After the prefix is stripped, the connector validates the channel **more strictly than the
underlying KubeMQ array layer**. A channel that works on the gRPC/native side can be rejected
over AMQP. A violation closes the link with `DETACH(amqp:not-found)`:
| Rejected channel | Example |
| ------------------------------ | -------------------------- |
| empty | `queues/` |
| longer than **255** characters | `queues/<256+ chars>` |
| has a **trailing `.`** | `queues/orders.` |
| contains **whitespace** | `queues/my orders` |
| contains `*` or `>` wildcards | `queues/orders.*` |
| contains `;` or `:` | `queues/a:b`, `queues/a;b` |
A channel name that works on the native KubeMQ side can be **rejected over AMQP** because of
the extra `;`, `:`, and trailing-`.` restrictions. Keep AMQP channel names to `[a-zA-Z0-9._-]`,
≤ 255 chars, with no trailing dot, and you are never surprised.
## Dynamic and anonymous addresses [#dynamic-and-anonymous-addresses]
These are special address forms the connector mints or routes specially.
### Dynamic nodes (`source.dynamic` / `target.dynamic`) [#dynamic-nodes-sourcedynamic--targetdynamic]
Attach a receiver with **`DynamicAddress: true`** (a dynamic source) and the connector creates a
fresh node and echoes its address in the reply `ATTACH`: `_amqp10.tmp..`. This is
the mechanism for an **RPC reply node** — a requester opens a dynamic receiver, reads back its
echoed address, and stamps it as `reply-to`. See
[Commands](/connectors/amqp/concepts/commands).
Dynamic nodes are **node-local**: a temp node created on node A is not reachable from node B.
RPC *replies* are still cluster-safe (they travel the broker reply path), but a direct
cross-node send to a dynamic address is not.
### Anonymous terminus (null target sender) [#anonymous-terminus-null-target-sender]
A sender opened with a **null target** (`NewSender("", nil)`) is an *anonymous* sender: it has no
fixed destination, and each message selects its destination via **`properties.to`** (which itself
uses the `/` grammar). Because there is no fixed channel at attach,
authorization is deferred to a **per-message Write check** on each message's `to` (see
[Authentication](/connectors/amqp/how-to/authentication)). A bad `to` →
`amqp:precondition-failed`; a missing `to` → a Send error.
The connector advertises **no `ANONYMOUS-RELAY` capability** — anonymous-terminus routing works
by the connector inspecting `properties.to`, not by a capability handshake. Clients whose
anonymous-producer API depends on `ANONYMOUS-RELAY` negotiation (notably **Qpid JMS**) cannot
emit the single null-target link the connector routes on, so they cannot drive the anonymous
terminus — use explicit per-pattern senders there instead.
### `/responses/` reply tokens [#responses-reply-tokens]
`/responses/` is a synthetic RPC reply address. It is **valid only as a
server-receiver attach** (the reply path); a **receiver** attach on `/responses/` →
`DETACH(amqp:not-allowed)`. You do not construct these yourself in normal use — the RPC layer
manages them, and they are connection-scoped (not authorized via Casbin).
## No vhost [#no-vhost]
AMQP 1.0 has **no vhost**. The `OPEN` `hostname` field (which a client carrying over a 0-9-1
mental model might set) is **logged then ignored**. There is no vhost option to expose and no
namespace scoping by hostname.
## Reaching AMQP 0-9-1 data [#reaching-amqp-0-9-1-data]
The AMQP 1.0 and AMQP 0-9-1 connectors **do not share a namespace**. AMQP 0-9-1 queues live on
KubeMQ channels named `amqp..`. To reach the same data from an AMQP 1.0 client,
use the explicit queues prefix over that channel name:
```text
/queues/amqp..
```
Cross-protocol equivalence holds the other way too: an AMQP 1.0 `queues/` maps to the bare
KubeMQ channel ``, so a gRPC/native client producing to `` interoperates with an AMQP
1.0 consumer of `queues/`.
## Quick reference [#quick-reference]
| Destination | Address to use |
| ---------------------------- | --------------------------------------------------------------------- |
| Queue `orders` | `queues/orders` |
| Event stream `telemetry` | `events/telemetry` |
| Durable event stream `audit` | `events-store/audit` |
| Command channel `provision` | `commands/provision` |
| Query channel `lookup` | `queries/lookup` |
| RPC reply node | dynamic receiver (`DynamicAddress: true`); never a hand-built address |
| Route per-message | anonymous sender + `properties.to = "queues/"` etc. |
| AMQP 0-9-1 queue | `/queues/amqp..` |
| Fresh app code | **always the explicit prefix** — never rely on bare addressing |
## Related [#related]
# Architecture (/connectors/amqp/concepts/architecture)
The KubeMQ **AMQP 1.0 connector** is an embedded, wire-protocol bridge inside
kubemq-server. It speaks the AMQP 1.0 dialect on plain port **5672** (TCP / SASL) and TLS
port **5671**. The connector is **opt-in (disabled by default)** — enable it with
`CONNECTORS_AMQP10_ENABLE=true` (Docker) or `spec.amqp10.enabled: true` (Kubernetes). The
ports themselves are already bound on a stock server by the RabbitMQ (AMQP 0-9-1)
connector, which is on by default; enabling AMQP 1.0 adds its dialect to that listener. Any
standard AMQP 1.0 client connects to it with only a connection-string change — no code
rewrite, no library swap, no KubeMQ SDK.
Unlike the RabbitMQ (AMQP 0-9-1) connector — which bridges onto exactly one KubeMQ
primitive (the Queue) — the AMQP 1.0 connector bridges onto **all five** KubeMQ patterns:
Queues, Events, Events-Store, Commands, and Queries. The leading segment of the node
address selects which pattern a link is bound to. That single fact drives the whole mental
model.
AMQP 1.0 is a peer-to-peer link protocol — there are **no exchanges, no bindings, no
routing keys, and no publisher-confirms** here. Those are AMQP 0-9-1 concepts. In AMQP 1.0
a *link* is attached to a *node* (an address), message flow is governed by *credit*, and
delivery is resolved by *delivery state* (accepted / released / modified / rejected). If
you are migrating from 0-9-1 or ActiveMQ, see
[Migrating from ActiveMQ](/connectors/how-to/migration/from-activemq).
## How AMQP 1.0 maps to KubeMQ [#how-amqp-10-maps-to-kubemq]
The connector binds a link to a KubeMQ pattern by the **leading segment of the node
address**. The grammar is `[/]/` — the prefix selects the pattern and
the remainder is the KubeMQ channel.
*The address prefix selects the KubeMQ pattern; `events-store/` is matched before `events/` so it never collides.*
| Address prefix | KubeMQ pattern | Produce (client sender → target) | Consume (client receiver ← source) |
| ------------------- | ------------------ | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------- |
| `queues/` | **Queues** | at-least-once enqueue; the server dispositions `accepted` per send | credit-driven destructive consume; `accept` / `release` / `modify` / `reject` |
| `events/` | **Events** | pre-settled fan-out (at-most-once) | standing-credit fan-out; **0-credit → silent drop** |
| `events-store/` | **Events-Store** | persisted append | durable replay/resume; start positions via `x-opt-kubemq-start` |
| `commands/` | **Commands (RPC)** | request + dynamic reply node; reply carries `x-opt-kubemq-executed` / `-error` | responder consumes, replies to `/responses/` |
| `queries/` | **Queries (RPC)** | request + dynamic reply node; reply = body + metadata only | responder consumes, replies to `/responses/` |
Resolution rules:
* **Longest-prefix wins.** `events-store/` is matched before `events/`, so
`events-store/orders` never collides with the `events/` arm. The matching order is
`events-store → queues → events → commands → queries → responses`.
* **Leading slash is optional.** At most one leading `/` is stripped before matching, so
`queues/orders` and `/queues/orders` resolve identically.
* **Bare addresses** (no recognized prefix) resolve by a JMS node-capability hint
(`queue` → `queues`, `topic` → `events`) or fall back to the configured `DefaultPattern`
(`queues` by default). Best practice is to always emit the explicit prefix.
* **`/responses/`** is the write-only RPC reply path. A receiver attach on it is
refused with `amqp:not-allowed`.
* **Channel charset** is stricter than the array layer: non-empty, ≤255 chars, no trailing
`.`, no whitespace, no `*` `>` `;` `:`. A violation returns `amqp:not-found`.
See [Address mapping](/connectors/amqp/reference/address-mapping) for the master table
and [Addressing](/connectors/amqp/concepts/addressing) for narrative guidance.
## The shared front door: `amqpmux` [#the-shared-front-door-amqpmux]
KubeMQ ships two embedded AMQP dialects — 0-9-1 (RabbitMQ) and 1.0 — and they **share the
same listeners**. A single mux per `(port, tlsPort)` group accepts every connection, reads
the **8-byte AMQP protocol header**, and dispatches the raw connection to the engine that
speaks the matching dialect. The mux never speaks AMQP itself; once it classifies a
connection it hands the connection plus the consumed header to the engine, which resumes
the protocol exactly where the header left off.
*The mux classifies each connection by its 8-byte protocol header and routes it to the matching dialect engine.*
The 8-byte header is `"AMQP"` followed by a 4-byte `(protocol-id, major, minor, revision)`
tuple. The mux recognizes:
| Header bytes | Meaning | Listener | Dispatched to |
| ---------------------- | --------------------- | -------- | ---------------------------------- |
| `AMQP\x00\x00\x09\x01` | AMQP 0-9-1 | any | 0-9-1 engine |
| `AMQP\x00\x01\x00\x00` | AMQP 1.0 (bare) | any | 1.0 engine |
| `AMQP\x03\x01\x00\x00` | AMQP 1.0 (SASL layer) | any | 1.0 engine |
| `AMQP\x02\x01\x00\x00` | AMQP 1.0 (TLS token) | TLS only | 1.0 engine (after TLS termination) |
Key consequences:
* **Plain port `5672` and TLS port `5671` are shared with the AMQP 0-9-1 connector.**
Setting `CONNECTORS_AMQP10_PORT` equal to the 0-9-1 port is intentionally accepted — the
mux dedupes the bind, so the two dialects coexist on one listener.
* **Version negotiation:** if a client presents an AMQP 1.0-family header but no live 1.0
engine is available, the mux writes back the 0-9-1 header and closes (and vice-versa).
This is what an AMQP 1.0 client sees against a stock server: the TCP connect succeeds
(0-9-1 is on by default), then the connection is closed during negotiation. A
client that cannot even send a header gets nothing back — the connection is closed
silently.
* **The connector advertises no negotiated capabilities** (see
[What the server advertises](#what-the-server-advertises)).
## Connection → Session → Link [#connection--session--link]
AMQP 1.0 is a three-level container model. The connector implements the **server side** of
each finite-state machine, so the peer roles invert relative to your client: a client
**sender** is a server **receiver** (you produce to a `target`), and a client **receiver**
is a server **sender** (you consume from a `source`).
| Level | Client performative | Connector behavior |
| -------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Connection** | `OPEN` | `container-id` is required and non-empty (empty → `amqp:invalid-field`), sanitized to `[a-zA-Z0-9_-]`, capped at 256 chars. It becomes the ClientID when there is no SASL identity and is **half the durable-subscription identity — so it must be stable across reconnects** for durable subscribers. The OPEN `hostname` (vhost) is accepted but **ignored**. |
| **Session** | `BEGIN` | The server advertises `channel-max = min(client, SessionMax-1)` (255 with defaults). A session window violation closes with `amqp:session:window-violation`; an unattached or in-use handle is `amqp:session:errant-link`. |
| **Link** | `ATTACH` | The peer role inverts (sender ↔ receiver). The address resolves to a `(pattern, channel)` pair. Receivers grant credit via `FLOW`; the server never delivers without it. The receive settle mode is `first` (only). |
## What the server advertises [#what-the-server-advertises]
On `OPEN` the connector sends back **only** `container-id` (`"KubeMQ"`), `max-frame-size`,
`channel-max`, and `idle-time-out`. It sets **no offered/desired connection or link
capabilities** — in particular **no `ANONYMOUS-RELAY`** and no `queue`/`topic` node
capabilities. Clients must not depend on capability negotiation.
This is why the **anonymous terminus** (a sender with a null target that routes per-message
by `properties.to`) is driven entirely by the *null target address*, not by an advertised
capability. It is also why Apache Qpid JMS cannot drive the anonymous-terminus path — it
has no API to force a raw null-target link, and there is no capability to trigger its
anonymous-producer path. See [Capabilities](/connectors/amqp/reference/capabilities).
## The metadata envelope and type markers [#the-metadata-envelope-and-type-markers]
KubeMQ messages carry a JSON `Metadata` string. The connector serializes the full AMQP
message context into a single canonical envelope keyed by **`amqp10`**:
```json
{
"amqp10": {
"props": { "...": "original-form AMQP properties (message_id, correlation_id, to, reply_to, subject, content_type, group_id, ttl, ...)" },
"app": { "...": "application-properties, type-preserved" },
"annotations": { "x-opt-...": "message-annotations" },
"delivery_annotations": { "...": "opaque pass-through" },
"footer": { "...": "opaque pass-through" },
"body_section": "data"
}
}
```
* The envelope is **always present** — even `{"amqp10":{}}` for an empty/property-less
message — so every message carries non-empty `Metadata`.
* `body_section` discriminates the body: **`"data"`** (binary `Data` section) or
**`"value"`** (`AmqpValue` section). An `AmqpSequence` body is **rejected** with
`amqp:not-implemented`.
* Treat the envelope as **opaque** from a client's point of view. Set standard AMQP
properties natively (message-id, correlation-id, content-type, ttl, group-id) and let the
connector derive the `amqp10.*` tags; do not hand-build the envelope.
### Type markers [#type-markers]
JSON has no native unsigned, 64-bit, binary, or timestamp types, so the codec wraps AMQP
scalar values that would otherwise lose fidelity using a `$`-prefixed marker. Integers
within ±2^53 are emitted as plain JSON numbers; only out-of-range or type-ambiguous values
are wrapped, and egress restores the exact AMQP type the client sent.
| Marker | AMQP type → JSON form |
| ------------------------------------------------- | --------------------------- |
| `$int64` | int64 beyond ±2^53 → string |
| `$u64` | uint64 → string |
| `$ts` | timestamp → Unix seconds |
| `$bin` | binary → base64 |
| `$uuid` | UUID → RFC-4122 string |
| `$u8` / `$i8` / `$i16` / `$u16` / `$i32` / `$u32` | sized integers |
| `$f32` / `$f64` | 32- / 64-bit floats |
Receiver-set link properties (on the consuming ATTACH, not the message) carry pattern
options: `x-opt-kubemq-group` (consumer group for events / events-store / queues) and
`x-opt-kubemq-start` (the events-store start position, `new-only` by default). Inert
sections are accepted but not acted on: message `priority`, `group-id` ordering, and
`footer` are pass-through only.
## Cross-protocol interop [#cross-protocol-interop]
Because every pattern is backed by a normal KubeMQ channel, a message sent over AMQP 1.0
to `queues/orders` is consumable by a gRPC or REST queue client on the same channel, and
vice-versa. The connector asserts this equivalence: `queues/` over AMQP 1.0 maps to the
bare channel `` over gRPC.
*The same KubeMQ channel backs both connectors, so an AMQP 1.0 client and a gRPC/REST client interoperate transparently.*
The RabbitMQ (AMQP 0-9-1) connector uses a **different** namespace
(`amqp..`), so the two AMQP connectors do **not** share an address space. To
reach 0-9-1 queue data from AMQP 1.0, address it explicitly through the queues pattern:
`queues/amqp..` (a naming convention, not a real vhost — AMQP 1.0 has none).
## Related [#related]
# Commands (/connectors/amqp/concepts/commands)
Commands are **native, in-protocol request/reply** over the AMQP 1.0 connector. Attach a link to a node whose address begins with `commands/` and the connector binds it to the KubeMQ **Commands** pattern. RPC here is **fully native** — there is **no gRPC responder and no KubeMQ SDK**; a responder is just a normal AMQP consumer that publishes a reply.
This page documents the shared RPC mechanics — the dynamic reply node, the anonymous responder, and correlation matching. [Queries](/connectors/amqp/concepts/queries) use the **same** request path and defer to this page; the only differences are the reply shape and the failure contract.
## Overview [#overview]
A requester opens a dynamic reply node, sends a request to `commands/` naming that node as `reply-to`, and matches the reply by `correlation-id`. The connector fires `SendCommand`; the responder consumes `commands/`, does the work, and sends a reply back.
| Step | Who | Action |
| --------------- | --------- | -------------------------------------------------------------------------------------------- |
| Open reply node | Requester | Attach a receiver with `source.dynamic = true`; the server mints `_amqp10.tmp..` |
| Send request | Requester | `TRANSFER` to `commands/` with `reply-to` = the minted node + a `correlation-id` |
| Route | Connector | Verifies reply-to ownership, then `SendCommand` |
| Reply | Responder | Anonymous sender with `properties.to = /responses/` + the echoed `correlation-id` |
| Match | Requester | Correlate the reply to its request by `correlation-id` |
The reply's `correlation-id` is the request's `correlation-id`, or — when the request carried none — its **`message-id`** (the Qpid JMS convention). Set one or the other on every request and match the reply on it.
## How it works [#how-it-works]
*The requester's dynamic reply node receives the responder's reply out-of-band; the requester matches it by `correlation-id`.*
**`reply-to` must name a node this connection owns (snooping guard).** A requester cannot point `reply-to` at an arbitrary or foreign node — that would let it direct a response to another client's node. A **missing** `reply-to` returns `amqp:not-allowed` ("request missing reply-to"); a `reply-to` naming a node **this connection does not own** returns `amqp:not-allowed` ("reply-to is not a node this connection owns"). Always create a dynamic reply node per requester and use its echoed `_amqp10.tmp.*` address.
## Commands vs Queries — the failure contract [#commands-vs-queries--the-failure-contract]
Both patterns share the dynamic-reply path, but their reply shape and failure behavior differ:
| | **Commands** | **Queries** |
| -------------------- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| Reply body | optional | the result **body + metadata** |
| Reply app-properties | `x-opt-kubemq-executed` (bool) **always**; `x-opt-kubemq-error` (string) when non-empty | **none** |
| On success | `executed=true` | body + metadata returned |
| **On failure** | a reply **is** delivered with **`executed=false`** (+ error text) — the requester is never left waiting | **nothing is delivered** — the requester **times out** (\~30 s) |
In short: a **command** always answers (success or `executed=false`); a query answers on success and goes silent on failure. Choose commands when you need a positive failure signal.
## Request and reply [#request-and-reply]
Each example runs a responder and a requester (separate connections, so the snooping guard is honored), sends a successful command (`executed=true`) and a failing one (`executed=false`), and shows that **both** round-trip — neither hangs. Every client reads the broker endpoint from `KUBEMQ_AMQP_URL` (default `amqp://localhost:5672`).
```go
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"sync"
"time"
amqp "github.com/Azure/go-amqp"
)
const channel = "amqp10.examples.commands"
func amqpURL() string {
if v := os.Getenv("KUBEMQ_AMQP_URL"); v != "" {
return v
}
return "amqp://localhost:5672"
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
addr := "commands/" + channel // commands/ prefix → KubeMQ Commands pattern
ready := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); runResponder(ctx, addr, ready) }()
<-ready
runRequester(ctx, addr)
cancel()
wg.Wait()
}
// Responder: consume commands/, reply via an anonymous sender.
func runResponder(ctx context.Context, addr string, ready chan<- struct{}) {
conn, _ := amqp.Dial(ctx, amqpURL(), nil)
defer func() { _ = conn.Close() }()
session, _ := conn.NewSession(ctx, nil)
rcv, _ := session.NewReceiver(ctx, addr, &amqp.ReceiverOptions{Credit: 10})
snd, _ := session.NewSender(ctx, "", nil) // anonymous sender (null target)
close(ready)
for {
req, err := rcv.Receive(ctx, nil)
if err != nil {
if ctx.Err() != nil || errors.Is(err, context.Canceled) {
return
}
return
}
_ = rcv.AcceptMessage(context.Background(), req)
if req.Properties == nil || req.Properties.ReplyTo == nil {
continue
}
body := string(req.GetData())
// A command body of "fail" is rejected (executed=false); both paths reply.
ok := body != "fail"
errText := ""
if !ok {
errText = "command rejected by handler"
}
replyTo := *req.Properties.ReplyTo
reply := amqp.NewMessage([]byte("ack:" + body))
reply.Properties = &amqp.MessageProperties{To: &replyTo}
if req.Properties.CorrelationID != nil {
reply.Properties.CorrelationID = req.Properties.CorrelationID
} else {
reply.Properties.CorrelationID = req.Properties.MessageID
}
// A COMMAND reply carries the execution outcome as application-properties.
reply.ApplicationProperties = map[string]any{
"x-opt-kubemq-executed": ok,
"x-opt-kubemq-error": errText,
}
_ = snd.Send(ctx, reply, nil)
}
}
// Requester: dynamic reply node + sender on commands/; correlate replies.
func runRequester(ctx context.Context, addr string) {
conn, _ := amqp.Dial(ctx, amqpURL(), nil)
defer func() { _ = conn.Close() }()
session, _ := conn.NewSession(ctx, nil)
// DYNAMIC reply node: empty source + DynamicAddress:true → server echoes its address.
replyRcv, _ := session.NewReceiver(ctx, "", &amqp.ReceiverOptions{DynamicAddress: true, Credit: 5})
replyNode := replyRcv.Address()
snd, _ := session.NewSender(ctx, addr, nil)
doRequest(ctx, snd, replyRcv, replyNode, "reboot-node-7", "corr-cmd-1") // executed=true
doRequest(ctx, snd, replyRcv, replyNode, "fail", "corr-cmd-2") // executed=false
}
func doRequest(ctx context.Context, snd *amqp.Sender, replyRcv *amqp.Receiver, replyNode, body, corr string) {
req := amqp.NewMessage([]byte(body))
req.Properties = &amqp.MessageProperties{
ReplyTo: &replyNode, // MUST name a node this connection owns (snooping guard)
CorrelationID: corr,
}
if err := snd.Send(ctx, req, nil); err != nil {
log.Fatalf("send command: %v", err)
}
// A command ALWAYS replies (success or failure), so this never times out.
reply, err := replyRcv.Receive(ctx, nil)
if err != nil {
log.Fatalf("await reply: %v", err)
}
_ = replyRcv.AcceptMessage(context.Background(), reply)
executed, _ := reply.ApplicationProperties["x-opt-kubemq-executed"].(bool)
errText, _ := reply.ApplicationProperties["x-opt-kubemq-error"].(string)
fmt.Printf("reply for %q: executed=%v error=%q\n", body, executed, errText)
}
```
```python
import os
import threading
from proton import Message
from proton.utils import BlockingConnection
CHANNEL = "amqp10.examples.commands"
EXECUTED_PROP = "x-opt-kubemq-executed"
ERROR_PROP = "x-opt-kubemq-error"
def amqp_url() -> str:
return os.environ.get("KUBEMQ_AMQP_URL", "amqp://localhost:5672")
def run_responder(addr: str, ready: threading.Event, stop: threading.Event) -> None:
conn = BlockingConnection(amqp_url())
try:
rcv = conn.create_receiver(addr, credit=10)
snd = conn.create_sender(None) # anonymous reply sender (null target)
ready.set()
while not stop.is_set():
try:
req = rcv.receive(timeout=1.0)
except Exception:
continue
rcv.accept()
if not req.reply_to:
continue
body = str(req.body)
# A command body of "fail" is rejected (executed=false); both paths reply.
ok = body != "fail"
err_text = "" if ok else "command rejected by handler"
reply = Message(body="ack:" + body)
reply.address = req.reply_to
reply.correlation_id = req.correlation_id if req.correlation_id else req.id
# A COMMAND reply carries the execution outcome as application-properties.
reply.properties = {EXECUTED_PROP: ok, ERROR_PROP: err_text}
snd.send(reply)
finally:
conn.close()
def do_request(snd, reply_rcv, reply_node: str, body: str, corr: str) -> None:
req = Message(body=body)
req.reply_to = reply_node # MUST name a node this connection owns (snooping guard)
req.correlation_id = corr
snd.send(req)
# A command ALWAYS replies (success or failure), so this never times out.
reply = reply_rcv.receive(timeout=30.0)
reply_rcv.accept()
props = reply.properties or {}
print(f"reply for {body!r}: executed={bool(props.get(EXECUTED_PROP))} error={str(props.get(ERROR_PROP, ''))!r}")
def run_requester(addr: str) -> None:
conn = BlockingConnection(amqp_url())
try:
# DYNAMIC reply node: dynamic=True → server echoes its address.
reply_rcv = conn.create_receiver(None, dynamic=True, credit=5)
reply_node = reply_rcv.link.remote_source.address
snd = conn.create_sender(addr)
do_request(snd, reply_rcv, reply_node, "reboot-node-7", "corr-cmd-1") # executed=true
do_request(snd, reply_rcv, reply_node, "fail", "corr-cmd-2") # executed=false
finally:
conn.close()
def main() -> None:
addr = "commands/" + CHANNEL # commands/ prefix → KubeMQ Commands pattern
ready, stop = threading.Event(), threading.Event()
responder = threading.Thread(target=run_responder, args=(addr, ready, stop), daemon=True)
responder.start()
ready.wait(timeout=30.0)
try:
run_requester(addr)
finally:
stop.set()
responder.join(timeout=10.0)
if __name__ == "__main__":
main()
```
```java
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import javax.jms.TextMessage;
import org.apache.qpid.jms.JmsConnectionFactory;
public final class Main {
private static final String CHANNEL = "amqp10.examples.commands";
private static final String PROP_EXECUTED = "x-opt-kubemq-executed";
private static final String PROP_ERROR = "x-opt-kubemq-error";
public static void main(String[] args) throws Exception {
String url = System.getenv().getOrDefault("KUBEMQ_AMQP_URL", "amqp://localhost:5672");
String address = "commands/" + CHANNEL; // commands/ prefix → KubeMQ Commands
// jms.validatePropertyNames=false lets us set/read the hyphenated
// x-opt-kubemq-executed / -error application-properties.
JmsConnectionFactory factory = new JmsConnectionFactory(url);
factory.setValidatePropertyNames(false);
Thread responder = new Thread(() -> runResponder(factory, address), "responder");
responder.setDaemon(true);
responder.start();
Thread.sleep(1_000); // let the responder attach before sending
runRequester(factory, address);
}
// Responder: consume commands/, reply to each request's JMSReplyTo.
private static void runResponder(JmsConnectionFactory factory, String address) {
try (Connection connection = factory.createConnection()) {
connection.start();
try (Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) {
Queue commands = session.createQueue(address);
try (MessageConsumer consumer = session.createConsumer(commands);
MessageProducer replyProducer = session.createProducer(null)) { // unidentified
while (true) {
Message req = consumer.receive(1_000);
if (req == null) continue;
Destination replyTo = req.getJMSReplyTo();
if (replyTo == null) continue;
String body = (req instanceof TextMessage) ? ((TextMessage) req).getText() : "";
boolean ok = !"fail".equals(body);
String errText = ok ? "" : "command rejected by handler";
TextMessage reply = session.createTextMessage("ack:" + body);
reply.setJMSCorrelationID(req.getJMSCorrelationID());
reply.setBooleanProperty(PROP_EXECUTED, ok);
reply.setStringProperty(PROP_ERROR, errText);
replyProducer.send(replyTo, reply);
}
}
}
} catch (Exception e) {
// connection torn down on shutdown
}
}
// Requester: a JMS temporary queue is the dynamic reply node.
private static void runRequester(JmsConnectionFactory factory, String address) throws Exception {
try (Connection connection = factory.createConnection()) {
connection.start();
try (Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) {
TemporaryQueue replyNode = session.createTemporaryQueue();
Queue commands = session.createQueue(address);
try (MessageConsumer replyConsumer = session.createConsumer(replyNode);
MessageProducer producer = session.createProducer(commands)) {
doRequest(session, producer, replyConsumer, replyNode, "reboot-node-7", "corr-cmd-1");
doRequest(session, producer, replyConsumer, replyNode, "fail", "corr-cmd-2");
}
}
}
}
private static void doRequest(Session session, MessageProducer producer, MessageConsumer replyConsumer,
TemporaryQueue replyNode, String body, String corr) throws Exception {
TextMessage req = session.createTextMessage(body);
req.setJMSReplyTo(replyNode); // MUST name a node this connection owns (snooping guard)
req.setJMSCorrelationID(corr);
producer.send(req);
Message reply = replyConsumer.receive(30_000); // a command always replies
if (reply == null) throw new IllegalStateException("timed out awaiting reply");
System.out.printf("reply for \"%s\": executed=%b error=\"%s\"%n",
body, reply.getBooleanProperty(PROP_EXECUTED), reply.getStringProperty(PROP_ERROR));
}
}
```
```csharp
using System.Text;
using Amqp;
using Amqp.Framing;
const string channel = "amqp10.examples.commands";
static string AmqpUrl() =>
Environment.GetEnvironmentVariable("KUBEMQ_AMQP_URL") is { Length: > 0 } v
? v
: "amqp://localhost:5672";
var addr = "commands/" + channel; // commands/ prefix → KubeMQ Commands pattern
using var responderDone = new CancellationTokenSource();
var responderReady = new TaskCompletionSource();
var responderTask = Task.Run(() => RunResponder(addr, responderReady, responderDone.Token));
await responderReady.Task.WaitAsync(TimeSpan.FromSeconds(20));
await RunRequester(addr);
responderDone.Cancel();
await responderTask;
// Responder: consume commands/, reply via an anonymous sender.
static void RunResponder(string addr, TaskCompletionSource ready, CancellationToken stop)
{
var connection = Connection.Factory.CreateAsync(new Address(AmqpUrl())).GetAwaiter().GetResult();
try
{
var session = new Session(connection);
var receiver = new ReceiverLink(session, "command-responder", addr);
receiver.SetCredit(10, autoRestore: true);
var anonAttach = new Attach { Source = new Source(), Target = null }; // anonymous sender
var sender = new SenderLink(session, "command-reply-sender", anonAttach, null);
ready.TrySetResult();
while (!stop.IsCancellationRequested)
{
var req = receiver.Receive(TimeSpan.FromSeconds(1));
if (req is null) continue;
receiver.Accept(req);
if (req.Properties?.ReplyTo is not { Length: > 0 } replyTo) continue;
var body = BodyString(req);
var ok = body != "fail";
var errText = ok ? "" : "command rejected by handler";
var reply = new Message { BodySection = new Data { Binary = Encoding.UTF8.GetBytes("ack:" + body) } };
reply.Properties = new Properties { To = replyTo };
var corr = req.Properties.GetCorrelationId() ?? req.Properties.GetMessageId();
if (corr is not null) reply.Properties.SetCorrelationId(corr);
// A COMMAND reply carries the execution outcome as application-properties.
reply.ApplicationProperties = new ApplicationProperties();
reply.ApplicationProperties.Map["x-opt-kubemq-executed"] = ok;
reply.ApplicationProperties.Map["x-opt-kubemq-error"] = errText;
sender.Send(reply, TimeSpan.FromSeconds(10));
}
}
catch (Exception ex) when (stop.IsCancellationRequested) { _ = ex; }
finally { try { connection.CloseAsync().Wait(2000); } catch (AmqpException) { } }
}
// Requester: dynamic reply node + sender on commands/; correlate replies.
static async Task RunRequester(string addr)
{
var connection = await Connection.Factory.CreateAsync(new Address(AmqpUrl()));
try
{
var session = new Session(connection);
// DYNAMIC reply node: Source.Dynamic = true; the server echoes the address
// via the OnAttached callback.
string? replyNode = null;
using var attached = new SemaphoreSlim(0, 1);
var dynAttach = new Attach { Source = new Source { Dynamic = true }, Target = new Target() };
var replyRcv = new ReceiverLink(session, "command-reply-node", dynAttach, (link, attach) =>
{
if (attach.Source is Source s) replyNode = s.Address;
attached.Release();
});
replyRcv.SetCredit(5, autoRestore: true);
await attached.WaitAsync(TimeSpan.FromSeconds(10));
var sender = new SenderLink(session, "command-requester", addr);
DoRequest(sender, replyRcv, replyNode!, "reboot-node-7", "corr-cmd-1"); // executed=true
DoRequest(sender, replyRcv, replyNode!, "fail", "corr-cmd-2"); // executed=false
await sender.CloseAsync();
await replyRcv.CloseAsync();
await session.CloseAsync();
}
finally { await connection.CloseAsync(); }
}
static void DoRequest(SenderLink sender, ReceiverLink replyRcv, string replyNode, string body, string corr)
{
var req = new Message { BodySection = new Data { Binary = Encoding.UTF8.GetBytes(body) } };
req.Properties = new Properties { ReplyTo = replyNode }; // snooping guard: must own this node
req.Properties.SetCorrelationId(corr);
sender.Send(req, TimeSpan.FromSeconds(15));
var reply = replyRcv.Receive(TimeSpan.FromSeconds(30)) // a command always replies
?? throw new InvalidOperationException("await reply: timed out");
replyRcv.Accept(reply);
var executed = reply.ApplicationProperties?.Map["x-opt-kubemq-executed"] as bool? ?? false;
var errText = reply.ApplicationProperties?.Map["x-opt-kubemq-error"] as string ?? "";
Console.WriteLine($"reply for \"{body}\": executed={executed} error=\"{errText}\"");
}
static string BodyString(Message message) => message.BodySection switch
{
Data d => Encoding.UTF8.GetString(d.Binary),
AmqpValue { Value: byte[] bytes } => Encoding.UTF8.GetString(bytes),
AmqpValue { Value: string str } => str,
AmqpValue v => v.Value?.ToString() ?? string.Empty,
_ => string.Empty,
};
```
```typescript
import {
Connection,
ReceiverEvents,
type AwaitableSender,
type ConnectionOptions,
type EventContext,
type Receiver,
} from "rhea-promise";
const channel = "amqp10.examples.commands";
function connectionOptions(suffix: string): ConnectionOptions {
const url = new URL(process.env["KUBEMQ_AMQP_URL"] ?? "amqp://localhost:5672");
return {
host: url.hostname,
port: url.port ? Number(url.port) : 5672,
container_id: `kubemq-amqp10-js-commands-${suffix}-${process.pid}`,
reconnect: false,
};
}
function bodyToString(body: unknown): string {
if (Buffer.isBuffer(body)) return body.toString("utf8");
if (typeof body === "string") return body;
return "";
}
// Responder: consume commands/, reply via an anonymous sender.
async function startResponder(address: string): Promise<{ stop: () => Promise }> {
const connection = new Connection(connectionOptions("responder"));
await connection.open();
const receiver = await connection.createReceiver({
source: { address }, credit_window: 0, autoaccept: false, autosettle: false,
});
const replySender = await connection.createAwaitableSender({ target: {} }); // null target
receiver.on(ReceiverEvents.message, (ctx: EventContext) => {
void onRequest(replySender, ctx).catch((err) => console.error(err));
});
receiver.addCredit(10);
return {
stop: async () => {
await replySender.close();
await receiver.close();
await connection.close();
},
};
}
async function onRequest(replySender: AwaitableSender, ctx: EventContext): Promise {
const req = ctx.message;
ctx.delivery?.accept();
if (!req || req.reply_to === undefined || req.reply_to === null) return;
const body = bodyToString(req.body);
const ok = body !== "fail";
const errText = ok ? "" : "command rejected by handler";
await replySender.send(
{
body: `ack:${body}`,
to: req.reply_to,
correlation_id: req.correlation_id ?? req.message_id,
// A COMMAND reply carries the execution outcome as application-properties.
application_properties: { "x-opt-kubemq-executed": ok, "x-opt-kubemq-error": errText },
},
{ timeoutInSeconds: 10 },
);
}
// Requester: dynamic reply node + sender on commands/; correlate replies.
async function runRequester(address: string): Promise {
const connection = new Connection(connectionOptions("requester"));
await connection.open();
try {
const replyReceiver = await connection.createReceiver({
source: { address: "", dynamic: true }, // server names the node
credit_window: 0, autoaccept: false, autosettle: false,
});
replyReceiver.addCredit(5);
const replyNode = replyReceiver.address || replyReceiver.source.address;
const sender = await connection.createAwaitableSender({ target: { address } });
await doRequest(sender, replyReceiver, replyNode!, "reboot-node-7", "corr-cmd-1"); // executed=true
await doRequest(sender, replyReceiver, replyNode!, "fail", "corr-cmd-2"); // executed=false
await sender.close();
await replyReceiver.close();
} finally {
await connection.close();
}
}
async function doRequest(
sender: AwaitableSender, replyReceiver: Receiver, replyNode: string, body: string, corr: string,
): Promise {
const replyPromise = awaitReply(replyReceiver, 30_000); // arm before sending
await sender.send(
{ body, reply_to: replyNode, correlation_id: corr }, // snooping guard: must own replyNode
{ timeoutInSeconds: 15 },
);
const reply = await replyPromise; // a command always replies
const props = (reply.application_properties ?? {}) as Record;
const executed = props["x-opt-kubemq-executed"] === true;
const errText = typeof props["x-opt-kubemq-error"] === "string" ? props["x-opt-kubemq-error"] : "";
console.log(`reply for "${body}": executed=${executed} error="${errText}"`);
}
interface ReplyMessage {
application_properties?: Record;
}
function awaitReply(replyReceiver: Receiver, timeoutMs: number): Promise {
return new Promise