Persistent Message Streams and Reactive Watch Bus

Updated:
Author: Erkin Khidirov

Alongside its transactional KV store, the Slyber DB core includes a persistent message Streams engine and a reactive Watch event bus, enabling chat systems, durable job queues, and signaling pipelines for media servers such as Slyber SFU Server without deploying separate message brokers.

1. Persistent Message Streams

Each stream is addressed by the tuple (Namespace, PartKey, StreamKey), assigns strictly sequential message numbers (Seq = 1, 2, 3, ...), and records byte offsets in a dense 16-byte .sidx index for O(1) random seeks to any Seq.

Go
const nsStreams uint16 = 12
roomPK := []byte("room:alpha")
streamKey := []byte("events")

rec, err := cli.AppendStream(ctx, nsStreams, roomPK, streamKey, 77001, []byte("type:text"), []byte("First message"))

page, err := cli.ReadStream(ctx, db.StreamReadOptions{
	Namespace:    nsStreams,
	PartKey:      roomPK,
	StreamKey:    streamKey,
	AfterSeq:     0,
	BeforeSeq:    0,
	Limit:        100,
	Reverse:      false,
	OmitRedacted: false,
	WaitTimeout:  5 * time.Second,
	ReadMode:     db.ReadLinearizable,
})
if page.Gap {
	_ = page.FirstSeq
}

err = cli.PatchStream(ctx, nsStreams, roomPK, streamKey, 1, []byte("type:text"), []byte("Edited message"))

err = cli.RedactStream(ctx, nsStreams, roomPK, streamKey, 1)

err = cli.TrimStream(ctx, nsStreams, roomPK, streamKey, 500)

err = cli.CommitCursor(ctx, nsStreams, roomPK, streamKey, "push-dispatcher", page.HeadSeq)
lastAckSeq, err := cli.GetCursor(ctx, nsStreams, roomPK, streamKey, "push-dispatcher", db.ReadLinearizable)

err = cli.DeleteStream(ctx, nsStreams, roomPK, streamKey)

Core Stream Capabilities

  • Persistent deduplication (IdempKey): passing a non-zero idempKey to AppendStream checks a per-stream deduplication ring sized by StreamDedupCapacity (default 4096). Retrying the same publish after a network drop returns the original rec.Seq with rec.Duplicate == true instead of inserting a duplicate.
  • Long-polling waits (WaitTimeout): when a reader has caught up to the stream head (AfterSeq == HeadSeq), the server holds the call up to WaitTimeout and pushes new records immediately on commit (ignored when Reverse: true).
  • In-place editing (PatchStream): updates the Header and Payload of an existing Seq, setting StreamFlagPatched and UpdatedAt (out-of-bounds sequence numbers return ErrStreamSeqOutOfRange).
  • Physical erasure (RedactStream): supports GDPR compliance and "delete for everyone" workflows. The record is immediately masked with StreamFlagRedacted (Header = nil, Payload = nil), and background garbage collection repacks sealed segments into a new Copy-on-Write generation slog_*_g1.dat, permanently wiping the original bytes from disk.
  • History trimming and O(1) deletion: TrimStream drops messages with Seq < minSeq (direct reads return ErrStreamTrimmed, while paged reads flag page.Gap = true), and DeleteStream clears an entire stream in O(1) so subsequent appends cleanly restart at Seq = 1.

2. Reactive Subscriptions (Watch)

The Watch bus delivers real-time WatchEventPut, WatchEventDelete, and WatchEventDeleteRange notifications:

  • Partition-scoped watch (partKey != nil): subscribes directly to the leader owning the target partition.
  • Cluster-wide watch (partKey == nil): the client automatically opens subscriptions across all nodes in the Multi-Raft cluster with FlagLeaderOnly, ensuring every mutation is delivered exactly once without duplicate events from followers.
Go
watchCtx, cancelWatch := context.WithCancel(ctx)
defer cancelWatch()

watcher, err := cli.Watch(watchCtx, 10, []byte("org:acme"), []byte("u:"), lastSeenVersion)
if err != nil {
	log.Fatal(err)
}
defer watcher.Close()

for ev := range watcher.Events() {
	switch ev.Type {
	case db.WatchEventPut:
		_ = ev.Value
	case db.WatchEventDelete:
		_ = ev.Key
	case db.WatchEventDeleteRange:
		_ = ev.AuxKey
	}
	lastSeenVersion = ev.Version
}

if errors.Is(watcher.Err(), db.ErrWatchLagged) {
	return
}

Passing afterVersion > 0 on reconnect replays missed recent events from the server ring buffer without gaps. If a slow consumer overflows WatchBufferSize and receives db.ErrWatchLagged, run a fresh Scan and resubscribe from the updated version.