Keel by ChimpLabs
Jump to page or section Esc
Primitives

DurableStream

Typed, durable, append-only streams with monotonic seqNum, optimistic CAS (412), leader fencing, trimming, long-polling, live tailing, and tenant isolation across Memory, S2 (s2-lite or s2.dev Cloud), and NATS JetStream, capable of backing Topic.

DurableStream (@chimp-labs/keel-streams) is a schema-typed, append-only stream package built on Keel’s Open Plugin Protocol (KeelKindSym, KeelInfraSym, KeelDefaultLayerSym, KeelEnsureSym, KeelTenantLifecycleSym, and KeelBindSym).

Use DurableStream for resumable AI agent token and tool streams, live CI and build logs, collaborative sync feeds, per-entity append logs, and the backing log underneath Topic.

A single DurableStream declaration, along with any Topic backed by it, runs on three backends without application code changes:

  • DurableStreamMemoryLive (@chimp-labs/keel-streams) is an in-memory backend with no external dependencies for 10 ms unit and integration tests.
  • DurableStreamS2Live (@chimp-labs/keel-streams/s2) is an S2 v1 HTTP and SSE client with no extra dependencies that targets self-hosted s2-lite (ghcr.io/s2-streamstore/s2 lite) or managed s2.dev Cloud.
  • DurableStreamNatsLive (@chimp-labs/keel-streams/nats) uses NATS JetStream with NATS KV fencing on self-hosted nats -js or Synadia Cloud / NGS.

When to use DurableStream

Component Best for Key semantics
DurableStream Resumable AI agent runs, build and deploy logs, per-session feeds, and backing logs Arbitrary dynamic stream keys in a basin, monotonic seqNum, matchSeqNum CAS (412), fencingToken leader fencing (412), trim, ?wait long-poll, and live tailing.
Topic Service-to-service pub/sub and fan-out Subject wildcards (orders.*), durable replay, schema upcasting, and transactional outbox. Optionally backed by TopicDurableStreamLive.

Installation

Install @chimp-labs/keel-streams alongside @chimp-labs/keel. DurableStream and DurableStreamS2Live have no extra runtime dependencies:

pnpm add @chimp-labs/keel @chimp-labs/keel-streams effect

To use the NATS JetStream backend (@chimp-labs/keel-streams/nats), install the NATS.js v3 peer packages:

pnpm add @nats-io/transport-node @nats-io/jetstream @nats-io/kv

1. Declaring a DurableStream

A DurableStream declares a basin namespace with an Effect Schema that validates every appended and read record, along with retention, timestamping, and optional multi-tenant scoping:

import { Schema } from "effect"
import { DurableStream } from "@chimp-labs/keel-streams"

export const AgentChunkSchema = Schema.Struct({
  type: Schema.Literals(["token", "tool", "done"]),
  text: Schema.String,
})

export const AgentRuns = DurableStream("agent_runs", {
  schema: AgentChunkSchema,
  retention: "7 days",           // Duration or "infinite" (default: "7 days")
  deleteOnEmptyAfter: "1 day",   // Optional auto-cleanup of empty streams
  timestamping: "client-prefer", // "client-prefer" | "client-require" | "arrival"
  storageClass: "express",       // "express" | "standard"
  createOnRead: true,            // Auto-create stream if reader arrives before first append
  tenantScoped: true,            // Auto-prefix keys with `${CurrentTenant.tenantId}/`
})

[!TIP] You can also use class-extension syntax (export class AgentRuns extends DurableStream("agent_runs", { ... }) {}) or import from the subpath @chimp-labs/keel-streams/durable-stream.

Configuration options

Option Type Default Description
schema Schema.Codec<A, I, never, never> Required Effect Schema that validates every record on encode (append) and decode (read or tail).
basin string Sanitized name Explicit basin name ([a-z0-9-], 3 to 48 characters).
retention Duration.Input | "infinite" "7 days" Record retention policy ({ age } in seconds or { infinite: {} }).
deleteOnEmptyAfter Duration.Input Disabled (0) Reaps empty streams after this inactivity duration.
timestamping "client-prefer" | "client-require" | "arrival" "client-prefer" How record timestamps in epoch milliseconds are assigned on append.
storageClass "express" | "standard" "express" Storage class hint for S2 basins.
createOnRead boolean true Creates a stream key when a reader or subscriber arrives before the first append.
tenantScoped boolean false Prefixes every stream key with ${CurrentTenant.tenantId}/ and fails closed with TenantContextMissingError when CurrentTenant is absent.

2. Plain TypeScript SDK (@chimp-labs/keel/sdk)

Passing DurableStream descriptors into createKeel({ resources }) wires DurableStreamMemoryLive by default and binds a typed async/await and AsyncIterable client onto keel.<key>:

import { Schema } from "effect"
import { DurableStream } from "@chimp-labs/keel-streams"
import { createKeel } from "@chimp-labs/keel/sdk"

const BuildLogs = DurableStream("build_logs", {
  schema: Schema.Struct({ line: Schema.String }),
  retention: "1 day",
})

const keel = await createKeel({
  backend: "memory",
  resources: { buildLogs: BuildLogs },
  ensureAll: true,
})

// Append a typed batch
const ack = await keel.buildLogs.append("build-42", [
  { line: "compiling..." },
  { line: "done!" },
])
console.log(ack.tail.seq_num) // 2

// Read from seqNum 0
const page = await keel.buildLogs.read("build-42", { seqNum: 0 })
console.log(page.records.map((r) => r.value.line)) // ["compiling...", "done!"]

// Live replay + push tailing via AsyncIterable
for await (const record of keel.buildLogs.tail("build-42", { seqNum: 0, count: 2 })) {
  console.log(record.seqNum, record.value.line)
}

// List streams in this basin & clean up
const listed = await keel.buildLogs.list({ prefix: "build-" })
await keel.buildLogs.delete("build-42")
await keel.close()

Swapping streaming backends in createKeel

Set streaming on createKeel(...) to wire DurableStream and Topic (EventBus and durable EventStore log) onto Memory, s2-lite, s2.dev Cloud, or NATS JetStream:

// Option A: Self-hosted s2-lite Docker container
const s2LiteKeel = await createKeel({
  streaming: {
    backend: "s2",
    endpoint: "http://127.0.0.1:8088",
  },
  resources: { agentRuns: AgentRuns },
  ensureAll: true,
})

// Option B: Managed s2.dev Cloud
const s2CloudKeel = await createKeel({
  streaming: {
    backend: "s2",
    accessToken: process.env.S2_ACCESS_TOKEN!,
    accountEndpoint: "https://aws.s2.dev",
    basinEndpoint: "https://{basin}.b.aws.s2.dev",
  },
  resources: { agentRuns: AgentRuns },
  ensureAll: true,
})

// Option C: NATS JetStream (local Docker or Synadia Cloud / NGS)
const natsKeel = await createKeel({
  streaming: {
    backend: "nats",
    servers: process.env.NATS_URL ?? "nats://127.0.0.1:4222",
    token: process.env.NATS_TOKEN,
  },
  resources: { agentRuns: AgentRuns },
  ensureAll: true,
})

Bound SDK methods (BoundDurableStream)

Method Signature Description
ensure() () => Promise<void> Creates or verifies the basin configuration idempotently.
append(key, values, options?) Promise<DurableStreamAppendAck> Validates and appends one or more records and returns { start, end, tail }.
checkTail(key) Promise<DurableStreamPosition> Returns { seq_num, timestamp } for the next sequence position.
read(key, options?) Promise<DurableStreamReadResult<A>> Reads a bounded batch of decoded records, with optional ?wait long-polling.
tail(key, options?) AsyncIterable<DurableStreamRecord<A>> Replays from an offset and then streams live records.
fence(key, token, options?) Promise<DurableStreamAppendAck> Sets the active leader epoch token for single-writer fencing.
trim(key, trimSeqNum, options?) Promise<DurableStreamAppendAck> Advances the minimum readable seqNum for compaction or purging.
list(options?) Promise<{ streams, hasMore }> Lists stream keys with optional prefix, startAfter, and limit filters.
delete(key) Promise<void> Deletes a stream and its records.

3. Effect v4 API (@chimp-labs/keel-streams)

All typed operations accept a DurableStream descriptor and require DurableStreamBackend:

import { Effect, Stream } from "effect"
import { withTenant } from "@chimp-labs/keel"
import {
  appendStream,
  checkStreamTail,
  deleteDurableStream,
  DurableStreamMemoryLive,
  ensureDurableStream,
  fenceStream,
  listDurableStreams,
  readStream,
  tailStream,
  trimStream,
} from "@chimp-labs/keel-streams"

const program = Effect.gen(function* () {
  yield* ensureDurableStream(AgentRuns)

  const ack = yield* withTenant(
    "tenant_acme",
    appendStream(AgentRuns, "run-1", [
      { type: "token", text: "Hello" },
      { type: "token", text: " world" },
    ])
  )

  const tail = yield* withTenant("tenant_acme", checkStreamTail(AgentRuns, "run-1"))
  const batch = yield* withTenant("tenant_acme", readStream(AgentRuns, "run-1", { seqNum: 0 }))

  return { ack, tail, count: batch.records.length }
}).pipe(Effect.provide(DurableStreamMemoryLive))

Read and tail options

Option Type Available in Description
seqNum number readStream, tailStream Starts reading inclusively at this sequence number (default 0).
tailOffset number readStream, tailStream Starts tailOffset records before the current tail (for example, the last 10 records).
timestamp number readStream, tailStream Starts at the first record with timestamp >= value in epoch milliseconds.
count number readStream, tailStream Maximum number of records to return or emit before closing the stream.
bytes number readStream, tailStream Maximum metered bytes to return or emit.
until number readStream, tailStream Exclusive upper bound on record timestamp in epoch milliseconds.
clamp boolean readStream, tailStream Clamps seqNum when it falls before the trim point or past the tail instead of failing with 416.
wait number readStream Long-polls up to wait seconds (0 to 60) when at the tail and returns when new records arrive.

4. Backing Topic with DurableStream

Topic (EventBus and durable replay log) and Outbox relays can store their underlying event stream in any DurableStreamBackend:

import { Layer } from "effect"
import { KeelMemoryLive } from "@chimp-labs/keel"
import { TopicDurableStreamLive } from "@chimp-labs/keel-streams"
import { KeelS2StreamingLive } from "@chimp-labs/keel-streams/s2"
import { KeelNatsStreamingLive } from "@chimp-labs/keel-streams/nats"

// One-line S2 / s2-lite streaming bundle (DurableStream + Topic)
const S2AppLayer = Layer.merge(
  KeelMemoryLive,
  KeelS2StreamingLive({ endpoint: "http://127.0.0.1:8088" })
)

// One-line NATS JetStream bundle (DurableStream + Topic)
const NatsAppLayer = Layer.merge(
  KeelMemoryLive,
  KeelNatsStreamingLive({ servers: "nats://127.0.0.1:4222" })
)

// Or compose TopicDurableStreamLive selectively on top of an existing DurableStreamBackend
const TopicOnlyLayer = TopicDurableStreamLive({ basin: "prod-topics" })

5. Concurrency control, leader fencing, and trimming

DurableStream supports optimistic CAS, leader fencing, and trimming across Memory, S2 (s2-lite and s2.dev Cloud), and NATS JetStream.

Optimistic concurrency (matchSeqNum, HTTP 412)

Pass matchSeqNum to ensure no concurrent writer appended between your read and write. If the tail sequence number differs, appendStream fails with DurableStreamPreconditionFailedError (code: "seq_num_mismatch"):

yield* appendStream(AgentRuns, "run-1", [{ type: "token", text: "next" }], {
  matchSeqNum: 2, // Succeeds only if current tail.seq_num === 2
})

Single-writer fencing (fenceStream and fencingToken, HTTP 412)

When a new worker takes over an active stream, for example after a crash or lease failover, call fenceStream with a new epoch token. DurableStream rejects any stale writer presenting an older fencingToken with DurableStreamPreconditionFailedError (code: "fencing_token_mismatch"):

// New leader establishes epoch 3 (consumes 1 seqNum as an internal fence command record)
yield* fenceStream(AgentRuns, "run-1", "worker-epoch-3")

// Zombie writer with epoch 2 fails with 412 DurableStreamPreconditionFailedError
// Active leader succeeds (can combine fencingToken + matchSeqNum together!)
yield* appendStream(AgentRuns, "run-1", [{ type: "done", text: "!" }], {
  fencingToken: "worker-epoch-3",
  matchSeqNum: 3,
})

Compaction and trimming (trimStream, HTTP 416 or clamp: true)

Advance the stream’s readable start sequence with trimStream. Readers that request a trimmed or out-of-range seqNum receive DurableStreamRangeNotSatisfiableError (416) unless they pass clamp: true. readStream and tailStream filter out internal command records (["", "fence"] and ["", "trim"]) during decoding:

yield* trimStream(AgentRuns, "run-1", 1, { fencingToken: "worker-epoch-3" })

// Skips trimmed records & internal command records automatically
const res = yield* readStream(AgentRuns, "run-1", { seqNum: 0, clamp: true })

6. Running self-hosted s2-lite and NATS JetStream

Self-hosted s2-lite (ghcr.io/s2-streamstore/s2)

Run s2-lite in memory, on local disk, or on S3, Garage, or R2:

# In-memory (default, fastest for local dev & CI)
docker run --rm -p 8088:80 ghcr.io/s2-streamstore/s2 lite

# Persistent local disk (SlateDB)
docker run --rm -p 8088:80 -v s2_data:/data ghcr.io/s2-streamstore/s2 lite --local-root /data

# S3 / Garage / R2 object storage
docker run --rm -p 8088:80 \
  -e AWS_ACCESS_KEY_ID=... -e AWS_SECRET_ACCESS_KEY=... \
  ghcr.io/s2-streamstore/s2 lite --bucket my-streams-bucket
DurableStreamS2Config option Default Description
endpoint None Shorthand base URL for s2-lite that sets both accountEndpoint and basinEndpoint.
accessToken "ignored" Bearer token (s2_live_... for s2.dev Cloud; ignored locally by s2-lite).
accountEndpoint endpoint ?? "https://aws.s2.dev" Account control-plane base URL (/v1/basins).
basinEndpoint endpoint ?? "https://{basin}.b.aws.s2.dev" Basin data-plane URL ({basin} template or S2-Basin header).
fetch globalThis.fetch Optional custom Fetch implementation.

NATS JetStream (nats:2.10-alpine)

# Local NATS server with JetStream enabled
docker run --rm -p 4222:4222 -p 8222:8222 nats:2.10-alpine -js -m 8222
DurableStreamNatsConfig option Default Description
servers Required NATS URL or array of URLs (for example, "nats://127.0.0.1:4222").
token / user / pass / creds / nkeySeed Optional Authentication options, including Synadia Cloud / NGS .creds.
streamPrefix "keel_ds" Prefix for JetStream stream names.
kvPrefix "keel_ds_meta" Prefix for per-basin NATS KV metadata and leader fencing buckets.
storage "file" JetStream storage engine ("file" | "memory").
replicas 1 JetStream replication factor (num_replicas).

[!NOTE] Both s2-lite (localhost:8088) and nats (localhost:4222) are preconfigured in the repository’s root docker-compose.yml (docker compose up -d s2-lite nats).


7. Multi-tenancy (tenantScoped: true)

When tenantScoped: true is set:

  1. Every operation requires ambient CurrentTenant (keel.asTenant(tenantId, fn) in the SDK or withTenant(tenantId, effect) in Effect v4) and fails closed with TenantContextMissingError when absent.
  2. DurableStream stores stream keys as ${tenantId}/${key} inside the basin. listDurableStreams filters by ${tenantId}/ and strips the prefix from returned keys so tenants do not see other tenants’ streams.
  3. DurableStream also implements [KeelTenantLifecycleSym] so custom multi-tenant export and erasure workflows can inspect or purge all streams under ${tenantId}/.

8. Typed errors and HTTP status classification

Every error in DurableStreamFailure carries [KeelErrorMetaSym], so classifyKeelError / reportCause and framework adapters such as @chimp-labs/keel-nestjs map each error to the HTTP status code listed below:

Error tag HTTP status Category Retryable When it occurs
DurableStreamSchemaError 400 invalid No Record failed Effect Schema encode on append or decode on read or tail.
DurableStreamBadRequestError 400 invalid No Invalid stream name, empty append batch, or invalid query parameter.
TenantContextMissingError 400 invalid No Operation called on a tenantScoped: true stream without CurrentTenant.
DurableStreamForbiddenError 403 forbidden No Access token lacks permission for the basin or stream operation.
DurableStreamNotFoundError 404 not_found No Basin or stream does not exist when createOnRead: false.
DurableStreamConflictError 409 conflict No Conflicting resource state or basin/stream creation race.
DurableStreamPreconditionFailedError 412 conflict No matchSeqNum (seq_num_mismatch) or fencingToken (fencing_token_mismatch) check failed.
DurableStreamRangeNotSatisfiableError 416 invalid No Requested seqNum is before trim_seq_num or past tail without clamp: true.
DurableStreamError 500 internal Yes Underlying storage, network, NATS, or SSE transport failure.

9. Infrastructure inference and in-memory testing

inferKeelInfra reports DurableStream metadata under infra.extensions.durableStreams without creating database tables or locks:

import { inferKeelInfra } from "@chimp-labs/keel"

const infra = inferKeelInfra([AgentRuns])
// infra.needsDatabase === false
// infra.extensions.durableStreams -> [{ name: "agent_runs", basinName: "agent-runs", tenantScoped: true, storageClass: "express" }]

DurableStreamMemoryLive runs in memory with no external dependencies or containers. End-to-end tests covering CAS, fencing, trimming, tenant isolation, and live tailStream finish in under 20 ms:

import { createKeel } from "@chimp-labs/keel/sdk"

const keel = await createKeel({
  backend: "memory",
  streaming: "memory",
  resources: { agentRuns: AgentRuns },
  ensureAll: true,
})

await keel.asTenant("tenant_a", async () => {
  const ack = await keel.agentRuns.append("run-1", [{ type: "token", text: "hi" }])
  expect(ack.tail.seq_num).toBe(1)
})

await keel.close()