Multi-Cluster Fleet & Security Sync
Live multi-cluster telemetry hub, reverse-dial NAT publishing, X-Spyd-Cluster proxy, and cross-node/cross-cluster RBAC & policy sync.
Monitor and operate hundreds of distributed SpydDB clusters from a single hub, accept reverse-dial telemetry from edge or firewalled clusters behind NAT, browse remote clusters safely through an audited server-side proxy (X-Spyd-Cluster), and keep RBAC roles and row policies consistent everywhere with an always-on fingerprint guard (X-Spyd-Security) and opt-in security synchronization.
1. Architecture Overview#
| Capability | Mechanism | Key Endpoint / Header |
|---|---|---|
| Hub Fleet Stream | Persistent async SSE watchers across up to 10,000 links on a shared 2-thread Tokio runtime (spyd-fleet), coalesced via StreamHub | GET /v1/cluster/fleet, GET /v1/cluster/fleet/stream |
| Reverse-Dial NAT Publishing | Firewalled/NAT clusters dial the hub over HTTPS and push event: telemetry every 2 s (MAX_PUBLISHERS = 4,096) | GET /v1/cluster/fleet/publish, X-Spyd-Cluster-Name |
| Cross-Cluster Proxy | Hub forwards allowlisted Studio, query, APM, alert, and security-sync routes server-side so remote tokens and CAs never reach browsers | X-Spyd-Cluster, X-Spyd-Proxy-Hop |
| Always-On Rule Guard | Coordinator stamps distributed queries with the statement's rule fingerprint; divergent nodes fail closed with 409 security_mismatch | X-Spyd-Security |
| Opt-In Security Sync | Synchronous parallel node push before ack + coalesced background link pusher + 5 s jittered gossip with deterministic LWW convergence | GET/PUT /v1/cluster/security/sync |
All outbound connections resolve DNS once and check every destination IP right before dialing against AddressPolicy::peers (blocking cloud metadata IMDS, link-local, unspecified, broadcast, and multicast ranges) plus any cluster_allowed_cidrs allowlist. See SSRF Defense & Hardening for details.
2. Linking Clusters (POST /v1/cluster/links)#
Register remote clusters from the hub (Admin → Cluster in Studio, or via HTTP by a cluster administrator). Deleting a link via DELETE /v1/cluster/links/{name} removes the link and any dependent CCR subscriptions.
Link Configuration Fields (CreateLinkInput)#
| Field | Type / Default | Purpose |
|---|---|---|
name | string (required) | Unique cluster link identifier (cannot be "local"). |
seed_urls | string[] (max 16) | HTTPS/HTTP seed endpoints for the remote cluster. Required unless inbound_user is configured for dial-in mode. |
auth_token | string (max 8 KiB) | Credential for CCR and link_token browsing. Required when auth_mode is "link_token". Redacted from GET /v1/cluster/topology. |
telemetry_token | string (optional) | Least-privilege token (holding the monitor role on the remote cluster) used by the fleet telemetry stream. Falls back to auth_token when omitted. |
auth_mode | "caller_token" | "link_token" | "caller_token" (default) forwards the caller's own Bearer token; "link_token" uses auth_token and restricts browsing to cluster administrators. |
environment | "production" | "staging" | "development" | "local" | Environment badge displayed in Studio (Production, Staging, Development, This cluster). Production non-loopback links require https://. |
ca_cert_pem | string (max 64 KiB) | Private PEM CA bundle used to verify the remote cluster's TLS certificates. |
certificate_pin | string (64 hex chars) | Expected SHA-256 digest of the remote leaf certificate, verified in constant time alongside normal chain validation. |
pin_only | bool (default false) | Trust only certificate_pin (for air-gapped self-signed certificates). Requires certificate_pin. |
sync_security | bool (default false) | Opt this link into automatic role/policy synchronization. Refused (400 invalid_link) when seed_urls is empty. |
inbound_user | string (1–256 chars, optional) | Identity that a dial-in cluster signs in as when publishing telemetry with empty seed_urls. |
Examples: Dial-Out and Dial-In Links#
# 1. Standard dial-out link with least-privilege telemetry token & TLS pin
curl -fsS -X POST --cacert tls/ca.crt https://hub.spyd.internal:8080/v1/cluster/links \
-H "Authorization: Bearer $SPYD_ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "eu-west",
"seed_urls": [
"https://eu-1.spyd.internal:8080",
"https://eu-2.spyd.internal:8080"
],
"environment": "production",
"auth_mode": "caller_token",
"telemetry_token": "'"$EU_MONITOR_TOKEN"'",
"ca_cert_pem": "'"$(cat tls/eu-ca.crt)"'",
"certificate_pin": "'"$EU_LEAF_SHA256"'",
"sync_security": true
}'
# 2. Watch-only dial-in link for an edge cluster behind NAT
curl -fsS -X POST --cacert tls/ca.crt https://hub.spyd.internal:8080/v1/cluster/links \
-H "Authorization: Bearer $SPYD_ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "edge-eu",
"environment": "production",
"inbound_user": "fleet-edge-eu"
}'
# 3. Remove a cluster link and its CCR subscriptions
curl -fsS -X DELETE --cacert tls/ca.crt https://hub.spyd.internal:8080/v1/cluster/links/edge-eu \
-H "Authorization: Bearer $SPYD_ADMIN_TOKEN"3. Live Fleet Monitoring & Telemetry Streams#
Every SpydDB server maintains a lightweight in-memory telemetry summary (LocalTelemetry) requiring zero queries or disk scans per tick:
- Summary refresh: Rebuilt at most once every
2seconds (TELEMETRY_INTERVAL) from atomic metric counters and statement-pool snapshots, with topology metadata refreshed every5seconds (TOPOLOGY_INTERVAL). - Telemetry endpoints (cluster admin or
monitorrole):GET /v1/cluster/telemetry: Returns the current node summary JSON immediately.GET /v1/cluster/telemetry/stream: Long-lived SSE stream emittingevent: telemetryframes.
Telemetry Payload Shape#
{
"version": "1.0.0",
"ready": true,
"draining": false,
"uptime_secs": 86420,
"active_queries": 4,
"queued_queries": 0,
"connections": 38,
"queries_total": 1842910,
"queries_failed": 12,
"http_requests": 920411,
"http_failed": 3,
"p99_query_ms": 8.0,
"topology": {
"node_id": "node-1",
"generation": 14,
"coordinator_leader": "node-1",
"nodes": 3,
"healthy_nodes": 3,
"sharded_collections": 6,
"shards": 24,
"links": 2,
"ccr_subscriptions": 1,
"ccr_errors": 0,
"migrations": 0,
"security": {
"version": 19,
"fingerprint": "9f8c...3a1b",
"sync_enabled": true
},
"databases": 2
}
}Hub Aggregation & StreamHub Coalescing#
A hub node continuously watches up to 10,000 outbound links (MAX_LINKS) using one async SSE connection per link on its shared 2-thread spyd-fleet Tokio runtime:
- Reconnection & backoff: Initial connections are staggered across
20 ms–5 s. Dropped streams retry with exponential backoff and full jitter up to30seconds, with5s connect timeouts and45s read idle timeouts. - Fleet HTTP endpoints (cluster admin or
monitorrole):GET /v1/cluster/fleet?offset=0&limit=500: Paginated JSON snapshot (limitclamped to1..=5000;"local"is always sorted first).GET /v1/cluster/fleet/stream: SSE stream backed byStreamHub. Emitsevent: snapshoton connect followed by coalescedevent: clustersdeltas (revision,clusters[],removed[]) every500 msand: keep-alivecomments every15 s.
- Backpressure isolation:
StreamHubserializes each revision once into sharedBytesbuffers and pushes to boundedmpsc::channel(1)queues consumed asynchronously by HTTP tasks. Slow subscribers whose queue is full are dropped cleanly without delaying other Studio viewers, and subscribers lagging behind the retained removal window (1,024removals) automatically receive a fresh fullsnapshot. - Subscription cap: Total concurrent telemetry + fleet SSE subscribers are bounded by
max_fleet_subscribers(default256, allowed1..=100000, returning503 too_many_streamswhen full).
Cluster Status Values#
| Status | Meaning |
|---|---|
connected | Receiving live event: telemetry updates. |
connecting | Initial outbound SSE handshake in progress. |
waiting | Dial-in link created; awaiting publisher connection from the remote cluster. |
reconnecting | Stream dropped or timed out; retrying with jittered backoff. |
unreachable | All configured seed_urls failed DNS, TCP, TLS, or address-policy checks. |
auth_failed | Linked cluster rejected the stream credential (401 / 403). |
4. Reverse-Dial NAT Publishing (fleet_publish)#
When a cluster sits behind NAT, CG-NAT, or an outbound-only firewall where the hub cannot initiate connections to it, configure it to dial the hub instead.
Publisher Configuration (server.json)#
{
"fleet_publish": {
"hub_url": "https://hub.spyd.internal:8080",
"token": "env:SPYD_HUB_PUBLISHER_TOKEN",
"name": "edge-eu",
"ca_cert_pem": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n",
"certificate_pin": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
}- Non-loopback
hub_urlvalues must usehttps://. namemust match the hub link name (letters, digits,-,_,., max 128 chars; cannot be"local").tokenmust authenticate on the hub as the user named in that link'sinbound_user.
Handshake, Rate Limits & Connection Lifecycle#
- The edge cluster opens
GET /v1/cluster/fleet/publishwithAuthorization: Bearer <token>andX-Spyd-Cluster-Name: <name>, then writesevent: telemetryframes every2seconds (PUBLISH_INTERVAL). - The hub checks that
X-Spyd-Cluster-Nameidentifies an active dial-in link (seed_urlsempty,inbound_userset) whoseinbound_usermatches the authenticated session user in constant time. Any unknown name, non-dial-in link, or wrong user returns a uniform403 forbiddenso callers cannot enumerate configured links. - Accepted sockets upgrade out of the HTTP worker pool onto the shared 2-thread
spyd-fleetasync runtime (spawn_inbound_reader), supporting up to4,096concurrent dial-in clusters (MAX_PUBLISHERS; excess connections get503 too_many_publishers). - Updates are rate-limited to at most two applied summaries per second (
500 msminimum gap), silent publishers are closed after45seconds, and a newer connection for the same cluster name replaces the prior generation.
Watch-Only Scope: Because the hub has no reachable
seed_urlsfor a dial-in cluster, Studio marks it Dial-in / Watch only — it cannot be browsed viaX-Spyd-Clusteror opted intosync_security.
5. Cross-Cluster Browsing Proxy (X-Spyd-Cluster)#
Authorized HTTP clients and Embedded Web Studio can inspect or query any dial-out linked cluster transparently by sending X-Spyd-Cluster: <link> to the hub (omitting the header or passing local runs against the hub itself).
Credential & Access Modes#
caller_token(default): Forwards the caller'sAuthorization: Bearer <token>header directly to the remote cluster so remote RBAC roles, row policies, field masks, and audit logs apply under that exact operator's identity.link_token: Uses the link's configuredauth_tokeninstead, and restricts access strictly to cluster administrators (403 forbiddenfor non-admin sessions).
# Query the "eu-west" linked cluster via the hub proxy
curl -fsS --cacert tls/ca.crt https://hub.spyd.internal:8080/v1/query \
-H "Authorization: Bearer $SPYD_TOKEN" \
-H "X-Spyd-Cluster: eu-west" \
-H "X-Spyd-Database: orders_prod" \
-H "Content-Type: application/json" \
-d '{"sql": "orders | agg count() as total"}'Security & Failure Guardrails#
- Pre-database routing:
X-Spyd-Clusteris evaluated before localX-Spyd-Databaselookup so requests succeed even if the target database exists only on the remote cluster. - Strict route allowlist: Only read/query/observability/security-sync routes needed by Studio (
GET /v1/session,/v1/catalog,/v1/stats,POST /v1/query,/v1/search,/v1/suggest,POST /v1/cancel/*, APM/Alerts/SLOs,/v1/replication/status, read-onlyGET /v1/admin/{databases,backups,extensions,audit/verify,audit/events,identities},/v1/cluster/{topology,raft/groups,ccr,ccr/conflicts}, andGET/PUT /v1/cluster/security/sync) are forwarded. Auth endpoints,/v1/health, catalog replication,/v1/cluster/security/apply, streams, extension install/drop, and link mutations are blocked with403 route_not_proxied. - Path-traversal rejection: Paths containing
/../,/./,//,\, or encoded%2e,%2f,%5c,%00are rejected immediately with403 route_not_proxied. - Single-hop loop guard: The proxy attaches
X-Spyd-Proxy-Hop: 1; any incoming request already carryingX-Spyd-Proxy-Hopfails closed with400 proxy_loop_detected. - Credential isolation: A remote
401is translated to502 remote_cluster_unauthorized(so a bad remote token never logs an operator out of their Studio hub session). - Concurrency & failover: Concurrent proxied requests are bounded by
max_cluster_proxy_requests(default32, allowed1..=10000,503 proxy_busywhen exceeded), with automatic seed failover constrained to safe retryable failures (502 remote_delivery_unknownif request delivery outcome is ambiguous).
6. Cross-Node and Cross-Cluster Security Sync#
Because every shard node enforces its own local catalog roles and row policies during query execution, SpydDB provides two complementary defenses to prevent rule drift.
1. The Always-On Guard (X-Spyd-Security)#
Whenever a coordinator forwards a statement to a shard node:
- The coordinator computes a cryptographic fingerprint (
security_fingerprint_for) covering all RBAC roles, rule policies (when ... then ...), and collection row policies referenced by that statement, and sends it in theX-Spyd-Securityheader. - The receiving node recomputes its local fingerprint for the same statement and compares them in constant time.
- If the fingerprints differ, the shard node refuses execution immediately with
409 security_mismatchrather than returning rows filtered under stale or missing rules.
2. Opt-In Sharing (GET / PUT /v1/cluster/security/sync)#
Opt individual cluster nodes or outbound cluster links into automatic synchronization per database (X-Spyd-Database):
# 1. Inspect local security fingerprint, opted-in nodes/links, and peer outcomes
curl -fsS --cacert tls/ca.crt https://hub.spyd.internal:8080/v1/cluster/security/sync \
-H "Authorization: Bearer $SPYD_ADMIN_TOKEN" \
-H "X-Spyd-Database: default"
# 2. Opt a cluster node or linked cluster in (reconciles immediately)
curl -fsS -X PUT --cacert tls/ca.crt https://hub.spyd.internal:8080/v1/cluster/security/sync \
-H "Authorization: Bearer $SPYD_ADMIN_TOKEN" \
-H "X-Spyd-Database: default" \
-H "Content-Type: application/json" \
-d '{"node_id": "node-2", "enabled": true}'
curl -fsS -X PUT --cacert tls/ca.crt https://hub.spyd.internal:8080/v1/cluster/security/sync \
-H "Authorization: Bearer $SPYD_ADMIN_TOKEN" \
-H "X-Spyd-Database: default" \
-H "Content-Type: application/json" \
-d '{"link": "eu-west", "enabled": true}'Propagation, Gossip & Conflict Resolution#
- Synced state (
SecuritySnapshot): Synchronizesroles,policies,rule_policies,version, andupdated_us. - Synchronous intra-cluster push: Changing a role or policy on an opted-in node pushes the new snapshot in parallel to every other opted-in reachable cluster node (
POST /v1/cluster/security/apply) before the statement is acknowledged. - Coalesced cross-cluster push: The background
spyd-security-linksworker coalesces rapid changes (queue limit1,024databases) and pushes snapshots to opted-in outbound links without blocking local DDL latency. (Dial-in links with emptyseed_urlscannot opt in.) - 5 s jittered gossip & auto-repair:
spyd-security-syncchecks one random opted-in node viaGET /v1/cluster/security/stateand one random opted-in link roughly every5seconds per open database to heal nodes that restarted or missed an update. Additionally, if a coordinator encounters409 security_mismatchfrom an opted-in peer during query forwarding, it pushes its snapshot and retries once automatically. - Fail-closed receiver: Nodes that have not opted in reject
/v1/cluster/security/applywith409 security_sync_disabled. - Deterministic LWW convergence: Concurrent security changes across nodes resolve deterministically by
(version, updated_us, fingerprint). If a target holds a newer snapshot,ApplyReplyreturnsnewerso the sender converges in the same round trip.
7. Server Configuration Reference (server.json)#
| Key | Default | Valid Range / Rules | Purpose |
|---|---|---|---|
cluster_allowed_cidrs | [] | Array of CIDR strings | Further restricts cluster link connections beyond built-in metadata/link-local blocking. |
max_fleet_subscribers | 256 | 1..=100000 | Maximum combined concurrent /v1/cluster/telemetry/stream and /v1/cluster/fleet/stream subscribers. |
max_cluster_proxy_requests | 32 | 1..=10000 | Maximum concurrent requests forwarded via X-Spyd-Cluster (503 proxy_busy when exceeded). |
fleet_publish | Unset | Object (hub_url, token, name, optional ca_cert_pem, certificate_pin) | Enables outbound reverse-dial telemetry publishing to a remote hub cluster. |