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.

9 min read Clustering & Operations

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#

CapabilityMechanismKey Endpoint / Header
Hub Fleet StreamPersistent async SSE watchers across up to 10,000 links on a shared 2-thread Tokio runtime (spyd-fleet), coalesced via StreamHubGET /v1/cluster/fleet, GET /v1/cluster/fleet/stream
Reverse-Dial NAT PublishingFirewalled/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 ProxyHub forwards allowlisted Studio, query, APM, alert, and security-sync routes server-side so remote tokens and CAs never reach browsersX-Spyd-Cluster, X-Spyd-Proxy-Hop
Always-On Rule GuardCoordinator stamps distributed queries with the statement's rule fingerprint; divergent nodes fail closed with 409 security_mismatchX-Spyd-Security
Opt-In Security SyncSynchronous parallel node push before ack + coalesced background link pusher + 5 s jittered gossip with deterministic LWW convergenceGET/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.

FieldType / DefaultPurpose
namestring (required)Unique cluster link identifier (cannot be "local").
seed_urlsstring[] (max 16)HTTPS/HTTP seed endpoints for the remote cluster. Required unless inbound_user is configured for dial-in mode.
auth_tokenstring (max 8 KiB)Credential for CCR and link_token browsing. Required when auth_mode is "link_token". Redacted from GET /v1/cluster/topology.
telemetry_tokenstring (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_pemstring (max 64 KiB)Private PEM CA bundle used to verify the remote cluster's TLS certificates.
certificate_pinstring (64 hex chars)Expected SHA-256 digest of the remote leaf certificate, verified in constant time alongside normal chain validation.
pin_onlybool (default false)Trust only certificate_pin (for air-gapped self-signed certificates). Requires certificate_pin.
sync_securitybool (default false)Opt this link into automatic role/policy synchronization. Refused (400 invalid_link) when seed_urls is empty.
inbound_userstring (1–256 chars, optional)Identity that a dial-in cluster signs in as when publishing telemetry with empty seed_urls.
sh
# 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 2 seconds (TELEMETRY_INTERVAL) from atomic metric counters and statement-pool snapshots, with topology metadata refreshed every 5 seconds (TOPOLOGY_INTERVAL).
  • Telemetry endpoints (cluster admin or monitor role):
    • GET /v1/cluster/telemetry: Returns the current node summary JSON immediately.
    • GET /v1/cluster/telemetry/stream: Long-lived SSE stream emitting event: telemetry frames.

Telemetry Payload Shape#

json
{
  "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 to 30 seconds, with 5 s connect timeouts and 45 s read idle timeouts.
  • Fleet HTTP endpoints (cluster admin or monitor role):
    • GET /v1/cluster/fleet?offset=0&limit=500: Paginated JSON snapshot (limit clamped to 1..=5000; "local" is always sorted first).
    • GET /v1/cluster/fleet/stream: SSE stream backed by StreamHub. Emits event: snapshot on connect followed by coalesced event: clusters deltas (revision, clusters[], removed[]) every 500 ms and : keep-alive comments every 15 s.
  • Backpressure isolation: StreamHub serializes each revision once into shared Bytes buffers and pushes to bounded mpsc::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,024 removals) automatically receive a fresh full snapshot.
  • Subscription cap: Total concurrent telemetry + fleet SSE subscribers are bounded by max_fleet_subscribers (default 256, allowed 1..=100000, returning 503 too_many_streams when full).

Cluster Status Values#

StatusMeaning
connectedReceiving live event: telemetry updates.
connectingInitial outbound SSE handshake in progress.
waitingDial-in link created; awaiting publisher connection from the remote cluster.
reconnectingStream dropped or timed out; retrying with jittered backoff.
unreachableAll configured seed_urls failed DNS, TCP, TLS, or address-policy checks.
auth_failedLinked 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)#

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_url values must use https://.
  • name must match the hub link name (letters, digits, -, _, ., max 128 chars; cannot be "local").
  • token must authenticate on the hub as the user named in that link's inbound_user.

Handshake, Rate Limits & Connection Lifecycle#

  1. The edge cluster opens GET /v1/cluster/fleet/publish with Authorization: Bearer <token> and X-Spyd-Cluster-Name: <name>, then writes event: telemetry frames every 2 seconds (PUBLISH_INTERVAL).
  2. The hub checks that X-Spyd-Cluster-Name identifies an active dial-in link (seed_urls empty, inbound_user set) whose inbound_user matches the authenticated session user in constant time. Any unknown name, non-dial-in link, or wrong user returns a uniform 403 forbidden so callers cannot enumerate configured links.
  3. Accepted sockets upgrade out of the HTTP worker pool onto the shared 2-thread spyd-fleet async runtime (spawn_inbound_reader), supporting up to 4,096 concurrent dial-in clusters (MAX_PUBLISHERS; excess connections get 503 too_many_publishers).
  4. Updates are rate-limited to at most two applied summaries per second (500 ms minimum gap), silent publishers are closed after 45 seconds, and a newer connection for the same cluster name replaces the prior generation.

Watch-Only Scope: Because the hub has no reachable seed_urls for a dial-in cluster, Studio marks it Dial-in / Watch only — it cannot be browsed via X-Spyd-Cluster or opted into sync_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's Authorization: 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 configured auth_token instead, and restricts access strictly to cluster administrators (403 forbidden for non-admin sessions).
sh
# 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-Cluster is evaluated before local X-Spyd-Database lookup 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-only GET /v1/admin/{databases,backups,extensions,audit/verify,audit/events,identities}, /v1/cluster/{topology,raft/groups,ccr,ccr/conflicts}, and GET/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 with 403 route_not_proxied.
  • Path-traversal rejection: Paths containing /../, /./, //, \, or encoded %2e, %2f, %5c, %00 are rejected immediately with 403 route_not_proxied.
  • Single-hop loop guard: The proxy attaches X-Spyd-Proxy-Hop: 1; any incoming request already carrying X-Spyd-Proxy-Hop fails closed with 400 proxy_loop_detected.
  • Credential isolation: A remote 401 is translated to 502 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 (default 32, allowed 1..=10000, 503 proxy_busy when exceeded), with automatic seed failover constrained to safe retryable failures (502 remote_delivery_unknown if 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:

  1. 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 the X-Spyd-Security header.
  2. The receiving node recomputes its local fingerprint for the same statement and compares them in constant time.
  3. If the fingerprints differ, the shard node refuses execution immediately with 409 security_mismatch rather 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):

sh
# 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): Synchronizes roles, policies, rule_policies, version, and updated_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-links worker coalesces rapid changes (queue limit 1,024 databases) and pushes snapshots to opted-in outbound links without blocking local DDL latency. (Dial-in links with empty seed_urls cannot opt in.)
  • 5 s jittered gossip & auto-repair: spyd-security-sync checks one random opted-in node via GET /v1/cluster/security/state and one random opted-in link roughly every 5 seconds per open database to heal nodes that restarted or missed an update. Additionally, if a coordinator encounters 409 security_mismatch from 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/apply with 409 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, ApplyReply returns newer so the sender converges in the same round trip.

7. Server Configuration Reference (server.json)#

KeyDefaultValid Range / RulesPurpose
cluster_allowed_cidrs[]Array of CIDR stringsFurther restricts cluster link connections beyond built-in metadata/link-local blocking.
max_fleet_subscribers2561..=100000Maximum combined concurrent /v1/cluster/telemetry/stream and /v1/cluster/fleet/stream subscribers.
max_cluster_proxy_requests321..=10000Maximum concurrent requests forwarded via X-Spyd-Cluster (503 proxy_busy when exceeded).
fleet_publishUnsetObject (hub_url, token, name, optional ca_cert_pem, certificate_pin)Enables outbound reverse-dial telemetry publishing to a remote hub cluster.