Topic is a named, schema-validated stream of domain events. Topics support live pub/sub subscriptions, durable catch-up-and-tail replay from sequence numbers, compile-time checked wildcard matching, and transactional outbox delivery alongside database writes.
Use Topic when multiple independent consumers, such as views, projections, policies, analytics, or webhooks, must react to domain events. For single-consumer background jobs with retries and dead-letter queues, see JobQueue.
Declaring a topic
Plain TypeScript SDK (@chimp-labs/keel/sdk)
import { k } from "@chimp-labs/keel/sdk"
export const OrderPlacedTopic = k.topic(
"acme.orders.placed",
k.object({
orderId: k.string(),
userId: k.string(),
totalCents: k.int(),
})
)
// Automatically derive a durable CDC topic from any Table with trackChanges: true
export const OrdersChangedTopic = k.tableChangeTopic(OrdersTable)
// Evolve an existing topic without mutating historical events using chained upcasters
export const OrderPlacedV2Topic = k.topic(
"acme.orders.placed",
k.object({
orderId: k.string(),
userId: k.string(),
totalCents: k.int(),
currency: k.string(),
}),
{
schemaVersion: 2, // stamped into `x-keel-schema-version` header on publish
upcasters: [
{ from: 1, to: 2, upcast: (e) => ({ ...e, currency: "BRL" }) },
],
}
)
[!TIP] See Event Versioning & Upcasting for chained upcasters from v1 to v2 to v3, expand-contract pipelines, and snapshot
stateVersioninvalidation.
Effect v4 (@chimp-labs/keel/topic)
import { Schema } from "effect"
import { Topic } from "@chimp-labs/keel/topic"
export class StockChangedEvent extends Schema.TaggedClass<StockChangedEvent>()(
"StockChangedEvent",
{ sku: Schema.String, delta: Schema.Int }
) {}
export class StockChangedTopic extends Topic(
"acme.inv.changed",
StockChangedEvent
) {}
Attaching to a service
export const OrdersService = k.service("orders", {
resources: [OrdersTable, OrderPlacedTopic],
operations: { /* ... */ },
})
Operations reference
Publish and live subscribe
// Publish an event immediately (returns EventEnvelope with id, sequence, timestamp)
const envelope = await keel.orderPlaced.publish({
orderId: "ord_1",
userId: "usr_1",
totalCents: 4500,
})
// Live pub/sub stream (stops automatically when AbortSignal aborts)
const controller = new AbortController()
for await (const ev of keel.orderPlaced.subscribe({ signal: controller.signal })) {
console.log(ev.sequence, ev.payload.orderId)
}
Durable replay and catch-up-and-tail
When backed by an EventStore on Memory, PostgreSQL 17, SQLite, or SurrealDB 4, consumers can replay past events from any sequence cursor and continue into live events without gaps:
// Replay historical events only (after sequence 0, live: false)
for await (const ev of keel.orderPlaced.durable({ after: 0, live: false })) {
console.log("Replayed:", ev.sequence, ev.payload)
}
// Catch up from a saved checkpoint and keep tailing live events
for await (const ev of keel.orderPlaced.catchUpAndTail({ after: lastSeq, signal })) {
await processEvent(ev)
}
Atomic transactional outbox
Write a database row and enqueue its domain event inside the same ACID transaction to prevent dual-write inconsistency. If the transaction rolls back, the relay never publishes the event:
await keel.transaction(async (tx) => {
const order = await tx.orders.insert({ userId, totalCents: 4500 })
await tx.orderPlaced.enqueueOutbox({
orderId: order.id,
userId,
totalCents: 4500,
})
})
// Relay pending outbox rows manually in tests, or run a push/poll relay daemon in prod
await keel.outbox.relayOnce()
const relay = await keel.outbox.startRelay({ mode: "push" })
Compile-time wildcard pattern subscriptions (Effect)
In Effect v4, subscribePattern and durablePatternStream check wildcard patterns at compile time. Typos such as "acme.invo.*" fail typechecking, and valid patterns narrow envelope.payload to the exact union of matching topics:
import { subscribePattern } from "@chimp-labs/keel/topic"
const Topics = [OrderPlacedTopic, OrderShippedTopic, StockChangedTopic] as const
// Narrowed automatically to OrderPlaced | OrderShipped
yield* subscribePattern(Topics, "acme.orders.*", (env) =>
Effect.logInfo(`Order event: ${env.subject}`)
)
SDK and Effect API mapping
SDK method (keel.<topic>.*) |
Effect function (@chimp-labs/keel/topic / outbox) |
Description |
|---|---|---|
publish(event) |
publish(topic, event) |
Validate and publish an event, returning an EventEnvelope. |
subscribe({ signal? }) |
liveStream(topic) / subscribe(topic, fn) |
Open an ephemeral live event stream. |
durable({ after?, live? }) |
durableStream(topic, opts) |
Replay durable events with an optional live tail. |
catchUpAndTail({ after? }) |
durableStream(topic, { after, live: true }) |
Replay from a cursor and then tail live events. |
enqueueOutbox(event) |
enqueueOutboxEvent(topic, event) |
Write an event to keel_outbox inside an active transaction. |
keel.outbox.relayOnce() |
relayOutboxOnce() |
Publish pending outbox rows once. |
keel.outbox.startRelay(opts) |
startOutboxRelay(opts) |
Start a scoped push or poll outbox relay daemon. |
| Effect only | subscribePattern / durablePatternStream |
Run compile-time checked wildcard subscriptions. |
Errors and failure modes
| Error tag | Category | HTTP status | Retryable | When it occurs |
|---|---|---|---|---|
EventTransportError |
internal |
500 |
Yes | Event bus or event store publish or subscribe failed. |
OutboxError |
internal |
500 |
Yes | Outbox table write or relay failed. |
SchemaError |
invalid |
400 |
No | The event payload failed schema validation. |
Backends and infrastructure
- Memory runs in-process pub/sub with an append-only sequence log and an in-process
OutboxNotifierpush relay. - PostgreSQL 17, using
KeelPostgresLive,EventPostgresLive, orbackend: "postgres", stores an append-onlykeel_eventslog with aBIGSERIALsequence andkey,partition, andheaderscolumns. It delivers catch-up-and-tail subscriptions throughLISTEN/NOTIFYand sendspg_notifyoutbox notifications onCOMMIT. - SQLite stores a persistent event log and a transactional
keel_outboxtable. - SurrealDB 4 stores a persistent event log and pushes live subscriptions through
LIVE SELECTwithout polling.
Testing in memory
await using keel = await createKeel({
backend: "memory",
resources: { orders: OrdersTable, orderPlaced: OrderPlacedTopic },
ensureAll: true,
})
await keel.transaction(async (tx) => {
const order = await tx.orders.insert({ userId: "u1", totalCents: 2000 })
await tx.orderPlaced.enqueueOutbox({
orderId: order.id,
userId: "u1",
totalCents: 2000,
})
})
await keel.outbox.relayOnce()
const seen: string[] = []
for await (const ev of keel.orderPlaced.durable({ after: 0, live: false })) {
seen.push(ev.payload.orderId)
}
// seen.length === 1