Skip to main content

.NET

tigerbeetle-dotnet

The TigerBeetle client for .NET.

Prerequisites

Linux >= 5.6 is the only production environment we support. But for ease of development we also support macOS and Windows.

  • .NET >= 8.0.

And if you do not already have NuGet.org as a package source, make sure to add it:

dotnet nuget add source https://api.nuget.org/v3/index.json -n nuget.org

Setup

First, create a directory for your project and cd into the directory.

Then, install the TigerBeetle client:

dotnet new console
dotnet add package tigerbeetle

Now, create Program.cs and copy this into it:

using System;

using TigerBeetle;

// Validate import works.
Console.WriteLine("SUCCESS");

Finally, build and run:

dotnet run

Now that all prerequisites and dependencies are correctly set up, let's dig into using TigerBeetle.

Sample projects

This document is primarily a reference guide to the client. Below are various sample projects demonstrating features of TigerBeetle.

  • Basic: Create two accounts and transfer an amount between them.
  • Two-Phase Transfer: Create two accounts and start a pending transfer between them, then post the transfer.
  • Many Two-Phase Transfers: Create two accounts and start a number of pending transfer between them, posting and voiding alternating transfers.

Creating a Client

A client is created with a cluster ID and replica addresses for all replicas in the cluster. The cluster ID and replica addresses are both chosen by the system that starts the TigerBeetle cluster.

Clients are thread-safe and a single instance should be shared between multiple concurrent tasks.

Multiple clients are useful when connecting to more than one TigerBeetle cluster.

In this example the cluster ID is 0 and there is one replica. The address is read from the TB_ADDRESS environment variable and defaults to port 3000.

var tbAddress = Environment.GetEnvironmentVariable("TB_ADDRESS");
var clusterID = UInt128.Zero;
var addresses = new[] { tbAddress != null ? tbAddress : "3000" };
using (var client = new Client(clusterID, addresses))
{
// Use client
}

The Client class is thread-safe and for better performance, a single instance should be shared between multiple concurrent tasks. Multiple clients can be instantiated in case of connecting to more than one TigerBeetle cluster.

The following are valid addresses:

  • 3000 (interpreted as 127.0.0.1:3000)
  • 127.0.0.1:3000 (interpreted as 127.0.0.1:3000)
  • 127.0.0.1 (interpreted as 127.0.0.1:3001, 3001 is the default port)

Creating Accounts

See details for account fields in the Accounts reference.

var accounts = new[] {
new Account
{
Id = ID.Create(), // TigerBeetle time-based ID.
UserData128 = 0,
UserData64 = 0,
UserData32 = 0,
Ledger = 1,
Code = 718,
Flags = AccountFlags.None,
Timestamp = 0,
},
};

var accountErrors = client.CreateAccounts(accounts);
// Error handling omitted.

See details for the recommended ID scheme in time-based identifiers.

The UInt128 fields like ID, UserData128, Amount and account balances have a few extension methods to make it easier to convert 128-bit little-endian unsigned integers between BigInteger, byte[], and Guid.

See the class UInt128Extensions for more details.

Account Flags

The account flags value is a bitfield. See details for these flags in the Accounts reference.

To toggle behavior for an account, combine enum values stored in the AccountFlags object with bitwise-or:

  • AccountFlags.None
  • AccountFlags.Linked
  • AccountFlags.DebitsMustNotExceedCredits
  • AccountFlags.CreditsMustNotExceedDebits
  • AccountFlags.History

For example, to link two accounts where the first account additionally has the debits_must_not_exceed_credits constraint:

var account0 = new Account
{
Id = 100,
Ledger = 1,
Code = 1,
Flags = AccountFlags.Linked | AccountFlags.DebitsMustNotExceedCredits,
};
var account1 = new Account
{
Id = 101,
Ledger = 1,
Code = 1,
Flags = AccountFlags.History,
};

var accountErrors = client.CreateAccounts(new[] { account0, account1 });
// Error handling omitted.

Response and Errors

The response is an empty array if all accounts were created successfully. If the response is non-empty, each object in the response array contains error information for an account that failed. The error object contains an error code and the index of the account in the request batch.

See all error conditions in the create_accounts reference.

var account0 = new Account
{
Id = 102,
Ledger = 1,
Code = 1,
Flags = AccountFlags.None,
};
var account1 = new Account
{
Id = 103,
Ledger = 1,
Code = 1,
Flags = AccountFlags.None,
};
var account2 = new Account
{
Id = 104,
Ledger = 1,
Code = 1,
Flags = AccountFlags.None,
};

var accountErrors = client.CreateAccounts(new[] { account0, account1, account2 });
foreach (var error in accountErrors)
{
switch (error.Result)
{
case CreateAccountResult.Exists:
Console.WriteLine($"Batch account at ${error.Index} already exists.");
break;
default:
Console.WriteLine($"Batch account at ${error.Index} failed to create ${error.Result}");
break;
}
return;
}

Account Lookup

Account lookup is batched, like account creation. Pass in all IDs to fetch. The account for each matched ID is returned.

If no account matches an ID, no object is returned for that account. So the order of accounts in the response is not necessarily the same as the order of IDs in the request. You can refer to the ID field in the response to distinguish accounts.

Account[] accounts = client.LookupAccounts(new UInt128[] { 100, 101 });

Create Transfers

This creates a journal entry between two accounts.

See details for transfer fields in the Transfers reference.

var transfers = new[] {
new Transfer
{
Id = ID.Create(), // TigerBeetle time-based ID.
DebitAccountId = 102,
CreditAccountId = 103,
Amount = 10,
UserData128 = 0,
UserData64 = 0,
UserData32 = 0,
Timeout = 0,
Ledger = 1,
Code = 1,
Flags = TransferFlags.None,
Timestamp = 0,
}
};

var transferErrors = client.CreateTransfers(transfers);
// Error handling omitted.

See details for the recommended ID scheme in time-based identifiers.

Response and Errors

The response is an empty array if all transfers were created successfully. If the response is non-empty, each object in the response array contains error information for a transfer that failed. The error object contains an error code and the index of the transfer in the request batch.

See all error conditions in the create_transfers reference.

var transfers = new[] {
new Transfer
{
Id = 1,
DebitAccountId = 102,
CreditAccountId = 103,
Amount = 10,
Ledger = 1,
Code = 1,
Flags = TransferFlags.None,
},
new Transfer
{
Id = 2,
DebitAccountId = 102,
CreditAccountId = 103,
Amount = 10,
Ledger = 1,
Code = 1,
Flags = TransferFlags.None,
},
new Transfer
{
Id = 3,
DebitAccountId = 102,
CreditAccountId = 103,
Amount = 10,
Ledger = 1,
Code = 1,
Flags = TransferFlags.None,
},
};

var transferErrors = client.CreateTransfers(transfers);
foreach (var error in transferErrors)
{
switch (error.Result)
{
case CreateTransferResult.Exists:
Console.WriteLine($"Batch transfer at ${error.Index} already exists.");
break;
default:
Console.WriteLine($"Batch transfer at ${error.Index} failed to create: ${error.Result}");
break;
}
}

Batching

TigerBeetle performance is maximized when you batch API requests. The client does not do this automatically for you. So, for example, you can insert 1 million transfers one at a time like so:

var batch = new Transfer[] { }; // Array of transfer to create.
foreach (var t in batch)
{
var transferErrors = client.CreateTransfer(t);
// Error handling omitted.
}

But the insert rate will be a fraction of potential. Instead, always batch what you can.

The maximum batch size is set in the TigerBeetle server. The default is 8190.

var batch = new Transfer[] { }; // Array of transfer to create.
var BATCH_SIZE = 8190;
for (int firstIndex = 0; firstIndex < batch.Length; firstIndex += BATCH_SIZE)
{
var lastIndex = firstIndex + BATCH_SIZE;
if (lastIndex > batch.Length)
{
lastIndex = batch.Length;
}
var transferErrors = client.CreateTransfers(batch[firstIndex..lastIndex]);
// Error handling omitted.
}

Queues and Workers

If you are making requests to TigerBeetle from workers pulling jobs from a queue, you can batch requests to TigerBeetle by having the worker act on multiple jobs from the queue at once rather than one at a time. i.e. pulling multiple jobs from the queue rather than just one.

Transfer Flags

The transfer flags value is a bitfield. See details for these flags in the Transfers reference.

To toggle behavior for an account, combine enum values stored in the TransferFlags object with bitwise-or:

  • TransferFlags.None
  • TransferFlags.Linked
  • TransferFlags.Pending
  • TransferFlags.PostPendingTransfer
  • TransferFlags.VoidPendingTransfer

For example, to link transfer0 and transfer1:

var transfer0 = new Transfer
{
Id = 4,
DebitAccountId = 102,
CreditAccountId = 103,
Amount = 10,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Linked,
};
var transfer1 = new Transfer
{
Id = 5,
DebitAccountId = 102,
CreditAccountId = 103,
Amount = 10,
Ledger = 1,
Code = 1,
Flags = TransferFlags.None,
};

var transferErrors = client.CreateTransfers(new[] { transfer0, transfer1 });
// Error handling omitted.

Two-Phase Transfers

Two-phase transfers are supported natively by toggling the appropriate flag. TigerBeetle will then adjust the credits_pending and debits_pending fields of the appropriate accounts. A corresponding post pending transfer then needs to be sent to post or void the transfer.

Post a Pending Transfer

With flags set to post_pending_transfer, TigerBeetle will post the transfer. TigerBeetle will atomically roll back the changes to debits_pending and credits_pending of the appropriate accounts and apply them to the debits_posted and credits_posted balances.

var transfer0 = new Transfer
{
Id = 6,
DebitAccountId = 102,
CreditAccountId = 103,
Amount = 10,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Pending,
};

var transferErrors = client.CreateTransfers(new[] { transfer0 });
// Error handling omitted.

var transfer1 = new Transfer
{
Id = 7,
// Post the entire pending amount.
Amount = Transfer.AmountMax,
PendingId = 6,
Flags = TransferFlags.PostPendingTransfer,
};

transferErrors = client.CreateTransfers(new[] { transfer1 });
// Error handling omitted.

Void a Pending Transfer

In contrast, with flags set to void_pending_transfer, TigerBeetle will void the transfer. TigerBeetle will roll back the changes to debits_pending and credits_pending of the appropriate accounts and not apply them to the debits_posted and credits_posted balances.

var transfer0 = new Transfer
{
Id = 8,
DebitAccountId = 102,
CreditAccountId = 103,
Amount = 10,
Ledger = 1,
Code = 1,
Flags = TransferFlags.Pending,
};

var transferErrors = client.CreateTransfers(new[] { transfer0 });
// Error handling omitted.

var transfer1 = new Transfer
{
Id = 9,
// Post the entire pending amount.
Amount = 0,
PendingId = 8,
Flags = TransferFlags.VoidPendingTransfer,
};

transferErrors = client.CreateTransfers(new[] { transfer1 });
// Error handling omitted.

Transfer Lookup

NOTE: While transfer lookup exists, it is not a flexible query API. We are developing query APIs and there will be new methods for querying transfers in the future.

Transfer lookup is batched, like transfer creation. Pass in all ids to fetch, and matched transfers are returned.

If no transfer matches an id, no object is returned for that transfer. So the order of transfers in the response is not necessarily the same as the order of ids in the request. You can refer to the id field in the response to distinguish transfers.

Transfer[] transfers = client.LookupTransfers(new UInt128[] { 1, 2 });

Get Account Transfers

NOTE: This is a preview API that is subject to breaking changes once we have a stable querying API.

Fetches the transfers involving a given account, allowing basic filter and pagination capabilities.

The transfers in the response are sorted by timestamp in chronological or reverse-chronological order.

var filter = new AccountFilter
{
AccountId = 101,
UserData128 = 0, // No filter by UserData.
UserData64 = 0,
UserData32 = 0,
Code = 0, // No filter by Code.
TimestampMin = 0, // No filter by Timestamp.
TimestampMax = 0, // No filter by Timestamp.
Limit = 10, // Limit to ten transfers at most.
Flags = AccountFilterFlags.Debits | // Include transfer from the debit side.
AccountFilterFlags.Credits | // Include transfer from the credit side.
AccountFilterFlags.Reversed, // Sort by timestamp in reverse-chronological order.
};

Transfer[] transfers = client.GetAccountTransfers(filter);

Get Account Balances

NOTE: This is a preview API that is subject to breaking changes once we have a stable querying API.

Fetches the point-in-time balances of a given account, allowing basic filter and pagination capabilities.

Only accounts created with the flag history set retain historical balances.

The balances in the response are sorted by timestamp in chronological or reverse-chronological order.

var filter = new AccountFilter
{
AccountId = 101,
UserData128 = 0, // No filter by UserData.
UserData64 = 0,
UserData32 = 0,
Code = 0, // No filter by Code.
TimestampMin = 0, // No filter by Timestamp.
TimestampMax = 0, // No filter by Timestamp.
Limit = 10, // Limit to ten balances at most.
Flags = AccountFilterFlags.Debits | // Include transfer from the debit side.
AccountFilterFlags.Credits | // Include transfer from the credit side.
AccountFilterFlags.Reversed, // Sort by timestamp in reverse-chronological order.
};

AccountBalance[] accountBalances = client.GetAccountBalances(filter);

Query Accounts

NOTE: This is a preview API that is subject to breaking changes once we have a stable querying API.

Query accounts by the intersection of some fields and by timestamp range.

The accounts in the response are sorted by timestamp in chronological or reverse-chronological order.

var filter = new QueryFilter
{
UserData128 = 1000, // Filter by UserData.
UserData64 = 100,
UserData32 = 10,
Code = 1, // Filter by Code.
Ledger = 0, // No filter by Ledger.
TimestampMin = 0, // No filter by Timestamp.
TimestampMax = 0, // No filter by Timestamp.
Limit = 10, // Limit to ten balances at most.
Flags = QueryFilterFlags.Reversed, // Sort by timestamp in reverse-chronological order.
};

Account[] accounts = client.QueryAccounts(filter);

Query Transfers

NOTE: This is a preview API that is subject to breaking changes once we have a stable querying API.

Query transfers by the intersection of some fields and by timestamp range.

The transfers in the response are sorted by timestamp in chronological or reverse-chronological order.

var filter = new QueryFilter
{
UserData128 = 1000, // Filter by UserData
UserData64 = 100,
UserData32 = 10,
Code = 1, // Filter by Code
Ledger = 0, // No filter by Ledger
TimestampMin = 0, // No filter by Timestamp.
TimestampMax = 0, // No filter by Timestamp.
Limit = 10, // Limit to ten balances at most.
Flags = QueryFilterFlags.Reversed, // Sort by timestamp in reverse-chronological order.
};

Transfer[] transfers = client.QueryTransfers(filter);

Linked Events

When the linked flag is specified for an account when creating accounts or a transfer when creating transfers, it links that event with the next event in the batch, to create a chain of events, of arbitrary length, which all succeed or fail together. The tail of a chain is denoted by the first event without this flag. The last event in a batch may therefore never have the linked flag set as this would leave a chain open-ended. Multiple chains or individual events may coexist within a batch to succeed or fail independently.

Events within a chain are executed within order, or are rolled back on error, so that the effect of each event in the chain is visible to the next, and so that the chain is either visible or invisible as a unit to subsequent events after the chain. The event that was the first to break the chain will have a unique error result. Other events in the chain will have their error result set to linked_event_failed.

var batch = new System.Collections.Generic.List<Transfer>();

// An individual transfer (successful):
batch.Add(new Transfer { Id = 1, /* ... rest of transfer ... */ });

// A chain of 4 transfers (the last transfer in the chain closes the chain with linked=false):
batch.Add(new Transfer { Id = 2, /* ... rest of transfer ... */ Flags = TransferFlags.Linked }); // Commit/rollback.
batch.Add(new Transfer { Id = 3, /* ... rest of transfer ... */ Flags = TransferFlags.Linked }); // Commit/rollback.
batch.Add(new Transfer { Id = 2, /* ... rest of transfer ... */ Flags = TransferFlags.Linked }); // Fail with exists
batch.Add(new Transfer { Id = 4, /* ... rest of transfer ... */ }); // Fail without committing

// An individual transfer (successful):
// This should not see any effect from the failed chain above.
batch.Add(new Transfer { Id = 2, /* ... rest of transfer ... */ });

// A chain of 2 transfers (the first transfer fails the chain):
batch.Add(new Transfer { Id = 2, /* ... rest of transfer ... */ Flags = TransferFlags.Linked });
batch.Add(new Transfer { Id = 3, /* ... rest of transfer ... */ });

// A chain of 2 transfers (successful):
batch.Add(new Transfer { Id = 3, /* ... rest of transfer ... */ Flags = TransferFlags.Linked });
batch.Add(new Transfer { Id = 4, /* ... rest of transfer ... */ });

var transferErrors = client.CreateTransfers(batch.ToArray());
// Error handling omitted.

Imported Events

When the imported flag is specified for an account when creating accounts or a transfer when creating transfers, it allows importing historical events with a user-defined timestamp.

The entire batch of events must be set with the flag imported.

It's recommended to submit the whole batch as a linked chain of events, ensuring that if any event fails, none of them are committed, preserving the last timestamp unchanged. This approach gives the application a chance to correct failed imported events, re-submitting the batch again with the same user-defined timestamps.

// External source of time
ulong historicalTimestamp = 0UL;
var historicalAccounts = new Account[] { /* Loaded from an external source */ };
var historicalTransfers = new Transfer[] { /* Loaded from an external source */ };

// First, load and import all accounts with their timestamps from the historical source.
var accountsBatch = new System.Collections.Generic.List<Account>();
for (var index = 0; index < historicalAccounts.Length; index++)
{
var account = historicalAccounts[index];

// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
account.Timestamp = historicalTimestamp;
// Set the account as `imported`.
account.Flags = AccountFlags.Imported;
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalAccounts.Length - 1)
{
account.Flags |= AccountFlags.Linked;
}

accountsBatch.Add(account);
}

var accountErrors = client.CreateAccounts(accountsBatch.ToArray());
// Error handling omitted.

// Then, load and import all transfers with their timestamps from the historical source.
var transfersBatch = new System.Collections.Generic.List<Transfer>();
for (var index = 0; index < historicalTransfers.Length; index++)
{
var transfer = historicalTransfers[index];

// Set a unique and strictly increasing timestamp.
historicalTimestamp += 1;
transfer.Timestamp = historicalTimestamp;
// Set the account as `imported`.
transfer.Flags = TransferFlags.Imported;
// To ensure atomicity, the entire batch (except the last event in the chain)
// must be `linked`.
if (index < historicalTransfers.Length - 1)
{
transfer.Flags |= TransferFlags.Linked;
}

transfersBatch.Add(transfer);
}

var transferErrors = client.CreateTransfers(transfersBatch.ToArray());
// Error handling omitted.
// Since it is a linked chain, in case of any error the entire batch is rolled back and can be retried
// with the same historical timestamps without regressing the cluster timestamp.