Go Events
Full API reference for the go-events library — transports, EventBus, filters, typed messages.
Module: github.com/redelay/go-events
Overview
go-events provides a high-level EventBus over pluggable transport backends (Kafka, NATS,
Redis Streams, in-memory). The canonical event types (EventMessage, ConsumerRegistration,
EventBus interface) are defined in go-framework/runtime/transport (stdlib-only, zero
external deps) and re-exported as type aliases from both go-events/core and
go-framework/modules. This means all three import paths refer to identical types with no
circular module dependency.
Dependency graph
go-framework/runtime/transport ← canonical zero-dep type home (stdlib only)
↑ ↑
go-events/core go-framework/modules (type aliases — identical types)
↑
go-events/eventbus ← no mongo/chi/JWT/zap
go-events/module ← imports go-framework/modules (lifecycle only)
Lightweight workers (Kafka consumers, scheduled jobs) that only need event types and no HTTP
server can import go-events/core without pulling in the full framework stack.
FlowDSL integration — go-flowdsl/nodes
The redelay/event-source node subscribes to any event on the bus. It replaces
the per-event source nodes that each module used to emit.
The node ships from go-flowdsl/nodes, not from go-events (it lived at
go-events/flowdsl until the 2026-04-16 flowdsl refactor).
Why it lives there: the node pack programs against the EventBus interface
in go-framework/runtime/transport and imports go-events nowhere. Had it
stayed under go-events, every flow using redelay/event-source would have
pulled in the event library — and transitively sarama or nats.go — regardless of
which transport the project actually ran. Keeping it in go-flowdsl/nodes means
FlowDSL depends on the transport interface only, so any implementation
(kafka, nats, redis, memory) satisfies it.
It is packaged with the other transport-entry nodes (json-stream-source,
json-to-event, kafka-produce, nats-publish, redis-stream-publish), so one
import gets the whole entry-node pack.
Enable with a blank import:
import _ "github.com/redelay/go-flowdsl/nodes" // event/stream sources + publishers
import _ "github.com/redelay/go-flowdsl/nodes/core" // stdlib primitives (transforms, control flow)
Configurable event-source node
One node type serves every event in the system. The specific event is picked
via the node's eventName setting, which Studio renders as a dropdown.
on_user_signup:
kind: source
nodeType: redelay/event-source
settings:
eventName: users.user_created # chosen from live dropdown
groupID: onboarding-welcome
filter: "payload.email_verified == true" # optional, server-side
outputs:
- name: Event
message:
$ref: "asyncapi:default#/components/schemas/EventMessage"
Settings:
| Setting | Type | Description |
|---|---|---|
eventName | enum (required) | Event topic to subscribe to — enum populated at runtime from the live module registry |
groupID | string | Consumer group — defaults to a flow-id-scoped auto-generated value |
filter | string | Optional expression evaluated by the event bus filter chain before the flow wakes |
Output port is always the generic EventMessage envelope. Payload shape
varies per event — refer to the live AsyncAPI document for per-event payload
schemas. In edge transforms, project payload fields via {{.payload.*}}:
edges:
- from: on_user_signup
to: send_welcome_email
when: "output.name == 'Event'"
transform:
to: "{{.payload.email}}"
name: "{{.payload.name}}"
Deduplicated triggers. With flowexec ≥ v0.2.27 on go-events ≥ v0.6.3, a
published flow's event trigger subscribes through the bus
(Subscribe) under the stable consumer name
flow:<flowID>:<triggerNodeID>, the same across versions of the flow. With
EVENTS_DEDUPE on, a redelivered event runs the flow
once. Older versions subscribed on the raw transport, which skipped every
consume middleware, so a redelivery re-ran the flow.
How the live enum works
go-flowdsl/nodes/module.go overrides FlowDSLNodes() on its Module. At
spec-build time it walks registry.IRModules(), collects every declared event
name across all loaded modules, and injects them as the enum on
settings.eventName in the node manifest. The module YAML ships with
enum: [] — the list is always live.
New events show up in Studio automatically as soon as the corresponding module is loaded; no manifest regeneration required.
JSON stream ingestion nodes
Two companion nodes let a flow ingest arbitrary JSON from external sources (webhooks, NDJSON streams, raw message buses) and map the fields into one of the system's declared events.
Typical pipeline:
redelay/json-stream-source ──► redelay/json-to-event ──► publish / downstream action
The split lets you either chain both nodes for a full receive-map-publish
flow, or use redelay/json-to-event alone with JSON from any upstream node.
redelay/json-stream-source (source)
Subscribes to an external JSON message stream and emits each decoded document as a packet. Does not interpret the payload.
Supported transports (transport setting):
| Value | Description |
|---|---|
http-webhook | Exposes an HTTP POST endpoint at the configured path |
ndjson | Tails an NDJSON file/URL |
kafka-raw | Reads a Kafka topic where the value is raw JSON (no envelope) |
nats | Subscribes to a NATS subject (core or JetStream); optional natsQueue for queue groups |
redis-stream | Reads entries from a Redis Stream |
Common settings: path, url, topic, natsQueue, groupID, authHeader,
authSecret (secret), maxBodyBytes. Emits on the message output port with
fields raw, received_at, source_transport, headers.
redelay/json-to-event (transform)
Consumes a JSON document and transforms it into a typed Redelay event,
optionally publishing it to the bus. Target event is picked via the
eventName dropdown (live enum, same mechanism as redelay/event-source).
Mapping rules are JSONPath-style key/value pairs:
{
"entity_id": "$.customer.id",
"payload.email": "$.customer.email_address",
"payload.status": "$.status || \"pending\""
}
Settings: eventName (required), mapping (required), actorType,
actorID, publish, strict. Two outputs: event (the constructed envelope)
and error (emitted when mapping fails — required fields missing, invalid
JSONPath, etc.).
When publish=true, the transformed event is published to the bus in
addition to being emitted on the event output port.
Consumer auto-wiring
When using the auto-wire pattern (import _ "github.com/redelay/go-events/module"), the
framework automatically discovers and registers all consumer subscriptions declared by other
modules. No manual bus.Register() call is needed anywhere in your code.
How it works:
- Each module that wants to consume events implements
Consumers()from theEventsProviderinterface:func (m *Module) Consumers() []*modules.ConsumerRegistration { return []*modules.ConsumerRegistration{{ Topic: "email.send", GroupID: "email-sender", Handler: m.handleEmailSend, }} } - During the
Configurelifecycle phase (beforeStartup), the events module iterates all registered modules, finds everyEventsProvider, and callsbus.Register(reg)for each declared consumer. bus.Start()is called inStartup— all consumers are already registered and wired to the transport.
This means adding a new consumer to any module is a one-step change: return it from Consumers(). The rest is automatic.
Bootstrap patterns
Auto-wire (recommended)
import (
_ "github.com/redelay/go-events/module" // registers factory
)
inst, _ := app.Bootstrap() // EventBus auto-created from TRANSPORT env
app.Run(inst, server.Default(inst))
The TRANSPORT environment variable selects the backend (kafka by default). An explicit
app.WithEventBus(bus) always takes priority over the auto-wired bus.
Manual wiring
import (
"github.com/redelay/go-events/eventbus"
"github.com/redelay/go-events/transport/kafka"
)
t, err := kafka.NewFromEnv()
bus := eventbus.New(t)
inst, _ := app.Bootstrap(app.WithEventBus(bus))
Standalone worker (no full framework)
import (
"github.com/redelay/go-events/core"
"github.com/redelay/go-events/eventbus"
"github.com/redelay/go-events/transport/kafka"
)
// Only core + eventbus + transport — no mongo-driver, chi, JWT, zap.
t, _ := kafka.NewFromEnv()
bus := eventbus.New(t)
bus.Register(&core.ConsumerRegistration{
Topic: "user.created",
GroupID: "my-worker",
Handler: func(ctx context.Context, msg *core.EventMessage) error { ... },
})
bus.Start(ctx)
Transport backends
NewFromEnv() (recommended)
Every transport exposes a NewFromEnv() constructor that reads all settings from environment variables:
// Pick one:
t, err := kafka.NewFromEnv() // reads KAFKA_BOOTSTRAP_SERVERS, KAFKA_SASL_*, ...
t, err := nats.NewFromEnv() // reads NATS_URL, NATS_JETSTREAM, NATS_CREDENTIALS_FILE, ...
t, err := redis.NewFromEnv() // reads REDIS_STREAMS_URL, REDIS_STREAMS_BATCH_SIZE, ...
bus := eventbus.New(t)
See Transports for the full environment variable reference and cluster configuration.
Kafka
import "github.com/redelay/go-events/transport/kafka"
t, err := kafka.New(kafka.Config{
Brokers: []string{"kafka:9092"},
GroupID: "my-service",
ClientID: "my-service",
// SASL for managed Kafka (Confluent Cloud, MSK, Aiven):
// SASL: &kafka.SASLConfig{
// Mechanism: kafka.SASLMechanismSCRAMSHA256,
// Username: "user",
// Password: "secret",
// },
})
NATS
import "github.com/redelay/go-events/transport/nats"
// Core pub/sub (ephemeral — no persistence):
t, err := nats.New(nats.Config{
URL: "nats://localhost:4222",
UseJetStream: false,
})
// JetStream (durable — persistent, consumer groups, replay):
t, err := nats.New(nats.Config{
URL: "nats://nats1:4222,nats://nats2:4222", // cluster
UseJetStream: true,
AckWait: 30 * time.Second,
MaxDeliver: 3,
})
JetStream auto-creates streams on demand — no manual NATS admin needed. A
stream is provisioned before the first QueueSubscribe and before the first
Publish to a subject. The publish-side provisioning matters: without it,
JetStream rejects a publish to a subject that has no stream, so publishing only
worked for topics the same process happened to subscribe to first — an event
consumed by another service, or by nothing yet, failed with "no response from
stream". The stream-existence check is cached per subject, so it costs one
round-trip per new topic, not one per message.
Redis Streams
import "github.com/redelay/go-events/transport/redis"
t, err := redis.New(redis.Config{
Addr: "redis:6379",
BlockDuration: 200 * time.Millisecond,
BatchSize: 10,
MaxLen: 10_000,
})
Uses XADD / XREADGROUP under the hood. Consumer group semantics: each GroupID receives exactly one delivery across all replicas.
Memory (for tests)
import "github.com/redelay/go-events/transport/memory"
tr := memory.New()
// Full consumer-group semantics: each group gets the message,
// round-robin dispatch within a group.
No infrastructure required. Use for unit tests and fast feedback loops.
EventBus
import "github.com/redelay/go-events/eventbus"
bus := eventbus.New(t) // t is any transport.Transport
bus.UsePublish(eventbus.LoggingPublishMiddleware)
bus.UseConsume(eventbus.LoggingConsumeMiddleware)
Key methods
| Method | Description |
|---|---|
New(t) | Create EventBus wrapping transport t |
UsePublish(mw...) | Append publish middleware |
UseConsume(mw...) | Append consume middleware |
Register(reg) | Register a ConsumerRegistration (before Start) |
Start(ctx) | Wire registrations to transport and start consuming |
Subscribe(ctx, reg) | Register a consumer after Start (v0.6.3+) — same decode, filter, consume middleware and observers as a registration made before Start; this is how flowexec subscribes event-triggered flows |
Stop(ctx) | Stop consuming |
Publish(ctx, msg) | Publish a modules.EventMessage |
Close() | Close the underlying transport |
Built-in middleware
| Middleware | Side | Effect |
|---|---|---|
CorrelationPublishMiddleware | Publish | Sets correlation_id header from context (default) |
CorrelationConsumeMiddleware | Consume | Injects correlation_id from message into context (default) |
LoggingPublishMiddleware | Publish | Logs entity_type, action, latency |
LoggingConsumeMiddleware | Consume | Logs entity_type, action, latency |
IdempotentConsume(store, opts) | Consume | Runs each named handler once per event ID — see Idempotent consumers |
Context helpers
ctx = eventbus.WithCorrelationID(ctx, "req-abc")
cid := eventbus.CorrelationIDFromContext(ctx) // "req-abc"
c := eventbus.ConsumerFromContext(ctx) // in a handler: {Bus, Topic, Group, Name}
Typed event definitions
Import github.com/redelay/go-events/typed to declare strongly-typed
event definitions with JSON-serialised payloads.
import "github.com/redelay/go-events/typed"
type UserCreatedPayload struct {
ID string `json:"id"`
Email string `json:"email"`
}
var UserCreatedEvent = typed.EventDefinition[UserCreatedPayload]{
Name: "user.created",
EntityType: "user",
Action: "created",
Topic: "user.created",
}
msg, err := UserCreatedEvent.NewMessage(
user.ID,
typed.Actor{Type: typed.ActorTypeUser, ID: actorID},
UserCreatedPayload{ID: user.ID, Email: user.Email},
)
bus.Publish(ctx, msg)
MustNewMessage panics instead of returning an error — tests only.
Where the pieces live
| Type | Package |
|---|---|
EventDefinition[T], Actor, ActorType*, SystemActor | go-events/typed |
EmailSendPayload + EmailSendEvent | go-module-email/events |
Implementation sits in go-framework/runtime/events (stdlib + uuid,
sibling to runtime/transport). go-events/typed re-exports from
there so neither direction introduces a module cycle.
Filters
import "github.com/redelay/go-events/filter"
| Filter | Description |
|---|---|
HeaderFilter{Key, Value} | Match headerKey == Value |
ActionFilter{EntityType, Action} | Match entity_type + action |
RegexFilter{Key, Pattern} | Match headerKey against regexp |
CompositeFilter{Filters, Op} | AND / OR combinator |
PrefixFilter{Prefix} | EntityType starts with prefix |
FuncFilter{Fn} | Custom predicate |
All(filters...) | Shorthand for AND composite |
Any(filters...) | Shorthand for OR composite |
Func(fn) | Shorthand for FuncFilter |
Using a filter in a ConsumerRegistration:
bus.Register(&modules.ConsumerRegistration{
Topic: "events",
GroupID: "g",
Filter: filter.All(&filter.ActionFilter{EntityType: "user", Action: "created"}).Matches,
Handler: ...,
})
EventMessage
EventMessage is defined in go-framework/runtime/transport and aliased in both
go-events/core and go-framework/modules — all three import paths refer to the same type.
type EventMessage struct {
ID string `json:"event_id"`
CorrelationID string `json:"correlation_id,omitempty"`
Timestamp string `json:"timestamp"`
EntityType string `json:"entity_type"`
EntityID string `json:"entity_id"`
Action string `json:"action"`
ActorType string `json:"actor_type,omitempty"`
ActorID string `json:"actor_id,omitempty"`
Payload []byte `json:"payload"`
Headers map[string]string `json:"headers,omitempty"`
}
Extract a typed payload:
var p OrderCreatedPayload
json.Unmarshal(msg.Payload, &p)
Publishing many events {#bulk-publish}
Publish waits for the broker's acknowledgement. The Kafka transport uses
RequiredAcks = WaitForAll, so on a multi-node cluster every message waits for
each in-sync replica — ~200 ms across data centres. A loop publishing 50,000
requests one at a time therefore takes hours (and a deploy that restarts the
process mid-loop starts it over). Publish with bounded concurrency instead —
e.g. 32 goroutines draining a channel, first error cancels the rest, count what
was sent. The producer batches concurrent sends into fewer requests. Watch
events_publish_duration_seconds{transport="kafka"} (p95) to see when acks get slow.
Outbox {#outbox}
v0.5.0+. A publish waits for the partition leader and its followers. With
brokers in several regions, a request can cross the ocean twice per publish.
go-events/outbox stores the event in Mongo instead — inside the caller's
transaction when ctx is a mongo.SessionContext — and a background relay
publishes it on the same bus (built on go-framework's runtime/outbox:
at-least-once, claim tokens, dead rows after 20 attempts).
import _ "github.com/redelay/go-events/outbox" // registers the "events-outbox" module
err := outbox.Add(ctx, outbox.MainBus, deps.EventBus, msg) // the main bus
err := outbox.Add(ctx, "domains", nil, msg) // a named bus (EVENTS_BUSES)
- One collection per bus:
events_outbox(main) andevents_outbox_<bus>. Bus names are lower-cased everywhere. - The module's migration creates the collections known at deploy. A bus or region configured later gets its collection and claim index when its outbox is first built.
- With no outbox for the bus in this process (no Mongo, not started, bus not
connected yet)
Addpublishes directly onfallback, else on the bus — except inside a transaction, where it returnsErrNoOutboxInTransaction: a direct publish would survive an abort and repeat on every retry of the transaction. - A regional relay (
EVENTS_OUTBOX_REGION) only takes rows of its region. SetEVENTS_OUTBOX_DEFAULT_REGION, or keep one relay without a region, or rows added without a region are never relayed (startup warns). - Delivery is at-least-once: consumers deduplicate on the event ID — use Idempotent consumers.
| Variable | Default | Purpose |
|---|---|---|
EVENTS_OUTBOX_RELAY | true | false = write rows only (a node far from the brokers) |
EVENTS_OUTBOX_REGION | Relay only this home region's rows (zone-sharded data) | |
EVENTS_OUTBOX_DEFAULT_REGION | Region stamped on rows added without one | |
EVENTS_OUTBOX_COLLECTION | events_outbox | The main bus's collection; named buses append _<bus> |
Metrics (relaying processes only), labelled {bus}:
redelay_events_outbox_pending, redelay_events_outbox_dead,
redelay_events_outbox_oldest_pending_seconds, redelay_events_outbox_unstamped.
Alert on the oldest pending age, on dead > 0, and on absent() per relaying service.
Idempotent consumers {#idempotent-consumers}
v0.6.0+. Delivery is at-least-once: Kafka rebalances and retries, and an
outbox relay, can redeliver an event. eventbus.IdempotentConsume runs each
handler once per (bus, group, topic, registration name, event ID).
bus.UseConsume(eventbus.IdempotentConsume(
dedupe.NewRedis(rdb, "myapp:dedupe:"), // shared by every replica
eventbus.IdempotentOptions{},
))
// or eventbus.New(t, eventbus.WithConsume(mw))
How a delivery is handled:
| State of the key | Result |
|---|---|
| New | Claimed (InFlight TTL) → handler → recorded as done (Remember, 24 h). A handler error releases the claim, so the redelivery retries — only the registrations that failed run again |
| Done | ErrDuplicate (wraps ErrSkipped): acked, counted as skipped |
| In flight in another attempt (a rebalance handed the offset to a new owner mid-handler) | Waits in place — polling from 250 ms, for at most InFlightWait — for the original to finish (→ duplicate, acked) or release (→ handled here). Still held after the wait → ErrInFlight: not acked, so the transport retries or redelivers. Never lost |
Rules:
- Only registrations with an
EventNameare deduplicated — it is the handler's stable identity, never a position. Unnamed registrations pass through, with one warning per (bus, group, topic). Messages without an ID are not deduplicated. - A handler's own
ErrSkippedis remembered like a success. - The done marker (and a release) is written on a context the consumer's
cancellation cannot reach, with a 5 s timeout (v0.7.0+). Before, a
rebalance or shutdown that ended the session while a handler finished made
the write fail with
context canceled, and the redelivery ran the handler again. - A store error fails open: the message is handled (maybe twice), never
lost, and
OnErroris told. InFlight(default 60 s) must exceed the slowest handler. A claim that lapsed under a running handler shows asErrClaimLostinOnError. Give a slow consumer a long claim per group (InFlightFor) instead of raising it for everyone.InFlightWait(v0.6.8+, default min(InFlight, 60 s)) caps the in-place wait, not the claim: a group with a 15 min claim keeps it, but a duplicate behind an owner that died no longer holds its partition for several claim lengths.- Broadcast groups (
KAFKA_BROADCAST_GROUP_PREFIXES, one per process) are never deduplicated: their keys could not match. dedupe.Memoryis for tests and single-process use only.
With go-events/module, by env, for every bus it creates:
| Variable | Default | Purpose |
|---|---|---|
EVENTS_DEDUPE | off | redis (shared by every replica) or memory (one process: tests) |
EVENTS_DEDUPE_REDIS_URL / EVENTS_DEDUPE_REDIS_CLUSTER_NODES (+ _PASSWORD) | The Redis every replica of a group reaches | |
EVENTS_DEDUPE_PREFIX | <APP_NAME>:dedupe: | Key prefix |
EVENTS_DEDUPE_REMEMBER | 24h | How long a done record is kept |
EVENTS_DEDUPE_INFLIGHT | 60s | Claim TTL — longer than the slowest handler |
EVENTS_DEDUPE_INFLIGHT_GROUPS | Per consumer group, e.g. "auctions-*=15m,backorders-*=15m" (path.Match globs, first match wins; malformed entries are logged and skipped) | |
EVENTS_DEDUPE_INFLIGHT_WAIT | min(INFLIGHT, 60s) | Longest an in-flight duplicate waits in place |
EVENTS_DEDUPE_INFLIGHT_WAIT_GROUPS | Per consumer group, same syntax as _INFLIGHT_GROUPS |
Guard: every consumer is named {#consumers-named}
v0.6.8+. An unnamed consumer silently loses deduplication. Add one test per app:
import "github.com/redelay/go-events/eventstest"
func TestConsumersAreNamed(t *testing.T) {
eventstest.AssertConsumersNamed(t, "../..",
eventstest.AllowUnnamed("settings-invalidator-"), // broadcast groups
eventstest.SkipDirs("gen")) // also AllowDuplicate(names...), StrictLiterals()
}
It parses every ConsumerRegistration under the root — explicit
&…ConsumerRegistration{…} literals and elided []…ConsumerRegistration{{…}}
entries, any field order — and requires a stable EventName: a non-empty
literal, or literals joined with constants or static-table fields
("auctions." + src.template). Calls (fmt.Sprintf) and indexing
(names[0]) are rejected, because that is how positional names creep in.
Names must be unique per (GroupID, Topic). From v0.6.9, literals and
same-package constants (tickEntity + "." + tickAction) resolve, so duplicates
among constant-based registrations are caught too. Where a group or topic still
does not resolve (another package's constant, a field), the name alone must be
unique; AllowDuplicate(names...) exempts an intended repeat. _test.go,
vendor, testdata and dot-dirs are skipped, and an empty scan fails (a wrong
root).
Broker-side dedupe {#broker-dedupe}
Complements Idempotent consumers; it never replaces them. Only consumer-side dedupe catches rebalances, replays and slow relays.
- Kafka (v0.6.6+): the producer is idempotent by default
(
Producer.Idempotent, acks=all,Net.MaxOpenRequests=1), so a retry after a lost broker ack is not written twice. It covers the producer's own retries only.KAFKA_PRODUCER_IDEMPOTENT=false(Config.DisableIdempotence) turns it off for brokers older than 0.11 or ACLs withoutIdempotentWrite. Because sarama re-sends an idempotent "not the leader" batch without backoff, the transport waits up to 15 s for a new topic's leaders after creating it, and retries leader errors itself (250 ms → 2 s, about 10 s, refreshing metadata between tries, ending with the publish's context). - NATS JetStream (v0.6.4+): Publish sets
Nats-Msg-Idto the event ID, so the stream drops a republish of the same event within its duplicate window (2 min by default). Core NATS has no dedupe.
Poison messages: bounded redelivery and dead letters {#dead-letters}
v0.7.0+. A handler that fails the same message every time used to run it
forever. On Kafka the session ended, the group rejoined within milliseconds and
the same offset came back; one Gymmer backup event ran its consumer 2,517
times. On NATS JetStream the message stopped after NATS_MAX_DELIVER and was
dropped, with a log line as the only trace.
Both transports now behave the same way:
- Redeliveries back off. The wait before each one starts at 1 s and
doubles up to 5 min. On Kafka the wait holds the partition, which the
failing offset holds anyway. On JetStream it is a
NakWithDelay. - After the last delivery the message is dead-lettered. It is copied to
<topic>.dlq(the logical topic, so Kafka's topic prefix applies as usual) and then acknowledged, so the partition or consumer moves on. On Kafka the last delivery is the 10th (EVENTS_MAX_DELIVERIES); each delivery already retries the handler 4 times in place. On JetStream it isNATS_MAX_DELIVER(default 3). events_dead_lettered_total{topic,group}counts it. Alert on any increase. v0.7.4+: the series is present at0for every(topic, group)the bus consumes, fromRegister/Subscribeon, with the same label values a dead letter uses. So a missing series means "not consumed by this process", not "nothing dead-lettered", and the first dead letter is an increase from 0 thatincrease(...[10m]) > 0sees. Before v0.7.4 the series appeared only with the first dead letter, already at 1, andincrease()missed that one. The shared monitoring ruleevents_dead_lettered(infra/monitoring/alert.yml) catches both shapes. The count says that something was dead-lettered; to see which events and errors, group them and replay them from the admin, review the.dlqtopics with go-modules failures (≥ v0.84.0), which does not add to this count.
The copy keeps the original key, value and headers, and adds:
| Header | Value |
|---|---|
x-dlq-group | the consumer group whose handler failed |
x-dlq-topic | the logical topic it came from |
x-dlq-error | the last handler error (≤ 1 KiB) |
x-dlq-attempts | deliveries before giving up |
x-dlq-failed-at | RFC 3339, UTC |
x-dlq-transport | kafka | nats |
Nothing consumes <topic>.dlq by default. Read it, fix the cause, and
republish what deserves it to the original topic; x-dlq-group tells you
which consumer failed. Other groups on the same topic were not affected.
- If writing the copy fails, the message is not acknowledged on Kafka (it
is retried, never lost). JetStream will not deliver past
MaxDeliver, so there the message is terminated and the failure logged. - A delivery that failed because the consumer was shutting down or rebalancing does not count.
- Kafka counts deliveries per process. A partition that moves to another replica starts counting again there: that delays the bound but never removes it.
EVENTS_DLQ=offturns dead-lettering off. Kafka then keeps redelivering (with the backoff); JetStream drops afterMaxDeliver, as before.- Redis Streams (v0.7.1+) follows the same policy: a failed entry stays
pending and each worker reclaims it after the backoff (
XCLAIMwith a minimum idle time, so one replica wins — including entries a dead consumer held), and after the last delivery it goes to<stream>.dlqand is acknowledged. Before v0.7.1 a failed entry was never redelivered at all. - Kafka, a brand-new consumer group (v0.7.1+): a failed message commits its own offset, so the group rejoins at it. Before, a group with no committed offset rejoined at the newest offset and the first message it ever read was lost if it failed.
- In code:
kafka.Config.DeadLetter/nats.Config.DeadLetter(*deadletter.Policy, packagego-events/transport/deadletter); nil reads the environment.
Handlers should still record their own failure where they can and return nil — a backup run that failed is a result, not a reason to run the backup again. Dead-lettering is the bound for the failures nobody planned for.
| Variable | Default | Purpose |
|---|---|---|
EVENTS_DLQ | on | off keeps redelivering instead of dead-lettering |
EVENTS_MAX_DELIVERIES | 10 | Kafka: failed deliveries before dead-lettering (JetStream uses NATS_MAX_DELIVER; with -1, this) |
EVENTS_REDELIVERY_BACKOFF | 1s | wait before the first redelivery, doubling after each |
EVENTS_REDELIVERY_BACKOFF_MAX | 5m | cap on that wait |
Metrics (Prometheus) {#metrics}
Since v0.4.3 the bus reports every publish and every handler invocation to
an eventbus.Observer. eventbus imports no metrics library;
github.com/redelay/go-events/metrics/prom implements the observer with
client_golang, so core and eventbus stay Prometheus-free. An observer
that also implements the optional eventbus.SubscribeObserver (v0.7.4+) is
told about every Register / Subscribe (SubscribeInfo{Bus, Topic, Group});
prom uses it to start events_dead_lettered_total at 0.
| Metric | Labels |
|---|---|
events_published_total | bus, topic, entity, action, result (ok | error) |
events_consumed_total | bus, topic, group, entity, action, result (ok | error | skipped) |
events_handle_duration_seconds (histogram) | bus, topic, group, action |
events_publish_duration_seconds (histogram) | bus, transport, topic (transport since v0.8.0) |
events_dead_lettered_total (v0.7.0+) | topic, group — messages copied to <topic>.dlq; at 0 for every consumed (topic, group) since v0.7.4 (Poison messages) |
busis theWithNamevalue —defaultunless set; named buses use theirEVENTS_BUSESentry.topicis the logical topic, beforeKAFKA_TOPIC_PREFIX. Labels never carry entity or event ids.transport(v0.8.0+) iskafka,nats,redisormemory—eventbus.TransportName(t): a transport implementingeventbus.TransportNamernames itself (a wrapper returns its inner transport's name), any other is named after its Go package. Onmemorya publish runs every consumer inline, so its duration is the consumers' time (an LLM flow, an SMTP send), not a broker round trip — compare broker latency within one transport only (events_publish_duration_seconds{transport="kafka"}).- Values are sanitised (
[A-Za-z0-9._:/-], ≤ 80 chars, empty →unknown) and each label is capped at 200 distinct values per observer (thenother), so a bad producer cannot blow up the series count. - Consume counts one per handler invocation: Kafka's in-place retries count each attempt. A message the
codec cannot decode counts
result="error"(entity/action from the transport headers, elseunknown). A message a registrationFilterrejects is not counted. - Return
eventbus.ErrSkipped(or wrap it:fmt.Errorf("bad payload: %w", eventbus.ErrSkipped)) for a message you deliberately drop. The bus recordsskippedand acks it exactly like a nil return — it does not inflate the failure rate.
Enabling
With go-events/module (auto-wire) it is on by default for the main bus and every named bus;
EVENTS_METRICS=false turns it off. Serve the default registry — go-modules/metrics mounts /metrics.
Manual wiring (standalone workers):
import (
"github.com/redelay/go-events/eventbus"
"github.com/redelay/go-events/metrics/prom"
)
bus := eventbus.New(tr,
eventbus.WithName("default"),
eventbus.WithObserver(prom.Default()), // prometheus.DefaultRegisterer
)
http.Handle("/metrics", promhttp.Handler()) // a worker with no HTTP server needs its own listener
prom.New(prom.Options{Registerer: reg}) targets a custom registry. Calling New/Default twice
returns the same observer (an AlreadyRegisteredError is absorbed).
bus.Register) is invisible to the observer. Call the observer yourself after each handled message
(obs.Consumed(ctx, eventbus.ConsumeInfo{Bus: "default", Topic: …, Group: …, Result: …, Duration: …})),
otherwise the dashboard shows the topic filling up with no consumer activity.The Events & services dashboard guide shows how to chart these next to broker counters, consumer lag and container metrics.
Legacy packages (backward compat)
| Package | Description |
|---|---|
consumer/ | EventConsumer — direct sarama consumer group with handler registry |
producer/ | EventProducer — direct sarama sync producer |
messages/ | BaseEventMessage, TypedEventMessage[T], FlexTime, EventDefinition |
schema/ | AsyncAPI schema registry + JSON Schema validator |
client.go | EventClient — legacy top-level API |
These remain for backward compatibility. New code should use eventbus/ and transport/.
Configuration (env vars)
Kafka
| Variable | Description | Default |
|---|---|---|
KAFKA_BOOTSTRAP_SERVERS | Comma-separated broker list | localhost:9092 |
KAFKA_GROUP_ID | Consumer group ID | "" |
KAFKA_SECURITY_PROTOCOL | plaintext | sasl_plaintext | sasl_ssl | ssl | plaintext |
KAFKA_SASL_MECHANISM | plain | scram-sha-256 | scram-sha-512 | "" |
KAFKA_SASL_USERNAME | SASL username | "" |
KAFKA_SASL_PASSWORD | SASL password | "" |
KAFKA_PRODUCER_IDEMPOTENT | true turns the idempotent producer on — only for a producer that publishes from one goroutine (Broker-side dedupe) | false (since v0.6.10) |
KAFKA_TOPIC_RACK | Create new topics only on brokers with this broker.rack (replication capped at that rack's broker count, preferred leaders rotated). Keeps a region's topics in that region: acks=all waits for every in-sync replica, and one across an ocean costs ~1 s per publish. No broker with the rack: logged, topic created as before. See Regions | "" (since v0.7.3) |
ASYNCAPI_URL | AsyncAPI schema endpoint for validation | "" |
NATS
| Variable | Description | Default |
|---|---|---|
NATS_URL | Server URL or comma-separated cluster URLs | nats://localhost:4222 |
NATS_JETSTREAM | true to enable durable JetStream delivery | false |
NATS_CREDENTIALS_FILE | Path to .creds file (NGS/Synadia accounts) | "" |
NATS_NKEY_FILE | Path to NKey seed file | "" |
NATS_TLS | true to require TLS | false |
NATS_ACK_WAIT_SECONDS | JetStream ack wait before redelivery | 30 |
NATS_MAX_DELIVER | JetStream max redelivery attempts (-1 = unlimited) | 3 |
Outbox, dedupe and dead-letter variables: see Outbox, Idempotent consumers and Poison messages.
Redis Streams
| Variable | Description | Default |
|---|---|---|
REDIS_STREAMS_URL | Redis URL (redis://host:port); falls back to REDIS_URL | redis://localhost:6379 |
REDIS_STREAMS_BLOCK_MS | XREADGROUP block duration in ms | 200 |
REDIS_STREAMS_BATCH_SIZE | Messages per XREADGROUP fetch | 10 |
REDIS_STREAMS_MAX_LEN | Max stream length (0 = unlimited) | 10000 |
Build and test
# Build all packages
cd go-events && go build ./...
# Unit tests (no infrastructure needed)
cd go-events && go test -count=1 -race ./...
# or via Makefile:
cd go-events && make test
# Integration tests (requires Docker — starts real Kafka, NATS, Redis containers)
cd go-events && go test -tags integration -v -timeout 180s ./transport/integration/
# or via Makefile:
cd go-events && make test-integration
# Both
cd go-events && make test-all
The integration test suite (transport/integration/) uses testcontainers-go to spin up:
| Test | Container |
|---|---|
TestMemoryTransport* | None — in-process |
TestNATSCoreTransport* | nats:2-alpine |
TestNATSJetStreamTransport* | nats:2-alpine (JetStream enabled) |
TestRedisStreamsTransport* | redis:7-alpine |
TestKafkaTransport* | confluentinc/confluent-local:7.5.0 |
Each transport runs the same 5 scenarios: publish/subscribe, consumer groups, filtered delivery, correlation ID propagation, graceful shutdown.