NEW

Streaming Queries

Real-time query subscriptions via WebSocket and Server-Sent Events. Stream continuous query results to clients as new data arrives, enabling live dashboards, alerting pipelines, and real-time data feeds.

⚡ Push-Based Query Results

Streaming queries automatically re-execute at a configurable interval and push new results to connected clients. Unlike polling, streaming subscriptions maintain a persistent connection and deliver updates with minimal latency.

WebSocket Subscriptions

WebSocket subscriptions provide full-duplex communication for real-time query streaming. Clients connect to the WebSocket endpoint, send a SQL subscription message, and receive continuous result updates.

Endpoint

URL ws://host:port/ws/query/:db
Protocol WebSocket (RFC 6455)
Message Format JSON

Subscription Message

After connecting, send a JSON message to start a streaming subscription:

json
{
  "sql": "SELECT host, AVG(usage) as avg_cpu FROM cpu WHERE time > now() - interval '5 minutes' GROUP BY host",
  "interval_ms": 5000,
  "format": "json"
}
Field Type Required Description
sql string Yes SQL query to execute on each interval
interval_ms integer No Re-execution interval in milliseconds (default: 1000)
format string No Result format: json or arrow (default: json)

JavaScript Example

javascript
// Connect to the WebSocket streaming endpoint
const ws = new WebSocket("ws://localhost:7000/ws/query/mydb");

ws.onopen = () => {
  console.log("Connected to MynaDB streaming");

  // Subscribe to a streaming query
  ws.send(JSON.stringify({
    sql: "SELECT host, AVG(usage) as avg_cpu FROM cpu WHERE time > now() - interval '5 minutes' GROUP BY host",
    interval_ms: 5000
  }));
};

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);

  if (message.type === "result") {
    // Query result received
    console.log("Subscription:", message.subscription_id);
    console.log("Rows:", message.data.length);
    message.data.forEach(row => {
      console.log(`  ${row.host}: ${row.avg_cpu.toFixed(2)}%`);
    });
  } else if (message.type === "heartbeat") {
    // Connection keep-alive
    console.log("Heartbeat received");
  } else if (message.type === "error") {
    console.error("Stream error:", message.message);
  }
};

ws.onclose = (event) => {
  console.log(`Connection closed: ${event.code} ${event.reason}`);
};

ws.onerror = (error) => {
  console.error("WebSocket error:", error);
};

Response Messages

The server sends the following message types:

json
// Subscription confirmed
{
  "type": "subscribed",
  "subscription_id": "sub_a1b2c3d4",
  "sql": "SELECT host, AVG(usage) ...",
  "interval_ms": 5000
}

// Query result
{
  "type": "result",
  "subscription_id": "sub_a1b2c3d4",
  "timestamp": 1704067200000,
  "data": [
    {"host": "server-01", "avg_cpu": 45.2},
    {"host": "server-02", "avg_cpu": 62.8}
  ],
  "row_count": 2,
  "execution_time_ms": 12
}

// Heartbeat
{
  "type": "heartbeat",
  "timestamp": 1704067230000
}

// Error
{
  "type": "error",
  "subscription_id": "sub_a1b2c3d4",
  "message": "Table 'cpu' not found"
}

Server-Sent Events (SSE)

Server-Sent Events provide a simpler, HTTP-based streaming mechanism. SSE is ideal for browser clients that only need to receive data (one-way communication) and want automatic reconnection built into the protocol.

Endpoint

URL GET /stream/query/:db?sql=...&interval_ms=...
Content-Type text/event-stream
Method GET
Parameter Type Required Description
sql string (query) Yes URL-encoded SQL query
interval_ms integer (query) No Re-execution interval in milliseconds (default: 1000)

curl Example

bash
# Stream query results every 5 seconds
curl -N "http://localhost:7000/stream/query/mydb?sql=SELECT%20host%2C%20AVG(usage)%20as%20avg_cpu%20FROM%20cpu%20WHERE%20time%20%3E%20now()%20-%20interval%20'5%20minutes'%20GROUP%20BY%20host&interval_ms=5000"

# Output (Server-Sent Events format):
# event: result
# id: 1
# data: {"data":[{"host":"server-01","avg_cpu":45.2}],"row_count":1,"execution_time_ms":8}
#
# event: result
# id: 2
# data: {"data":[{"host":"server-01","avg_cpu":47.1}],"row_count":1,"execution_time_ms":6}

JavaScript EventSource API

javascript
// Build the SSE URL with query parameters
const sql = encodeURIComponent(
  "SELECT host, AVG(usage) as avg_cpu FROM cpu WHERE time > now() - interval '5 minutes' GROUP BY host"
);
const url = `http://localhost:7000/stream/query/mydb?sql=${sql}&interval_ms=5000`;

// Create EventSource connection (auto-reconnects on failure)
const source = new EventSource(url);

// Listen for query results
source.addEventListener("result", (event) => {
  const result = JSON.parse(event.data);
  console.log(`Received ${result.row_count} rows in ${result.execution_time_ms}ms`);

  result.data.forEach(row => {
    console.log(`  ${row.host}: ${row.avg_cpu.toFixed(2)}%`);
  });
});

// Listen for heartbeats
source.addEventListener("heartbeat", (event) => {
  console.log("Heartbeat:", event.data);
});

// Handle errors
source.onerror = (error) => {
  console.error("SSE connection error:", error);
  // EventSource will automatically attempt to reconnect
};

// To stop streaming
// source.close();
🔄 WebSocket vs SSE

WebSocket is best when you need bidirectional communication (e.g., dynamically changing queries, managing multiple subscriptions on one connection). SSE is simpler for read-only streams and provides built-in reconnection in browsers via the EventSource API.

Subscription Management

Active streaming subscriptions can be listed and canceled through the management API. This is useful for monitoring resource usage and terminating runaway queries.

List Active Subscriptions

bash
# List all active streaming subscriptions
curl http://localhost:7000/stream/subscriptions

# Response:
# {
#   "subscriptions": [
#     {
#       "id": "sub_a1b2c3d4",
#       "database": "mydb",
#       "sql": "SELECT host, AVG(usage) ...",
#       "interval_ms": 5000,
#       "protocol": "websocket",
#       "created_at": "2026-01-15T10:30:00Z",
#       "last_execution": "2026-01-15T10:35:00Z",
#       "execution_count": 60,
#       "avg_execution_time_ms": 11
#     }
#   ],
#   "count": 1
# }

Cancel a Subscription

bash
# Cancel a specific subscription by ID
curl -X DELETE http://localhost:7000/stream/subscriptions/sub_a1b2c3d4

# Response:
# {"status": "canceled", "subscription_id": "sub_a1b2c3d4"}

# Cancel all subscriptions for a database
curl -X DELETE http://localhost:7000/stream/subscriptions?database=mydb

# Response:
# {"status": "canceled", "count": 3}

WebSocket Subscription Control

You can also manage subscriptions directly over an active WebSocket connection:

javascript
// Cancel a specific subscription over the WebSocket
ws.send(JSON.stringify({
  action: "cancel",
  subscription_id: "sub_a1b2c3d4"
}));

// Pause a subscription (stop execution, keep connection)
ws.send(JSON.stringify({
  action: "pause",
  subscription_id: "sub_a1b2c3d4"
}));

// Resume a paused subscription
ws.send(JSON.stringify({
  action: "resume",
  subscription_id: "sub_a1b2c3d4"
}));

// List active subscriptions on this connection
ws.send(JSON.stringify({
  action: "list"
}));

Configuration

Streaming queries are configured in the [streaming] section of config.toml.

toml
[streaming]
# Enable streaming query endpoints (WebSocket and SSE)
enabled = true

# Maximum number of concurrent streaming subscriptions per server
max_subscriptions = 100

# Heartbeat interval in seconds (keeps connections alive)
heartbeat_interval_secs = 30

# Internal buffer size per subscription (number of result sets)
buffer_size = 16
Parameter Default Description
enabled true Enable or disable the streaming query feature
max_subscriptions 100 Maximum number of concurrent streaming subscriptions across all clients. Prevents resource exhaustion from too many active queries.
heartbeat_interval_secs 30 Interval in seconds between heartbeat messages sent to connected clients. Helps detect stale connections and keeps firewalls from closing idle connections.
buffer_size 16 Number of result sets buffered per subscription. If a client is slow to consume results, older results are dropped when the buffer is full.
⚠ Resource Considerations

Each streaming subscription maintains an active query execution loop. Be mindful of max_subscriptions and interval_ms settings to avoid overloading the query engine. For high-frequency subscriptions (interval < 1s), consider using Continuous Aggregates to pre-compute results.

Use Cases

Real-Time Dashboards

Build live monitoring dashboards that update automatically as new metrics arrive. Streaming queries eliminate the need for client-side polling and reduce latency.

javascript
// Dashboard: live CPU usage across all hosts
const ws = new WebSocket("ws://localhost:7000/ws/query/mydb");

ws.onopen = () => {
  // Subscribe to aggregated CPU metrics
  ws.send(JSON.stringify({
    sql: `SELECT
      host,
      AVG(usage) as avg_cpu,
      MAX(usage) as max_cpu,
      MIN(usage) as min_cpu
    FROM cpu
    WHERE time > now() - interval '1 minute'
    GROUP BY host
    ORDER BY avg_cpu DESC`,
    interval_ms: 2000
  }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === "result") {
    updateDashboard(msg.data);
  }
};

Alerting

Use streaming queries to detect anomalies and trigger alerts in real time. When a threshold is crossed, immediately notify operators.

javascript
// Alert: detect hosts with CPU usage > 90%
const ws = new WebSocket("ws://localhost:7000/ws/query/monitoring");

ws.onopen = () => {
  ws.send(JSON.stringify({
    sql: `SELECT host, AVG(usage) as avg_cpu
      FROM cpu
      WHERE time > now() - interval '2 minutes'
      GROUP BY host
      HAVING AVG(usage) > 90`,
    interval_ms: 10000
  }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === "result" && msg.data.length > 0) {
    msg.data.forEach(row => {
      sendAlert({
        severity: "critical",
        host: row.host,
        cpu: row.avg_cpu,
        message: `CPU usage at ${row.avg_cpu.toFixed(1)}% on ${row.host}`
      });
    });
  }
};

Live Data Feeds

Stream raw or lightly transformed data to downstream consumers such as data pipelines, event processors, or external analytics systems.

python
import json
import requests

# Stream data via SSE using the requests library
url = "http://localhost:7000/stream/query/mydb"
params = {
    "sql": "SELECT * FROM sensor_readings WHERE time > now() - interval '10 seconds' ORDER BY time DESC LIMIT 50",
    "interval_ms": 1000
}

response = requests.get(url, params=params, stream=True)

for line in response.iter_lines():
    if line:
        decoded = line.decode("utf-8")
        if decoded.startswith("data: "):
            data = json.loads(decoded[6:])
            print(f"Received {data['row_count']} rows")
            # Forward to downstream pipeline...
            process_batch(data["data"])

Next Steps