NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / C# / .NET CLIENT / TRANSACTIONS IN .NET

Transactions in .NET

This page shows how to group statements into a transaction with RasterizedDb.Data: starting and ending one, choosing an isolation level, savepoints, and handling the conflicts and lost connections that a real application meets. The server's own transaction rules are in Transactions.

A transaction

csharp
using RasterizedDb.Data;

await using var dataSource = new RasterizedDbDataSource("Host=127.0.0.1;Username=app;Password=change-me-now");
await using var connection = await dataSource.OpenConnectionAsync();

await using (var transaction = await connection.BeginTransactionAsync())
{
    await using (var debit = connection.CreateCommand("UPDATE accounts SET balance = balance - @amount WHERE id = @id"))
    {
        debit.Parameters.Add("amount", 25.00m);
        debit.Parameters.Add("id", 1L);
        await debit.ExecuteNonQueryAsync();
    }

    await using (var credit = connection.CreateCommand("UPDATE accounts SET balance = balance + @amount WHERE id = @id"))
    {
        credit.Parameters.Add("amount", 25.00m);
        credit.Parameters.Add("id", 2L);
        await credit.ExecuteNonQueryAsync();
    }

    await transaction.CommitAsync();
}
  • A transaction belongs to its connection. Every command run on that connection while it is open runs inside it; setting command.Transaction is allowed but not needed.
  • Disposing a transaction that was neither committed nor rolled back rolls it back.
  • Closing a connection with a transaction still open rolls it back before the connection goes back to the pool.
  • connection.InTransaction says whether a transaction is open. It also follows BEGIN, COMMIT and ROLLBACK sent as plain statements.
  • One transaction at a time per connection: BeginTransaction while one is open throws InvalidOperationException. Nest with savepoints.
  • DDL (CREATE TABLE, ALTER TABLE, CREATE INDEX, …) inside a transaction rolls back with it. A few statements are refused inside one, such as CREATE DATABASE and DROP DATABASE; see Transactions.

The synchronous forms (BeginTransaction, Commit, Rollback) work the same way.

Isolation levels

Pass an IsolationLevel to BeginTransactionAsync:

csharp
using System.Data;

await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.RepeatableRead);
IsolationLevelstatement senton the server
Unspecified (default)BEGINthe server's default, READ COMMITTED
ReadUncommitted, ReadCommittedBEGIN ISOLATION LEVEL READ COMMITTEDa fresh snapshot for every statement
RepeatableRead, SnapshotBEGIN ISOLATION LEVEL REPEATABLE READone snapshot for the whole transaction
SerializableBEGIN ISOLATION LEVEL SERIALIZABLEaccepted, and behaves as REPEATABLE READ
ChaosNotSupportedException

SERIALIZABLE on RasterizedDB does not detect write skew; do not rely on it for that.

A read-only transaction:

csharp
await using var report = await connection.BeginTransactionAsync(IsolationLevel.RepeatableRead, readOnly: true);

When a statement fails

A statement that fails inside a transaction fails the whole transaction. Every later statement is refused with SQLSTATE 25P02 until you roll back, either all the way or to a savepoint. The connection itself stays usable.

csharp
await using var transaction = await connection.BeginTransactionAsync();
try
{
    await using var insert = connection.CreateCommand("INSERT INTO orders (id, customer_id) VALUES (@id, @customer)");
    insert.Parameters.Add("id", 1001L);
    insert.Parameters.Add("customer", 7L);
    await insert.ExecuteNonQueryAsync();
    await transaction.CommitAsync();
}
catch (RasterizedDbException)
{
    await transaction.RollbackAsync();
    throw;
}

A COMMIT of a failed transaction rolls it back.

Savepoints

csharp
await using var transaction = await connection.BeginTransactionAsync();

await using (var first = connection.CreateCommand("INSERT INTO audit (message) VALUES ('first')"))
{
    await first.ExecuteNonQueryAsync();
}

await transaction.SaveAsync("before_optional");
try
{
    await using var optional = connection.CreateCommand("INSERT INTO audit (message) VALUES ('optional')");
    await optional.ExecuteNonQueryAsync();
    await transaction.ReleaseAsync("before_optional");
}
catch (RasterizedDbException)
{
    // Undo only the optional part; the transaction is usable again.
    await transaction.RollbackAsync("before_optional");
}

await transaction.CommitAsync();
callstatement
SaveAsync(name) / Save(name)SAVEPOINT name
RollbackAsync(name) / Rollback(name)ROLLBACK TO SAVEPOINT name
ReleaseAsync(name) / Release(name)RELEASE SAVEPOINT name

A savepoint name is letters, digits and _, starting with a letter or _, at most 63 characters; anything else throws ArgumentException. Rolling back to a savepoint also clears a failed state, so it is the way to recover from one failed statement without losing the whole transaction.

Retrying conflicts

Two concurrent transactions that change the same rows can conflict. The loser fails with one of:

SQLSTATEmeaning
40001serialization failure: under REPEATABLE READ (and SERIALIZABLE), a row this transaction wants to change was changed by another one since its snapshot
40P01deadlock: two transactions were waiting on each other, and this one was chosen to fail

At READ COMMITTED a writer that meets a row another transaction is changing waits for it instead, then applies its change to the committed row.

Both errors mean the transaction did nothing and can be run again from the start. RasterizedDbException.IsTransient is true for exactly these two.

With ExecuteInTransactionAsync

RasterizedDbDataSource.ExecuteInTransactionAsync runs a body in a transaction, commits when it returns, rolls back when it throws, and runs it again in a new transaction after a serialization failure or deadlock:

csharp
using System.Data;
using RasterizedDb.Data;

await using var dataSource = new RasterizedDbDataSource("Host=127.0.0.1;Username=app;Password=change-me-now");

decimal newBalance = await dataSource.ExecuteInTransactionAsync(async (connection, transaction, token) =>
{
    await using var update = connection.CreateCommand(
        "UPDATE accounts SET balance = balance - @amount WHERE id = @id RETURNING balance");
    update.Parameters.Add("amount", 10.00m);
    update.Parameters.Add("id", 1L);
    return Convert.ToDecimal(await update.ExecuteScalarAsync(token));
},
IsolationLevel.RepeatableRead,
retries: 3);
parameterdefault
bodyFunc<RasterizedDbConnection, RasterizedDbTransaction, CancellationToken, Task<T>>, or Task for a body with no result
isolationLevelUnspecifiedas in Isolation levels
retries2how many times to run the body again after a transient failure
cancellationTokennonestops waiting and retrying

Between attempts it waits a short, growing, randomised delay. After the last retry the error is thrown. Any other error is thrown at once.

The body may run more than once. Keep anything that must happen only once (sending an email, calling another service) until after ExecuteInTransactionAsync returns.

By hand

The same pattern written out, for code that manages its own connection:

csharp
using System.Data;
using RasterizedDb.Data;

static async Task TransferAsync(RasterizedDbDataSource dataSource, long from, long to, decimal amount)
{
    for (var attempt = 1; ; attempt++)
    {
        await using var connection = await dataSource.OpenConnectionAsync();
        await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.RepeatableRead);
        try
        {
            await using (var debit = connection.CreateCommand("UPDATE accounts SET balance = balance - @amount WHERE id = @id"))
            {
                debit.Parameters.Add("amount", amount);
                debit.Parameters.Add("id", from);
                await debit.ExecuteNonQueryAsync();
            }

            await using (var credit = connection.CreateCommand("UPDATE accounts SET balance = balance + @amount WHERE id = @id"))
            {
                credit.Parameters.Add("amount", amount);
                credit.Parameters.Add("id", to);
                await credit.ExecuteNonQueryAsync();
            }

            await transaction.CommitAsync();
            return;
        }
        catch (RasterizedDbException e) when (e.IsTransient && attempt < 4)
        {
            await transaction.RollbackAsync();
            await Task.Delay(TimeSpan.FromMilliseconds(20 * attempt + Random.Shared.Next(20)));
        }
    }
}

Never retry an error whose CommitOutcomeUnknown is true; see the next section.

Lost transactions

A transaction lives on one connection. If that connection goes, so does the transaction:

  • The connection fails (network, server restart). The next statement, or the statement in flight, throws RasterizedDbException with Kind TransactionLost. The server rolls the transaction back.
  • The failing request was the COMMIT. Then the transaction may have committed before the connection went. The exception has CommitOutcomeUnknown = true. Do not run the transaction again blindly: check whether its effects are there first, or make it safe to repeat (for example, an idempotency key with a unique constraint).
  • The transaction sat idle. The server closes a native connection that has been quiet for 30 seconds, rolling back its transaction. The driver does not send on a connection inside a transaction that has been quiet that long; it throws TransactionLost instead. Keep the gap between two statements of a transaction under 30 seconds, and do slow work (calls to other services, user input) outside it.

Transactions and data sources

A command made by dataSource.CreateCommand runs on a shared connection and commits on its own; BEGIN, COMMIT and savepoints are refused there. Open a connection for anything transactional:

csharp
await using var connection = await dataSource.OpenConnectionAsync();
await using var transaction = await connection.BeginTransactionAsync();

A batch, and a command holding several statements, runs as one implicit transaction: all of it takes effect or none does.

Limits

  • No distributed or ambient transactions: connections do not join a TransactionScope, and connection.EnlistTransaction throws NotSupportedException.
  • SERIALIZABLE behaves as REPEATABLE READ and does not detect write skew.
  • A transaction quiet for 30 seconds is lost, whatever the server's request timeout is set to.
  • One transaction per connection; nest with savepoints.
✓ page rendered in 150 µs axum + tera + htmx · no other javascript