📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What does ACID mean? Explain atomicity, consistency, isolation and durability, and how SQL Server actually provides each one: the transaction log, write-ahead logging, locks and row versioning.

ACID properties mapped to SQL Server mechanisms: the transaction log and write-ahead logging, rollback and recovery, constraints, locks and row versioning, and durability on commit.

Junior Theory Beginner acid durability isolation-levels sql-server transaction-log transactions

🎯 Key points

  • Atomicity: all statements commit or the log is used to roll back
  • Write-ahead logging: log record hardened before the data page is written
  • Consistency: constraints, FKs and triggers checked inside the transaction
  • Isolation: locks (pessimistic) or row versions (RCSI, on by default in Azure SQL Database)
  • Higher isolation (serializable) = more blocking; versioning trades locks for tempdb/version store
  • Durability: COMMIT returns only after the log block is flushed to disk
  • Crash recovery: analysis, redo, undo (faster with ADR)
  • SET XACT_ABORT ON so a runtime error rolls back the whole transaction

⏱ 30-second answer

ACID is the promise a transaction makes. Atomicity: all of its changes happen or none do; SQL Server records every change in the transaction log and uses those records to roll back. Consistency: the database moves from one valid state to another, enforced by constraints, foreign keys and triggers. Isolation: concurrent transactions don't see each other's half-finished work, through locks or row versioning (RCSI, snapshot) depending on the isolation level. Durability: once COMMIT returns, the change survives a crash, because of write-ahead logging: the log is flushed to disk before commit is acknowledged, and recovery replays it.

The trade-off: stronger isolation and synchronous durability cost concurrency and latency, so you choose the isolation level deliberately.

🗣 Full answer (senior)

How I would answer this in an interview

"ACID is four guarantees a transaction gives you, and in SQL Server each one maps to a concrete mechanism. Atomicity and durability both come from the transaction log. Every change is written as a log record before the data page changes on disk, which is write-ahead logging. If the transaction fails or I roll it back, SQL Server walks the log backwards and undoes it. When I commit, SQL Server flushes the log buffer to disk and only then returns success, so if the server loses power a second later, crash recovery redoes the committed work from the log.

Consistency is mostly about the rules I declare: primary keys, foreign keys, unique and check constraints. They are checked inside the transaction, so a violation fails the statement. Isolation is the interesting one: by default SQL Server uses read committed, implemented with shared and exclusive locks, or with row versioning when read committed snapshot is on, which it is by default in Azure SQL Database. Higher levels like serializable hold more locks for longer.

The mistake I see is assuming a statement error rolls back the whole transaction. It doesn't by default: in T-SQL many errors only abort the statement, and the transaction carries on. That's why I put SET XACT_ABORT ON at the top of every procedure that opens a transaction, and from .NET I always commit explicitly and dispose the transaction. ACID is only as good as the transaction boundaries you draw."


Each property and its mechanism

Property What it promises SQL Server mechanism
Atomicity All or nothing Log records with undo information; ROLLBACK; undo phase of recovery
Consistency Valid state to valid state PK, FK, UNIQUE, CHECK constraints, triggers; checked per statement
Isolation No interference from concurrent work Locks (S, U, X, intent) or row versions in the version store
Durability Committed data survives a crash Write-ahead logging; log flush on commit; redo phase of recovery

What can weaken each guarantee

Setting Effect
XACT_ABORT OFF (default) Some errors abort only the statement; the transaction can commit half the work
NOLOCK / read uncommitted Gives up isolation: dirty reads, missing or double-counted rows
Delayed durability Commit returns before the log flush; a crash can lose the last few milliseconds of commits
Disabled or untrusted constraints Consistency is no longer enforced for existing rows

Production example

An order import inserted the order header, then failed on one order line with a check-constraint error. Without XACT_ABORT, the procedure carried on and committed headers without lines, about [N] broken orders a week. Adding SET XACT_ABORT ON plus TRY...CATCH with THROW made each order all-or-nothing, and the broken orders stopped.

🔍 What the interviewer is checking

Checks that the candidate can connect each ACID property to a real SQL Server mechanism rather than reciting definitions.

Green flags

  • Mentions the transaction log and write-ahead logging for atomicity and durability
  • Names locks and row versioning for isolation
  • Knows XACT_ABORT and statement-level aborts
  • Says consistency means declared constraints, not app code

Red flags

  • Only textbook definitions with no mechanism
  • Thinks NOLOCK is a harmless performance tip
  • Believes data pages are written to disk at commit

📚 Learn in depth

1. The transaction log is the heart of ACID

Every database has a log file (.ldf). Each change produces a log record with a log sequence number (LSN), the transaction id, and enough information to redo and undo it.

BEGIN TRAN
  UPDATE Stock ...   -> log record LSN 100 (before/after image)
  INSERT Orders ...  -> log record LSN 101
COMMIT               -> commit record LSN 102, log flushed to disk, then 'OK' to client

Data pages are changed in memory (the buffer pool) and written to the data file later by checkpoints or the lazy writer. That is safe because of write-ahead logging (WAL): a dirty page is never written to disk before the log records that describe it.

2. Atomicity: rollback

On ROLLBACK, or when the session dies, SQL Server reads the transaction's log records backwards and applies compensating changes. A long transaction therefore takes a long time to roll back, which is why killing a big batch job is not instant.

3. Durability: commit and recovery

COMMIT writes a commit record and waits for the log block to be hardened (flushed). The wait shows as the WRITELOG wait type. After a crash, recovery runs three phases:

Analysis -> find active transactions and dirty pages
Redo     -> replay logged changes from the oldest dirty page LSN
Undo     -> roll back transactions that never committed

Accelerated Database Recovery (ADR), always on in Azure SQL Database, keeps row versions in a persistent version store so undo is near-instant instead of proportional to the transaction size.

4. Isolation: locks or versions

  • Pessimistic (locking): writers take exclusive (X) locks held until commit; readers take shared (S) locks under read committed, released as soon as the row is read.
  • Optimistic (versioning): with RCSI or snapshot isolation, an update keeps the previous row version, and readers get the last committed version instead of waiting.

The isolation level decides which anomalies (dirty reads, non-repeatable reads, phantoms) are possible.

5. Consistency: what the database can and can't guarantee

The database enforces declared rules. A business rule that lives only in C#, such as "stock never goes below zero", is not part of ACID consistency unless you add a CHECK (Quantity >= 0) constraint or a conditional update.

6. Error handling and atomicity

T-SQL error behaviour is uneven: a constraint violation aborts the statement but not the batch unless XACT_ABORT is on. SET XACT_ABORT ON turns most runtime errors into a full rollback, and is what you want in nearly every transactional procedure. Note that compile errors and some errors are not caught by TRY...CATCH in the same scope.

Try it yourself

  1. Create a table with CHECK (Quantity >= 0), run a transaction with two inserts where the second fails, with XACT_ABORT off and then on, and count the rows each time.
  2. Run SELECT * FROM sys.fn_dblog(NULL, NULL) (test database only) after a small update and find your transaction's log records.
  3. Start a transaction in one SSMS window, update a row, and query it from another window under read committed; then turn on READ_COMMITTED_SNAPSHOT and repeat.
  4. Check sys.dm_os_wait_stats for WRITELOG before and after inserting 10,000 rows one transaction per row versus one transaction for all rows.

💻 Code

Atomic order insert in T-SQL, and the same boundary from .NET with Microsoft.Data.SqlClient.

CREATE TABLE dbo.Stock (ProductId int PRIMARY KEY, Quantity int NOT NULL CHECK (Quantity >= 0));
CREATE TABLE dbo.Orders (OrderId int IDENTITY PRIMARY KEY, ProductId int NOT NULL REFERENCES dbo.Stock(ProductId), Quantity int NOT NULL);
GO
CREATE OR ALTER PROCEDURE dbo.PlaceOrder @ProductId int, @Quantity int
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;          -- any runtime error rolls back the whole transaction

    BEGIN TRY
        BEGIN TRAN;
            UPDATE dbo.Stock SET Quantity -= @Quantity WHERE ProductId = @ProductId; -- CHECK keeps it >= 0
            INSERT dbo.Orders (ProductId, Quantity) VALUES (@ProductId, @Quantity);
        COMMIT;                 -- returns only after the log is hardened
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0 ROLLBACK;
        THROW;                  -- surface the original error to the caller
    END CATCH
END
namespace Shop.Data;

using Microsoft.Data.SqlClient;

public sealed class OrderWriter(string connectionString)
{
    public async Task PlaceOrderAsync(int productId, int quantity, CancellationToken ct)
    {
        await using var conn = new SqlConnection(connectionString);
        await conn.OpenAsync(ct);
        // Dispose without Commit = rollback, so an exception can never leave half an order.
        await using var tx = (SqlTransaction)await conn.BeginTransactionAsync(ct);

        await using (var cmd = new SqlCommand(
            "UPDATE dbo.Stock SET Quantity -= @q WHERE ProductId = @p;" +
            "INSERT dbo.Orders (ProductId, Quantity) VALUES (@p, @q);", conn, tx))
        {
            cmd.Parameters.AddWithValue("@p", productId);
            cmd.Parameters.AddWithValue("@q", quantity);
            await cmd.ExecuteNonQueryAsync(ct);
        }

        await tx.CommitAsync(ct);
    }
}

⚠ Common mistakes

  • Mistake: Assuming any error inside BEGIN TRAN rolls everything back. Why it is wrong: With XACT_ABORT OFF, a constraint violation aborts only that statement and the transaction can still commit. Instead: SET XACT_ABORT ON plus TRY...CATCH with ROLLBACK and THROW.
  • Mistake: Thinking durability means the data file is updated at commit. Why it is wrong: Only the log is flushed at commit; data pages are written later. Instead: Explain write-ahead logging and redo during recovery.
  • Mistake: Treating C# validation as ACID consistency. Why it is wrong: Two concurrent requests can both pass the check. Instead: Declare constraints and use conditional updates so the database enforces the rule.
  • Mistake: Using NOLOCK to fix blocking. Why it is wrong: It drops isolation and returns uncommitted or duplicated rows. Instead: Use RCSI and shorten write transactions.
  • Mistake: Committing one row per transaction in a big import. Why it is wrong: Every commit waits for a log flush (WRITELOG), so throughput collapses. Instead: Commit in batches of a few thousand rows.
  • Mistake: Leaving a transaction open while calling an external API. Why it is wrong: Locks are held for the whole call and block other sessions. Instead: Do the slow work outside the transaction.

🏛 Senior insight: trade-offs

Even for a junior question, the strong answer ties each letter to a mechanism, because that is what lets you reason about failures: a long rollback is the undo phase, WRITELOG waits are durability, blocking is isolation. Knowing that statement-level aborts are the default in T-SQL is the single most practical point.

Isolation is where ACID costs the most. Locking isolation makes readers and writers wait for each other, and serializable adds range locks that raise blocking and deadlocks; row versioning (RCSI, the Azure SQL Database default) removes reader/writer waits at the cost of version store space. ACID also stops at the database boundary: a transaction can't include a message broker or another service, so in microservices you use an outbox or a saga for cross-service consistency.

Knob When it fits Cost When not to
XACT_ABORT ON Every procedure with a transaction None meaningful Rare cases needing to continue after an expected error (use TRY...CATCH instead)
RCSI OLTP with readers blocked by writers tempdb/version store space, small update overhead Code that relies on readers blocking to stay correct
Serializable Range rules such as 'no overlapping booking' Range locks, deadlocks As a default for every transaction
Delayed durability High-volume, loss-tolerant logging tables Can lose recent commits on crash Money, orders, anything you can't recompute

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions isolation levels or locks vs row versioning. Why: Checks the candidate can go from the I in ACID to concrete isolation levels.
    How to answer

    Isolation levels decide which anomalies a transaction can see. Read uncommitted takes no shared locks, so dirty reads are possible (it's what NOLOCK does). Read committed, the default, only reads committed data, using short-lived S locks, or row versions when RCSI is on, but a re-read can change (non-repeatable read). Repeatable read holds S locks to the end of the transaction, so rows you read can't change, but new rows can appear (phantoms). Serializable adds key-range locks so ranges can't change either. Snapshot gives a transaction-consistent view from row versions.

    The trade-off: each step up holds more locks for longer, which means more blocking and deadlocks. Pick the lowest level that is correct, and solve specific races with targeted locks or constraints.

  2. When: Candidate mentions NOLOCK as a way around blocking. Why: Checks the candidate knows which ACID guarantee NOLOCK gives up.
    How to answer

    NOLOCK is read uncommitted: it reads rows other transactions haven't committed (which may be rolled back), and because it can use allocation-order scans without shared locks, it can skip rows or read them twice when pages split during the scan. It can even fail with error 601. It removes blocking by giving up correctness. Use read committed snapshot isolation (RCSI), the default in Azure SQL Database, so readers see the last committed version without blocking writers, and fix the long write transactions that cause blocking.

  3. When: Candidate talks about transactions from .NET or EF Core. Why: Checks how the transaction boundary looks in EF Core, including SaveChanges' implicit transaction.
    How to answer

    By default every SaveChanges is atomic: EF Core opens a transaction, sends all the INSERT/UPDATE/DELETE batches and commits, or rolls back on any failure (since EF Core 7 it skips the transaction when there is only one statement). You call Database.BeginTransactionAsync yourself only when several SaveChanges calls or raw SQL must commit together; inside that, EF Core takes a savepoint before each SaveChanges so one failed save can be undone without losing the rest. TransactionScope works but defaults to Serializable isolation, needs TransactionScopeAsyncFlowOption.Enabled for async, and cannot escalate to a distributed transaction on Azure SQL. With EnableRetryOnFailure, an explicit transaction must run inside CreateExecutionStrategy().ExecuteAsync, so the whole unit is retried. The trade-off: explicit transactions give you multi-step atomicity at the cost of longer-held locks and retry complexity, so prefer one SaveChanges per use case.

More in Transactions and Locking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me