Go Events

Full API reference for the go-events library — transports, EventBus, filters, typed messages.

22 min readReference

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

text
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:

go
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.

yaml
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:

SettingTypeDescription
eventNameenum (required)Event topic to subscribe to — enum populated at runtime from the live module registry
groupIDstringConsumer group — defaults to a flow-id-scoped auto-generated value
filterstringOptional 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.*}}:

yaml
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:

text
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):

ValueDescription
http-webhookExposes an HTTP POST endpoint at the configured path
ndjsonTails an NDJSON file/URL
kafka-rawReads a Kafka topic where the value is raw JSON (no envelope)
natsSubscribes to a NATS subject (core or JetStream); optional natsQueue for queue groups
redis-streamReads 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:

json
{
  "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:

  1. Each module that wants to consume events implements Consumers() from the EventsProvider interface:
    go
    func (m *Module) Consumers() []*modules.ConsumerRegistration {
        return []*modules.ConsumerRegistration{{
            Topic:   "email.send",
            GroupID: "email-sender",
            Handler: m.handleEmailSend,
        }}
    }
    
  2. During the Configure lifecycle phase (before Startup), the events module iterates all registered modules, finds every EventsProvider, and calls bus.Register(reg) for each declared consumer.
  3. bus.Start() is called in Startup — 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

go
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

go
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)

go
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

Every transport exposes a NewFromEnv() constructor that reads all settings from environment variables:

go
// 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

go
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

go
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

go
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)

go
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

go
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

MethodDescription
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

MiddlewareSideEffect
CorrelationPublishMiddlewarePublishSets correlation_id header from context (default)
CorrelationConsumeMiddlewareConsumeInjects correlation_id from message into context (default)
LoggingPublishMiddlewarePublishLogs entity_type, action, latency
LoggingConsumeMiddlewareConsumeLogs entity_type, action, latency
IdempotentConsume(store, opts)ConsumeRuns each named handler once per event ID — see Idempotent consumers

Context helpers

go
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.

go
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

TypePackage
EventDefinition[T], Actor, ActorType*, SystemActorgo-events/typed
EmailSendPayload + EmailSendEventgo-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

go
import "github.com/redelay/go-events/filter"
FilterDescription
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:

go
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.

go
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:

go
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).

go
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) and events_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) Add publishes directly on fallback, else on the bus — except inside a transaction, where it returns ErrNoOutboxInTransaction: 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. Set EVENTS_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.
VariableDefaultPurpose
EVENTS_OUTBOX_RELAYtruefalse = write rows only (a node far from the brokers)
EVENTS_OUTBOX_REGIONRelay only this home region's rows (zone-sharded data)
EVENTS_OUTBOX_DEFAULT_REGIONRegion stamped on rows added without one
EVENTS_OUTBOX_COLLECTIONevents_outboxThe 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).

go
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 keyResult
NewClaimed (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
DoneErrDuplicate (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 EventName are 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 ErrSkipped is 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 OnError is told.
  • InFlight (default 60 s) must exceed the slowest handler. A claim that lapsed under a running handler shows as ErrClaimLost in OnError. 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.Memory is for tests and single-process use only.

With go-events/module, by env, for every bus it creates:

VariableDefaultPurpose
EVENTS_DEDUPEoffredis (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_REMEMBER24hHow long a done record is kept
EVENTS_DEDUPE_INFLIGHT60sClaim TTL — longer than the slowest handler
EVENTS_DEDUPE_INFLIGHT_GROUPSPer consumer group, e.g. "auctions-*=15m,backorders-*=15m" (path.Match globs, first match wins; malformed entries are logged and skipped)
EVENTS_DEDUPE_INFLIGHT_WAITmin(INFLIGHT, 60s)Longest an in-flight duplicate waits in place
EVENTS_DEDUPE_INFLIGHT_WAIT_GROUPSPer 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:

go
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 without IdempotentWrite. 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-Id to 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.
Do not use v0.6.4. It made the Kafka producer idempotent without the leader wait and retry above, and the first publish to a newly created topic fails. Use v0.6.6 or later.

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:

  1. 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.
  2. 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 is NATS_MAX_DELIVER (default 3).
  3. events_dead_lettered_total{topic,group} counts it. Alert on any increase. v0.7.4+: the series is present at 0 for every (topic, group) the bus consumes, from Register / Subscribe on, 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 that increase(...[10m]) > 0 sees. Before v0.7.4 the series appeared only with the first dead letter, already at 1, and increase() missed that one. The shared monitoring rule events_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 .dlq topics 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:

HeaderValue
x-dlq-groupthe consumer group whose handler failed
x-dlq-topicthe logical topic it came from
x-dlq-errorthe last handler error (≤ 1 KiB)
x-dlq-attemptsdeliveries before giving up
x-dlq-failed-atRFC 3339, UTC
x-dlq-transportkafka | 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=off turns dead-lettering off. Kafka then keeps redelivering (with the backoff); JetStream drops after MaxDeliver, as before.
  • Redis Streams (v0.7.1+) follows the same policy: a failed entry stays pending and each worker reclaims it after the backoff (XCLAIM with a minimum idle time, so one replica wins — including entries a dead consumer held), and after the last delivery it goes to <stream>.dlq and 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, package go-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.

VariableDefaultPurpose
EVENTS_DLQonoff keeps redelivering instead of dead-lettering
EVENTS_MAX_DELIVERIES10Kafka: failed deliveries before dead-lettering (JetStream uses NATS_MAX_DELIVER; with -1, this)
EVENTS_REDELIVERY_BACKOFF1swait before the first redelivery, doubling after each
EVENTS_REDELIVERY_BACKOFF_MAX5mcap 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.

MetricLabels
events_published_totalbus, topic, entity, action, result (ok | error)
events_consumed_totalbus, 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)
  • bus is the WithName value — default unless set; named buses use their EVENTS_BUSES entry.
  • topic is the logical topic, before KAFKA_TOPIC_PREFIX. Labels never carry entity or event ids.
  • transport (v0.8.0+) is kafka, nats, redis or memory — eventbus.TransportName(t): a transport implementing eventbus.TransportNamer names itself (a wrapper returns its inner transport's name), any other is named after its Go package. On memory a 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 (then other), 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, else unknown). A message a registration Filter rejects is not counted.
  • Return eventbus.ErrSkipped (or wrap it: fmt.Errorf("bad payload: %w", eventbus.ErrSkipped)) for a message you deliberately drop. The bus records skipped and 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):

go
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).

Consumers outside the bus — a worker that reads Kafka through its own sarama/franz loop (not 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)

PackageDescription
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.goEventClient — legacy top-level API

These remain for backward compatibility. New code should use eventbus/ and transport/.

Configuration (env vars)

Kafka

VariableDescriptionDefault
KAFKA_BOOTSTRAP_SERVERSComma-separated broker listlocalhost:9092
KAFKA_GROUP_IDConsumer group ID""
KAFKA_SECURITY_PROTOCOLplaintext | sasl_plaintext | sasl_ssl | sslplaintext
KAFKA_SASL_MECHANISMplain | scram-sha-256 | scram-sha-512""
KAFKA_SASL_USERNAMESASL username""
KAFKA_SASL_PASSWORDSASL password""
KAFKA_PRODUCER_IDEMPOTENTtrue turns the idempotent producer on — only for a producer that publishes from one goroutine (Broker-side dedupe)false (since v0.6.10)
KAFKA_TOPIC_RACKCreate 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_URLAsyncAPI schema endpoint for validation""

NATS

VariableDescriptionDefault
NATS_URLServer URL or comma-separated cluster URLsnats://localhost:4222
NATS_JETSTREAMtrue to enable durable JetStream deliveryfalse
NATS_CREDENTIALS_FILEPath to .creds file (NGS/Synadia accounts)""
NATS_NKEY_FILEPath to NKey seed file""
NATS_TLStrue to require TLSfalse
NATS_ACK_WAIT_SECONDSJetStream ack wait before redelivery30
NATS_MAX_DELIVERJetStream max redelivery attempts (-1 = unlimited)3

Outbox, dedupe and dead-letter variables: see Outbox, Idempotent consumers and Poison messages.

Redis Streams

VariableDescriptionDefault
REDIS_STREAMS_URLRedis URL (redis://host:port); falls back to REDIS_URLredis://localhost:6379
REDIS_STREAMS_BLOCK_MSXREADGROUP block duration in ms200
REDIS_STREAMS_BATCH_SIZEMessages per XREADGROUP fetch10
REDIS_STREAMS_MAX_LENMax stream length (0 = unlimited)10000

Build and test

shell
# 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:

TestContainer
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.

Was this page helpful?