Java 21+ Native SDK & ORM

Virtual-thread SpydWireClient, SpydAsyncClient, HTTPS SpydClient, and record/POJO ORM.

4 min read Official SDKs (12 Languages)

The official Java 21+ SDK (1.0.0) delivers four integrated layers in a single dependency with full 128-route server parity:

  1. SpydWireClient / SpydAsyncClient: Unpinned Java 21 virtual-thread-safe SPD2 binary TCP/TLS clients (ReentrantLock, 64 KiB buffered reads, prepared statement caching, transactions, leader-hint failover).
  2. SpydGrpcClient: HTTP/2 gRPC transport covering all 6 RPCs (Execute, Query, Catalog, Cancel, Health, and streaming SubscribeEvents).
  3. SpydClient: HTTPS client with rotating token supplier, explicit trust anchor (ca), mTLS (clientCertificate / custom SSLContext), database() / cluster() routing headers, maxConcurrency gating, automatic read retries, streaming row decoding, interactive 2PC (beginTransaction()), durable SSE subscriptions (events()), structured explain plans (explain()), and typed admin/cluster/observability sub-clients.
  4. dev.spyddb.orm (SpydDatabase / SpydAsyncDatabase): Zero-reflection-overhead ORM supporting immutable Java records, POJOs, relations (@SpydOneToOne, @SpydOneToMany, @SpydManyToOne, @SpydManyToMany), tenant ownership & record sharing, fluent Col / Expr / Aggregate / stage() builders (including vector, sparse, ColBERT, geo, full-text, graph, and GBDT/TreeSHAP), schema diffing (SchemaDiffer), and checksummed migrations (Migrator).

1. Installation (Maven & Gradle)#

xml
<dependency>
  <groupId>io.github.muhibnayem</groupId>
  <artifactId>spyddb-client</artifactId>
  <version>1.0.0</version>
</dependency>
kotlin
implementation("io.github.muhibnayem:spyddb-client:1.0.0")

Requires Java 21+ (HttpClient.shutdownNow(), virtual threads, and Java records).

2. Sync & Async SpydWire (SpydWireClient / SpydAsyncClient)#

java
import dev.spyddb.*;

// Synchronous binary SPD2 client
try (SpydWireClient wire = SpydWireClient.connect(
        "spydwire://YOUR_TOKEN@127.0.0.1:5433/default?tls=true&ca=docker/tls/ca.crt&server_name=localhost")) {

    SpydResult res = wire.query(
            "orders | where status == $1 | pick id, customer, total | take 10",
            SpydValue.string("paid"));

    for (SpydRow row : res.rows()) {
        System.out.println(row.getLong("id") + ": " + row.getDecimal("total"));
    }
}

// Asynchronous client returning CompletableFuture
try (SpydAsyncClient async = SpydAsyncClient.connect(
        "spydwire://YOUR_TOKEN@127.0.0.1:5433/default?tls=true&ca=docker/tls/ca.crt&server_name=localhost")) {

    async.query("orders | where active == $1", SpydValue.bool(true))
         .thenAccept(r -> System.out.println("Matched rows: " + r.size()))
         .join();
}

3. HTTPS Query Client (SpydClient)#

java
import dev.spyddb.*;
import java.nio.file.Path;
import java.time.Duration;

try (SpydClient client = SpydClient.builder()
        .endpoint("https://localhost:8080")
        .token(() -> System.getenv("SPYD_TOKEN")) // rotating token supplier
        .ca(Path.of("docker/tls/ca.crt"))
        .database("default")                      // X-Spyd-Database header
        .cluster("eu-west")                       // optional X-Spyd-Cluster proxy target
        .requestTimeout(Duration.ofSeconds(30))
        .maxConcurrency(32)
        .retries(2)
        .maxResponseBytes(64L * 1024 * 1024)
        .build()) {

    // 1. Parameterized read with automatic read retry
    SpydResult result = client.query(
            "users | where id == $1 | pick id, email",
            SpydValue.u64(1));

    // 2. Structured query execution plan
    SpydPlan plan = client.explain("orders | where status == \"paid\" | take 10");

    // 3. Prepared statement with automatic DDL invalidation reprepare
    try (SpydPreparedStatement prepared = client.prepare(
            "orders | where status == $1 | pick id, total")) {
        SpydResult paid = prepared.execute(SpydValue.string("paid"));
        System.out.println("Prepared rows: " + paid.size());
    }

    // 4. Streaming decode for large result sets without full materialization
    client.stream("orders | pick id, customer", row ->
            System.out.println(row.getString("customer")));

    // 5. Health, session, catalog, and client-side latency metrics
    SpydHealth health = client.health();
    SpydSession session = client.session();
    SpydCatalog catalog = client.catalog();
    SpydMetrics metrics = client.metrics();
}

Typed Control-Plane & Observability Sub-Clients#

Every operational subsystem is exposed as a typed accessor on SpydClient (plus client.request(method, path, jsonBody) as an escape hatch for custom routes):

AccessorClassCoverage
client.auth()SpydAuthOIDC/SAML providers, SCRAM/LDAP login, logout
client.cluster()SpydClusterTopology, nodes, shards, rebalance, scatter/gather, Multi-Raft groups, leases, row locks, HLC, links, fleet, security sync
client.beginTransaction(...)SpydDistributedTransactionInteractive distributed 2PC sessions (begin, query, stage, end) & participant recovery
client.replication()SpydReplicationWAL streaming status, follow, lease renewal, fenced promote
client.ccr() / client.dr()SpydCcr / SpydDrCross-cluster replication feeds, conflicts, DR drills, failover, failback
client.backups()SpydBackupsOnline base backups, cryptographic verify, WAL archive, PITR restore
client.admin()SpydAdminOnline databases, tamper-evident audit verify/events, column & storage key rotation
client.extensions()SpydExtensionsSigned .spydext WebAssembly extension install, list, policy status, drop
client.apm() / slos() / alerts()SpydApm / SpydSlos / SpydAlertsOTLP ingest, traces, service maps, RUM, synthetics, SLO error budgets, alert channels/rules/silences

4. Full Java ORM: CRUD, Relations, Locking Reads & Migrations (dev.spyddb.orm)#

Define entities as immutable Java records (or POJOs) with @SpydCollection, @SpydField, @SpydIndex, @SpydForeignKey, and relation annotations (@SpydOneToOne, @SpydOneToMany, @SpydManyToOne, @SpydManyToMany):

java
import dev.spyddb.orm.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@SpydCollection("customers")
@SpydIndex(name = "idx_customers_email", columns = {"email"}, unique = true)
public record Customer(
    @SpydField(primary = true, autoIncrement = true) Long id,
    @SpydField(notNull = true, maxLength = 160) String email,
    @SpydField(notNull = true, maxLength = 80) String name,
    @SpydOneToMany(mappedBy = "customerId", target = Order.class) List<Order> orders
) {}

@SpydCollection("orders")
@SpydIndex(name = "idx_orders_customer", columns = {"customerId"})
@SpydForeignKey(name = "fk_order_customer", columns = {"customerId"}, references = "customers", refColumns = {"id"})
public record Order(
    @SpydField(primary = true, autoIncrement = true) Long id,
    @SpydField(notNull = true) Long customerId,
    @SpydField(notNull = true, maxLength = 32, defaultValue = "pending") String status,
    @SpydField(precision = 12, scale = 2, notNull = true) BigDecimal total
) {}

Complete CRUD, Upsert, Relations, Locking Reads, Prepared Queries & Migrations#

java
try (SpydDatabase db = SpydDatabase.connect(
        "spydwire://YOUR_TOKEN@127.0.0.1:5433?tls=true&ca=docker/tls/ca.crt&server_name=localhost")) {

    // 1. Schema creation, diff & online sync
    db.createAll(Customer.class, Order.class);
    SchemaDiff diff = db.diff(Customer.class, Order.class);
    if (!diff.changes().isEmpty()) {
        db.sync(Customer.class, Order.class);
    }

    // 2. Create (single & batch)
    Customer ada = db.create(new Customer(null, "ada@example.test", "Ada Lovelace", null));
    List<Order> batch = db.createMany(List.of(
        new Order(null, ada.id(), "paid", new BigDecimal("149.50")),
        new Order(null, ada.id(), "queued", new BigDecimal("89.00"))
    ));

    // 3. Read by primary key (Optional or throwing require) + eager relation loading
    Optional<Customer> loaded = db.get(Customer.class, ada.id(), "orders");
    Customer required = db.require(Customer.class, ada.id(), "orders");

    // 4. Filter, sort, paginate, count, exists & bulk update
    List<Order> paidOrders = db.query(Order.class)
        .filter(Col.of("status").eq("paid").and(Col.of("total").gte(new BigDecimal("100.00"))))
        .orderBy(Col.of("id").desc())
        .limit(20)
        .offset(0)
        .all();

    long totalPaid = db.query(Order.class).filter(Col.of("status").eq("paid")).count();
    boolean hasQueued = db.query(Order.class).filter(Col.of("status").eq("queued")).exists();

    // 5. Save (update), idempotent Upsert & Delete
    Order first = batch.getFirst();
    db.save(new Order(first.id(), first.customerId(), "shipped", first.total()));
    db.upsert(new Order(first.id(), first.customerId(), "delivered", first.total()), "id");
    db.delete(batch.getLast());

    // 6. Bulk query update & delete
    db.query(Order.class)
        .filter(Col.of("status").eq("pending"))
        .update(Col.of("status").set("expired"));

    // 7. ACID SSI transaction with FOR UPDATE SKIP LOCKED queue claiming
    db.transaction(tx -> {
        Optional<Order> job = tx.query(Order.class)
            .filter(Col.of("status").eq("queued"))
            .orderBy(Col.of("id").asc())
            .limit(1)
            .lockRows("update skip_locked")
            .first();
        job.ifPresent(o -> tx.save(new Order(o.id(), o.customerId(), "processing", o.total())));
        return job;
    });

    // 8. Reusable prepared entity query & explain plan
    PreparedEntityQuery<Order> byStatus = db.query(Order.class)
        .filter(Col.of("status").eq("paid"))
        .orderBy(Col.of("total").desc())
        .prepare();
    List<String> planLines = db.query(Order.class).filter(Col.of("status").eq("paid")).explain(true);

    // 9. Checksummed schema migrations
    Migrator migrator = db.migrator();
}

Asynchronous ORM (SpydAsyncDatabase)#

java
try (SpydAsyncDatabase asyncDb = SpydAsyncDatabase.connect(
        "spydwire://YOUR_TOKEN@127.0.0.1:5433?tls=true&ca=docker/tls/ca.crt&server_name=localhost")) {

    asyncDb.createAll(Order.class).join();
    List<Order> recent = asyncDb.query(Order.class)
        .filter(Col.of("total").gte(new BigDecimal("50.00")))
        .orderBy(Col.of("id").desc())
        .limit(25)
        .all()
        .join();
}

5. Full-Text BM25 Search, Vector (Dense, Sparse SPLADE, ColBERT), Geo & 4-Model Hybrid Retrieval#

Model a multi-model collection combining relational columns, BM25 full-text, dense HNSW vector(384), learned sparse sparse_vector (SPLADE Block-Max WAND), ColBERT multi_vector(128) (MUVERA FDE + exact MaxSim), and R-Tree geo_point:

java
import dev.spyddb.*;
import dev.spyddb.orm.*;
import java.util.List;
import java.util.Map;

// 1. Create the multi-model collection with all 4 specialized indexes
wire.query("""
    create collection if not exists catalog_items {
      id: u64 primary auto_increment,
      title: text not_null,
      description: text not_null,
      category: string(64) not_null,
      coords: geo_point,
      embedding: vector(384),
      splade: sparse_vector,
      token_vecs: multi_vector(128),

      index idx_items_fts on (title, description) using fulltext,
      index idx_items_vec on (embedding) using hnsw,
      index idx_items_sparse on (splade) using sparse,
      index idx_items_colbert on (token_vecs) using colbert,
      index idx_items_geo on (coords) using rtree
    }
    """);

// 2. Insert a multi-model document with exact typed GeoPoint & Vector values
wire.query(
    "catalog_items | insert { title: $1, description: $2, category: $3, coords: $4, embedding: $5 }",
    SpydValue.string("Mechanical Wireless Keyboard"),
    SpydValue.string("Low-latency tactile wireless keyboard with hot-swap switches"),
    SpydValue.string("peripherals"),
    SpydValue.geoPoint(37.7749, -122.4194),
    SpydValue.vector(queryEmbedding384)
);

A. Full-Text BM25 Search (ORM + HTTP /v1/search & /v1/suggest)#

java
// ORM full-text filter + relevance ranking
List<Map<String, Object>> ftsHits = db.query(CatalogItem.class)
    .filter(Expr.raw("match(description, ?)", "wireless mechanical"))
    .stage("pick id, title, score(description, $1) as bm25", SpydValue.string("wireless mechanical"))
    .orderBy(Col.of("bm25").desc())
    .limit(10)
    .rows();

// Cross-collection BM25 search with highlights & autocomplete via HTTPS SpydClient
SpydClient.RawResponse search = client.request(
    "POST", "/v1/search",
    """
    {"query":"wireless mechanical","collections":["catalog_items"],"take":10}
    """);
SpydClient.RawResponse suggest = client.request(
    "POST", "/v1/suggest",
    """
    {"prefix":"wirel","collections":["catalog_items"],"take":5}
    """);

B. Dense HNSW, Learned Sparse SPLADE & ColBERT Multi-Vector Retrieval#

java
// 1. Dense HNSW nearest-neighbor vector search
SpydResult denseHits = wire.query(
    """
    catalog_items
    | where nearest(embedding, $1, 20)
    | pick id, title, vector_similarity(embedding, $1) as similarity
    | sort similarity desc
    | take 10
    """,
    SpydValue.vector(queryEmbedding384)
);

// 2. Learned Sparse SPLADE retrieval (Block-Max WAND dynamic pruning)
SpydResult sparseHits = wire.query(
    """
    catalog_items
    | where sparse_nearest(splade, $1, 20)
    | pick id, title, sparse_dot(splade, $1) as lexical_score
    | sort lexical_score desc
    | take 10
    """,
    querySparseVector
);

// 3. ColBERT late-interaction retrieval (MUVERA FDE + exact MaxSim rescoring)
SpydResult colbertHits = wire.query(
    """
    catalog_items
    | where nearest_maxsim(token_vecs, $1, 20)
    | pick id, title, maxsim(token_vecs, $1) as colbert_score
    | sort colbert_score desc
    | take 10
    """,
    queryMultiVector
);

C. Geospatial Queries (geo_within, geo_near, geo_radius, geo_distance)#

java
// 1. Bounding-box R-Tree query (San Francisco Bay Area)
List<CatalogItem> inBayArea = db.query(CatalogItem.class)
    .filter(Expr.raw("geo_within(coords, 37.60, -122.60, 37.90, -122.20)"))
    .limit(50)
    .all();

// 2. Top-k spatial nearest neighbors with exact Haversine distance in meters
SpydResult nearestStores = wire.query(
    """
    catalog_items
    | where geo_near(coords, 37.7749, -122.4194, 5)
    | pick id, title, geo_distance(coords, $1) as meters
    | sort meters asc
    """,
    SpydValue.geoPoint(37.7749, -122.4194)
);

// 3. Radius search (within 5 km)
List<CatalogItem> within5km = db.query(CatalogItem.class)
    .filter(Expr.raw("geo_radius(coords, 37.7749, -122.4194, 5000)"))
    .all();

D. 4-Model Hybrid Omni Query with Reciprocal Rank Fusion (RRF)#

Combine dense HNSW vector search, BM25 full-text search, R-Tree geospatial bounding, relational filtering, and RRF ranking inside one MVCC snapshot:

java
SpydResult hybrid = wire.query(
    """
    catalog_items
    | where hybrid(description, $1, embedding, $2, 50)
        and geo_within(coords, 37.60, -122.60, 37.90, -122.20)
        and category == $3
    | fuse rrf 60 (score(description, $1), vector_similarity(embedding, $2) weight 1.5) as rank_score
    | pick id, title, rank_score
    | sort rank_score desc
    | take 10
    """,
    SpydValue.string("wireless mechanical"),
    SpydValue.vector(queryEmbedding384),
    SpydValue.string("peripherals")
);

6. Durable Realtime SSE & gRPC Subscriptions#

Stream live committed insert, update, and delete events with automatic cursor resume (Last-Event-ID). Ensure realtime.auto_enable_local_journal: true is set in server.json (or activate the commit journal first).

HTTP SSE Event Loop (SpydEventStream)#

java
import dev.spyddb.*;

SpydSubscription sub = SpydSubscription.builder()
    .collections("orders", "catalog_items")
    .events("insert", "update", "delete")
    .where("total >= 100.0")
    .includeBefore(true)
    .heartbeatMillis(15_000L)
    .build();

String resumeCursor = null;
try (SpydEventStream stream = client.events(SpydClient.StreamRoute.SUBSCRIBE, sub)) {
    SpydEventStream.Event ev;
    while ((ev = stream.next()) != null) {
        switch (ev.name()) {
            case "ready" -> System.out.println("Subscribed at cursor " + stream.lastEventId());
            case "insert", "update", "delete" -> {
                System.out.println(ev.name() + " payload=" + ev.data());
                resumeCursor = stream.lastEventId();
            }
            case "reconnect", "resync_required" -> {
                resumeCursor = stream.lastEventId();
                break; // reconnect with sub.resumeFrom(resumeCursor)
            }
            case "access_revoked", "session_expired" -> {
                throw new IllegalStateException("Subscription revoked: " + ev.name());
            }
        }
    }
}

// Resume cleanly without missed commits after a network drop
if (resumeCursor != null) {
    try (SpydEventStream resumed = client.events(
            SpydClient.StreamRoute.SUBSCRIBE, sub.resumeFrom(resumeCursor))) {
        // continue consuming
    }
}

HTTP/2 gRPC Client & Streaming SubscribeEvents (SpydGrpcClient)#

java
import dev.spyddb.SpydGrpcClient;
import spyddb.v1.SpyddbOuterClass.*;

try (SpydGrpcClient grpc = SpydGrpcClient.connect(
        "127.0.0.1", 4317, System.getenv("SPYD_TOKEN"), "docker/tls/ca.crt")) {

    QueryResponse resp = grpc.query("orders | pick id, total | take 10");

    SubscribeRequest req = SubscribeRequest.newBuilder()
        .addCollections("orders")
        .setHeartbeatMs(15_000)
        .build();
    grpc.subscribe(req,
        event -> System.out.println("gRPC event=" + event.getKind() + " cursor=" + event.getCursor()),
        Throwable::printStackTrace);
}

7. Triggers, Stored Procedures (SP & PL/pgSQL), UDFs & Signed WASM Extensions#

Execute DDL for functions, procedures, and triggers over SpydWireClient or SpydClient, and manage signed .spydext WebAssembly extensions via client.extensions():

java
// 1. Scalar UDF (SpydQL) & Sandboxed WASM UDF
wire.query("""
    create or replace function discounted_total(amount: f64, bps: i32) -> f64 as
      amount * (1.0 - cast(bps as f64) / 10000.0)
    """);

// 2. Before-Row Trigger (normalizes every incoming write before indexes & constraints run)
wire.query("""
    create trigger normalize_order_status
    before insert on orders for each row as
      new | set { status: lower(status) }
    """);

// 3. Transactional Stored Procedure (PL/pgSQL with SAVEPOINT & OUT parameter)
wire.query("""
    CREATE OR REPLACE PROCEDURE transfer_funds(
      IN from_id bigint, IN to_id bigint, IN amount numeric(12, 2),
      OUT new_balance numeric(12, 2)
    )
    LANGUAGE plpgsql AS $$
    BEGIN
      SAVEPOINT before_debit;
      UPDATE accounts SET balance = balance - amount WHERE id = from_id;
      SELECT balance INTO STRICT new_balance FROM accounts WHERE id = from_id;
      IF new_balance < 0 THEN
        ROLLBACK TO SAVEPOINT before_debit;
        RAISE EXCEPTION 'insufficient funds';
      END IF;
      UPDATE accounts SET balance = balance + amount WHERE id = to_id;
    END;
    $$;
    """);

// Call the procedure and read OUT parameter
SpydResult procRes = wire.query(
    "call transfer_funds($1, $2, $3)",
    SpydValue.i64(1), SpydValue.i64(2), SpydValue.decimal(new BigDecimal("25.00"))
);

// 4. Signed WebAssembly Extension (.spydext) management via SpydClient
var installed = client.extensions().list();

8. In-Engine GBDT ML, TreeSHAP & Property Graph#

Train regression, binary logistic, or multi-class softmax GBDT models directly through the ORM Aggregate builder, filter with Expr.mlScore(...), and decode exact TreeSHAP explanations into SpydMlExplanation:

java
import dev.spyddb.SpydMlExplanation;
import dev.spyddb.SpydRow;
import dev.spyddb.orm.*;
import java.util.List;
import java.util.Map;

// 1. Train a 3-class fraud triage GBDT (0=Approve, 1=ManualReview, 2=AutoBlock) inside SpydDB
List<Map<String, Object>> trained = db.query(FraudSample.class)
    .aggregate(Aggregate.mlTrainGbdtMulticlass("features", 3, 25, 3).as("model"))
    .rows();
String modelJson = (String) trained.getFirst().get("model");

// 2. Filter high-risk rows in ORM using Expr.mlScore(...)
List<OrderFeatures> flagged = db.query(OrderFeatures.class)
    .filter(Expr.mlScore(modelJson, Col.of("amount"), Col.of("velocity"), Col.of("country")).gte(0.75))
    .limit(50)
    .all();

// 3. Score, extract softmax class probabilities & exact TreeSHAP attributions
SpydResult explained = wire.query(
    """
    order_features
    | pick id,
           ml_class($1, amount, velocity, country) as tier,
           ml_proba($1, amount, velocity, country) as probs,
           ml_explain($1, amount, velocity, country) as shap
    | take 25
    """,
    SpydValue.string(modelJson)
);

SpydRow top = explained.rows().getFirst();
SpydMlExplanation shap = SpydMlExplanation.parse(top.getString("shap"));
System.out.println("base=" + shap.baseValue() + " pred=" + shap.prediction() + " contributions=" + shap.contributions());

// 4. Property Graph traversal & PageRank over transactional edge collections
SpydResult ring = wire.query("account_edges | traverse from 999 over (src, dst) depth 3");
SpydResult leaders = wire.query("account_edges | pagerank damping 0.85 iterations 20 over src, dst | sort rank desc | take 10");

See examples/spring-boot-ecommerce in the repository for a complete Spring Boot 3-tier GBDT fraud triage service (FraudRiskService, FraudRiskController, and live TLS integration tests) running against SpydDB.

9. Multi-Node, Multi-Raft, Interactive 2PC, Multi-Cluster (CCR/DR) & Failover#

All distributed topologies — single-cluster Multi-Raft, sharded multi-node, and multi-region multi-cluster — are first-class typed APIs on SpydClient:

Multi-Node Topology, Sharding, Leases, Row Locks & HLC#

java
import dev.spyddb.*;

SpydCluster cluster = client.cluster();

// 1. Inspect topology, nodes, shards, and Multi-Raft groups
SpydCluster.Topology topo = cluster.topology();

// 2. Register a peer node & configure sharding / online shard split
cluster.publishNode(new SpydCluster.NodeRequest("node-2", "https://node2.internal:8080", "node2.internal:5433", "voter", null));
cluster.shard(new SpydCluster.ShardRequest("orders", "customer_id", "hash", 8, 3));
cluster.split(new SpydCluster.SplitRequest("orders", 0));

// 3. Synchronize Hybrid Logical Clocks (HLC) across nodes
SpydCluster.Clock clock = cluster.hlc();
SpydCluster.Clock synced = cluster.syncClock(clock.hlc());

// 4. Regional write leases & distributed row locks
var leases = cluster.leases();
var lockGrant = cluster.acquireLocks(new SpydCluster.LockRequest(1001L, "orders", List.of("101"), "exclusive", 15_000L));
cluster.releaseLocks(1001L);

Interactive Cross-Shard 2PC Transactions (SpydDistributedTransaction)#

java
try (SpydDistributedTransaction dtx = client.beginTransaction(15_000L, "order-checkout-42")) {
    SpydResult current = dtx.query("orders | where id == $1", SpydValue.u64(42));
    dtx.stage("ledger", Map.of(
        "order_id", SpydValue.u64(42),
        "amount", SpydValue.decimal(new BigDecimal("199.95"))
    ));
    dtx.commit(); // atomic cross-shard 2PC commit (auto-aborts on close if uncommitted)
}
java
// Link a remote cluster and enable automatic RBAC & policy sync
client.cluster().addLink(new SpydCluster.LinkRequest(
    "eu-west", List.of("https://eu-1.spyd.internal:8080"),
    "production", "caller_token", System.getenv("EU_MONITOR_TOKEN"),
    null, null, false, true, null));
client.cluster().setSecuritySync(true);

// Route queries through the hub to the linked cluster via X-Spyd-Cluster
try (SpydClient euClient = SpydClient.builder()
        .endpoint("https://hub.spyd.internal:8080")
        .token(System.getenv("SPYD_TOKEN"))
        .ca(Path.of("docker/tls/ca.crt"))
        .cluster("eu-west")
        .build()) {
    SpydResult euOrders = euClient.query("orders | take 10");
}

Cross-Cluster Replication (CCR), Disaster Recovery (DR), WAL Streaming & Leader Failover#

java
// 1. Continuous Cross-Cluster Replication & conflict inspection
SpydCcr.SyncReport sync = client.ccr().sync("orders-eu-sync");
SpydCcr.Conflicts conflicts = client.ccr().conflicts();

// 2. Non-disruptive DR readiness drill, failover & failback
SpydDr.Drill drill = client.dr().drill(SpydDr.DrRequest.defaults());
if (!drill.losesWrites() && drill.failures().isEmpty()) {
    SpydDr.Failover fo = client.dr().failover(new SpydDr.DrRequest("eu-west", "node-eu-1", 10_000L, false));
}

// 3. Physical WAL streaming replication (follow, lease renewal, fenced promote)
client.replication().follow(new SpydReplication.FollowRequest("https://primary.internal:8080", token, 50L));
client.replication().renewLease(10_000L, "standby-1");
client.replication().promote(SpydReplication.PromoteRequest.defaults());

// 4. Multi-Raft leader failover classification
try {
    client.query("orders | insert { id: 101, total: 95.0 }");
} catch (SpydException ex) {
    if (ex.isNotLeader()) {
        // Retry against the new Raft leader or next seed endpoint
    }
    throw ex;
}

10. Tenant Ownership, Record Sharing, Security, Backups & Observability#

java
// 1. Tenant-owned ORM collection with immutable record identity for cross-tenant sharing
@SpydCollection(value = "invoices", tenantOwnedBy = "tenantId", recordIdentity = "recordId")
public record Invoice(
    @SpydField(primary = true) Long tenantId,
    @SpydField(primary = true) Long id,
    @SpydField(notNull = true) java.util.UUID recordId,
    @SpydField(precision = 12, scale = 2) BigDecimal total
) {}

// Share one specific invoice record with an external auditor until a microsecond expiry
wire.query(
    "grant select on collection(invoices) record \"550e8400-e29b-41d4-a716-446655440000\" until 1893456000000000 to external_auditor"
);

// 2. Online backups, cryptographic audit verification & key rotation
client.backups().create("daily-2026-12-02");
client.admin().verifyAudit();
client.admin().rotateColumnKey();

// 3. Observability: APM services, SLOs & alerts
var services = client.apm().services();
var slos = client.slos().list();
var alerts = client.alerts().events();

11. Exact Typed Values, AI Types & Error Codes#

SpydValue and SpydType prevent silent loss across unsigned 64-bit values, fixed-point decimals, AI vectors, and nulls:

  • Integers & Floats: SpydValue.u8, u16, u32, u64, i8, i16, i32, i64, f32, f64
  • Decimals & Booleans: SpydValue.decimal(BigDecimal), SpydValue.bool(boolean)
  • Text & Binary: SpydValue.string(String), SpydValue.bytes(byte[]), SpydValue.json(...)
  • Temporal: SpydValue.timestamp(Instant), SpydValue.date(LocalDate), SpydValue.time(...)
  • AI Retrieval & Multi-Model: SpydValue.vector(float[]), SpydType.sparseVector(), SpydType.multiVector(dim), SpydValue.geoPoint(lat, lng), SpydValue.enumValue(ordinal), SpydValue.nullValue()

Calling row.getLong, row.getString, or row.getDecimal on a mismatched column throws SpydException immediately with a typed SpydErrorCode.