Realtime Subscriptions, CDC & Pipelines
Durable SSE/gRPC/SpydWire live subscriptions, CDC change streams, ILM data streams, scheduled transforms, Kafka pipelines, and logical slots.
SpydDB includes an integrated durable logical change log (logical_max_bytes, logical_max_age_secs) powering five event-driven capabilities: Change Streams, Data Streams & ILM, Scheduled Transforms, Kafka Ingestion Pipelines, and Logical Replication Slots.
1. Change Streams (CDC Cursors)#
Subscribe to durable committed insert, update, and delete events with persistent named cursors stored atomically in the catalog:
-- 1. Register a persistent cursor tracking inserts & updates on `orders`
create change stream orders_cdc on orders kinds (insert, update)
-- 2. Read the next batch of committed events
read change stream orders_cdc limit 100
-- 3. Acknowledge processed sequence position atomically
ack change stream orders_cdc 4172
-- 4. Remove cursor when no longer needed
drop change stream if exists orders_cdcChange Event Record Shape#
| Column | Type | Meaning |
|---|---|---|
sequence | u64 | Strictly monotonic global commit log position |
time | timestamp | UTC commit timestamp |
kind | text | "insert", "update", or "delete" |
collection | text | Source collection name |
tenant | u64 | Physical tenant ID (or null) |
key | bytes | Canonical encoded primary key bytes |
before | json | Complete prior row mapped to current field names (null on insert) |
after | json | Complete new row mapped to current field names (null on delete) |
If an upstream schema renames a column, before and after resolve automatically to the current field names.
2. Data Streams & Index Lifecycle Management (ILM)#
Automate warm compression and age-out deletion based on each row's event-time timestamp field:
create data stream app_logs
on logs by ts
stages { hot, warm after 7d, cold after 30d, delete after 90d }
drop data stream if exists app_logsValidation guarantees:
- Policies must start at
hot. - Stage durations must strictly increase (
hot->warm->cold->delete). - The target field must be a
timestampcolumn. - Lifecycle deletions execute through the normal engine write path, so downstream change streams emit real
deleterecords.
Configure background tick cadence via lifecycle_interval_secs in server.json.
3. Scheduled Transforms#
Maintain continuously updated rollup tables in upsert or full replace mode:
create transform regional_sales
from orders | group by region | agg sum(total) as revenue, count() as orders
into sales_summary key region mode replace every 60s
-- Execute immediately on demand
run transform regional_sales
-- Clean up
drop transform if exists regional_sales| Mode | Behavior |
|---|---|
upsert | Updates or inserts rows currently produced by the source query without deleting prior rows |
replace | Updates produced rows and removes stale rows in the target key space that the source no longer outputs |
Enrich transform pipelines with standard SpydQL joins (e.g., | join regions on sales.region == regions.code).
4. Ingestion Pipelines (kafka, http, file)#
Stream records continuously from Apache Kafka topics, HTTP endpoints, or files into SpydDB collections with atomic checkpoint advancement (read -> optional SpydQL transform -> upsert into sink -> commit checkpoint):
create pipeline if not exists ingest_orders
from kafka "orders-topic" options (topic = "orders", group = "spyddb-ingest")
| pick ord, body.id as id, body.label as label, cast(body.total as decimal(12, 2)) as total
into orders_raw key id
on error dead letter orders_dlq
every 5s
-- Run one poll immediately on demand
run pipeline ingest_orders
drop pipeline if exists ingest_ordersSupported error policies (on error):
stop— halt batch and leave checkpoint unmoved (replays safely)retry— retry batch on next tickdead letter <collection>— route malformed/failed records into a dead-letter collection without blocking good records
Configure Kafka bootstrap servers (kafka_bootstrap) and polling cadence (pipeline_interval_secs) in server.json.
5. Windowed Stream Jobs (Tumbling & Hopping Watermarks)#
Run event-time tumbling or hopping (sliding) windowed aggregations continuously over any change stream, with configurable late-event tolerance (allowed lateness):
-- Create source change stream
create change stream events_stream on events
-- Tumbling 1-minute event-time window with 2-minute late-arrival watermark
create stream job if not exists traffic_1m
from stream events_stream
window tumbling 1m by ts
agg count() as total, avg(latency) as mean
into metrics key window_start
allowed lateness 2m
every 10s
-- Sliding / hopping 5-minute window advancing every 1 minute
create stream job if not exists traffic_5m_sliding
from stream events_stream
window hopping 5m slide 1m by ts
agg count() as total, max(latency) as p_max
into metrics_sliding key window_start
every 15s
-- Execute immediately or clean up
run stream job traffic_1m
drop stream job if exists traffic_1mSet background schedule cadence via stream_job_interval_secs in server.json.
6. Object-Store Archives (create archive) & External Lake Tables#
Offload historical subsets into queryable S3/MinIO object storage and read them in place without restoring:
create archive if not exists cold_orders
from orders
to "s3://telemetry-archive/orders/2025"
where placed_at < "2026-01-01T00:00:00Z"
drop archive if exists cold_ordersSee External Tables, Lakehouse & Connectors for Iceberg, Delta Lake, Hudi, Parquet, CSV, S3, and Kafka external table connectors.
7. Durable Realtime Subscriptions (SSE, gRPC & SpydWire)#
Stream live committed row changes directly to web apps, microservices, and Embedded Web Studio over Server-Sent Events (POST /v1/events/subscribe), gRPC (SubscribeEvents), or SpydWire (SPD2) — backed by SpydDB's durable commit journal and shard fan-in coordinator.
Enabling Realtime Subscriptions in server.json#
By default, realtime.auto_enable_local_journal is false (unactivated databases return 409 event_source_inactive until their commit journal is enabled). Set auto_enable_local_journal: true to activate the local commit journal automatically on the first subscription:
{
"realtime": {
"auto_enable_local_journal": true,
"max_event_streams": 10000,
"max_event_streams_per_tenant": 2000,
"max_event_streams_per_user": 100,
"max_event_payload_bytes": 262144,
"require_shard_fan_in": false
}
}Subscribing over HTTP SSE#
curl -N -fsS --cacert tls/ca.crt https://localhost:8080/v1/events/subscribe \
-H "Authorization: Bearer $SPYD_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-H "X-Spyd-Database: default" \
-d '{"collections":["orders"],"events":["insert","update","delete"]}'- Lifecycle events:
ready(cursor established),insert,update,delete,reconnect(with resumeid),resync_required,session_expired, andaccess_revoked. - Resumable cursors: Pass the last received event ID via the
Last-Event-IDheader to replay missed commits without gaps. - Browser
EventSourcetickets: Mint a short-lived ticket viaPOST /v1/events/ticketwhen connecting viaGET /v1/events/subscribe, or subscribe to a named stream viaGET /v1/streams/{name}/events. - Fail-closed security: Subscriptions enforce the caller's RBAC policies, tenant ownership, and time-bounded record grants; revocations or expired grants emit
access_revoked/session_expiredimmediately. - Sharded clusters: Set
require_shard_fan_in: trueonce all peers support/v1/cluster/events/shard-streamso managed distributed commits are verified against shard streams before live delivery.
8. Logical Replication Slots & Consistent Snapshots#
For external data warehouses (Snowflake, BigQuery, ClickHouse, DuckDB, Iceberg), bootstrap from a transactionally consistent snapshot.json + snapshot.ndjson export carrying the exact global sequence watermark, then stream every subsequent committed row change forward without gaps or overlaps.
See Replication & Backup for slot lifecycle and PITR workflows.