CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com-apple-foundationdb-bindings-go

Go language bindings for FoundationDB, a distributed key-value store with ACID transactions

Pending
Overview
Eval results
Files

fdb.mddocs/

FDB Package - FoundationDB Go Bindings

Overview

The fdb package provides comprehensive Go bindings for FoundationDB, a distributed key-value store with strong ACID guarantees. This package enables Go applications to interact with FoundationDB clusters through a high-level, idiomatic Go API.

Package Path: github.com/apple/foundationdb/bindings/go/src/fdb

Supported API Versions: 200-730

Requirements:

  • CGO enabled
  • FoundationDB C API client libraries installed

API Version Management

Functions

{ .api }

APIVersion

func APIVersion(version int) error

Sets the runtime behavior of the fdb package. Must be called before any other fdb functions. This function is thread-safe.

Parameters:

  • version: API version to use (200-730)

Returns: Error if version is not supported

Example:

if err := fdb.APIVersion(730); err != nil {
    log.Fatal(err)
}

MustAPIVersion

func MustAPIVersion(version int)

Like APIVersion but panics on error. Convenient for initialization.

Example:

fdb.MustAPIVersion(730)

GetAPIVersion

func GetAPIVersion() (int, error)

Returns the selected API version, or error if not yet set.

Returns:

  • API version number
  • Error if version not set

MustGetAPIVersion

func MustGetAPIVersion() int

Like GetAPIVersion but panics if API version has not been set.

IsAPIVersionSelected

func IsAPIVersionSelected() bool

Checks if API version has been selected.

Returns: true if APIVersion or MustAPIVersion has been called


Database Connection

Constants

{ .api }

const DefaultClusterFile string = ""

Empty string constant that allows platform-appropriate default cluster file selection.

Functions

{ .api }

OpenDefault

func OpenDefault() (Database, error)

Opens database using the platform's default cluster file.

Returns:

  • Database handle
  • Error if connection fails

Example:

db, err := fdb.OpenDefault()
if err != nil {
    log.Fatal(err)
}
defer db.Close()

MustOpenDefault

func MustOpenDefault() Database

Like OpenDefault but panics on error.

OpenDatabase

func OpenDatabase(clusterFile string) (Database, error)

Opens database with specified cluster file path.

Parameters:

  • clusterFile: Path to cluster file, or empty string for default

Returns:

  • Database handle
  • Error if connection fails

Note: Multiple calls with the same clusterFile return a cached database instance. Call Close() to release resources.

MustOpenDatabase

func MustOpenDatabase(clusterFile string) Database

Like OpenDatabase but panics on error.

OpenWithConnectionString

func OpenWithConnectionString(connectionString string) (Database, error)

Opens database using a connection string instead of a cluster file. Useful for short-lived connections or testing different connection strings.

Parameters:

  • connectionString: Non-empty connection string

Returns:

  • Database handle (not cached)
  • Error if connection fails

Note: Caller must call Close() to release resources.


Database Type

Type Definition

{ .api }

type Database struct {
    // contains filtered or unexported fields
}

Database is a handle to a FoundationDB database. Database is lightweight, efficiently copied, and safe for concurrent use by multiple goroutines.

Methods

{ .api }

CreateTransaction

func (d Database) CreateTransaction() (Transaction, error)

Creates a new transaction. Generally preferable to use Transact method which handles retries automatically.

Returns:

  • Transaction handle
  • Error if transaction creation fails

Transact

func (d Database) Transact(f func(Transaction) (interface{}, error)) (interface{}, error)

Runs a function inside a retry loop with automatic commit. Handles retryable errors automatically.

Parameters:

  • f: Transactional function that receives a Transaction

Returns:

  • Result from function f
  • Error if non-retryable error occurs

Example:

result, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
    tr.Set(fdb.Key("key"), []byte("value"))
    return tr.Get(fdb.Key("key")).MustGet(), nil
})

Important Notes:

  • Do not return Future objects from the function
  • The transaction is committed automatically after the function completes
  • Use MustGet() for panic-based error handling within transactional functions
  • Retryable errors trigger automatic retry

ReadTransact

func (d Database) ReadTransact(f func(ReadTransaction) (interface{}, error)) (interface{}, error)

Runs a read-only function inside a retry loop. Transactions are not committed and are destroyed automatically.

Parameters:

  • f: Read-only transactional function

Returns:

  • Result from function f
  • Error if non-retryable error occurs

Example:

result, err := db.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) {
    return rtr.Get(fdb.Key("key")).Get()
})

Options

func (d Database) Options() DatabaseOptions

Returns a DatabaseOptions instance for setting database-specific options.

Close

func (d Database) Close()

Closes the database and cleans up resources. Must be called exactly once for each created database. Do not reuse database after closing.

CreateTenant

func (d Database) CreateTenant(name KeyConvertible) error

Creates a new tenant in the cluster. Tenant name cannot start with \xff byte.

Parameters:

  • name: Tenant name

Returns: Error if tenant exists or name is invalid

DeleteTenant

func (d Database) DeleteTenant(name KeyConvertible) error

Deletes an existing tenant.

Parameters:

  • name: Tenant name

Returns: Error if tenant doesn't exist

OpenTenant

func (d Database) OpenTenant(name KeyConvertible) (Tenant, error)

Opens a handle to an existing tenant.

Parameters:

  • name: Tenant name

Returns:

  • Tenant handle
  • Error if tenant doesn't exist

ListTenants

func (d Database) ListTenants() ([]Key, error)

Lists all existing tenants in the cluster.

Returns:

  • Slice of tenant names
  • Error if operation fails

LocalityGetBoundaryKeys

func (d Database) LocalityGetBoundaryKeys(er ExactRange, limit int, readVersion int64) ([]Key, error)

Returns keys at the start of contiguous ranges stored on a single server.

Parameters:

  • er: Range to query
  • limit: Maximum keys to return (0 = unlimited)
  • readVersion: Read version to use (0 = latest)

Returns:

  • Slice of boundary keys
  • Error if operation fails

GetClientStatus

func (d Database) GetClientStatus() ([]byte, error)

Returns JSON-formatted client status information including multi-version client details and connection status.

Returns:

  • JSON byte slice
  • Error if multi-version client API is unavailable

RebootWorker

func (d Database) RebootWorker(address string, checkFile bool, suspendDuration int) error

Reboots a worker process at the specified address.

Parameters:

  • address: Process address as "IP:Port"
  • checkFile: Whether to check data directory writability
  • suspendDuration: Suspension duration in seconds (0 = no suspension)

Returns: Error if reboot request fails


DatabaseOptions Type

Type Definition

{ .api }

type DatabaseOptions struct {
    // contains filtered or unexported fields
}

DatabaseOptions is a handle for setting options that affect a Database object.

Methods

{ .api }

SetLocationCacheSize

func (o DatabaseOptions) SetLocationCacheSize(param int64) error

Sets the size of the location cache. Default: 100000.

SetMaxWatches

func (o DatabaseOptions) SetMaxWatches(param int64) error

Sets the maximum number of outstanding watches. Default: 10000, Maximum: 1000000.

SetMachineId

func (o DatabaseOptions) SetMachineId(param string) error

Sets machine ID for location-aware load balancing.

SetDatacenterId

func (o DatabaseOptions) SetDatacenterId(param string) error

Sets datacenter ID for location-aware load balancing.

SetSnapshotRywEnable

func (o DatabaseOptions) SetSnapshotRywEnable() error

Enables snapshot read-your-writes. This is the default behavior.

SetSnapshotRywDisable

func (o DatabaseOptions) SetSnapshotRywDisable() error

Disables snapshot read-your-writes.

SetTransactionTimeout

func (o DatabaseOptions) SetTransactionTimeout(param int64) error

Sets transaction timeout in milliseconds for all transactions on this database.

SetTransactionRetryLimit

func (o DatabaseOptions) SetTransactionRetryLimit(param int64) error

Sets maximum retry count for all transactions.

SetTransactionMaxRetryDelay

func (o DatabaseOptions) SetTransactionMaxRetryDelay(param int64) error

Sets maximum backoff delay in milliseconds for retries.

SetTransactionSizeLimit

func (o DatabaseOptions) SetTransactionSizeLimit(param int64) error

Sets transaction size limit in bytes.

SetTransactionCausalReadRisky

func (o DatabaseOptions) SetTransactionCausalReadRisky() error

Sets causal read risky mode for all transactions.

SetTransactionIncludePortInAddress

func (o DatabaseOptions) SetTransactionIncludePortInAddress() error

Deprecated: Enabled by default in API version 630+.

SetTransactionAutomaticIdempotency

func (o DatabaseOptions) SetTransactionAutomaticIdempotency() error

Sets random idempotency ID for all transactions on this database.

SetTransactionBypassUnreadable

func (o DatabaseOptions) SetTransactionBypassUnreadable() error

Allows get operations on unreadable keyspace for all transactions.

SetTransactionUsedDuringCommitProtectionDisable

func (o DatabaseOptions) SetTransactionUsedDuringCommitProtectionDisable() error

Disables operation-during-commit protection for all transactions.

SetTransactionLoggingMaxFieldLength

func (o DatabaseOptions) SetTransactionLoggingMaxFieldLength(param int64) error

Sets maximum field length for transaction logging.

SetTransactionReportConflictingKeys

func (o DatabaseOptions) SetTransactionReportConflictingKeys() error

Enables conflicting key reporting for all transactions.

SetTestCausalReadRisky

func (o DatabaseOptions) SetTestCausalReadRisky(param int64) error

Enables causal read risky verification for testing.

SetUseConfigDatabase

func (o DatabaseOptions) SetUseConfigDatabase() error

Uses configuration database instead of cluster file.


Transaction Type

Type Definition

{ .api }

type Transaction struct {
    // contains filtered or unexported fields
}

Transaction is a handle to a FoundationDB transaction. It is lightweight, efficiently copied, and safe for concurrent use by multiple goroutines.

Transactions provide ACID properties: atomicity, isolation, durability, and consistency. All read and write operations see a consistent snapshot of the database. Changes only persist if the transaction commits successfully.

Read Methods

{ .api }

Get

func (t Transaction) Get(key KeyConvertible) FutureByteSlice

Reads the value associated with a key asynchronously.

Parameters:

  • key: Key to read

Returns: FutureByteSlice that will contain the value (or nil if key doesn't exist)

Example:

future := tr.Get(fdb.Key("mykey"))
value, err := future.Get()
if err != nil {
    return err
}
if value != nil {
    fmt.Printf("Value: %s\n", value)
}

GetKey

func (t Transaction) GetKey(sel Selectable) FutureKey

Resolves a key selector to an actual key asynchronously.

Parameters:

  • sel: Key selector (FirstGreaterOrEqual, LastLessThan, etc.)

Returns: FutureKey containing the resolved key

GetRange

func (t Transaction) GetRange(r Range, options RangeOptions) RangeResult

Reads a range of key-value pairs asynchronously.

Parameters:

  • r: Range specifying begin and end
  • options: Range options (limit, mode, reverse)

Returns: RangeResult for iterating over key-value pairs

Example:

kr := fdb.KeyRange{Begin: fdb.Key("a"), End: fdb.Key("z")}
rangeResult := tr.GetRange(kr, fdb.RangeOptions{Limit: 100})
kvs, err := rangeResult.GetSliceWithError()
if err != nil {
    return err
}
for _, kv := range kvs {
    fmt.Printf("%s = %s\n", kv.Key, kv.Value)
}

GetReadVersion

func (t Transaction) GetReadVersion() FutureInt64

Returns the transaction's read version asynchronously.

Returns: FutureInt64 containing read version

GetVersionstamp

func (t Transaction) GetVersionstamp() FutureKey

Returns the versionstamp for this transaction. Only ready after successful commit.

Returns: FutureKey containing 10-byte versionstamp

GetApproximateSize

func (t Transaction) GetApproximateSize() FutureInt64

Returns approximate transaction size (mutations + conflict ranges) in bytes.

Returns: FutureInt64 containing size estimate

GetEstimatedRangeSizeBytes

func (t Transaction) GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64

Estimates the number of bytes stored in a range. More accurate for ranges larger than 3MB.

Parameters:

  • r: Exact range to estimate

Returns: FutureInt64 containing size estimate

GetRangeSplitPoints

func (t Transaction) GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArray

Returns keys that split a range into roughly equal chunks.

Parameters:

  • r: Range to split
  • chunkSize: Target chunk size in bytes

Returns: FutureKeyArray containing split point keys (includes begin and end keys)

GetDatabase

func (t Transaction) GetDatabase() Database

Returns the database handle associated with this transaction.

Snapshot

func (t Transaction) Snapshot() Snapshot

Returns a Snapshot view of the transaction for snapshot reads with relaxed isolation.

Returns: Snapshot handle

Example:

snapshot := tr.Snapshot()
value := snapshot.Get(fdb.Key("key")).MustGet()

GetCommittedVersion

func (t Transaction) GetCommittedVersion() (int64, error)

Returns the version at which the transaction was committed. Must be called after successful commit.

Returns:

  • Committed version (-1 for read-only transactions)
  • Error if called before commit

Write Methods

{ .api }

Set

func (t Transaction) Set(key KeyConvertible, value []byte)

Sets a key to a value, overwriting any previous value.

Parameters:

  • key: Key to set
  • value: Value to store

Example:

tr.Set(fdb.Key("mykey"), []byte("myvalue"))

Clear

func (t Transaction) Clear(key KeyConvertible)

Removes a key and its associated value.

Parameters:

  • key: Key to remove

ClearRange

func (t Transaction) ClearRange(r ExactRange)

Removes all keys in a range [begin, end). Efficient for large ranges - only begin and end keys count toward transaction size.

Parameters:

  • r: Range to clear

Example:

kr := fdb.KeyRange{Begin: fdb.Key("a"), End: fdb.Key("z")}
tr.ClearRange(kr)

Atomic Operations

{ .api }

Atomic operations perform read-modify-write operations in a single command, without conflict.

Add

func (t Transaction) Add(key KeyConvertible, param []byte)

Performs atomic addition of little-endian integers. If key doesn't exist or is shorter than param, it's extended with zero bytes. If param is shorter, value is truncated.

Parameters:

  • key: Key to modify
  • param: Little-endian integer to add

Example:

// Increment counter by 1
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, 1)
tr.Add(fdb.Key("counter"), buf)

BitAnd

func (t Transaction) BitAnd(key KeyConvertible, param []byte)

Performs bitwise AND operation. If key doesn't exist, param is stored.

BitOr

func (t Transaction) BitOr(key KeyConvertible, param []byte)

Performs bitwise OR operation.

BitXor

func (t Transaction) BitXor(key KeyConvertible, param []byte)

Performs bitwise XOR operation.

Max

func (t Transaction) Max(key KeyConvertible, param []byte)

Performs little-endian comparison and stores the larger value.

Min

func (t Transaction) Min(key KeyConvertible, param []byte)

Performs little-endian comparison and stores the smaller value.

ByteMax

func (t Transaction) ByteMax(key KeyConvertible, param []byte)

Performs lexicographic comparison and stores the larger value.

ByteMin

func (t Transaction) ByteMin(key KeyConvertible, param []byte)

Performs lexicographic comparison and stores the smaller value.

CompareAndClear

func (t Transaction) CompareAndClear(key KeyConvertible, param []byte)

Clears the key if its value equals param.

Parameters:

  • key: Key to conditionally clear
  • param: Value to compare against

SetVersionstampedKey

func (t Transaction) SetVersionstampedKey(key KeyConvertible, param []byte)

Transforms key using a versionstamp and sets it to param. The last 4 bytes of key specify the position where the 10-byte versionstamp will be placed.

SetVersionstampedValue

func (t Transaction) SetVersionstampedValue(key KeyConvertible, param []byte)

Sets key to a versionstamped value. The last 4 bytes of param specify the position where the 10-byte versionstamp will be placed.

AppendIfFits

func (t Transaction) AppendIfFits(key KeyConvertible, param []byte)

Appends param to existing value if final size is within limits. No error is returned if value is too large - mutation silently fails.

Transaction Control

{ .api }

Commit

func (t Transaction) Commit() FutureNil

Attempts to commit the transaction. Blocks until commit completes or fails.

Returns: FutureNil that resolves to nil on success or error on failure

Example:

err := tr.Commit().Get()
if err != nil {
    // Handle commit error
}

OnError

func (t Transaction) OnError(e Error) FutureNil

Determines if an error is retryable. Blocks for appropriate delay if retryable, returns same error if fatal.

Parameters:

  • e: FDB error to check

Returns: FutureNil that resolves to nil for retryable errors or error for fatal errors

Note: Typically used by Transact method - direct use is rare.

Reset

func (t Transaction) Reset()

Resets transaction to initial state. Equivalent to destroying and creating a new transaction.

Cancel

func (t Transaction) Cancel()

Cancels the transaction. All pending operations will fail. Transaction can be reused after Reset.

Warning: Racing Cancel with Commit has unpredictable behavior.

SetReadVersion

func (t Transaction) SetReadVersion(version int64)

Sets the read version for the transaction. Cannot guarantee causal consistency.

Parameters:

  • version: Database version to read from

Transact

func (t Transaction) Transact(f func(Transaction) (interface{}, error)) (interface{}, error)

Executes a function with this transaction. Does not retry or commit automatically. Allows transaction composition.

Parameters:

  • f: Function to execute

Returns:

  • Result from function
  • Error if function fails

ReadTransact

func (t Transaction) ReadTransact(f func(ReadTransaction) (interface{}, error)) (interface{}, error)

Executes a read-only function with this transaction. Does not retry.

Options

func (t Transaction) Options() TransactionOptions

Returns TransactionOptions for setting transaction-specific options.

Watch

{ .api }

Watch

func (t Transaction) Watch(key KeyConvertible) FutureNil

Creates a watch that triggers when the key's value changes. Watch is relative to this transaction's view.

Parameters:

  • key: Key to watch

Returns: FutureNil that completes when key changes

Important Notes:

  • Maximum 10,000 watches per database connection (configurable)
  • Watch outlives the transaction
  • Cancel unused watches to avoid hitting limit
  • Transaction errors set all watches to same error

Example:

watch := tr.Watch(fdb.Key("key"))
err := tr.Commit().Get()
if err != nil {
    return err
}
// Wait for key to change
err = watch.Get()

Conflict Ranges

{ .api }

AddReadConflictRange

func (t Transaction) AddReadConflictRange(er ExactRange) error

Adds a range to the transaction's read conflict ranges. Other transactions writing to this range will cause conflict.

Parameters:

  • er: Exact range to add

Returns: Error if operation fails

AddReadConflictKey

func (t Transaction) AddReadConflictKey(key KeyConvertible) error

Adds a single key to read conflict ranges.

Parameters:

  • key: Key to add

Returns: Error if operation fails

AddWriteConflictRange

func (t Transaction) AddWriteConflictRange(er ExactRange) error

Adds a range to write conflict ranges. Other transactions reading this range will cause conflict.

AddWriteConflictKey

func (t Transaction) AddWriteConflictKey(key KeyConvertible) error

Adds a single key to write conflict ranges.

Locality

{ .api }

LocalityGetAddressesForKey

func (t Transaction) LocalityGetAddressesForKey(key KeyConvertible) FutureStringSlice

Returns public network addresses of storage servers responsible for a key.

Parameters:

  • key: Key to query

Returns: FutureStringSlice containing server addresses


TransactionOptions Type

Type Definition

{ .api }

type TransactionOptions struct {
    // contains filtered or unexported fields
}

TransactionOptions provides methods to set options that affect a Transaction.

Key Methods

{ .api }

SetCausalWriteRisky

func (o TransactionOptions) SetCausalWriteRisky() error

Enables causal write risky mode.

SetCausalReadRisky

func (o TransactionOptions) SetCausalReadRisky() error

Enables causal read risky mode.

SetCausalReadDisable

func (o TransactionOptions) SetCausalReadDisable() error

Disables causal read guarantees.

SetReadYourWritesDisable

func (o TransactionOptions) SetReadYourWritesDisable() error

Disables read-your-writes behavior.

SetReadAheadDisable

func (o TransactionOptions) SetReadAheadDisable() error

Disables read-ahead optimization.

SetAccessSystemKeys

func (o TransactionOptions) SetAccessSystemKeys() error

Allows reading and writing system keys (keys starting with \xff).

SetReadSystemKeys

func (o TransactionOptions) SetReadSystemKeys() error

Allows reading system keys.

SetPrioritySystemImmediate

func (o TransactionOptions) SetPrioritySystemImmediate() error

Sets transaction priority to system immediate (highest).

SetPriorityBatch

func (o TransactionOptions) SetPriorityBatch() error

Sets transaction priority to batch (lowest).

SetInitializeNewDatabase

func (o TransactionOptions) SetInitializeNewDatabase() error

Allows transaction to initialize a new database.

SetTimeout

func (o TransactionOptions) SetTimeout(param int64) error

Sets transaction timeout in milliseconds.

SetRetryLimit

func (o TransactionOptions) SetRetryLimit(param int64) error

Sets maximum number of retries.

SetMaxRetryDelay

func (o TransactionOptions) SetMaxRetryDelay(param int64) error

Sets maximum backoff delay in milliseconds.

SetSizeLimit

func (o TransactionOptions) SetSizeLimit(param int64) error

Sets transaction size limit in bytes.

SetLockAware

func (o TransactionOptions) SetLockAware() error

Allows transaction to read and write in locked keyspace.

SetReadLockAware

func (o TransactionOptions) SetReadLockAware() error

Allows transaction to read from locked keyspace.

SetDebugTransactionIdentifier

func (o TransactionOptions) SetDebugTransactionIdentifier(param string) error

Sets debug identifier for transaction logging.

SetLogTransaction

func (o TransactionOptions) SetLogTransaction() error

Enables transaction logging for debugging.

SetTransactionLoggingMaxFieldLength

func (o TransactionOptions) SetTransactionLoggingMaxFieldLength(param int64) error

Sets maximum field length for transaction logs.

SetServerRequestTracing

func (o TransactionOptions) SetServerRequestTracing() error

Enables server-side request tracing.

SetUsedDuringCommitProtectionDisable

func (o TransactionOptions) SetUsedDuringCommitProtectionDisable() error

Disables protection against operations during commit.

SetReportConflictingKeys

func (o TransactionOptions) SetReportConflictingKeys() error

Enables conflicting key reporting on transaction conflict.

SetExpensiveClearCostEstimationEnable

func (o TransactionOptions) SetExpensiveClearCostEstimationEnable() error

Enables expensive clear cost estimation.

SetBypassUnreadable

func (o TransactionOptions) SetBypassUnreadable() error

Allows get operations on unreadable keyspace.

SetFirstInBatch

func (o TransactionOptions) SetFirstInBatch() error

Marks transaction as first in batch.

SetIdempotencyId

func (o TransactionOptions) SetIdempotencyId(param [16]byte) error

Sets idempotency ID for transaction deduplication.

SetAutomaticIdempotency

func (o TransactionOptions) SetAutomaticIdempotency() error

Enables automatic idempotency ID generation.

SetSpecialKeySpaceEnableWrites

func (o TransactionOptions) SetSpecialKeySpaceEnableWrites() error

Enables writes to special keyspace (required for tenant operations).

SetAuthorizationToken

func (o TransactionOptions) SetAuthorizationToken(param string) error

Sets authorization token for authentication.


ReadTransaction Interface

Interface Definition

{ .api }

type ReadTransaction interface {
    Get(key KeyConvertible) FutureByteSlice
    GetKey(sel Selectable) FutureKey
    GetRange(r Range, options RangeOptions) RangeResult
    GetReadVersion() FutureInt64
    GetDatabase() Database
    Snapshot() Snapshot
    GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64
    GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArray
    Options() TransactionOptions
    Cancel()

    ReadTransactor
}

ReadTransaction defines read-only operations available on transactions and snapshots. Both Transaction and Snapshot implement this interface.


Transactor Interface

Interface Definition

{ .api }

type Transactor interface {
    Transact(func(Transaction) (interface{}, error)) (interface{}, error)
    ReadTransactor
}

Transactor is implemented by Database, Transaction, and Tenant. Allows transactional functions to accept any of these types.

Example:

func updateCounter(t fdb.Transactor, key fdb.Key) error {
    _, err := t.Transact(func(tr fdb.Transaction) (interface{}, error) {
        val := tr.Get(key).MustGet()
        count := binary.LittleEndian.Uint64(val)
        count++
        buf := make([]byte, 8)
        binary.LittleEndian.PutUint64(buf, count)
        tr.Set(key, buf)
        return nil, nil
    })
    return err
}

// Can be called with Database, Transaction, or Tenant
updateCounter(db, fdb.Key("counter"))

ReadTransactor Interface

Interface Definition

{ .api }

type ReadTransactor interface {
    ReadTransact(func(ReadTransaction) (interface{}, error)) (interface{}, error)
}

ReadTransactor is implemented by Database, Transaction, Snapshot, and Tenant. Allows read-only transactional functions.

Example:

func getKey(rt fdb.ReadTransactor, key fdb.Key) ([]byte, error) {
    result, err := rt.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) {
        return rtr.Get(key).Get()
    })
    if err != nil {
        return nil, err
    }
    return result.([]byte), nil
}

Tenant Type

Type Definition

{ .api }

type Tenant struct {
    // contains filtered or unexported fields
}

Tenant is a handle to a FoundationDB tenant. All transactions created by a tenant operate on the tenant's isolated keyspace. Tenant is lightweight, efficiently copied, and safe for concurrent use.

Methods

{ .api }

CreateTransaction

func (t Tenant) CreateTransaction() (Transaction, error)

Creates a transaction in the tenant's keyspace.

Returns:

  • Transaction operating on tenant keyspace
  • Error if creation fails

Transact

func (t Tenant) Transact(f func(Transaction) (interface{}, error)) (interface{}, error)

Runs a function in a retry loop with automatic commit in tenant keyspace.

Example:

tenant, _ := db.OpenTenant(fdb.Key("my-tenant"))
result, err := tenant.Transact(func(tr fdb.Transaction) (interface{}, error) {
    tr.Set(fdb.Key("key"), []byte("value"))
    return nil, nil
})

ReadTransact

func (t Tenant) ReadTransact(f func(ReadTransaction) (interface{}, error)) (interface{}, error)

Runs a read-only function in tenant keyspace.


Snapshot Type

Type Definition

{ .api }

type Snapshot struct {
    // contains filtered or unexported fields
}

Snapshot provides snapshot reads with relaxed isolation. Snapshot reads see a consistent view of the database but don't create read conflicts, reducing transaction conflicts.

Methods

{ .api }

All read methods from ReadTransaction are available:

Get

func (s Snapshot) Get(key KeyConvertible) FutureByteSlice

Performs snapshot read of a key.

GetKey

func (s Snapshot) GetKey(sel Selectable) FutureKey

Resolves key selector as snapshot read.

GetRange

func (s Snapshot) GetRange(r Range, options RangeOptions) RangeResult

Performs snapshot range read.

GetReadVersion

func (s Snapshot) GetReadVersion() FutureInt64

Gets read version for snapshot.

GetDatabase

func (s Snapshot) GetDatabase() Database

Returns associated database handle.

GetEstimatedRangeSizeBytes

func (s Snapshot) GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64

Estimates range size as snapshot read.

GetRangeSplitPoints

func (s Snapshot) GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArray

Gets split points as snapshot read.

Snapshot

func (s Snapshot) Snapshot() Snapshot

Returns self.

Options

func (s Snapshot) Options() TransactionOptions

Returns transaction options.

Cancel

func (s Snapshot) Cancel()

Cancels the underlying transaction.

ReadTransact

func (s Snapshot) ReadTransact(f func(ReadTransaction) (interface{}, error)) (interface{}, error)

Executes read-only function without retry.


Future Types

Futures represent asynchronous operations. All futures provide BlockUntilReady, IsReady, and Cancel methods.

Future Interface

{ .api }

type Future interface {
    BlockUntilReady()
    IsReady() bool
    Cancel()
}

BlockUntilReady

func (f Future) BlockUntilReady()

Blocks until the future is ready (has value or error).

IsReady

func (f Future) IsReady() bool

Returns true if future is ready, false otherwise (non-blocking).

Cancel

func (f Future) Cancel()

Cancels the asynchronous operation. No effect if already ready.

FutureByteSlice

{ .api }

type FutureByteSlice interface {
    Get() ([]byte, error)
    MustGet() []byte
    Future
}

Result of Get operations. Returns byte slice or nil if key doesn't exist.

Get

func (f FutureByteSlice) Get() ([]byte, error)

Blocks and returns value or error.

MustGet

func (f FutureByteSlice) MustGet() []byte

Blocks and returns value, panics on error.

FutureKey

{ .api }

type FutureKey interface {
    Get() (Key, error)
    MustGet() Key
    Future
}

Result of GetKey operations.

Get

func (f FutureKey) Get() (Key, error)

Blocks and returns key or error.

MustGet

func (f FutureKey) MustGet() Key

Blocks and returns key, panics on error.

FutureNil

{ .api }

type FutureNil interface {
    Get() error
    MustGet()
    Future
}

Result of operations with no return value (Commit, Watch, OnError).

Get

func (f FutureNil) Get() error

Blocks and returns error or nil on success.

MustGet

func (f FutureNil) MustGet()

Blocks and panics on error.

FutureInt64

{ .api }

type FutureInt64 interface {
    Get() (int64, error)
    MustGet() int64
    Future
}

Result of operations returning int64 (GetReadVersion, GetApproximateSize, etc.).

Get

func (f FutureInt64) Get() (int64, error)

Blocks and returns int64 or error.

MustGet

func (f FutureInt64) MustGet() int64

Blocks and returns int64, panics on error.

FutureKeyArray

{ .api }

type FutureKeyArray interface {
    Get() ([]Key, error)
    MustGet() []Key
    Future
}

Result of operations returning key arrays (GetRangeSplitPoints).

Get

func (f FutureKeyArray) Get() ([]Key, error)

Blocks and returns key array or error.

MustGet

func (f FutureKeyArray) MustGet() []Key

Blocks and returns key array, panics on error.

FutureStringSlice

{ .api }

type FutureStringSlice interface {
    Get() ([]string, error)
    MustGet() []string
    Future
}

Result of locality operations returning string arrays.


Key Types

Key Type

{ .api }

type Key []byte

Key is a lexicographically-ordered byte sequence. Implements KeyConvertible.

FDBKey

func (k Key) FDBKey() Key

Returns self, implementing KeyConvertible.

String

func (k Key) String() string

Returns human-readable representation using Printable.

KeyConvertible Interface

{ .api }

type KeyConvertible interface {
    FDBKey() Key
}

Types implementing KeyConvertible can be used as keys. Includes Key, tuple.Tuple, and subspace.Subspace.

KeySelector Type

{ .api }

type KeySelector struct {
    Key     KeyConvertible
    OrEqual bool
    Offset  int
}

KeySelector describes a key relative to another key. Used for range queries and key resolution.

FDBKeySelector

func (ks KeySelector) FDBKeySelector() KeySelector

Returns self, implementing Selectable.

Key Selector Constructors

{ .api }

FirstGreaterOrEqual

func FirstGreaterOrEqual(key KeyConvertible) KeySelector

Returns selector for the first key >= given key.

FirstGreaterThan

func FirstGreaterThan(key KeyConvertible) KeySelector

Returns selector for the first key > given key.

LastLessOrEqual

func LastLessOrEqual(key KeyConvertible) KeySelector

Returns selector for the last key <= given key.

LastLessThan

func LastLessThan(key KeyConvertible) KeySelector

Returns selector for the last key < given key.

Example:

// Get all keys from "a" (inclusive) to "z" (exclusive)
begin := fdb.FirstGreaterOrEqual(fdb.Key("a"))
end := fdb.FirstGreaterOrEqual(fdb.Key("z"))
rangeResult := tr.GetRange(fdb.SelectorRange{begin, end}, fdb.RangeOptions{})

Selectable Interface

{ .api }

type Selectable interface {
    FDBKeySelector() KeySelector
}

Types that can be converted to KeySelector. Implemented by KeySelector and Key (which converts to FirstGreaterOrEqual).


Range Types

Range Interface

{ .api }

type Range interface {
    FDBRangeKeySelectors() (begin, end Selectable)
}

Describes a range using key selectors.

ExactRange Interface

{ .api }

type ExactRange interface {
    FDBRangeKeys() (begin, end KeyConvertible)
    Range
}

Describes a range using exact keys. All ExactRanges are also Ranges.

KeyRange Type

{ .api }

type KeyRange struct {
    Begin KeyConvertible  // Inclusive
    End   KeyConvertible  // Exclusive
}

Exact range specified by begin and end keys.

FDBRangeKeys

func (kr KeyRange) FDBRangeKeys() (KeyConvertible, KeyConvertible)

Returns begin and end keys.

FDBRangeKeySelectors

func (kr KeyRange) FDBRangeKeySelectors() (Selectable, Selectable)

Returns FirstGreaterOrEqual selectors for begin and end.

Example:

kr := fdb.KeyRange{
    Begin: fdb.Key("user/"),
    End:   fdb.Key("user0"),
}
kvs, _ := tr.GetRange(kr, fdb.RangeOptions{}).GetSliceWithError()

SelectorRange Type

{ .api }

type SelectorRange struct {
    Begin Selectable
    End   Selectable
}

Range specified by key selectors.

FDBRangeKeySelectors

func (sr SelectorRange) FDBRangeKeySelectors() (Selectable, Selectable)

Returns begin and end selectors.

PrefixRange Function

{ .api }

func PrefixRange(prefix []byte) (KeyRange, error)

Returns a KeyRange for all keys with the given prefix.

Parameters:

  • prefix: Key prefix

Returns:

  • KeyRange from prefix to first key after prefix
  • Error if prefix is empty or all 0xFF bytes

Example:

pr, _ := fdb.PrefixRange([]byte("user/"))
// Returns range ["user/", "user0")

RangeResult Type

Type Definition

{ .api }

type RangeResult struct {
    // contains filtered or unexported fields
}

RangeResult is a handle to an asynchronous range read. Safe for concurrent use.

Methods

{ .api }

GetSliceWithError

func (rr RangeResult) GetSliceWithError() ([]KeyValue, error)

Returns all key-value pairs in the range. Blocks until all reads complete.

Returns:

  • Slice of KeyValue pairs
  • Error if any read fails

GetSliceOrPanic

func (rr RangeResult) GetSliceOrPanic() []KeyValue

Returns all key-value pairs, panics on error.

Iterator

func (rr RangeResult) Iterator() *RangeIterator

Returns an iterator for lazy evaluation.

Example:

ri := rangeResult.Iterator()
for ri.Advance() {
    kv, err := ri.Get()
    if err != nil {
        return err
    }
    fmt.Printf("%s = %s\n", kv.Key, kv.Value)
}

RangeIterator Type

Type Definition

{ .api }

type RangeIterator struct {
    // contains filtered or unexported fields
}

RangeIterator iterates over key-value pairs from a range read. Should not be copied or used concurrently, but multiple iterators can be created from one RangeResult.

Methods

{ .api }

Advance

func (ri *RangeIterator) Advance() bool

Advances to next key-value pair. Must be called before each Get/MustGet.

Returns: true if more pairs exist, false if exhausted

Get

func (ri *RangeIterator) Get() (KeyValue, error)

Returns current key-value pair. Advance must have returned true.

Returns:

  • Current KeyValue
  • Error if operation failed

MustGet

func (ri *RangeIterator) MustGet() KeyValue

Returns current key-value pair, panics on error.


RangeOptions Type

Type Definition

{ .api }

type RangeOptions struct {
    Limit   int
    Mode    StreamingMode
    Reverse bool
}

RangeOptions specifies how a range read is performed.

Fields:

  • Limit: Maximum key-value pairs to return (0 = unlimited)
  • Mode: Streaming mode (default: StreamingModeIterator)
  • Reverse: If true, iterate in reverse order

Example:

opts := fdb.RangeOptions{
    Limit:   100,
    Mode:    fdb.StreamingModeWantAll,
    Reverse: false,
}

StreamingMode Type

Type Definition

{ .api }

type StreamingMode int

StreamingMode controls how range data is transferred from server to client.

Constants

{ .api }

const (
    StreamingModeWantAll  StreamingMode = -1  // Transfer entire range immediately
    StreamingModeIterator StreamingMode = 0   // Default: balance performance
    StreamingModeExact    StreamingMode = 1   // Transfer exact row limit
    StreamingModeSmall    StreamingMode = 2   // Small batches
    StreamingModeMedium   StreamingMode = 3   // Medium batches
    StreamingModeLarge    StreamingMode = 4   // Large batches
    StreamingModeSerial   StreamingMode = 5   // Maximum bandwidth batches
)

StreamingModeWantAll: Client intends to consume entire range. Transfers all data as early as possible.

StreamingModeIterator (default): Balances concerns. Starts with small batches, increases batch size as iteration continues.

StreamingModeExact: Requires specific row limit. Delivers exactly that many rows in one batch.

StreamingModeSmall: Small batches to minimize cost if iteration stops early.

StreamingModeMedium: Between small and large batches.

StreamingModeLarge: Large batches for high concurrency efficiency.

StreamingModeSerial: Maximum throughput batches for single client bandwidth.


KeyValue Type

Type Definition

{ .api }

type KeyValue struct {
    Key   Key
    Value []byte
}

KeyValue represents a single key-value pair.


Error Type

Type Definition

{ .api }

type Error struct {
    Code int
}

Error represents a FoundationDB error with error code.

Methods

{ .api }

Error

func (e Error) Error() string

Returns formatted error message with code and description.

Example:

if err != nil {
    var fdbErr fdb.Error
    if errors.As(err, &fdbErr) {
        fmt.Printf("FDB error code: %d\n", fdbErr.Code)
    }
}

Error Variables

{ .api }

var (
    ErrNetworkAlreadyStopped = errors.New("network has already been stopped")
    ErrNetworkIsStopped      = errors.New("network is stopped")
    ErrNetworkNotStarted     = errors.New("network has not been started")
    ErrMultiVersionClientUnavailable = errors.New("multi-version client API is unavailable")
)

ErrorPredicate Type

Type Definition

{ .api }

type ErrorPredicate int

ErrorPredicate constants for checking error properties.

Constants

{ .api }

const (
    ErrorPredicateRetryable             ErrorPredicate = 50000
    ErrorPredicateMaybeCommitted        ErrorPredicate = 50001
    ErrorPredicateRetryableNotCommitted ErrorPredicate = 50002
)

ErrorPredicateRetryable: Error is retryable due to transient issue.

ErrorPredicateMaybeCommitted: Transaction may have succeeded but system cannot verify.

ErrorPredicateRetryableNotCommitted: Transaction not committed but is retryable.


Utility Functions

Functions

{ .api }

Printable

func Printable(d []byte) string

Returns human-readable representation of byte array. ASCII printable characters [32-127) pass through, others shown as \xHH.

Example:

key := []byte{0x01, 'h', 'e', 'l', 'l', 'o', 0xff}
fmt.Println(fdb.Printable(key))  // Output: \x01hello\xff

Strinc

func Strinc(prefix []byte) ([]byte, error)

Returns first key outside the prefixed range. Useful for range queries.

Parameters:

  • prefix: Byte prefix

Returns:

  • First key after prefix range
  • Error if prefix is empty or all 0xFF bytes

Example:

end, _ := fdb.Strinc([]byte("user/"))
// Returns "user0" (last byte incremented)

kr := fdb.KeyRange{
    Begin: fdb.Key("user/"),
    End:   fdb.Key(end),
}

Network Functions

Functions

{ .api }

StartNetwork

func StartNetwork() error

Deprecated: Network starts automatically when database is opened. Does nothing but ensures API version is set.

StopNetwork

func StopNetwork() error

Signals network event loop to terminate and waits for completion. Thread-safe.

Returns: Error if network not started or already stopped

Example:

// At application shutdown
if err := fdb.StopNetwork(); err != nil {
    log.Printf("Error stopping network: %v", err)
}

Options

func Options() NetworkOptions

Returns a NetworkOptions instance for setting network-level options. These options must be set before opening any databases.

Returns: NetworkOptions handle for configuring the network

Example:

// Configure network options before opening database
fdb.MustAPIVersion(730)

// Enable trace logging
if err := fdb.Options().SetTraceEnable("/var/log/fdb-traces"); err != nil {
    log.Fatal(err)
}

// Set trace format to JSON
if err := fdb.Options().SetTraceFormat("json"); err != nil {
    log.Fatal(err)
}

// Configure TLS
if err := fdb.Options().SetTLSCertPath("/path/to/cert.pem"); err != nil {
    log.Fatal(err)
}
if err := fdb.Options().SetTLSKeyPath("/path/to/key.pem"); err != nil {
    log.Fatal(err)
}

// Now open database
db := fdb.MustOpenDefault()
defer db.Close()

Important: Network options must be set before calling any database opening functions (OpenDefault, OpenDatabase, etc.).


Deprecated Types

Cluster Type (Deprecated)

{ .api }

type Cluster struct {
    // contains filtered or unexported fields
}

Deprecated: Use OpenDatabase or OpenDefault to obtain database handles directly.

CreateCluster (Deprecated)

func CreateCluster(clusterFile string) (Cluster, error)

Returns cluster handle. Use OpenDatabase instead.

OpenDatabase (Deprecated)

func (c Cluster) OpenDatabase(dbName []byte) (Database, error)

Opens database from cluster. Database name must be []byte("DB"). Use fdb.OpenDatabase instead.


NetworkOptions Type

Type Definition

{ .api }

type NetworkOptions struct {
    // contains filtered or unexported fields
}

NetworkOptions is a handle for setting options that affect the entire FoundationDB client network. These options must be set before opening any databases.

Methods

{ .api }

Trace Configuration

SetTraceEnable
func (o NetworkOptions) SetTraceEnable(param string) error

Enables trace output to a file in a directory of the client's choosing.

Parameters:

  • param: Path to output directory (or empty string for current working directory)
SetTraceRollSize
func (o NetworkOptions) SetTraceRollSize(param int64) error

Sets the maximum size in bytes of a single trace output file. Range: [0, INT64_MAX]. Default: 10,485,760 bytes.

SetTraceMaxLogsSize
func (o NetworkOptions) SetTraceMaxLogsSize(param int64) error

Sets the maximum size of all trace output files combined. Range: [0, INT64_MAX]. Default: 104,857,600 bytes.

SetTraceLogGroup
func (o NetworkOptions) SetTraceLogGroup(param string) error

Sets the 'LogGroup' attribute for all events in trace output. Default: "default".

SetTraceFormat
func (o NetworkOptions) SetTraceFormat(param string) error

Selects the format of log files. Supported: "xml" (default), "json".

SetTraceClockSource
func (o NetworkOptions) SetTraceClockSource(param string) error

Selects clock source for trace files. Supported: "now" (default), "realtime".

SetTraceFileIdentifier
func (o NetworkOptions) SetTraceFileIdentifier(param string) error

String used to replace the port/PID in log file names.

SetTraceShareAmongClientThreads
func (o NetworkOptions) SetTraceShareAmongClientThreads() error

Uses the same base trace file name for all client threads (pre-7.2 behavior).

SetTraceInitializeOnSetup
func (o NetworkOptions) SetTraceInitializeOnSetup() error

Initializes trace files on network setup. Otherwise tracing starts when opening first database.

SetTracePartialFileSuffix
func (o NetworkOptions) SetTracePartialFileSuffix(param string) error

Sets file suffix for partially written log files. Include separator if adding extension (e.g., ".tmp").

TLS Configuration

SetTLSCertBytes
func (o NetworkOptions) SetTLSCertBytes(param []byte) error

Sets the certificate chain from bytes.

SetTLSCertPath
func (o NetworkOptions) SetTLSCertPath(param string) error

Sets the file path from which to load the certificate chain.

SetTLSKeyBytes
func (o NetworkOptions) SetTLSKeyBytes(param []byte) error

Sets the private key corresponding to your certificate from bytes.

SetTLSKeyPath
func (o NetworkOptions) SetTLSKeyPath(param string) error

Sets the file path from which to load the private key.

SetTLSVerifyPeers
func (o NetworkOptions) SetTLSVerifyPeers(param []byte) error

Sets the peer certificate field verification criteria.

SetTLSCaBytes
func (o NetworkOptions) SetTLSCaBytes(param []byte) error

Sets the CA bundle from bytes.

SetTLSCaPath
func (o NetworkOptions) SetTLSCaPath(param string) error

Sets the file path from which to load the CA bundle.

SetTLSPassword
func (o NetworkOptions) SetTLSPassword(param string) error

Sets the password for encrypted private key.

Client Configuration

SetKnob
func (o NetworkOptions) SetKnob(param string) error

Sets internal tuning or debugging knobs. Format: "knob_name=knob_value".

SetDisableMultiVersionClientApi
func (o NetworkOptions) SetDisableMultiVersionClientApi() error

Disables the multi-version client API and only uses the current version.

SetCallbacksOnExternalThreads
func (o NetworkOptions) SetCallbacksOnExternalThreads() error

Allows network callbacks to be called on external threads.

SetExternalClientLibrary
func (o NetworkOptions) SetExternalClientLibrary(param string) error

Adds an external client library for multi-version support.

Parameters:

  • param: Path to client library or linker-resolved name
SetExternalClientDirectory
func (o NetworkOptions) SetExternalClientDirectory(param string) error

Searches for client libraries in the specified directory for multi-version support.

SetDisableLocalClient
func (o NetworkOptions) SetDisableLocalClient() error

Prevents connections through the local client.

SetClientThreadsPerVersion
func (o NetworkOptions) SetClientThreadsPerVersion(param int64) error

Sets the number of client threads per version.

SetFutureVersionClientLibrary
func (o NetworkOptions) SetFutureVersionClientLibrary(param string) error

Adds a future version client library for testing.

SetRetainClientLibraryCopies
func (o NetworkOptions) SetRetainClientLibraryCopies() error

Prevents cleanup of client library copies loaded by the multi-version client.

SetIgnoreExternalClientFailures
func (o NetworkOptions) SetIgnoreExternalClientFailures() error

Ignores failures to load external client libraries.

SetFailIncompatibleClient
func (o NetworkOptions) SetFailIncompatibleClient() error

Fails when encountering an incompatible client library.

SetDisableClientStatisticsLogging
func (o NetworkOptions) SetDisableClientStatisticsLogging() error

Disables logging of client statistics.

SetEnableRunLoopProfiling
func (o NetworkOptions) SetEnableRunLoopProfiling() error

Enables run loop profiling for performance analysis.

SetDisableClientBypass
func (o NetworkOptions) SetDisableClientBypass() error

Disables client-side bypass optimization.

SetDistributedClientTracer
func (o NetworkOptions) SetDistributedClientTracer(param string) error

Sets the tracer type for distributed tracing.

SetClientTmpDir
func (o NetworkOptions) SetClientTmpDir(param string) error

Sets the temporary directory for client use.

Buggify Options (Testing)

SetBuggifyEnable
func (o NetworkOptions) SetBuggifyEnable() error

Enables buggify for testing. Not yet fully implemented.

SetBuggifyDisable
func (o NetworkOptions) SetBuggifyDisable() error

Disables buggify. Not yet fully implemented.

SetBuggifySectionActivatedProbability
func (o NetworkOptions) SetBuggifySectionActivatedProbability(param int64) error

Sets probability (0-100) of a BUGGIFY section being active.

SetBuggifySectionFiredProbability
func (o NetworkOptions) SetBuggifySectionFiredProbability(param int64) error

Sets probability (0-100) of an active BUGGIFY section being fired.

SetClientBuggifyEnable
func (o NetworkOptions) SetClientBuggifyEnable() error

Enables client-side buggify for testing.

SetClientBuggifyDisable
func (o NetworkOptions) SetClientBuggifyDisable() error

Disables client-side buggify.

SetClientBuggifySectionActivatedProbability
func (o NetworkOptions) SetClientBuggifySectionActivatedProbability(param int64) error

Sets probability (0-100) for client buggify section activation.

SetClientBuggifySectionFiredProbability
func (o NetworkOptions) SetClientBuggifySectionFiredProbability(param int64) error

Sets probability (0-100) for client buggify section firing.

Deprecated Options

SetLocalAddress
func (o NetworkOptions) SetLocalAddress(param string) error

Deprecated. Sets local address in "IP:PORT" format.

SetClusterFile
func (o NetworkOptions) SetClusterFile(param string) error

Deprecated. Sets path to cluster file.

SetTLSPlugin
func (o NetworkOptions) SetTLSPlugin(param string) error

Deprecated. Sets TLS plugin file path or linker-resolved name.

SetEnableSlowTaskProfiling
func (o NetworkOptions) SetEnableSlowTaskProfiling() error

Deprecated. Enables slow task profiling.


Usage Examples

Basic Transaction

fdb.MustAPIVersion(730)
db := fdb.MustOpenDefault()
defer db.Close()

// Write and read
_, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
    tr.Set(fdb.Key("hello"), []byte("world"))
    value := tr.Get(fdb.Key("hello")).MustGet()
    fmt.Printf("Value: %s\n", value)
    return nil, nil
})
if err != nil {
    log.Fatal(err)
}

Range Query with Iterator

_, err := db.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) {
    kr := fdb.KeyRange{
        Begin: fdb.Key("user/"),
        End:   fdb.Key("user0"),
    }

    ri := rtr.GetRange(kr, fdb.RangeOptions{Limit: 100}).Iterator()
    for ri.Advance() {
        kv := ri.MustGet()
        fmt.Printf("%s = %s\n", kv.Key, kv.Value)
    }
    return nil, nil
})

Atomic Counter

import "encoding/binary"

func incrementCounter(db fdb.Database, key fdb.Key) error {
    _, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
        // Atomic increment by 1
        buf := make([]byte, 8)
        binary.LittleEndian.PutUint64(buf, 1)
        tr.Add(key, buf)
        return nil, nil
    })
    return err
}

Watch for Changes

_, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
    watch := tr.Watch(fdb.Key("config"))

    // Commit must succeed for watch to be active
    if err := tr.Commit().Get(); err != nil {
        return nil, err
    }

    // Wait for change (in separate goroutine in real code)
    go func() {
        err := watch.Get()
        if err != nil {
            log.Printf("Watch failed: %v", err)
        } else {
            log.Println("Config changed!")
        }
    }()

    return nil, nil
})

Tenant Operations

// Create tenant
if err := db.CreateTenant(fdb.Key("tenant-1")); err != nil {
    log.Fatal(err)
}

// Open tenant
tenant, err := db.OpenTenant(fdb.Key("tenant-1"))
if err != nil {
    log.Fatal(err)
}

// Use tenant (isolated keyspace)
_, err = tenant.Transact(func(tr fdb.Transaction) (interface{}, error) {
    tr.Set(fdb.Key("data"), []byte("tenant data"))
    return nil, nil
})

Snapshot Reads

_, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
    // Regular read - creates read conflict
    value1 := tr.Get(fdb.Key("key1")).MustGet()

    // Snapshot read - no read conflict
    snapshot := tr.Snapshot()
    value2 := snapshot.Get(fdb.Key("key2")).MustGet()

    // Write based on both values
    tr.Set(fdb.Key("result"), append(value1, value2...))
    return nil, nil
})

Conflict Range Management

_, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
    // Add explicit read conflict
    kr := fdb.KeyRange{
        Begin: fdb.Key("protected/"),
        End:   fdb.Key("protected0"),
    }
    if err := tr.AddReadConflictRange(kr); err != nil {
        return nil, err
    }

    // Other transactions writing to protected/ will cause conflict
    tr.Set(fdb.Key("data"), []byte("value"))
    return nil, nil
})

Best Practices

Transaction Guidelines

  1. Keep transactions short: Long-running transactions increase conflict probability
  2. Use MustGet() in transactional functions: Panics are caught and converted to errors
  3. Don't return Futures: Futures become invalid after transaction finishes
  4. Use Transact() for automatic retry: Handles retryable errors automatically
  5. Avoid goroutines in transactions: Creates race conditions and unpredictable behavior

Performance Optimization

  1. Use snapshot reads when appropriate to reduce conflicts
  2. Choose appropriate StreamingMode for range queries
  3. Set transaction options to match workload (batch priority, timeouts)
  4. Use atomic operations instead of read-modify-write when possible
  5. Cache Database handles: Opening databases is expensive
  6. Limit range query results: Use RangeOptions.Limit to avoid memory issues

Error Handling

  1. Check error types using errors.As() for FDB errors
  2. Use OnError() to determine retryability (or use Transact)
  3. Handle commit_unknown_result carefully - transaction may have committed
  4. Set appropriate timeouts to avoid hanging operations
  5. Monitor error codes for operational issues

Key Design

  1. Use tuple encoding for hierarchical keys (see tuple package)
  2. Avoid hot keys: Distribute writes across key space
  3. Design for range queries: Group related data with common prefixes
  4. Keep keys under 10KB: Recommended limit
  5. Keep values under 100KB: Hard limit, but smaller is better

Additional Resources

  • FoundationDB Developer Guide
  • API Error Codes
  • Known Limitations
  • Tuple Package Documentation
  • Subspace Package Documentation
  • Directory Package Documentation

Install with Tessl CLI

npx tessl i tessl/golang-github-com-apple-foundationdb-bindings-go

docs

directory.md

fdb.md

index.md

subspace.md

tuple.md

tile.json