Distributed Transactions from the .NET SDK

  • Developer Preview
    +
    A practical guide to using Couchbase’s distributed ACID transactions, via the .NET API.

    Distributed Transactions for Couchbase provide these semantics and features:

    • Insertion, mutation, and removal of multiple documents can be staged inside a transaction.

    • Until the transaction is committed, these changes will not be visible to other transactions, or any other part of the Couchbase Data Platform.

    • An isolation level of Read Committed, to support high performance and scalability.

    • A high-level and easy-to-use API that allows the developer to express what they want the transaction to do as a block of logic, while the library takes care of the details of error handling, including conflicts with other transactions.

    Please see our introduction to ACID Transactions for a guide to the benefits and trade-offs of multi-document transactions.

    Below we show you how to create Transactions, step-by-step. You may also want to start with our transactions examples repository, which features useful downloadable examples of using Distributed Transactions.

    API Docs are available online.

    Requirements

    • Couchbase Server 6.6 or above.

    • Couchbase .NET client 3.0.5 or above. It is recommended you use the package on NuGet.

    • NTP should be configured so nodes of the Couchbase cluster are in sync with time.

    • The application, if it is using extended attributes (XATTRs), must avoid using the XATTR field txn, which is reserved for Couchbase use.

    If using a single node cluster (for example, during development), then note that the default number of replicas for a newly created bucket is 1. If left at this default, then all Key-Value writes performed at with durabiltiy will fail with a DurabilityImpossibleException. In turn this will cause all transactions (which perform all Key-Value writes durably) to fail. This setting can be changed via GUI or command line.

    Getting Started

    Couchbase transactions require no additional components or services to be configured. Simply add the transactions library into your project. The latest version, as of October 2020, is 1.0.0-alpha.1.

    With NuGut this can be accomplished by using the NuGet Package Manager in your IDE:

    PM > Install-Package Couchbase.Transactions -Version 1.0.0-alpha.1

    Or via the CLI

    dotnet add package Couchbase.Transactions --version 1.0.0-alpha.1

    Or by using PackageReference in your .csproj file:

    <PackageReference Include="Couchbase.Transactions" Version="1.0.0-alpha.1" />

    A complete simple NuGet example is available on our transactions examples repository.

    Initializing Transactions

    Here are all imports used by the following examples:

    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using Couchbase.KeyValue;
    using Couchbase.Query;
    using Couchbase.Transactions.Config;
    using Couchbase.Transactions.Deferred;
    using Couchbase.Transactions.Error;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json.Linq;

    The starting point is the Transactions object. It is very important that the application ensures that only one of these is created, as it performs automated background clean-up processes that should not be duplicated.

    // Initialize the Couchbase cluster
    var options = new ClusterOptions().WithCredentials("Administrator", "password");
    var cluster = await Cluster.ConnectAsync("couchbase://localhost", options).ConfigureAwait(false);
    var bucket = await cluster.BucketAsync("default").ConfigureAwait(false);
    var collection = bucket.DefaultCollection();
    
    // Create the single Transactions object
    var transactions = Transactions.Create(cluster, TransactionConfigBuilder.Create());

    Configuration

    Transactions can optionally be configured at the point of creating the Transactions object:

    var transactions = Transactions.Create(_cluster,
        TransactionConfigBuilder.Create()
            .DurabilityLevel(DurabilityLevel.PersistToMajority)
            .Build());

    The default configuration will perform all writes with the durability setting Majority, ensuring that each write is available in-memory on the majority of replicas before the transaction continues. There are two higher durability settings available that will additionally wait for all mutations to be written to physical storage on either the active or the majority of replicas, before continuing. This further increases safety, at a cost of additional latency.

    A level of None is present but its use is discouraged and unsupported. If durability is set to None, then atomicity cannot be guaranteed.

    Creating a Transaction

    A core idea of the library is that the application supplies the logic for transaction inside a lambda, including any conditional logic required, and the transactions library takes care of getting the transaction committed.

    It is important to understand that the lambda may be run multiple times in order to handle some types of transient error, such as a temporary conflict with another transaction.

    Each run of the lambda is called an attempt, inside an overall transaction.

    As with the Couchbase .NET Client, you should use the library asynchronusly using the async/await keywords (the exceptions will be explained later in Error Handling):

    try
    {
        await _transactions.RunAsync(async (ctx)=>
        {
            // 'ctx' is an AttemptContext, which permits getting, inserting,
            // removing and replacing documents, along with committing and
            // rolling back the transaction.
    
            // ... Your transaction logic here ...
    
            // This call is optional - if you leave it off, the transaction
            // will be committed anyway.
            await ctx.CommitAsync().ConfigureAwait(false);
        }).ConfigureAwait(false);
    }
    catch (TransactionCommitAmbiguousException e)
    {
        // The application will of course want to use its own logging rather
        // than Console.WriteLine
        Console.Error.WriteLine("Transaction possibly committed");
        Console.Error.WriteLine(e);
    }
    catch (TransactionFailedException e)
    {
        Console.Error.WriteLine("Transaction did not reach commit point");
        Console.Error.WriteLine(e);
    }

    The asynchronous API allows you to use the thread pool, which can help you scale with excellent efficiency. Those new to the TAP API (Task Asynchronous Programming) may want to check out Task asynchronous programming model for more details on this powerful paradigm.

    Examples

    A code example is worth a thousand words, so here is a quick summary of the main transaction operations. They are described in more detail below.

    try
    {
        var result = await _transactions.RunAsync(async (ctx) =>
        {
            // Inserting a doc:
            await ctx.InsertAsync(_collection, "doc-a", new {}).ConfigureAwait(false);
    
            // Getting documents:
            // Use ctx.GetAsync if the document should exist, and the transaction
            // will fail if it does not
            var docA = await ctx.GetAsync(_collection, "doc-a").ConfigureAwait(false);
    
            // Replacing a doc:
            var docB = await ctx.GetAsync(_collection, "doc-b").ConfigureAwait(false);
            var content = docB.ContentAs<dynamic>();
            content.put("transactions", "are awesome");
            await ctx.ReplaceAsync(docB, content);
    
            // Removing a doc:
            var docC = await ctx.GetAsync(_collection, "doc-c").ConfigureAwait(false);
            await ctx.RemoveAsync(docC).ConfigureAwait(false);
    
            await ctx.CommitAsync().ConfigureAwait(false);
        }).ConfigureAwait(false);
    }
    catch (TransactionCommitAmbiguousException e)
    {
       Console.WriteLine("Transaction possibly committed");
       Console.WriteLine(e);
    }
    catch (TransactionFailedException e)
    {
        Console.WriteLine("Transaction did not reach commit point");
        Console.WriteLine(e);
    }

    Transaction Mechanics

    While this document is focussed on presenting how transactions are used at the API level, it is useful to have a high-level understanding of the mechanics. Reading this section is completely optional.

    Recall that the application-provided lambda (containing the transaction logic) may be run multiple times by the transactions library. Each such run is called an 'attempt' inside the overall transaction.

    Active Transaction Record Entries

    The first mechanic is that each of these attempts adds an entry to a metadata document in the Couchbase cluster. These metadata documents:

    • Are named Active Transaction Records, or ATRs.

    • Are created and maintained automatically.

    • Begin with "_txn:atr-".

    • Each contain entries for multiple attempts.

    • Are viewable, and they should not be modified externally.

    Each such ATR entry stores some metadata and, crucially, whether the attempt has committed or not. In this way, the entry acts as the single point of truth for the transaction, which is essential for providing an 'atomic commit' during reads.

    Staged Mutations

    The second mechanic is that mutating a document inside a transaction, does not directly change the body of the document. Instead, the post-transaction version of the document is staged alongside the document (technically in its extended attributes (XATTRs)). In this way, all changes are invisible to all parts of the Couchbase Data Platform until the commit point is reached.

    These staged document changes effectively act as a lock against other transactions trying to modify the document, preventing write-write conflicts.

    Cleanup

    There are safety mechanisms to ensure that leftover staged changes from a failed transaction cannot block live transactions indefinitely. These include an asynchronous cleanup process that is started with the creation of the Transactions object, and scans for expired transactions created by any application, on all buckets.

    Note that if an application is not running, then this cleanup is also not running.

    The cleanup process is detailed below in Asynchronous Cleanup.

    Committing

    Only once the lambda has successfully run to conclusion, will the attempt be committed. This updates the attempt entry, which can be used as a signal by transactional actors as to whether to use the post-transaction version of a document from its XATTRs. Hence updating the ATR entry is effectively an 'atomic commit' switch for the transaction.

    After this atomic commit point is reached, the individual documents be committed (or "unstaged"). This provides an eventually consistent commit for non-transactional actors (including standard Key-Value reads and N1QL statements). Transactions will begin reading the post-transactional version of documents as soon as the ATR entry is changed to committed.

    Mutating Documents

    Replacing

    Replacing a document requires awaiting a ctx.GetAsync() call first. This is necessary to ensure that the document is not involved in another transaction. (If it is, then the transaction will handle this, generally by rolling back what has been done so far, and retrying the lambda.)

    await _transactions.RunAsync(async ctx =>
    {
        var anotherDoc = await ctx.GetAsync(_collection, "anotherDoc").ConfigureAwait(false);
        var content = anotherDoc.ContentAs<dynamic>();
        content.put("transactions", "are awesome");
        await ctx.ReplaceAsync(anotherDoc, content);
    }).ConfigureAwait(false);

    Removing

    As with replaces, removing a document requires awaiting a ctx.GetAsync() call first.

    await _transactions.RunAsync(async ctx =>
    {
        var anotherDoc = await ctx.GetAsync(_collection, "anotherDoc").ConfigureAwait(false);
        await ctx.RemoveAsync(anotherDoc).ConfigureAwait(false);
    }).ConfigureAwait(false);

    Inserting

    await _transactions.RunAsync(async ctx =>
    {
        await ctx.InsertAsync(_collection, "docId", new { }).ConfigureAwait(false);
    }).ConfigureAwait(false);

    Getting Documents

    There are two ways to get a document, get and getOptional:

    await _transactions.RunAsync(async ctx =>
    {
        var docId = "a-doc";
        var docOpt = await ctx.GetAsync(_collection, docId).ConfigureAwait(false);
    }).ConfigureAwait(false);

    GetAsync will cause the transaction to fail with TransactionFailedException (after rolling back any changes, of course). It is provided as a convenience method so the developer does not have to check the Optional if the document must exist for the transaction to succeed.

    Gets will 'read your own writes', e.g. this will succeed:

    await _transactions.RunAsync(async ctx =>
    {
        var docId = "docId";
        await ctx.InsertAsync(_collection, docId, new { }).ConfigureAwait(false);
        var doc = await ctx.GetAsync(_collection, docId).ConfigureAwait(false);
        Console.WriteLine((object) doc.ContentAs<dynamic>());
    }).ConfigureAwait(false);

    Committing

    Committing is automatic: if there is no explicit call to ctx.CommitAsync() at the end of the transaction logic callback, and no exception is thrown, it will be committed.

    var result = await _transactions.RunAsync(async (ctx) =>
    {
        var doc = await ctx.GetAsync(_collection, "anotherDoc").ConfigureAwait(false);
        var content = doc.ContentAs<JObject>();
        content.Add("transactions", "are awesome");
    
        await ctx.ReplaceAsync(doc, content).ConfigureAwait(false);
    }).ConfigureAwait(false);

    As described above, as soon as the transaction is committed, all its changes will be atomically visible to reads from other transactions. The changes will also be committed (or "unstaged") so they are visible to non-transactional actors, in an eventually consistent fashion.

    Commit is final: after the transaction is committed, it cannot be rolled back, and no further operations are allowed on it.

    An asynchronous cleanup process ensures that once the transaction reaches the commit point, it will be fully committed — even if the application crashes.

    A Full Transaction Example

    Let’s pull together everything so far into a more real-world example of a transaction.

    This example simulates a simple Massively Multiplayer Online game, and includes documents representing:

    • Players, with experience points and levels;

    • Monsters, with hitpoints, and the number of experience points a player earns from their death.

    In this example, the player is dealing damage to the monster. The player’s client has sent this instruction to a central server, where we’re going to record that action. We’re going to do this in a transaction, as we don’t want a situation where the monster is killed, but we fail to update the player’s document with the earned experience.

    (Though this is just a demo - in reality, the game would likely live with the small risk and limited impact of this, rather than pay the performance cost for using a transaction.)

    A complete version of this example is available on our GitHub transactions examples page.

    try
    {
        await _transactions.RunAsync(async (ctx) =>
        {
            _logger.LogInformation(
                "Starting transaction, player {playerId} is hitting monster {monsterId} for {damage} points of damage.",
                playerId, monsterId, damage);
    
            var monster = await ctx.GetAsync(_collection, monsterId).ConfigureAwait(false);
            var player = await ctx.GetAsync(_collection, playerId).ConfigureAwait(false);
    
            var monsterContent = monster.ContentAs<JObject>();
            var playerContent = player.ContentAs<JObject>();
    
            var monsterHitPoints = monsterContent.GetValue("hitpoints").ToObject<int>();
            var monsterNewHitPoints = monsterHitPoints - damage;
    
            _logger.LogInformation(
                "Monster {monsterId} had {monsterHitPoints} hitpoints, took {damage} damage, now has {monsterNewHitPoints} hitpoints.",
                monsterId, monsterHitPoints, damage, monsterNewHitPoints);
    
            if (monsterNewHitPoints <= 0)
            {
                // Monster is killed.  The remove is just for demoing, and a more realistic example would set a
                // "dead" flag or similar.
    
                await ctx.RemoveAsync(monster).ConfigureAwait(false);
    
                // The player earns experience for killing the monster
                var experienceForKillingMonster =
                    monsterContent.GetValue("experienceWhenKilled").ToObject<int>();
                var playerExperience = playerContent.GetValue("experiance").ToObject<int>();
                var playerNewExperience = playerExperience + experienceForKillingMonster;
                var playerNewLevel = CalculateLevelForExperience(playerNewExperience);
    
                _logger.LogInformation(
                    "Monster {monsterId} was killed.  Player {playerId} gains {experienceForKillingMonster} experience, now has level {playerNewLevel}.",
                    monsterId, playerId, experienceForKillingMonster, playerNewLevel);
    
                playerContent["experience"] = playerNewExperience;
                playerContent["level"] = playerNewLevel;
    
                await ctx.ReplaceAsync(player, playerContent).ConfigureAwait(false);
            }
            else
            {
                _logger.LogInformation("Monster {monsterId} is damaged but alive.", monsterId);
    
                // Monster is damaged but still alive
                monsterContent.Add("hitpoints", monsterNewHitPoints);
    
                await ctx.ReplaceAsync(monster, monsterContent).ConfigureAwait(false);
            }
    
            _logger.LogInformation("About to commit transaction");
    
        }).ConfigureAwait(false);
    }
    catch (TransactionCommitAmbiguousException e)
    {
        _logger.LogWarning("Transaction possibly committed:{0}{1}", Environment.NewLine, e);
    }
    catch (TransactionFailedException e)
    {
        // The operation timed out (the default timeout is 15 seconds) despite multiple attempts to commit the
        // transaction logic.   Both the monster and the player will be untouched.
    
        // This situation should be very rare.  It may be reasonable in this situation to ignore this particular
        // failure, as the downside is limited to the player experiencing a temporary glitch in a fast-moving MMO.
    
        // So, we will just log the error
        _logger.LogWarning("Transaction did not reach commit:{0}{1}", Environment.NewLine, e);
    }

    Rollback

    If an exception is thrown, either by the application from the lambda, or by the transactions library, then that attempt is rolled back. The transaction logic may or may not be retried, depending on the exception.

    If the transaction is not retried then it will throw a TransactionFailedException exception, and its getCause method can be used for more details on the failure.

    The application can use this to signal why it triggered a rollback, as so:

    
    try
    {
        await _transactions.RunAsync(async ctx =>
        {
            var customer = await ctx.GetAsync(_collection, "customer-name").ConfigureAwait(false);
    
            if (customer.ContentAs<dynamic>().balance < costOfItem) throw new BalanceInsufficientException();
            // else continue transaction
        }).ConfigureAwait(false);
    }
    catch (TransactionCommitAmbiguousException e)
    {
        // This exception can only be thrown at the commit point, after the
        // BalanceInsufficient logic has been passed, so there is no need to
        // check getCause here.
        Console.Error.WriteLine("Transaction possibly committed");
        Console.Error.WriteLine(e);
    }
    catch (TransactionFailedException e)
    {
        Console.Error.WriteLine("Transaction did not reach commit point");
    }

    The transaction can also be explicitly rolled back:

    await _transactions.RunAsync(async (ctx) => {
        var customer = await ctx.GetAsync(_collection, "customer-name").ConfigureAwait(false);
    
        if (customer.ContentAs<dynamic>().balance < costOfItem)
        {
            await ctx.RollbackAsync().ConfigureAwait(false);
        }
        // else continue transaction
    }).ConfigureAwait(false);

    In this case, if ctx.rollback() is reached, then the transaction will be regarded as successfully rolled back and no TransactionFailed will be thrown.

    After a transaction is rolled back, it cannot be committed, no further operations are allowed on it, and the library will not try to automatically commit it at the end of the code block.

    Error Handling

    As discussed previously, the transactions library will attempt to resolve many errors itself, through a combination of retrying individual operations and the application’s lambda. This includes some transient server errors, and conflicts with other transactions.

    But there are situations that cannot be resolved, and total failure is indicated to the application via exceptions. These errors include:

    • Any exception thrown by your transaction lambda, either deliberately or through an application logic bug.

    • Attempting to insert a document that already exists.

    • Attempting to remove or replace a document that does not exist.

    • Calling ctx.get on a document key that does not exist.

    Once one of these errors occurs, the current attempt is irrevocably failed (though the transaction may retry the lambda). It is not possible for the application to catch the failure and continue. Once a failure has occurred, all other operations tried in this attempt (including commit) will instantly fail.

    Transactions, as they are multi-stage and multi-document, also have a concept of partial success/failure. This is signalled to the application through the TransactionResult.unstagingComplete() method, described later.

    There are three exceptions that the transactions library can raise to the application: TransactionFailed, TransactionExpired and TransactionCommitAmbiguous. All exceptions derive from TransactionFailed for backwards-compatibility purposes.

    TransactionFailed and TransactionExpired

    The transaction definitely did not reach the commit point. TransactionFailed indicates a fast-failure whereas TransactionExpired indicates that retries were made until the expiration point was reached, but this distinction is not normally important to the application and generally TransactionExpired does not need to be handled individually.

    Either way, an attempt will have been made to rollback all changes. This attempt may or may not have been successful, but the results of this will have no impact on the protocol or other actors. No changes from the transaction will be visible (presently with the potential and temporary exception of staged inserts being visible to non-transactional actors, as discussed under Inserting).

    Handling: Generally, debugging exactly why a given transaction failed requires review of the logs, so it is suggested that the application log these on failure. (see Logging). The application may want to try the transaction again later. Alternatively, if transaction completion time is not a priority, then transaction expiration times (which default to 15 seconds) can be extended across the board through TransactionConfigBuilder:

    Transactions transactions = Transactions.Create(_cluster, TransactionConfigBuilder.Create()
        .ExpirationTime(TimeSpan.FromSeconds(120))
        .Build());

    This will allow the protocol more time to get past any transient failures (for example, those caused by a cluster rebalance). The tradeoff to consider with longer expiration times, is that documents that have been staged by a transaction are effectively locked from modification from other transactions, until the expiration time has exceeded.

    Note that expiration is not guaranteed to be followed precisely. For example, if the application were to do a long blocking operation inside the lambda (which should be avoided), then expiration can only trigger after this finishes. Similarly, if the transaction attempts a key-value operation close to the expiration time, and that key-value operation times out, then the expiration time may be exceeded.

    TransactionCommitAmbiguous

    As discussed previously, each transaction has a 'single point of truth' that is updated atomically to reflect whether it is committed.

    However, it is not always possible for the protocol to become 100% certain that the operation was successful, before the transaction expires. That is, the operation may have successfully completed on the cluster, or may succeed soon, but the protocol is unable to determine this (whether due to transient network failure or other reason). This is important as the transaction may or may not have reached the commit point, e.g. succeeded or failed.

    The library raises TransactionCommitAmbiguous to indicate this state. It should be rare to receive this exception.

    If the transaction had in fact successfully reached the commit point, then the transaction will be fully completed ("unstaged") by the asynchronous cleanup process at some point in the future. With default settings this will usually be within a minute, but whatever underlying fault has caused the TransactionCommitAmbiguous may lead to it taking longer.

    If the transaction had not in fact reached the commit point, then the asynchronous cleanup process will instead attempt to roll it back at some point in the future. If unable to, any staged metadata from the transaction will not be visible, and will not cause problems (e.g. there are safety mechanisms to ensure it will not block writes to these documents for long).

    Handling: This error can be challenging for an application to handle. As with TransactionFailed it is recommended that it at least writes any logs from the transaction, for future debugging. It may wish to retry the transaction at a later point, or globally extend transactional expiration times to give the protocol additional time to resolve the ambiguity.

    TransactionResult.unstagingComplete()

    As above, there is a 'single point of truth' for a transaction. After this atomic commit point is reached, the documents themselves will still be individually committed (we also call this "unstaging"). However, transactionally-aware actors will now be returning the post-transaction versions of the documents, and the transaction is effectively fully committed to those actors.

    So if the application is solely working with transaction-aware actors, then the unstaging process is optional. And failures during the unstaging process are not particularly important, in this case. (Note the asynchronous cleanup process will still complete the unstaging process at a later point.)

    Hence, many errors during unstaging will cause the transaction to immediately return success. That is, successful return simply means that the commit point was reached.

    A method TransactionResult.unstagingComplete() indicates whether the unstaging process completed successfully or not. This should be used any time that the application needs all results of the transaction to be immediately available to non-transactional actors (which currently includes N1QL and non-transactional Key-Value reads).

    Error handling differs depending on whether a transaction is before or after the point of commit (or rollback).

    Full Error Handling Example

    Pulling all of the above together, this is the suggested best practice for error handling:

    try
    {
        var result = await _transactions.RunAsync(async (ctx) => {
            // ... transactional code here ...
        });
    
        // The transaction definitely reached the commit point. Unstaging
        // the individual documents may or may not have completed
    
        if (result.UnstagingComplete)
        {
            // Operations with non-transactional actors will want
            // unstagingComplete() to be true.
            await _cluster.QueryAsync<dynamic>(" ... N1QL ... ",
                new QueryOptions()).ConfigureAwait(false);
    
            var documentKey = "a document key involved in the transaction";
            var getResult = await _collection.GetAsync(documentKey).ConfigureAwait(false);
        }
        else
        {
            // This step is completely application-dependent.  It may
            // need to throw its own exception, if it is crucial that
            // result.unstagingComplete() is true at this point.
            // (Recall that the asynchronous cleanup process will
            // complete the unstaging later on).
        }
    }
    catch (TransactionCommitAmbiguousException err)
    {
        // The transaction may or may not have reached commit point
        Console.Error.WriteLine("Transaction returned TransactionCommitAmbiguous and" +
                " may have succeeded, logs:");
    
        // Of course, the application will want to use its own logging rather
        // than System.err
        Console.Error.WriteLine(err);
    }
    catch (TransactionFailedException err)
    {
        // The transaction definitely did not reach commit point
        Console.Error.WriteLine("Transaction failed with TransactionFailed, logs:");
        Console.Error.WriteLine(err);
    }

    Asynchronous Cleanup

    Transactions will try to clean up after themselves in the advent of failures. However, there are situations that inevitably created failed, or 'lost' transactions, such as an application crash.

    This requires an asynchronous cleanup task, described in this section.

    Creating the Transactions object spawns a background cleanup task, whose job it is to periodically scan for expired transactions and clean them up. It does this by scanning a subset of the Active Transaction Record (ATR) transaction metadata documents on a bucket. As you’ll recall from earlier, an entry for each transaction attempt exists in one of these documents. (They are removed during cleanup or at some time after successful completion.)

    The default settings are tuned to find expired transactions reasonably quickly, while creating neglible impact from the background reads required by the scanning process. To be exact, with default settings it will generally find expired transactions within 60 seconds, and use less than 20 reads per second. This is unlikely to impact performance on any cluster, but the settings may be tuned as desired.

    Cleanup is done on each bucket in the cluster.

    All applications connected to the same cluster and running Transactions will share in the cleanup, via a low-touch communication protocol on the "_txn:client-record" metadata document that will be created in each bucket in the cluster. This document is visible and should not be modified externally. It is maintained automatically by the transactions library. All ATRs on a bucket will be distributed between all cleanup clients, so increasing the number of applications will not increase the reads required for scanning.

    An application may cleanup transactions created by another application.

    It is important to understand that if an application is not running, then cleanup is not running. (This is particularly relevant to developers running unit tests or similar.)

    If this is an issue, then the deployment may want to consider running a simple application at all times that just opens a Transactions object, to guarantee that cleanup is running.

    Configuring Cleanup

    The cleanup settings can be configured as so:

    Setting Default Description

    cleanupWindow

    60 seconds

    This determines how long a cleanup 'run' is; that is, how frequently this client will check its subset of ATR documents. It is perfectly valid for the application to change this setting, which is at a conservative default. Decreasing this will cause expiration transactions to be found more swiftly (generally, within this cleanup window), with the tradeoff of increasing the number of reads per second used for the scanning process.

    cleanupLostAttempts

    true

    This is the thread that takes part in the distributed cleanup process described above, that cleans up expired transactions created by any client. It is strongly recommended that it is left enabled.

    cleanupClientAttempts

    true

    This thread is for cleaning up transactions created just by this client. The client will preferentially aim to send any transactions it creates to this thread, leaving transactions for the distributed cleanup process only when it is forced to (for example, on an application crash). It is strongly recommended that it is left enabled.

    Logging

    To aid troubleshooting, each transaction maintains a list of log entries, which can be logged on failure like this:

                }
                catch (TransactionCommitAmbiguousException e)
                {
                    // The application will of course want to use its own logging rather
                    // than Console.WriteLine
                    Console.Error.WriteLine("Transaction possibly committed");
                    Console.Error.WriteLine(e);
                }
                catch (TransactionFailedException e)
                {
                    Console.Error.WriteLine("Transaction did not reach commit point");
                    Console.Error.WriteLine(e);
                }
            }
    
            async Task Examples()
            {
                try
                {
                    var result = await _transactions.RunAsync(async (ctx) =>
                    {
                        // Inserting a doc:
                        await ctx.InsertAsync(_collection, "doc-a", new {}).ConfigureAwait(false);
    
                        // Getting documents:
                        // Use ctx.GetAsync if the document should exist, and the transaction
                        // will fail if it does not
                        var docA = await ctx.GetAsync(_collection, "doc-a").ConfigureAwait(false);
    
                        // Replacing a doc:
                        var docB = await ctx.GetAsync(_collection, "doc-b").ConfigureAwait(false);
                        var content = docB.ContentAs<dynamic>();
                        content.put("transactions", "are awesome");
                        await ctx.ReplaceAsync(docB, content);
    
                        // Removing a doc:
                        var docC = await ctx.GetAsync(_collection, "doc-c").ConfigureAwait(false);
                        await ctx.RemoveAsync(docC).ConfigureAwait(false);
    
                        await ctx.CommitAsync().ConfigureAwait(false);
                    }).ConfigureAwait(false);
                }
                catch (TransactionCommitAmbiguousException e)
                {
                   Console.WriteLine("Transaction possibly committed");
                   Console.WriteLine(e);
                }
                catch (TransactionFailedException e)
                {
                    Console.WriteLine("Transaction did not reach commit point");
                    Console.WriteLine(e);
                }
            }
    
            private async Task InsertAsync()
            {
                await _transactions.RunAsync(async ctx =>
                {
                    await ctx.InsertAsync(_collection, "docId", new { }).ConfigureAwait(false);
                }).ConfigureAwait(false);
    
            }
    
            private async Task GetAsync()
            {
                await _transactions.RunAsync(async ctx =>
                {
                    var docId = "a-doc";
                    var docOpt = await ctx.GetAsync(_collection, docId).ConfigureAwait(false);
                }).ConfigureAwait(false);
            }
    
            private async Task GetReadOwnWritesAsync()
            {
                await _transactions.RunAsync(async ctx =>
                {
                    var docId = "docId";
                    await ctx.InsertAsync(_collection, docId, new { }).ConfigureAwait(false);
                    var doc = await ctx.GetAsync(_collection, docId).ConfigureAwait(false);
                    Console.WriteLine((object) doc.ContentAs<dynamic>());
                }).ConfigureAwait(false);
            }
    
            async Task ReplaceAsync()
            {
                await _transactions.RunAsync(async ctx =>
                {
                    var anotherDoc = await ctx.GetAsync(_collection, "anotherDoc").ConfigureAwait(false);
                    var content = anotherDoc.ContentAs<dynamic>();
                    content.put("transactions", "are awesome");
                    await ctx.ReplaceAsync(anotherDoc, content);
                }).ConfigureAwait(false);
            }
    
            private async Task RemoveAsync()
            {
                await _transactions.RunAsync(async ctx =>
                {
                    var anotherDoc = await ctx.GetAsync(_collection, "anotherDoc").ConfigureAwait(false);
                    await ctx.RemoveAsync(anotherDoc).ConfigureAwait(false);
                }).ConfigureAwait(false);
            }
    
            private async Task CommitAsync()
            {
                var result = await _transactions.RunAsync(async (ctx) =>
                {
                    var doc = await ctx.GetAsync(_collection, "anotherDoc").ConfigureAwait(false);
                    var content = doc.ContentAs<JObject>();
                    content.Add("transactions", "are awesome");
    
                    await ctx.ReplaceAsync(doc, content).ConfigureAwait(false);
                }).ConfigureAwait(false);
            }
    
    
            public async Task PlayerHitsMonster(string actionUuid, int damage, string playerId, string monsterId)
            {
                try
                {
                    await _transactions.RunAsync(async (ctx) =>
                    {
                        _logger.LogInformation(
                            "Starting transaction, player {playerId} is hitting monster {monsterId} for {damage} points of damage.",
                            playerId, monsterId, damage);
    
                        var monster = await ctx.GetAsync(_collection, monsterId).ConfigureAwait(false);
                        var player = await ctx.GetAsync(_collection, playerId).ConfigureAwait(false);
    
                        var monsterContent = monster.ContentAs<JObject>();
                        var playerContent = player.ContentAs<JObject>();
    
                        var monsterHitPoints = monsterContent.GetValue("hitpoints").ToObject<int>();
                        var monsterNewHitPoints = monsterHitPoints - damage;
    
                        _logger.LogInformation(
                            "Monster {monsterId} had {monsterHitPoints} hitpoints, took {damage} damage, now has {monsterNewHitPoints} hitpoints.",
                            monsterId, monsterHitPoints, damage, monsterNewHitPoints);
    
                        if (monsterNewHitPoints <= 0)
                        {
                            // Monster is killed.  The remove is just for demoing, and a more realistic example would set a
                            // "dead" flag or similar.
    
                            await ctx.RemoveAsync(monster).ConfigureAwait(false);
    
                            // The player earns experience for killing the monster
                            var experienceForKillingMonster =
                                monsterContent.GetValue("experienceWhenKilled").ToObject<int>();
                            var playerExperience = playerContent.GetValue("experiance").ToObject<int>();
                            var playerNewExperience = playerExperience + experienceForKillingMonster;
                            var playerNewLevel = CalculateLevelForExperience(playerNewExperience);
    
                            _logger.LogInformation(
                                "Monster {monsterId} was killed.  Player {playerId} gains {experienceForKillingMonster} experience, now has level {playerNewLevel}.",
                                monsterId, playerId, experienceForKillingMonster, playerNewLevel);
    
                            playerContent["experience"] = playerNewExperience;
                            playerContent["level"] = playerNewLevel;
    
                            await ctx.ReplaceAsync(player, playerContent).ConfigureAwait(false);
                        }
                        else
                        {
                            _logger.LogInformation("Monster {monsterId} is damaged but alive.", monsterId);
    
                            // Monster is damaged but still alive
                            monsterContent.Add("hitpoints", monsterNewHitPoints);
    
                            await ctx.ReplaceAsync(monster, monsterContent).ConfigureAwait(false);
                        }
    
                        _logger.LogInformation("About to commit transaction");
    
                    }).ConfigureAwait(false);
                }
                catch (TransactionCommitAmbiguousException e)
                {
                    _logger.LogWarning("Transaction possibly committed:{0}{1}", Environment.NewLine, e);
                }
                catch (TransactionFailedException e)
                {
                    // The operation timed out (the default timeout is 15 seconds) despite multiple attempts to commit the
                    // transaction logic.   Both the monster and the player will be untouched.
    
                    // This situation should be very rare.  It may be reasonable in this situation to ignore this particular
                    // failure, as the downside is limited to the player experiencing a temporary glitch in a fast-moving MMO.
    
                    // So, we will just log the error
                    _logger.LogWarning("Transaction did not reach commit:{0}{1}", Environment.NewLine, e);
                }
    
                _logger.LogInformation("Transaction is complete");
            }
    
            private int CalculateLevelForExperience(int exp)
            {
                return exp / 100;
            }
    
            private async Task Rollback()
            {
                const int costOfItem = 10;
                await _transactions.RunAsync(async (ctx) => {
                    var customer = await ctx.GetAsync(_collection, "customer-name").ConfigureAwait(false);
    
                    if (customer.ContentAs<dynamic>().balance < costOfItem)
                    {
                        await ctx.RollbackAsync().ConfigureAwait(false);
                    }
                    // else continue transaction
                }).ConfigureAwait(false);
            }
    
            public class BalanceInsufficientException : Exception { }
    
            private async Task RollbackCause()
            {
                const int costOfItem = 10;
    
    
                try
                {
                    await _transactions.RunAsync(async ctx =>
                    {
                        var customer = await ctx.GetAsync(_collection, "customer-name").ConfigureAwait(false);
    
                        if (customer.ContentAs<dynamic>().balance < costOfItem) throw new BalanceInsufficientException();
                        // else continue transaction
                    }).ConfigureAwait(false);
                }
                catch (TransactionCommitAmbiguousException e)
                {
                    // This exception can only be thrown at the commit point, after the
                    // BalanceInsufficient logic has been passed, so there is no need to
                    // check getCause here.
                    Console.Error.WriteLine("Transaction possibly committed");
                    Console.Error.WriteLine(e);
                }
                catch (TransactionFailedException e)
                {
                    Console.Error.WriteLine("Transaction did not reach commit point");
                }
    
            }
    
            async Task CompleteErrorHandling()
            {
                try
                {
                    var result = await _transactions.RunAsync(async (ctx) => {
                        // ... transactional code here ...
                    });
    
                    // The transaction definitely reached the commit point. Unstaging
                    // the individual documents may or may not have completed
    
                    if (result.UnstagingComplete)
                    {
                        // Operations with non-transactional actors will want
                        // unstagingComplete() to be true.
                        await _cluster.QueryAsync<dynamic>(" ... N1QL ... ",
                            new QueryOptions()).ConfigureAwait(false);
    
                        var documentKey = "a document key involved in the transaction";
                        var getResult = await _collection.GetAsync(documentKey).ConfigureAwait(false);
                    }
                    else
                    {
                        // This step is completely application-dependent.  It may
                        // need to throw its own exception, if it is crucial that
                        // result.unstagingComplete() is true at this point.
                        // (Recall that the asynchronous cleanup process will
                        // complete the unstaging later on).
                    }
                }
                catch (TransactionCommitAmbiguousException err)
                {
                    // The transaction may or may not have reached commit point
                    Console.Error.WriteLine("Transaction returned TransactionCommitAmbiguous and" +
                            " may have succeeded, logs:");
    
                    // Of course, the application will want to use its own logging rather
                    // than System.err
                    Console.Error.WriteLine(err);
                }
                catch (TransactionFailedException err)
                {
                    // The transaction definitely did not reach commit point
                    Console.Error.WriteLine("Transaction failed with TransactionFailed, logs:");
                    Console.Error.WriteLine(err);
                }
            }
    
    
            async Task CompleteLogging()
            {
                //Logging dependencies
                var services = new ServiceCollection();
                services.AddLogging(builder =>
                {
                    builder.AddFile(AppContext.BaseDirectory);
                    builder.AddConsole();
                });
                await using var provider = services.BuildServiceProvider();
                var loggerFactory = provider.GetService<ILoggerFactory>();
                var logger = loggerFactory.CreateLogger<Program>();
    
                //create the transactions object and add the ILoggerFactory
                var transactions = Transactions.Create(_cluster,
                    TransactionConfigBuilder.Create().LoggerFactory(loggerFactory));
                try
                {
                    var result = await transactions.RunAsync(async ctx => {
                        // ... transactional code here ...
                    });
                }
                catch (TransactionCommitAmbiguousException err)
                {
                    // The transaction may or may not have reached commit point
                    logger.LogInformation("Transaction returned TransactionCommitAmbiguous and" +
                                " may have succeeded, logs:");
                    Console.Error.WriteLine(err);
                }
                catch (TransactionFailedException err)
                {
                    // The transaction definitely did not reach commit point
                    logger.LogInformation("Transaction failed with TransactionFailed, logs:");
                    Console.Error.WriteLine(err);
                }
            }
    
            public void Dispose()
            {
                _cluster.Dispose();
                _transactions.Dispose();
            }
        }
    }

    A failed transaction can involve dozens, even hundreds, of lines of logging, so the application may prefer to write failed transactions into a separate file.

    For convenience there is also a config option that will automatically write this programmatic log to the standard Couchbase Java logging configuration inherited from the SDK if a transaction fails. This will log all lines of any failed transactions, to WARN level:

    [data-source-url=https://github.com/couchbase/docs-sdk-dotnet/blob/63abd2a4ebc67825d6268245a04fc98cae43075e/modules/howtos/examples/TransactionsExample.cs]

    Please see the .NET SDK logging documentation for details.

    Here is an example of configuring a Microsoft.Extensions.Logging.ILoggingFactory:

    //Logging dependencies
    var services = new ServiceCollection();
    services.AddLogging(builder =>
    {
        builder.AddFile(AppContext.BaseDirectory);
        builder.AddConsole();
    });
    await using var provider = services.BuildServiceProvider();
    var loggerFactory = provider.GetService<ILoggerFactory>();
    var logger = loggerFactory.CreateLogger<Program>();
    
    //create the transactions object and add the ILoggerFactory
    var transactions = Transactions.Create(_cluster,
        TransactionConfigBuilder.Create().LoggerFactory(loggerFactory));
    try
    {
        var result = await transactions.RunAsync(async ctx => {
            // ... transactional code here ...
        });
    }
    catch (TransactionCommitAmbiguousException err)
    {
        // The transaction may or may not have reached commit point
        logger.LogInformation("Transaction returned TransactionCommitAmbiguous and" +
                    " may have succeeded, logs:");
        Console.Error.WriteLine(err);
    }
    catch (TransactionFailedException err)
    {
        // The transaction definitely did not reach commit point
        logger.LogInformation("Transaction failed with TransactionFailed, logs:");
        Console.Error.WriteLine(err);
    }

    Deferred Commits

    The deferred commit feature is currently in alpha, and the API may change.

    Deferred commits allow a transaction to be paused just before the commit point. Optionally, everything required to finish the transaction can then be bundled up into a context that may be serialized into a String or byte array, and deserialized elsewhere (for example, in another process). The transaction can then be committed, or rolled back.

    The intention behind this feature is to allow multiple transactions, potentially spanning multiple databases, to be brought to just before the commit point, and then all committed together.

    Here’s an example of deferring the initial commit and serializing the transaction:

    try
    {
        var result = await _transactions.RunAsync(async (ctx)=>
        {
            var initial = new {val = 1};
            await ctx.InsertAsync(_collection, "a-doc-id", initial).ConfigureAwait(false);
    
            // Defer means don't do a commit right now.  `serialized` in the result will be present.
            await ctx.DeferAsync().ConfigureAwait(false);
        }).ConfigureAwait(false);
    
        // Available because ctx.defer() was called
        TransactionSerializedContext serialized = result.Serialized;
    
        // This is going to store a serialized form of the transaction to pass around
        var encoded = serialized.EncodeAsBytes();
    
    }
    catch (TransactionFailedException e)
    {
        // System.err is used for example, log failures to your own logging system
        Console.Error.WriteLine("Transaction did not reach commit point");
        Console.Error.WriteLine(e);
    }

    And then committing the transaction later:

    var serialized = TransactionSerializedContext.CreateFrom(encoded);
    
    try
    {
        var result = await _transactions.RunAsync(async (ctx) =>
        {
            await ctx.CommitAsync().ConfigureAwait(false);
        });
    
    }
    catch (TransactionFailedException e)
    {
        // System.err is used for example, log failures to your own logging system
        System.err.println("Transaction did not reach commit point");
    
        for (LogDefer err : e.result().log().logs())
        {
            System.err.println(err.toString());
        }
    }

    Further Reading