PubSub
In microservice architectures, an event-driven approach is common, and zero has built-in support for message-queue systems.
Sometimes our app must react to signals from external services. These arrive as API calls or as events, and they tell us what state the data or action should be in.
Like the other built-in integrations, zero adds the PubSub clients to the container automatically once the required service config is present.
zero tries to connect and tracks the ping status, then ties the client to the app's lifetime. If the connection can't be made, PubSub stays disabled.
try ctx.pubsub.Publish("zero", "publisher 1 says hello! via NATS");
try app.addPubSubSubscription("zero", onMessage);#ctx.KF will be deperecated
ctx.KF.publish(ctx, "topic", "message-key", "payload"); #publishes message to a topic on the subscribed client
app.addKafkaSubscription("topic", subscriberHandler); #listens for upcoming event and injects into subscriber handler for further actions.#ctx.KF will be deperecated
ctx.MQ.Publish("topic", "payload"); #publishes message to a topic on the subscribed client
app.addSubscription("topic", subscriber-handler); #listens for upcoming event and injects into subscriber handler.ctx.pubsub.Publish("subject", "payload"); #publishes message to a NATS subject
app.addPubSubSubscription("subject", subscriber-handler); #listens for upcoming event and injects into subscriber handler.Resilience
All brokers degrade gracefully when the broker is unhealthy:
- Reconnect & re-subscribe — on a broker drop the client reconnects and re-subscribes automatically; no restart required.
- Retry — a failing message handler is retried up to 3× with a 500 ms backoff before the message is given up.
- Dead-letter — poison messages that keep failing are dead-lettered to a side topic so they don't block the stream:
- Kafka:
<topic>__dlq - MQTT / NATS / Redis:
<topic>/dlq
- Kafka:
Each dead-lettered message increments the app_pubsub_dlq_total counter (labels topic, consumer) see Observability.
The X-Correlation-ID set by the inbound request is propagated into Kafka/NATS record headers and the outbound HTTP client, so a single id flows across services and brokers.
Message slices
From 0.5.4 the per-message arena is freed as soon as the hook returns. Copy m.payload or m.subject if you need them after that point. A slice kept past the handler now points at freed memory. Private plugins also need updating: the publish vtable method gained a key: ?[]const u8 argument. Use PublishWithKey(subject, payload, key) to send a key.
Redis shares one connection with the KV store and the rate limiter. If that connection drops, the health probe reconnects it once, and the three features recover together. The Redis pub/sub client keeps its own sockets and reconnects on its own.
Support
zero supports the following brokers for publishing and subscribing.
| Message Broker | Support |
|---|---|
| Kafka | ✅ |
| MQTT | ✅ |
| NATS | ✅ |
| Redis | ✅ |
| AWS SQS | ✅ (guide) |
| GCP Pub/Sub | ✅ (guide) |
Configurations
These settings let you choose Kafka, MQTT, NATS, Redis, AWS SQS, or GCP Pub/Sub per instance. SQS and GCP Pub/Sub have their own guides: AWS SQS and GCP Pub/Sub.
| kafka config | Remarks | Default* / Others | Required |
|---|---|---|---|
| PUBSUB_BACKEND | Choose kafka, mqtt or nats as pubsub mq | None (KAFKA / MQTT / NATS) | Yes |
| PUBSUB_BROKER | Set the addresses of the Kafka cluster | localhost:9092 [one or multiple host address] | Yes |
| PUBSUB_OFFSET | Allow the subscription to begin from | None | No |
| CONSUMER_ID | Unique identifier of the subscribing group | None | No |
| KAFKA_BATCH_SIZE | Number of messages added in one messageSet | 100* | No |
| KAFKA_BATCH_BYTES | The overall size of the messageSet that includes one or more message | 1048576* | No |
| KAFKA_BATCH_TIMEOUT | MessageSet flush timeout | 1000* | No |
| KAFKA_SECURITY_PROTOCOL | Protocol used to communicate with kafka cluster | plaintext*,ssl,sasl_plaintext, sasl_ssl | No |
| KAFKA_SASL_MECHANISM | SASL Authentication mechanism | plain* | No |
| KAFKA_SASL_USERNAME | SASL Authentication username | Applicable only with sasl plain mode | No |
| KAFKA_SASL_PASSWORD | SASL Authentication password | Applicable only with sasl plain mode | No |
| KAFKA_TLS_CERT_FILE | Path to client's public key (PEM) used for authentication. | None | No |
| KAFKA_TLS_KEY_FILE | Path to client's private key (PEM) used for authentication. | None | No |
| KAFKA_TLS_CA_CERT_FILE | Path to client's CA cert (PEM) used for authentication. | None | No |
| KAFKA_TLS_INSECURE_SKIP_VERIFY | Skip client certificate verifications | true*, false | No |
| MQTT config | Remarks | Default* / Others | Required |
|---|---|---|---|
| MQTT_PROTOCOL | Protocol used to communicate with MQTT server | tcp* | Yes |
| MQTT_HOST | IP Address of the MQTT Server | None | Yes |
| MQTT_PORT | Port of the MQTT Server | None | Yes |
| MQTT_CLIENT_ID_SUFFIX | Client ID name for the debug messages | None | No |
| NATS config | Remarks | Default* / Others | Required |
|---|---|---|---|
| PUBSUB_BACKEND | Set to NATS to use the NATS broker | NATS | Yes |
| PUBSUB_BROKER | NATS server URL | nats://localhost:4222 | Yes |
| NATS_STREAM | JetStream stream name | None | No |
| NATS_SUBJECTS | Comma-separated subjects to subscribe to | None | No |
| NATS_CONSUMER | Durable consumer name | None | No |
| NATS_MAX_WAIT | Max wait (ms) for a pull subscription | None | No |
| NATS_MAX_PULL_WAIT | Max pull wait (ms) | 5000* | No |
| NATS_CREDS_FILE | Path to a NATS credentials file | None | No |
| Redis config | Remarks | Default* / Others | Required |
|---|---|---|---|
| PUBSUB_BACKEND | Set to REDIS to use the Redis broker | REDIS | Yes |
| REDIS_HOST | Redis server host | 127.0.0.1 | Yes |
| REDIS_PORT | Redis server port | 6379 | Yes |
| REDIS_USER | Redis username | None | No |
| REDIS_PASSWORD | Redis password | None | No |
| REDIS_DB | Redis logical database | 0 | No |
Redis
Select Redis with PUBSUB_BACKEND=REDIS. Redis Pub/Sub uses the same REDIS_* connection settings as the cache/KV store.
Publish through the unified ctx.pubsub interface (works across Kafka, MQTT, NATS and Redis); subscribe with app.addPubSubSubscription(...).
In the handler the message is available on ctx.message.?.redis, which exposes .subject and .payload ([]const u8).
// from a handler or cron job
try ctx.pubsub.Publish("zero", "publisher 1 says hello! via Redis");fn onMessage(ctx: *Context) !void {
if (ctx.message) |message| {
const m = message.redis;
ctx.info(m.payload); // m.subject and m.payload are []const u8
}
}
// register at startup
try app.addPubSubSubscription("zero", onMessage);NATS
Select NATS with PUBSUB_BACKEND=NATS.
Publish through the unified ctx.pubsub interface (works across Kafka, MQTT, NATS and Redis); subscribe with app.addPubSubSubscription(...).
In the handler the message is available on ctx.message.?.nats, which exposes .subject and .payload ([]const u8).
// from a handler or cron job
try ctx.pubsub.Publish("zero", "publisher 1 says hello! via NATS");fn onMessage(ctx: *Context) !void {
if (ctx.message) |message| {
const m = message.nats;
ctx.info(m.payload); // m.subject and m.payload are []const u8
}
}
// register at startup
try app.addPubSubSubscription("zero", onMessage);Kafka
Select Kafka with PUBSUB_BACKEND=KAFKA.
Publish through the ctx.KF interface: resolve the topic handler once with ctx.KF.getTopicHandler(ctx, topic), then ctx.KF.publish(ctx, topic, key, payload); subscribe with app.addKafkaSubscription(...).
In the handler the message is available on ctx.message.?.kafka, which exposes .topic and .payload (?[]const u8).
// from a handler or cron job
const topic = try ctx.KF.getTopicHandler(ctx, "zero-topic");
try ctx.KF.publish(ctx, topic, "publisher-1", "publisher message!");fn subscribeTask(ctx: *Context) !void {
if (ctx.message) |message| {
const k = message.kafka;
ctx.info(k.payload); // k.topic and k.payload are []const u8 (?[]const u8)
}
}
// register at startup
try app.addKafkaSubscription("zero-topic", subscribeTask);MQTT
Select MQTT with PUBSUB_BACKEND=MQTT.
Publish through the ctx.MQ interface (ctx.MQ.Publish(topic, payload)); subscribe with app.addSubscription(...).
In the handler the message is available on ctx.message.?.mqtt, which exposes .topic and .payload (?[]const u8).
// from a handler or cron job
const id = try ctx.MQ.Publish("zero", "publisher 1 says hello!");fn subscribeTask(ctx: *Context) !void {
if (ctx.message) |message| {
const mq = message.mqtt;
ctx.info(mq.payload); // mq.topic and mq.payload are []const u8 (?[]const u8)
}
}
// register at startup
try app.addSubscription("zero", subscribeTask);AWS SQS & GCP Pub/Sub
zero can also publish to and subscribe from Amazon SQS and Google Cloud Pub/Sub through the same unified ctx.pubsub interface. No AWS or GCP SDK to link (SQS is signed with SigV4, GCP Pub/Sub uses OAuth2 bearer tokens). See AWS SQS and GCP Pub/Sub for configuration and examples.