.NET Architecture & System Design Interview Question #76

What is a database transaction?

Transactions, CQRS, Event Sourcing & Distributed Consistency Mid-Level Intermediate

Quick Interview Answer

A database transaction groups one or more operations into a logical unit of work. The transaction either completes according to the database's commit rules or is rolled back when it cannot complete.

Detailed Explanation

A database transaction groups one or more operations into a logical unit of work. The transaction either completes according to the database's commit rules or is rolled back when it cannot complete.

Transactions are important when multiple changes must remain consistent, such as creating an order and updating related records. In distributed systems, transaction boundaries should usually remain as small and local as practical.

Code Example

await using var tx =
    await db.Database.BeginTransactionAsync();

await SaveOrderAsync();
await SaveItemsAsync();

await tx.CommitAsync();