Realtime Subscriptions, CDC & Pipelines

Durable SSE/gRPC/SpydWire live subscriptions, CDC change streams, ILM data streams, scheduled transforms, Kafka pipelines, and logical slots.

4 min read SpydQL & Data Modeling

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:

spydql
-- 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_cdc

Change Event Record Shape#

ColumnTypeMeaning
sequenceu64Strictly monotonic global commit log position
timetimestampUTC commit timestamp
kindtext"insert", "update", or "delete"
collectiontextSource collection name
tenantu64Physical tenant ID (or null)
keybytesCanonical encoded primary key bytes
beforejsonComplete prior row mapped to current field names (null on insert)
afterjsonComplete 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:

spydql
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_logs

Validation guarantees:

  • Policies must start at hot.
  • Stage durations must strictly increase (hot -> warm -> cold -> delete).
  • The target field must be a timestamp column.
  • Lifecycle deletions execute through the normal engine write path, so downstream change streams emit real delete records.

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:

spydql
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
ModeBehavior
upsertUpdates or inserts rows currently produced by the source query without deleting prior rows
replaceUpdates 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):

spydql
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_orders

Supported error policies (on error):

  • stop — halt batch and leave checkpoint unmoved (replays safely)
  • retry — retry batch on next tick
  • dead 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):

spydql
-- 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_1m

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

spydql
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_orders

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

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

bash
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 resume id), resync_required, session_expired, and access_revoked.
  • Resumable cursors: Pass the last received event ID via the Last-Event-ID header to replay missed commits without gaps.
  • Browser EventSource tickets: Mint a short-lived ticket via POST /v1/events/ticket when connecting via GET /v1/events/subscribe, or subscribe to a named stream via GET /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_expired immediately.
  • Sharded clusters: Set require_shard_fan_in: true once all peers support /v1/cluster/events/shard-stream so 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.