Go SDK: Client, Tuples, KV Operations, and ACID Transactions

Updated:
Author: Erkin Khidirov

The Slyber DB Go SDK exposes a thread-safe db.DB interface identical across embedded and networked topologies, alongside the order-preserving composite key encoder in slyber.com/db/pkg/tuple.

1. Connecting the Network Client (db.Dial)

A *db.Client instance is designed to be shared as an application-wide singleton maintaining a pool of persistent multiplexed TLS 1.3 connections (Lanes) to each node:

Go
cli, err := db.Dial(ctx, db.ClientConfig{
	Addrs:          []string{"10.0.1.11:9110", "10.0.1.12:9110", "10.0.1.13:9110"},
	ClientSecret:   os.Getenv("SLYBER_DB_CLIENT_SECRET"),
	AdminAddr:      "10.0.1.11:9095",
	AdminSecret:    os.Getenv("SLYBER_DB_ADMIN_SECRET"),
	Lanes:          8,
	DialTimeout:    5 * time.Second,
	RequestTimeout: 15 * time.Second,
	MaxRetries:     3,
	MaxValueSize:   4 << 20,
})
if err != nil {
	log.Fatal(err)
}
defer cli.Close(context.Background())

Routing and safe retry policy:

  • When a Raft leader changes in a Multi-Raft cluster or a partition migrates online, the server responds with a typed RoutingError (ErrNotLeader / ErrPartitionMoved) carrying the new leader address and TopologyEpoch. The client updates its local partAddrs[4096] table and retries immediately on the new leader (even for non-idempotent calls, since the old node never applied the command).
  • On mid-flight TCP disconnection after sending a frame, idempotent operations (Get, Scan, Put, Delete, AppendStream with idempKey != 0, and Update transactions carrying a 16-byte TxID) are retried transparently.
  • Standalone non-idempotent calls outside a transaction (AddInt64, CAS, AppendStream with idempKey == 0) are never blindly retried to prevent double execution, returning db.ErrUncertainCommit instead. Wrap AddInt64 inside cli.Update(...) whenever automatic retry safety is required.

2. Composite Key Encoding (pkg/tuple)

The slyber.com/db/pkg/tuple package encodes typed tuples into byte slices so standard bytewise bytes.Compare inside the LSM tree preserves strict typed ordering: nil < false < true < int64 < uint64 < float64 < []byte < string < UUID. For float64, -0.0 == +0.0 and all NaN bit patterns are canonicalized to maintain -∞ < ... < 0.0 < ... < +∞ < NaN.

Go
import "slyber.com/db/pkg/tuple"

key := tuple.MustEncode("msg", uint64(774), int64(1795830000123), tuple.UUID{1, 2, 3})

prefix := tuple.MustEncode("msg", uint64(774))
startKey, endKey := tuple.PrefixRange(prefix)

var stackBuf [128]byte
rawKey := stackBuf[:0]
rawKey = tuple.AppendString(rawKey, "user")
rawKey = tuple.AppendInt64(rawKey, 100500)

sc := tuple.NewScanner(rawKey)
var tagScratch [32]byte
_, _ = sc.ReadStringBytes(tagScratch[:0])
userID, err := sc.ReadInt64()

3. KV Operations, Counters, CAS, and Range Scans

Go
const nsUsers uint16 = 10
partKey := []byte("org:acme")

ver, err := cli.Put(ctx, nsUsers, partKey, []byte("u:1"), []byte("Alice"), 24*time.Hour)

_, err = cli.Put(ctx, nsUsers, partKey, []byte("flag:verified"), nil, 0)

entry, err := cli.Get(ctx, nsUsers, partKey, []byte("u:1"), db.ReadLinearizable)

entries, err := cli.MultiGet(ctx, nsUsers, partKey, [][]byte{[]byte("u:1"), []byte("u:missing")}, db.ReadLinearizable)

newVer, currentEntry, err := cli.CAS(ctx, nsUsers, partKey, []byte("u:1"), []byte("Alice V2"), ver, 0)
if errors.Is(err, db.ErrCASConflict) {
	_ = currentEntry
}

balance, err := cli.AddInt64(ctx, nsUsers, partKey, []byte("wallet:1"), +500, 0)

it, err := cli.Scan(ctx, db.ScanOptions{
	Namespace: nsUsers,
	PartKey:   partKey,
	Prefix:    []byte("u:"),
	Limit:     100,
	Reverse:   false,
	ReadMode:  db.ReadLinearizable,
})
if err != nil {
	log.Fatal(err)
}
defer it.Close()

for it.Next() {
	e := it.Entry()
	_ = e
}
if err := it.Err(); err != nil {
	log.Fatal(err)
}

_ = cli.DeletePrefix(ctx, nsUsers, partKey, []byte("temp:"))
_ = cli.DeleteRange(ctx, nsUsers, partKey, []byte("a"), []byte("m"))
_ = cli.DropNamespace(ctx, 99)

Key KV behavioral notes:

  • Passing val = nil to Put stores an empty non-nil slice []byte{} (len == 0), cleanly distinct from a missing key (ErrNotFound).
  • ReadLinearizable confirms leader quorum via ReadIndex, while ReadStaleOK serves an immediate local read without quorum (allowing follower reads).
  • MultiGet does not fail on missing keys—absent entries return with entry.Version == 0.
  • In CAS, passing expectedVer == 0 inserts only if the key does not exist; on ErrCASConflict, currentEntry already contains the latest server value and version.
  • Scan, MultiGet, and DeleteRange operate either within a single partition (partKey != nil) or globally across all 4096 partitions when partKey == nil (via K-way merge). Always call it.Close() to release the snapshot lease before MaxSnapshotLifetime.

4. Atomic Batch Writes (KV + Streams in 1 WAL Entry)

db.Batch encodes mutations into a flat arena (achieving zero heap allocations when reused via batch.Reset()) and atomically applies KV updates, counters, stream appends, and cursor commits under one partKey:

Go
batch := db.NewBatch()
var unreadCount int64
var msgReceipt db.StreamReceipt

chatPK := []byte("chat:room-101")
batch.Put(10, []byte("room:last_active"), []byte("2026-11-30T12:00:00Z"), 0)
batch.AddInt64(10, []byte("room:total_msgs"), 1, 0, &unreadCount)
batch.AppendStream(12, []byte("messages"), 90001, []byte("sender:u42"), []byte("Hello!"), &msgReceipt)
batch.CommitCursor(12, []byte("messages"), "user:u42", 1)

if err := cli.ApplyBatch(ctx, chatPK, batch); err != nil {
	log.Fatal(err)
}

After ApplyBatch succeeds, &unreadCount and &msgReceipt are populated automatically with server-assigned values.

5. ACID Transactions (View and Update: RYOW, 1PC, and 2PC SSI)

  • View(ctx, mode, fn) executes multiple reads (Get, MultiGet, Scan, GetStream, ReadStream, GetCursor) against one consistent snapshot timestamp ReadTS.
  • Update(ctx, fn, opts...) provides a Read-Your-Own-Writes (RYOW) buffer and strict Serializable Snapshot Isolation (SSI). Single-partition transactions commit via a 1-RTT fast path (OpTxCommit1PC); transactions spanning 2 to 32 partitions automatically execute distributed 2PC SSI (Prewrite → Commit Primary → Commit Secondaries) with built-in zombie lock cleanup and forward recovery.
Go
err := cli.Update(ctx, func(tx db.WriteTx) error {
	fromPK := []byte("acct:alice")
	toPK := []byte("acct:bob")

	ent, err := tx.Get(ctx, 10, fromPK, []byte("balance"))
	if err != nil {
		return err
	}
	curBal := int64(binary.BigEndian.Uint64(ent.Value))
	if curBal < 250 {
		return errors.New("insufficient funds")
	}

	var newAliceBal, newBobBal int64
	if err := tx.AddInt64(ctx, 10, fromPK, []byte("balance"), -250, 0, &newAliceBal); err != nil {
		return err
	}
	if err := tx.AddInt64(ctx, 10, toPK, []byte("balance"), +250, 0, &newBobBal); err != nil {
		return err
	}

	return tx.Put(ctx, 10, toPK, []byte("last_tx"), []byte("from:alice:250"), 0)
})
if errors.Is(err, db.ErrTxConflict) {
	return
}
  • db.WithBlindWrite() option: when a transaction blindly overwrites keys without depending on read values, pass cli.Update(ctx, fn, db.WithBlindWrite()) to bypass ReadSet validation while still honoring active 2PC locks from concurrent transactions.
  • ModeCluster constraint: transactions containing Streams operations or DeleteRange/DeletePrefix must stay within a single partition in cluster mode (colocate them with a shared partKey). Cross-partition 2PC transactions support Put, Delete, and AddInt64.