Developer Guides, Cheat Sheets & Tools

SQL course - Part 14: ENGINEERING PRACTICE

Part index Prerequisites Previous Next Full course

🧰 PART 14 β€” ENGINEERING PRACTICE


63. Concurrency patterns for real applications

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
πŸ”΄ Expert 35 min Prevent the β€œlost update” when two users save at once Β· Use optimistic and pessimistic locking Β· Make retries safe Β· Build a job queue

[!NOTE] πŸ“Œ In plain words: Chapter 43 explained what the database does when two people collide. This chapter is what you must do about it β€” because the most common concurrency bug in production is not a deadlock. It is two users both clicking Save, and one of them silently winning.

🌍 Analogy: Two people editing the same paper form. Both photocopy it, both write on their copy, both hand it back. The second one filed overwrites the first, and nobody ever finds out. Databases will happily do this for you at any isolation level, because as far as the engine is concerned, both writes were perfectly legal.

63.1 πŸ’₯ The lost update β€” the bug isolation levels do not fix

10:00:00  User A reads the stock row.   qty_on_hand = 100
10:00:03  User B reads the same row.    qty_on_hand = 100
10:00:07  User B saves 90  (sold 10)
10:00:11  User A saves 95  (sold 5)     ← A never saw B's change

Final value: 95.   Actual sales: 15.   Truth: 85.

[!WARNING] ⚠️ Nothing here is a transaction failure. No deadlock, no error, no rollback. Both statements were valid. The data is simply wrong, and it will stay wrong until someone counts the shelf.

There are three correct answers. Pick deliberately.

63.2 βœ… Answer 1: don’t read-then-write at all

The best fix is to not have the race. If the new value can be expressed as a function of the old one, let the database compute it in a single statement β€” a single UPDATE takes its own locks and is atomic.

-- βœ… πŸŸ₯ MSSQL (in MySQL, read ROW_COUNT() instead of @@ROWCOUNT)
-- A one-row stock table to practise on (63.3 rebuilds it with a version column)
CREATE TABLE dbo.stock_items (
    product_id  INT PRIMARY KEY,
    qty_on_hand INT NOT NULL
);
INSERT INTO dbo.stock_items (product_id, qty_on_hand) VALUES (1, 100);

-- Atomic, no read, no race, no retry logic
UPDATE dbo.stock_items
SET qty_on_hand = qty_on_hand - 5
WHERE product_id = 1
  AND qty_on_hand >= 5;         -- and it cannot go negative

-- 0 rows changed = not enough stock. That is your business answer.
SELECT @@ROWCOUNT AS rows_changed;

[!IMPORTANT] 🎯 @@ROWCOUNT (🟦 MySQL: ROW_COUNT()) is the whole concurrency check. If the guard in the WHERE clause did not hold, zero rows change and you know immediately β€” no SELECT first, no lock hint, no retry. This single pattern removes most concurrency bugs people write elaborate machinery to solve.

[!TIP] πŸ’‘ This is set-based thinking applied to concurrency. β€œRead it, change it in the application, write it back” is the row-by-row mindset. β€œDescribe the change and let the engine apply it” is the set-based one, and it happens to be race-free.

63.3 🏷️ Answer 2: optimistic concurrency (the default for web apps)

When a human edits a form over 30 seconds, you cannot hold a lock that long. Instead, detect the conflict at save time: remember what version you read, and refuse to write if it has moved.

πŸŸ₯ MSSQL gives you ROWVERSION β€” an 8-byte value the engine increases on every update, automatically, with no clock involved.

-- πŸŸ₯ MSSQL
DROP TABLE IF EXISTS dbo.stock_items;      -- replaces the simple version from 63.2
CREATE TABLE dbo.stock_items (
    product_id  INT PRIMARY KEY,
    qty_on_hand INT NOT NULL,
    row_ver     ROWVERSION NOT NULL     -- maintained by the engine; you never write it
);
INSERT INTO dbo.stock_items (product_id, qty_on_hand) VALUES (1, 100);
-- πŸŸ₯ The full optimistic cycle, with a competing writer in the middle
DECLARE @seen_version BINARY(8);

-- 1. User A reads (this is your SELECT that fills the edit form)
SELECT @seen_version = row_ver FROM dbo.stock_items WHERE product_id = 1;

-- 2. User B changes the row while A is thinking
UPDATE dbo.stock_items SET qty_on_hand = 90 WHERE product_id = 1;

-- 3. User A saves, guarding on the version it read
UPDATE dbo.stock_items
SET qty_on_hand = 95
WHERE product_id = 1
  AND row_ver = @seen_version;          -- πŸ”‘ the whole mechanism

IF @@ROWCOUNT = 0
    SELECT 'CONFLICT - row changed since you read it' AS outcome;
ELSE
    SELECT 'OK - saved' AS outcome;

Result:

outcome
CONFLICT - row changed since you read it
-- πŸŸ₯ MSSQL
SELECT product_id, qty_on_hand FROM dbo.stock_items;
product_id qty_on_hand
1 90

[!IMPORTANT] 🎯 The lost update is now impossible. User B’s change survived, and User A was told. What the application does next is a product decision β€” reload and show the new values, merge the two edits, or ask the user β€” but it can no longer silently destroy data.

πŸ”€ MySQL has no ROWVERSION. Use an explicit integer version column and increase it yourself in the same statement:

-- 🟦 MySQL: the portable equivalent
CREATE TABLE stock_items (
    product_id  INT PRIMARY KEY,
    qty_on_hand INT NOT NULL,
    row_version INT NOT NULL DEFAULT 1
) ENGINE=InnoDB;

INSERT INTO stock_items (product_id, qty_on_hand) VALUES (1, 100);   -- row_version starts at 1

-- Save, guarding on the version read
UPDATE stock_items
SET qty_on_hand = 95,
    row_version = row_version + 1
WHERE product_id = 1
  AND row_version = 1;               -- the version the form was rendered from

SELECT ROW_COUNT();                  -- 0 = conflict

[!WARNING] ⚠️ Do not use updated_at as the version token. Two updates inside the same clock tick get the same timestamp, and the conflict goes undetected β€” which is the exact bug you were trying to fix. Use ROWVERSION πŸŸ₯ or an integer that only ever goes up 🟦. Both are exact.

[!TIP] πŸ’‘ Every mainstream ORM (a code library that writes SQL for your application, such as Entity Framework or Hibernate) already implements this. Entity Framework maps a ROWVERSION column marked [Timestamp] and throws DbUpdateConcurrencyException; Hibernate/JPA uses @Version; Django uses select_for_update or manual version fields. You are not building something exotic β€” you are turning on a feature.

63.4 πŸ”’ Answer 3: pessimistic locking (short, server-side work only)

When the read and the write happen microseconds apart inside one transaction β€” a stored procedure, a job β€” you can simply reserve the row while you work.

-- πŸŸ₯ MSSQL: take the update lock at read time, not at write time
BEGIN TRANSACTION;

    DECLARE @q INT;
    SELECT @q = qty_on_hand
    FROM dbo.stock_items WITH (UPDLOCK, ROWLOCK)      -- πŸ”‘
    WHERE product_id = 1;

    -- ... business logic that genuinely cannot be expressed as one UPDATE ...

    UPDATE dbo.stock_items SET qty_on_hand = @q - 5 WHERE product_id = 1;

COMMIT;
-- 🟦 MySQL: the same idea
START TRANSACTION;
    SELECT qty_on_hand FROM stock_items WHERE product_id = 1 FOR UPDATE;
    -- ...
    UPDATE stock_items SET qty_on_hand = qty_on_hand - 5 WHERE product_id = 1;
COMMIT;
Hint Meaning
πŸŸ₯ WITH (UPDLOCK) Β· 🟦 FOR UPDATE β€œI intend to update this row” β€” blocks other writers immediately, at read time
πŸŸ₯ WITH (UPDLOCK, HOLDLOCK) Β· 🟦 FOR UPDATE under SERIALIZABLE Also blocks inserts into the range β€” needed for check-then-insert
🟦 FOR SHARE (8.0+) β€œOthers may read, nobody may change”
READPAST / SKIP LOCKED β€œSkip rows someone else has locked” β€” the queue pattern, 63.6

[!WARNING] ⚠️ UPDLOCK without HOLDLOCK does not stop an insert. The classic β€œcheck if it exists, insert if not” race needs both, because you are locking a range that has no rows in it yet. Better still: put a UNIQUE constraint on the key and let the database refuse the duplicate (Chapter 9). A constraint has no race condition at all.

[!CAUTION] Never hold a pessimistic lock across a network round trip, a user’s think time, an HTTP call, or a file write. Locks held for seconds turn into blocking chains, an application that runs out of connections, and a system that looks hung. If a human is involved, you want 63.3, not this.

63.5 πŸ” Idempotency β€” surviving the retry

An operation is idempotent when doing it twice has exactly the same effect as doing it once. That matters because networks time out after the database committed. The client cannot tell β€œit failed” from β€œit worked and the reply was lost”, so it retries β€” and you get two payments.

-- πŸŸ₯ MSSQL: a unique idempotency key makes the retry harmless
CREATE TABLE payment_attempts (
    idempotency_key  CHAR(36)      NOT NULL PRIMARY KEY,   -- generated by the CLIENT
    order_id         INT           NOT NULL,
    amount           DECIMAL(10,2) NOT NULL,
    created_utc      DATETIME2(0)  NOT NULL DEFAULT SYSUTCDATETIME()
);

-- 🟦 MySQL: the same table
CREATE TABLE payment_attempts (
    idempotency_key  CHAR(36)      NOT NULL PRIMARY KEY,
    order_id         INT           NOT NULL,
    amount           DECIMAL(10,2) NOT NULL,
    created_utc      DATETIME      NOT NULL DEFAULT (UTC_TIMESTAMP())
);
-- πŸŸ₯ MSSQL: the second attempt with the same key does nothing, and says so
INSERT INTO payment_attempts (idempotency_key, order_id, amount)
SELECT '5f1c0a2e-0e1e-4d3a-9b7f-2a1c8e4d6b90', 1002, 250.00
WHERE NOT EXISTS (
    SELECT 1 FROM payment_attempts WITH (UPDLOCK, HOLDLOCK)
    WHERE idempotency_key = '5f1c0a2e-0e1e-4d3a-9b7f-2a1c8e4d6b90'
);

SELECT @@ROWCOUNT AS rows_inserted;   -- 1 = first time, 0 = a retry, already done
-- 🟦 MySQL: same guarantee, engine-native
INSERT IGNORE INTO payment_attempts (idempotency_key, order_id, amount)
VALUES ('5f1c0a2e-0e1e-4d3a-9b7f-2a1c8e4d6b90', 1002, 250.00);
SELECT ROW_COUNT();                   -- 1 = inserted, 0 = already there

[!TIP] πŸ’‘ The PRIMARY KEY is doing the real work. Even if the WHERE NOT EXISTS loses the race, the unique constraint rejects the duplicate β€” so the ledger can reject duplicate keys. This alone does not make a payment exactly-once: reject key reuse with different payloads, commit database effects with the ledger in the same transaction, and use the payment provider’s idempotency contract for remote charges.

[!IMPORTANT] 🎯 Rule of thumb: any operation a client can retry needs a client-supplied key. Server-generated IDs cannot help β€” the client never received the first one.

63.6 πŸ“¬ The queue pattern: many workers, one table

Turning a table into a work queue is a classic, and doing it the simple way means every worker fights for the same rows.

-- πŸŸ₯ MSSQL: a work-queue table
CREATE TABLE dbo.job_queue (
    job_id      INT IDENTITY(1,1) PRIMARY KEY,
    payload     NVARCHAR(400) NOT NULL,
    status      VARCHAR(20)   NOT NULL DEFAULT 'Pending',
    claimed_by  INT           NULL,
    claimed_utc DATETIME2(0)  NULL
);
INSERT INTO dbo.job_queue (payload) VALUES (N'email:1002'), (N'email:1013'), (N'email:1022');
GO

-- Claim a batch of jobs, skipping anything already claimed
UPDATE TOP (10) j
SET    status     = 'Processing',
       claimed_by = @@SPID,
       claimed_utc = SYSUTCDATETIME()
OUTPUT inserted.job_id, inserted.payload
FROM dbo.job_queue AS j WITH (READPAST, UPDLOCK, READCOMMITTEDLOCK)
WHERE j.status = 'Pending';
-- 🟦 MySQL 8.0+: the same idea
CREATE TABLE job_queue (
    job_id      INT AUTO_INCREMENT PRIMARY KEY,
    payload     VARCHAR(400) NOT NULL,
    status      VARCHAR(20)  NOT NULL DEFAULT 'Pending',
    claimed_by  BIGINT       NULL,
    claimed_utc DATETIME     NULL
);
INSERT INTO job_queue (payload) VALUES ('email:1002'), ('email:1013'), ('email:1022');

START TRANSACTION;
    SELECT job_id, payload FROM job_queue
    WHERE status = 'Pending'
    ORDER BY job_id
    LIMIT 10
    FOR UPDATE SKIP LOCKED;
    -- UPDATE those rows to 'Processing'
COMMIT;

[!TIP] πŸ’‘ READPAST πŸŸ₯ / SKIP LOCKED 🟦 is the whole trick. Instead of waiting for a row another worker has locked, the query steps over it. Workers can claim separate batches, although page locks, schema locks and other contention can still block them. The SQL Server example uses READCOMMITTEDLOCK so it also works at READ COMMITTED when READ_COMMITTED_SNAPSHOT is enabled; see table-hint restrictions. Without skip-locked behavior, workers may wait on each other; actual throughput depends on the plan, indexes, lock granularity and transaction duration.

[!TIP] πŸ’‘ OUTPUT πŸŸ₯ claims and reads in one statement (Chapter 12) β€” there is no window between β€œI claimed it” and β€œI read it” for a crash to fall into. 🟦 MySQL has no OUTPUT or RETURNING, which is why its version selects the rows FOR UPDATE SKIP LOCKED inside a transaction and then updates them.

[!WARNING] ⚠️ Always store claimed_utc and reset stale claims. A worker that dies mid-job leaves rows stuck in Processing forever. A scheduled job that resets anything claimed more than N minutes ago is not optional β€” it is the difference between a queue and a leak.

63.7 🚦 One-at-a-time work: application locks

Sometimes the thing that must run one at a time is not a row β€” it is a job. Two servers both firing the nightly rollup is a data-corruption event, not a performance problem.

-- πŸŸ₯ MSSQL: only one session can hold this named lock
BEGIN TRANSACTION;

DECLARE @rc INT;
EXEC @rc = sp_getapplock @Resource   = 'nightly_rollup',
                         @LockMode   = 'Exclusive',
                         @LockTimeout = 0;         -- do not wait; fail fast

SELECT @rc AS applock_result;    -- 0 = granted, -1 = someone else has it

IF @rc >= 0
BEGIN
    -- ... do the work ...
    EXEC sp_releaseapplock @Resource = 'nightly_rollup';
END;

COMMIT;
-- 🟦 MySQL application-controlled fragment: run work ONLY when got_lock = 1.
-- On 0 or NULL, skip work and report failure; release in application finally logic.
SELECT GET_LOCK('nightly_rollup', 0) AS got_lock;    -- 1 = granted, 0 = timeout
-- ... do the work ...
SELECT RELEASE_LOCK('nightly_rollup');

[!TIP] πŸ’‘ This coordinates application workers connected to the same database lock authority. It is not a lock shared across independent database servers. No extra infrastructure, no Redis, no ZooKeeper β€” and it releases automatically if the session dies, which is exactly the failure mode a home-made β€œis_running” flag column gets wrong.

63.8 ⏱️ Fail fast: timeouts every application should set

-- πŸŸ₯ MSSQL: session guards worth setting on every connection
SET NOCOUNT ON;             -- skip the "(n rows affected)" messages
SET XACT_ABORT ON;          -- πŸ”‘ any error aborts the whole transaction, not just the statement
SET LOCK_TIMEOUT 5000;      -- give up waiting for a lock after 5 seconds

SELECT @@LOCK_TIMEOUT AS lock_timeout_ms;   -- 5000
SET LOCK_TIMEOUT -1;                        -- back to "wait forever" (the default)
-- 🟦 MySQL
SET SESSION innodb_lock_wait_timeout = 5;
SET SESSION max_execution_time = 10000;     -- ms, SELECT statements

[!WARNING] ⚠️ SET XACT_ABORT ON is the setting most T-SQL is missing. Without it, some errors abort only the statement, leaving the transaction open and holding locks while the application moves on believing it failed cleanly. Combined with TRY … CATCH (Chapter 45) it is what makes a stored procedure genuinely safe.

[!TIP] πŸ’‘ Waiting forever is not β€œsafer” than failing. A query blocked indefinitely holds a connection, and a pool of blocked connections takes down the whole application, not just one request. A 5-second lock timeout turns a total outage into one failed request the client can retry.

63.9 🎯 Choosing the right tool

Situation Use
New value derives from the old (counters, stock, balances) A single UPDATE with a guard in WHERE (63.2)
A human edits a form over seconds or minutes Optimistic β€” ROWVERSION πŸŸ₯ / version column 🟦 (63.3)
Read and write are microseconds apart, inside one procedure Pessimistic β€” UPDLOCK πŸŸ₯ / FOR UPDATE 🟦 (63.4)
β€œInsert it if it does not exist” A UNIQUE constraint, plus upsert (Chapter 44)
The client may retry a request Idempotency key with a unique constraint (63.5)
Many workers, one work table READPAST πŸŸ₯ / SKIP LOCKED 🟦 (63.6)
Only one server may run this job sp_getapplock πŸŸ₯ / GET_LOCK 🟦 (63.7)
Deadlocks under load, all patterns already correct Retry after a short pause (Chapter 45), and check table access order

63.10 πŸ§ͺ Try it yourself

  1. Reproduce the lost update in two connections, step by step, and confirm no error is raised at any point.
  2. Add a ROWVERSION column and fix it. Prove the second writer now gets @@ROWCOUNT = 0.
  3. Rewrite the same logic as a single guarded UPDATE and explain why it needs neither a version column nor a lock hint.
  4. Build a two-row job_queue and pull from it in two sessions β€” first without READPAST / SKIP LOCKED, then with. Time both.
  5. Take sp_getapplock in one session and try to take it in another. Confirm you get -1, not a hang.
  6. Set LOCK_TIMEOUT 2000, block a row from a second session, and read the error number you get. Decide what your application should do with it.

🧭 In practice β€” concurrency patterns

How to use it. Pick a strategy deliberately. Optimistic: read a row with a version or timestamp, and on update check the version still matches β€” if not, someone else changed it, so retry. Pessimistic: take the lock while reading (WITH (UPDLOCK) in SQL Server, SELECT ... FOR UPDATE in MySQL). Atomic: express the change as a single conditional statement. Expected result: two simultaneous users cannot both succeed at something only one of them can have.

When to use it. Whenever two users can act on the same row: last item in stock, seat booking, account balance, a job queue.

Where to use it. Checkout, booking, and queue processing. Scenario: the last unit of stock. UPDATE products SET stock = stock - 1 WHERE product_id = ? AND stock >= 1 is atomic β€” the engine evaluates and applies it in one step, and the second caller updates zero rows and is told so. That single statement removes the race without any explicit locking at all.

When not to use it. Do not use optimistic concurrency where conflicts are frequent β€” you will spend all your time retrying. Do not use pessimistic locking where they are rare, or where a lock might be held across user thinking time. And never rely on a read-then-write pair without one of these mechanisms; the gap between the two is precisely where the bug lives.

Best practices. Prefer the atomic single statement whenever the change can be expressed that way β€” it is the simplest correct option and needs no retry logic. Where you must lock, keep transactions short and take locks in a consistent order. Always implement deadlock retry: deadlocks are an expected condition in a busy system, not an exceptional one. And test concurrency with actual concurrent sessions β€” a single-session test proves nothing about it.


64. Database DevOps: migrations, standards, and testing

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
πŸ”΄ Expert 40 min Keep every schema change in Git Β· Write safe, re-runnable migrations Β· Change a live schema without downtime Β· Test your database automatically

[!NOTE] πŸ“Œ In plain words: Application code lives in Git (a system that records every change to code), gets reviewed, gets tested, and gets deployed automatically. For most teams, the database does not β€” it lives in someone’s SSMS window and gets changed by hand at 11 p.m. This chapter closes that gap.

🌍 Analogy: You would never ship application code by remote-desktopping into production and editing a file. That is exactly what β€œjust run this ALTER on prod” is.

[!IMPORTANT] The one rule that makes everything else possible: the database schema is source code, and the only way it ever changes is by running a versioned script that is in Git. No exceptions, not even for a β€œtiny” index.

64.1 πŸ”€ State-based vs migration-based β€” pick one and commit

Β  State-based Migration-based
What is in Git The desired final schema An ordered list of change scripts
How deployment works A tool compares Git with the target database and generates the change Runs the scripts that have not run yet
Tools SSDT / DACPAC πŸŸ₯, MySQL Workbench sync 🟦 Flyway, Liquibase, EF Core Migrations, dbmate, Alembic
Strength The schema is easy to read and review as a whole Every change is explicit, ordered, and reviewable
Weakness Data migrations are guesswork. A rename looks like drop + add Nobody can see the current shape without replaying history
Best for Schema-only changes, brand-new projects, or teams already using the tool Almost everything else

[!IMPORTANT] 🎯 Default to migration-based. Its weakness (no single view of the schema) is solved by generating a schema snapshot into the repo on every build. Its strength β€” being explicit about data β€” is not something a diff tool can fake. A column rename is the classic example: a diff sees DROP name; ADD full_name and silently deletes every value.

64.2 πŸ“œ Anatomy of a migration

db/migrations/
    V0001__create_core_tables.sql
    V0002__add_order_status_check.sql
    V0003__index_orders_customer_date.sql
    V0004__backfill_loyalty_tier.sql
    V0005__add_customers_marketing_opt_in.sql

Four rules make a migration safe:

Rule Why
Immutable once merged Someone has already run it. Editing it means environments silently diverge
Forward-only, small, one concern each A 400-line migration that fails halfway is unreviewable and unrecoverable
Idempotent Deploys get retried. Running it twice must be harmless
Transactional where the engine allows πŸŸ₯ MSSQL wraps DDL in transactions. 🟦 MySQL 8.0 has atomic DDL per statement, but not across statements

The following ledger and migration template illustrate the mechanism; they are not a complete concurrent migration runner. A runner must hash the exact migration file bytes, compare previously applied checksums, serialize execution, and manage engine-specific transaction rules. Hashing a filename would not detect an edited file. For example, PowerShell Get-FileHash -LiteralPath ./db/migrations/V0007__add_opt_in.sql -Algorithm SHA256 computes the file hash.

-- πŸŸ₯ MSSQL: the ledger of what has been applied
IF OBJECT_ID('dbo.schema_migrations') IS NULL
CREATE TABLE dbo.schema_migrations (
    version      VARCHAR(20)   NOT NULL PRIMARY KEY,
    description  NVARCHAR(200) NOT NULL,
    checksum     CHAR(64)      NOT NULL,     -- detects an edited migration
    applied_at   DATETIME2(0)  NOT NULL DEFAULT SYSUTCDATETIME(),
    applied_by   NVARCHAR(128) NOT NULL DEFAULT SYSTEM_USER,
    duration_ms  INT           NOT NULL
);
GO
-- πŸŸ₯ Migration template: a runner must substitute the file-byte SHA-256 below.
-- The runner must serialize migrations and compare existing checksums before execution.
DECLARE @migration_sha256 CHAR(64) = '<replace with SHA-256 of exact migration file bytes>';
IF NOT EXISTS (SELECT 1 FROM dbo.schema_migrations WHERE version = '0007')
BEGIN
    DECLARE @t0 DATETIME2(3) = SYSUTCDATETIME();
    BEGIN TRY
        BEGIN TRANSACTION;

        IF NOT EXISTS (SELECT 1 FROM sys.columns
                       WHERE object_id = OBJECT_ID('dbo.customers')
                         AND name = 'marketing_opt_in')
            ALTER TABLE dbo.customers ADD marketing_opt_in BIT NOT NULL DEFAULT 0;

        INSERT INTO dbo.schema_migrations (version, description, checksum, duration_ms)
        VALUES ('0007', 'Add customers.marketing_opt_in',
                @migration_sha256,
                DATEDIFF(MILLISECOND, @t0, SYSUTCDATETIME()));

        COMMIT;
    END TRY
    BEGIN CATCH
        IF XACT_STATE() <> 0 ROLLBACK;
        THROW;
    END CATCH;
END;
GO

SELECT version, description, applied_by, duration_ms FROM dbo.schema_migrations;

Result β€” and running the exact same script a second time changes nothing:

version description applied_by duration_ms
0007 Add customers.marketing_opt_in sa 5

[!TIP] πŸ’‘ Two layers of idempotency, deliberately. The outer guard checks the ledger; the inner IF NOT EXISTS (SELECT … FROM sys.columns …) checks reality. The second one saves you when someone applied the change by hand before the migration ever ran β€” which, on a real team, they did.

[!TIP] πŸ’‘ The checksum column earns its place the day someone edits a merged migration. The runner compares the file’s hash against the stored one and refuses to continue, instead of quietly leaving production a schema version behind.

-- 🟦 MySQL: the equivalent guards
CREATE TABLE IF NOT EXISTS schema_migrations (
    version      VARCHAR(20)  NOT NULL PRIMARY KEY,
    description  VARCHAR(200) NOT NULL,
    checksum     CHAR(64)     NOT NULL,
    applied_at   DATETIME     NOT NULL DEFAULT (UTC_TIMESTAMP()),
    applied_by   VARCHAR(100) NOT NULL,
    duration_ms  INT          NOT NULL
) ENGINE=InnoDB;

-- ⚠️ MySQL has NO "ADD COLUMN IF NOT EXISTS" and NO "CREATE INDEX IF NOT EXISTS"
--    (that is MariaDB syntax). Check information_schema, then run the DDL only if needed:
SET @ddl = IF(
    (SELECT COUNT(*) FROM information_schema.columns
     WHERE table_schema = DATABASE() AND table_name = 'customers'
       AND column_name = 'marketing_opt_in') = 0,
    'ALTER TABLE customers ADD COLUMN marketing_opt_in BOOLEAN NOT NULL DEFAULT 0',
    'DO 0');
PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @ddl = IF(
    (SELECT COUNT(*) FROM information_schema.statistics
     WHERE table_schema = DATABASE() AND table_name = 'orders'
       AND index_name = 'ix_orders_customer_date') = 0,
    'CREATE INDEX ix_orders_customer_date ON orders (customer_id, order_date)',
    'DO 0');
PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt;

[!WARNING] ⚠️ 🟦 MySQL DDL is not transactional across statements. MySQL 8.0 made individual DDL statements atomic, but a migration containing three ALTERs that fails on the third leaves the first two applied. Either keep each migration to one DDL statement, or write an explicit rollback script and test it.

64.3 πŸ›‘οΈ Zero-downtime schema changes: the expand–contract pattern

The moment you have more than one application server, old and new code run at the same time during a deploy. Any migration the old code cannot survive is an outage.

❌ The one-step rename β€” guaranteed errors during the rollout
   EXEC sp_rename 'customers.full_name', 'customer_name', 'COLUMN';
   Old servers still SELECT full_name β†’ "Invalid column name"

Expand–contract splits every breaking change into three deploys:

Phase Deploy Schema state
1️⃣ Expand Add the new column. Backfill it. Write to both. Both columns exist; old code still works
2️⃣ Migrate New code reads the new column only. Verify nothing reads the old one Both exist; only new is read
3️⃣ Contract Drop the old column Only new exists
-- πŸŸ₯ MSSQL
-- 1️⃣ EXPAND: additive only, safe with old code running
ALTER TABLE dbo.customers ADD customer_name NVARCHAR(100) NULL;
GO
UPDATE dbo.customers SET customer_name = full_name WHERE customer_name IS NULL;
GO
-- (application now writes both columns)

-- 3️⃣ CONTRACT: days later, once nothing reads it
-- ⚠️ Left commented out here, because every other chapter of this guide still reads full_name:
-- ALTER TABLE dbo.customers DROP COLUMN full_name;
Change Safe in one step? If not, do this
Add a nullable column βœ… Yes β€”
Add NOT NULL with a default βœ… πŸŸ₯ instant on Enterprise/Developer edition (2012+) Β· βœ… 🟦 instant with ALGORITHM=INSTANT (8.0.12+) πŸŸ₯ Standard edition rewrites every row β€” test the timing on a copy first
Add NOT NULL without a default ❌ No Add nullable β†’ backfill β†’ add the NOT NULL constraint
Rename a column or table ❌ Never Expand–contract
Widen a column (VARCHAR(50) β†’ (100)) βœ… Usually Verify; narrowing is never safe
Narrow a type, or change its type ❌ No Expand–contract with a new column
Add an index ⚠️ Locks by default πŸŸ₯ WITH (ONLINE = ON) (Enterprise) Β· 🟦 ALGORITHM=INPLACE, LOCK=NONE
Add a foreign key ⚠️ Scans and locks πŸŸ₯ WITH NOCHECK, validate later (Chapter 9)
Drop anything ❌ Not until nothing references it Contract phase only, after a full deploy cycle

[!WARNING] ⚠️ A backfill is not a migration β€” it is a batch job. UPDATE customers SET customer_name = full_name on ten million rows takes one enormous lock and makes the transaction log balloon. Batch it, exactly as in Chapter 18 and 65.5, and run it outside the deploy transaction.

[!TIP] πŸ’‘ The rollback plan for expand–contract is β€œdo nothing”. Every phase is independently deployable and every phase leaves the previous version of the code working. That is what makes it safe, far more than any DOWN script.

64.4 ✍️ The house style guide

Consistency is not aesthetics. A schema where half the tables are Customer and half are tbl_customers costs every developer a lookup, every single time.

Naming

Object Convention Example
Table snake_case, plural, no prefix order_items
Column snake_case, singular unit_price
Primary key column <singular_table>_id customer_id
Foreign key column Same name as the key it points at orders.customer_id
Boolean A positive statement, no negatives is_active, ❌ not_disabled
UTC timestamp Say so in the name created_utc, shipped_utc
Money Include the unit if more than one is possible amount_usd
Primary key constraint pk_<table> pk_order_items
Foreign key constraint fk_<table>_<referenced> fk_orders_customer
Unique constraint uq_<table>_<columns> uq_customers_email
Check constraint ck_<table>_<rule> ck_orders_status
Index ix_<table>_<columns> ix_orders_customer_date
View v_<subject> v_order_summary
Stored procedure <verb>_<subject> place_order, get_customer_orders

[!WARNING] ⚠️ Never let the engine name a constraint for you. UQ__customer__AB6E61648F1FC932 is different on every environment, so any script that drops it by name works on your laptop and fails in production. Name every constraint explicitly at creation (Chapter 9).

[!TIP] πŸ’‘ Reserved words and pluralisation are not worth arguing about β€” pick one and write it down. What is worth being firm on: no spaces, no [Bracketed Names], no mixed case in a case-sensitive collation, and no type prefixes (tbl_, sp_). sp_ in particular is actively harmful in πŸŸ₯ MSSQL: the engine checks master first for anything starting with sp_, so you pay a lookup penalty on every call. (This guide’s examples use usp_, which is also fine β€” the harmful one is sp_.)

Formatting

-- βœ… House style: one clause per line, keywords upper, columns listed
SELECT  c.customer_id,
        c.full_name,
        COUNT(o.order_id)  AS order_count,
        SUM(p.amount)      AS lifetime_value
FROM        customers  AS c
LEFT JOIN   orders     AS o  ON o.customer_id = c.customer_id
LEFT JOIN   payments   AS p  ON p.order_id    = o.order_id
                            AND p.status      = 'Captured'
WHERE   c.country = 'Sri Lanka'
  AND   c.signup_date >= '2026-01-01'
GROUP BY c.customer_id, c.full_name
HAVING  COUNT(o.order_id) > 0
ORDER BY lifetime_value DESC;
  • Keywords upper-case, identifiers lower-case
  • One column per line in SELECT once there are more than two
  • Every table gets a meaningful alias β€” c, o, p, not a, b, t1
  • ON conditions immediately under their JOIN, continuation lines aligned
  • Leading commas or trailing commas β€” pick one, apply it everywhere
  • Never SELECT * outside a quick one-off query window (Chapter 13)

[!TIP] πŸ’‘ Enforce it with a tool, not with code review. sqlfluff (both engines, and it has a linter as well as a formatter), Poor Man’s T-SQL Formatter, or your editor’s formatter, wired into a pre-commit hook (a check that runs automatically before every Git commit). Humans arguing about comma placement in a pull request is the single lowest-value activity in software.

64.5 πŸ§ͺ Testing a database

β€œIt ran without an error” is not a test. These are, in ascending order of value:

Level What it proves How
Migration test The migration applies to a copy of production and is reversible Restore a prod backup, run all migrations, time it
Constraint test Bad data is actually rejected Insert a violating row, assert it fails
Unit test A procedure or function returns the right answer tSQLt πŸŸ₯, MyTAP / plain assertions 🟦
Regression test A query still returns the same rows after a rewrite EXCEPT in both directions
Performance test The plan did not change under real volume Capture the plan and row counts before and after
-- βœ… Works in BOTH (MySQL 8.0.31+): prove a rewritten query returns exactly the same rows
-- If BOTH counts are 0, the two queries return identical sets.
SELECT COUNT(*) AS rows_only_in_old FROM (
    SELECT customer_id, COUNT(*) AS order_count          -- the original query
    FROM orders
    GROUP BY customer_id
    EXCEPT
    SELECT c.customer_id, COUNT(o.order_id)              -- its rewrite
    FROM customers c
    JOIN orders o ON o.customer_id = c.customer_id
    GROUP BY c.customer_id
) AS d;

SELECT COUNT(*) AS rows_only_in_new FROM (
    SELECT c.customer_id, COUNT(o.order_id) AS order_count
    FROM customers c
    JOIN orders o ON o.customer_id = c.customer_id
    GROUP BY c.customer_id
    EXCEPT
    SELECT customer_id, COUNT(*)
    FROM orders
    GROUP BY customer_id
) AS d;

[!TIP] πŸ’‘ EXCEPT in both directions is the single most useful database test there is. Before you rewrite any query for performance, capture its output; after the rewrite, prove set equality. This catches the β€œfaster but wrong” rewrite, which is the only kind that actually hurts you. 🟦 MySQL 8.0.31+ supports EXCEPT; on older versions use LEFT JOIN … WHERE right IS NULL (Chapter 29).

-- βœ… πŸŸ₯ MSSQL β€” constraint test: assert that the database refuses bad data
BEGIN TRANSACTION;
BEGIN TRY
    INSERT INTO orders (customer_id, order_date, status)
    VALUES (1, '2026-01-01', 'Teleported');
    ROLLBACK;
    THROW 50001, 'FAIL - expected ck_orders_status to reject the insert', 1;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 ROLLBACK;
    IF ERROR_NUMBER() <> 547 OR ERROR_MESSAGE() NOT LIKE '%ck_orders_status%'
        THROW;  -- an unrelated error is a failed test, never a PASS
    SELECT 'PASS - expected status constraint rejected the insert' AS result;
END CATCH;

[!IMPORTANT] 🎯 Test your constraints, not just your queries. A disabled constraint permits invalid writes. A constraint added WITH NOCHECK can enforce new writes while leaving old data unvalidated and the constraint untrusted; validate existing rows with WITH CHECK CHECK CONSTRAINT when appropriate. One test per business rule, run in CI (the automatic build-and-test pipeline), and you find out in 30 seconds instead of 30 months.

64.6 πŸš€ The pipeline

  git push
     β”‚
     β”œβ”€β–Ά 1. Lint          sqlfluff / formatter check
     β”‚
     β”œβ”€β–Ά 2. Build         spin up a throwaway database container
     β”‚                    run every migration from empty
     β”‚
     β”œβ”€β–Ά 3. Test          constraint tests, unit tests, regression tests
     β”‚
     β”œβ”€β–Ά 4. Verify        run migrations against a RESTORED PROD COPY
     β”‚                    ← this step catches what step 2 cannot: real data
     β”‚
     β”œβ”€β–Ά 5. Review        a human reads the migration. Always.
     β”‚
     └─▢ 6. Deploy        same runner, same scripts, production
              └─ backup taken immediately before

[!CAUTION] Step 4 is the one teams skip, and it is the one that catches real failures. An empty database applies any migration in milliseconds. The same migration against 40 million real rows may take four hours, fill the transaction log, or fail on data that violates the constraint you are adding. Run it on a restored copy, and time it, before it ever meets production.

[!TIP] πŸ’‘ Every production deployment starts with a backup and ends with a verified restore path (Chapter 56). β€œWe can roll back the code” is not a plan when the migration dropped a column.

64.7 βœ… The database DevOps checklist

  • ☐ Every schema change is a script in Git β€” no exceptions, not even indexes
  • ☐ Migrations are immutable once merged, and checksummed
  • ☐ Every migration is idempotent and guarded
  • ☐ Breaking changes go through expand–contract, never one step
  • ☐ Backfills are batched and run outside the deploy transaction
  • ☐ Naming and formatting conventions are documented and linted automatically
  • ☐ Every constraint has an explicit name
  • ☐ Migrations are tested against a restored production copy, and timed
  • ☐ Constraint and regression tests run in CI
  • ☐ Production deploys are automated, backed up first, and reviewed by a human
  • ☐ Nobody β€” nobody β€” has a production SSMS window open for routine work

64.8 πŸ§ͺ Try it yourself

  1. Build the schema_migrations table and a two-script runner. Run it twice and prove the second run is a no-op.
  2. Take a column rename and write it out as three separate expand–contract deploys.
  3. Write a constraint test for every CHECK in ShopDB. Break one deliberately and confirm the test fails.
  4. Rewrite one of the Chapter 26 reporting queries and prove set equality with EXCEPT in both directions.
  5. Install sqlfluff, point it at your scripts, and fix everything it complains about. Then wire it into a pre-commit hook.

🧭 In practice β€” database DevOps

How to use it. Keep schema in source control as ordered, immutable migration scripts. Each has an up script and, ideally, a rollback. Apply them automatically through a tool (Flyway, Liquibase, EF Core migrations, DbUp). Test on a copy before production. Expected result: any environment can be rebuilt to any version, and every change has an author, a review, and a date.

When to use it. From the second person, or the second environment, onwards. Before that you can get away with hand-editing; after it, you cannot.

Where to use it. The deployment pipeline. Scenario: a release adds a column and backfills it. In CI the migration runs against a restored copy of production-shaped data, so the β€œthis takes four minutes and locks the table” discovery happens on a Tuesday afternoon rather than during the release window.

When not to use it. Never change production schema by hand, and never edit a migration that has already been applied anywhere β€” write a new one. Do not let the database be the one part of the system with no code review. Avoid tools that diff and auto-apply against production without a human reading the generated script; the generated DROP COLUMN is the one you needed to catch.

Best practices. Make migrations idempotent and forward-only, and write the rollback at the same time as the change. Prefer additive, multi-step changes β€” add, backfill, switch, remove in a later release β€” because each step can be stopped or reversed safely. Test migrations against realistic data volumes; a change that is instant on 18 rows can lock a table for minutes on 18 million.


65. SQL from the application layer

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
πŸŸ‘πŸ”΄ Intermediate–Expert 35 min Use connection pools correctly Β· Spot and fix the N+1 problem Β· Batch writes Β· Set timeouts and retry safely

[!NOTE] πŸ“Œ In plain words: Every query in this guide so far ran in a query window. In production they run from application code β€” and that changes what β€œfast” and β€œcorrect” mean. Most database outages are not caused by a bad query. They are caused by a fine query, called badly.

🌍 Analogy: A perfectly efficient checkout till is useless if the shop only lets one customer through the door at a time, or if each customer walks back to the car park between items. The till was never the bottleneck.

65.1 πŸ”Œ Connections are expensive β€” pool them

Opening a database connection costs a network handshake, a login check, and memory on the server. A connection pool keeps a set of connections open and lends them out, so the app does not pay that cost on every request. Doing that per request is the most common self-inflicted performance wound there is.

Β  Without pooling With pooling
Cost per query 20–100 ms of setup ~0
Server memory One session per in-flight request One session per pooled connection
Behaviour under load Collapses β€” connection storms Degrades gracefully β€” requests queue
// βœ… C# / ADO.NET β€” the pool is on by default. `using` RETURNS the connection, it does not close the socket.
var csb = new SqlConnectionStringBuilder
{
    DataSource = "prod-sql-01",
    InitialCatalog = "ShopDB",
    MinPoolSize = 5,
    MaxPoolSize = 100,          // must be < the server's worker limit, across ALL app servers
    ConnectTimeout = 5,         // fail fast on a dead server
    CommandTimeout = 30,        // ⚠️ separate setting β€” see 65.6
    Encrypt = true
};

using var conn = new SqlConnection(csb.ConnectionString);
await conn.OpenAsync();
# βœ… Python β€” a pool, not a connection per call
from sqlalchemy import create_engine
engine = create_engine(
    "mysql+mysqlconnector://app_user:***@db-host/ShopDB",
    pool_size=10, max_overflow=20, pool_pre_ping=True, pool_recycle=1800
)

[!WARNING] ⚠️ Size the pool for the database, not the application. Total connections across every app server, worker, and cron job must stay under what the server can handle. Ten services each configured MaxPoolSize = 100 is a thousand connections, and the server will fall over long before it runs a thousand queries at once. A pool much bigger than the number of CPU cores the database has mostly adds waiting, not speed.

[!TIP] πŸ’‘ pool_pre_ping / pool_recycle exist because firewalls silently kill idle TCP connections. Without them, the first query after a quiet period fails with a broken pipe. This is the classic β€œit only breaks at 3 a.m.” bug.

-- πŸŸ₯ MSSQL: who is connected right now, and what are they doing?
SELECT s.session_id, s.login_name, s.host_name, s.program_name,
       s.status, s.last_request_end_time,
       DB_NAME(s.database_id) AS db
FROM sys.dm_exec_sessions s
WHERE s.is_user_process = 1
ORDER BY s.last_request_end_time DESC;
-- 🟦 MySQL
SHOW STATUS LIKE 'Threads_connected';
SELECT @@max_connections;
SELECT * FROM performance_schema.threads WHERE type = 'FOREGROUND';

65.2 πŸ’£ The N+1 problem

This one is silent in development, where the table has 20 rows, and fatal in production, where it has 200,000.

// ❌ N+1: one query for the list, then one MORE per row. 501 round trips.
var customers = await db.Customers.Where(c => c.Country == "Sri Lanka").ToListAsync();
foreach (var c in customers)
    c.Orders = await db.Orders.Where(o => o.CustomerId == c.CustomerId).ToListAsync();
// βœ… One query. The database was built for this.
var customers = await db.Customers
    .Where(c => c.Country == "Sri Lanka")
    .Include(c => c.Orders)
    .ToListAsync();

[!WARNING] πŸ’₯ 500 queries at 2 ms each is a full second of pure latency (waiting), and a second of a connection held. The equivalent join runs in 3 ms. Nothing about the SQL was slow β€” the shape of the calling code was.

[!TIP] πŸ’‘ How to catch it: log the query count per request and alert when it exceeds a threshold. Every ORM can do this β€” EF Core LogTo, Hibernate statistics, Django Debug Toolbar, ActiveRecord query logs. An endpoint that fires 300 queries is an N+1, always, and no plan tuning will save it.

[!WARNING] ⚠️ The opposite mistake exists too. Include on five collections at once produces a row explosion β€” the same customer row repeated 40 times because they have 5 orders and 8 addresses. Split it into two queries, or project to exactly the columns you need. The cure for N+1 is fewer round trips, not one enormous join.

65.3 πŸ” Parameters are not optional (and they are also faster)

Chapter 55 covered this as a security rule. It is also a performance rule.

// ❌ Every distinct value compiles a NEW plan and fills the plan cache with garbage
cmd.CommandText = $"SELECT * FROM customers WHERE country = '{country}'";

// βœ… One plan, reused for every value β€” and injection-proof
cmd.CommandText = "SELECT customer_id, full_name FROM customers WHERE country = @country";
cmd.Parameters.Add("@country", SqlDbType.NVarChar, 60).Value = country;

[!WARNING] ⚠️ Declare the parameter’s type and length. Letting the driver infer NVARCHAR(4000) from a 6-character string causes an implicit conversion against an NVARCHAR(60) column, and that can turn a seek into a scan β€” the exact failure from Chapter 23. This is one of the most common β€œfast in SSMS, slow from the app” causes there is.

-- πŸŸ₯ Confirm you are getting plan reuse, not plan-cache pollution
SELECT TOP 10
    cp.usecounts,
    cp.objtype,
    LEFT(st.text, 80) AS query_text
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
WHERE cp.cacheobjtype = 'Compiled Plan'
ORDER BY cp.usecounts DESC;

[!TIP] πŸ’‘ A cache full of objtype = 'Adhoc' entries with usecounts = 1 is the signature of unparameterized SQL. Every one of those cost a compilation. Prepared and Proc entries with high usecounts are what healthy looks like.

65.4 πŸ“¦ Round trips: batch, don’t loop

// ❌ 10,000 round trips
foreach (var item in items)
    await conn.ExecuteAsync("INSERT INTO order_items VALUES (@a,@b,@c)", item);
Rows Reach for
1–10 A single multi-row INSERT … VALUES (…),(…),(…) (Chapter 12)
10–1,000 πŸŸ₯ A table-valued parameter (Chapter 37) Β· 🟦 a multi-row insert built with parameters
1,000–1,000,000 πŸŸ₯ SqlBulkCopy Β· 🟦 LOAD DATA INFILE / the C API’s bulk mode
Over a million πŸŸ₯ BULK INSERT / bcp Β· 🟦 LOAD DATA INFILE (Chapter 12)
// πŸŸ₯ MSSQL: bulk transfer in batches. Choose trigger behavior deliberately.
using var bulk = new SqlBulkCopy(conn, SqlBulkCopyOptions.CheckConstraints, null)
{
    DestinationTableName = "dbo.order_items",
    BatchSize = 5000,
    BulkCopyTimeout = 600
};
await bulk.WriteToServerAsync(dataTable);

SqlBulkCopy does not check CHECK/foreign-key constraints or fire insert triggers by default. This example opts into CheckConstraints; add SqlBulkCopyOptions.FireTriggers if insert triggers are part of the intended write path. Do not enable a stock trigger as well as explicit stock maintenance. Select transaction/batch atomicity deliberately and supply column mappings when source and destination orders differ. See SqlBulkCopyOptions.

[!TIP] πŸ’‘ The same rule applies to reads. Fetching 500 rows by primary key in a loop is an N+1 in disguise. Send one query with WHERE product_id IN (…) β€” as a table-valued parameter πŸŸ₯ or a properly parameterized list 🟦 β€” and get them in one trip.

65.5 πŸͺ“ Big writes: batch inside the database too

A single DELETE of ten million rows takes one enormous lock, generates gigabytes of log, and blocks everything until it finishes or times out. Chop it up.

-- βœ… πŸŸ₯ MSSQL: delete in small, committed batches
-- (a log table to practise on)
CREATE TABLE dbo.audit_log (
    log_id    BIGINT IDENTITY(1,1) PRIMARY KEY,
    logged_at DATETIME2(0)  NOT NULL,
    message   NVARCHAR(200) NOT NULL
);
CREATE INDEX ix_audit_log_logged_at ON dbo.audit_log (logged_at);   -- see the warning below
INSERT INTO dbo.audit_log (logged_at, message) VALUES
('2024-03-01', N'old entry'), ('2025-01-15', N'old entry'), (SYSUTCDATETIME(), N'recent entry');
GO

DECLARE @deleted INT = 1, @total INT = 0;

WHILE @deleted > 0
BEGIN
    DELETE TOP (5000) FROM dbo.audit_log
    WHERE logged_at < DATEADD(DAY, -365, CAST(SYSUTCDATETIME() AS DATE));

    SET @deleted = @@ROWCOUNT;
    SET @total  += @deleted;
    -- optional: WAITFOR DELAY '00:00:00.100';   -- let other work breathe
END;

SELECT @total AS rows_deleted;
-- βœ… 🟦 MySQL: the same shape
CREATE TABLE audit_log (
    log_id    BIGINT AUTO_INCREMENT PRIMARY KEY,
    logged_at DATETIME     NOT NULL,
    message   VARCHAR(200) NOT NULL,
    INDEX ix_audit_log_logged_at (logged_at)
);
INSERT INTO audit_log (logged_at, message) VALUES
('2024-03-01', 'old entry'), ('2025-01-15', 'old entry'), (UTC_TIMESTAMP(), 'recent entry');

DELETE FROM audit_log
WHERE logged_at < DATE_SUB(UTC_DATE(), INTERVAL 365 DAY)
LIMIT 5000;
-- repeat while ROW_COUNT() > 0

[!TIP] πŸ’‘ Each batch is its own transaction, so each one releases its locks and its log space. The total work is the same; the blocking is a hundredth of what it was. This is the pattern behind every safe archival job, backfill, and bulk correction.

[!WARNING] ⚠️ Make sure the WHERE clause is indexed. A batched delete that scans the whole table to find each 5,000 rows is worse than the single delete β€” you now do the full scan a thousand times. Check the plan first.

65.6 ⏱️ Timeouts, retries, and failing gracefully

Setting Where What it protects
Connect timeout Connection string A dead or unreachable server
Command timeout Per command β€” not the connection string in ADO.NET One runaway query holding a connection
Lock timeout SET LOCK_TIMEOUT πŸŸ₯ / innodb_lock_wait_timeout 🟦 Blocking chains (Chapter 63)
Statement timeout max_execution_time 🟦 Runaway SELECTs, server-side

[!WARNING] ⚠️ CommandTimeout and ConnectTimeout are different things, and the default CommandTimeout of 30 seconds applies per command, not per request. A page that runs six queries can legally take three minutes before anything complains. Set both explicitly, and set them shorter than your HTTP timeout so the database is not still working on a request the user abandoned.

// βœ… Retry only what is genuinely transient β€” deadlocks, timeouts, failovers
static readonly int[] Transient = { 1205, 1222, -2, 4060, 40197, 40501, 49918 };

for (var attempt = 1; attempt <= 3; attempt++)
{
    try { return await ExecuteAsync(); }
    catch (SqlException ex) when (Transient.Contains(ex.Number) && attempt < 3)
    {
        await Task.Delay(TimeSpan.FromMilliseconds(100 * Math.Pow(2, attempt)
                                                   + Random.Shared.Next(0, 50)));  // growing wait + a little randomness (jitter)
    }
}
Error Engine Retry?
1205 deadlock victim πŸŸ₯ βœ… Yes β€” retry is the designed response (Chapter 45)
1222 lock request timeout πŸŸ₯ βœ… Yes, with backoff
-2 command timeout πŸŸ₯ ⚠️ Once, then investigate β€” usually a real problem
1213 deadlock 🟦 βœ… Yes
1205 lock wait timeout 🟦 βœ… Yes
2627 / 2601 unique violation πŸŸ₯ ❌ Never β€” retrying inserts a duplicate. This is a business outcome
547 constraint violation πŸŸ₯ ❌ Never β€” the data is wrong

[!TIP] πŸ’‘ Jitter (a little randomness in the wait) is not decoration. Without it, every client that lost the same deadlock retries at exactly the same moment and deadlocks again. Randomising the backoff is what breaks the synchronisation.

[!WARNING] ⚠️ A retry is only safe if the operation is idempotent. Retrying a payment after a timeout is how customers get charged twice β€” see 63.5.

65.7 🌊 Streaming, paging, and not fetching everything

// ❌ Loads 2 million rows into application memory, then throws most away
var all = await db.Orders.ToListAsync();
var recent = all.Where(o => o.OrderDate > cutoff).Take(50);

// βœ… The database filters, sorts, and pages. 50 rows cross the network.
var recent = await db.Orders
    .Where(o => o.OrderDate > cutoff)
    .OrderByDescending(o => o.OrderDate)
    .Take(50)
    .ToListAsync();

[!IMPORTANT] 🎯 Filter, sort, aggregate, and page in the database β€” always. It has the indexes, the statistics, and the memory. The application has none of those, and every row it does not need costs network traffic, memory clean-up, and waiting time.

[!TIP] πŸ’‘ For genuinely large result sets β€” an export, a report β€” stream them. SqlDataReader / a server-side cursor in MySQL yields rows as they arrive instead of buffering the whole set. And for deep paging, use keyset pagination, not OFFSET (Chapter 17) β€” OFFSET 900000 makes the server read and discard 900,000 rows on every page.

65.8 🧭 Where should the logic live?

Logic Put it in the database when… Put it in the application when…
Data integrity rules Always. Constraints do not have bad days (Chapter 9) Never rely on the app alone
Set operations over many rows Always β€” that is what SQL is for Never loop rows in the app to do a join
Business workflow, orchestration Rarely Usually β€” it is easier to test, version, and debug
Calls to other systems Never (Chapter 39) Always
Formatting and localisation Never Always β€” the database should return raw values
Authorization rules Enforce at the row level where the data model allows (Chapter 54) Decide the policy here

[!TIP] πŸ’‘ The honest test: if you moved this logic, what would break? Integrity rules moved into the app break the moment anyone connects with a different client β€” a script, a migration, an admin. Workflow logic moved into the database becomes untestable, unversioned, and invisible to your debugger. Put each where it can actually be enforced.

65.9 βœ… The application-layer checklist

  • ☐ Connection pooling is on, and the total pool across all services fits the server
  • ☐ pool_pre_ping / connection validation is enabled
  • ☐ Query count per request is logged, with an alert on N+1 explosions
  • ☐ Every query is parameterized, with explicit types and lengths
  • ☐ Plan cache is dominated by Prepared/Proc, not single-use Adhoc
  • ☐ Bulk work uses bulk APIs, not loops
  • ☐ Large writes are batched inside the database too
  • ☐ Connect, command, and lock timeouts are all set explicitly, and shorter than the HTTP timeout
  • ☐ Retries cover only temporary errors, with a growing and slightly random wait between tries
  • ☐ Retried operations are idempotent
  • ☐ Filtering, sorting, and paging happen in the database
  • ☐ Deep paging uses keyset, not OFFSET
  • ☐ Credentials come from a secret store, and the app user is not sa / root

65.10 πŸ§ͺ Try it yourself

  1. Write the N+1 version and the joined version of β€œcustomers with their orders”. Time both against 10,000 customers.
  2. Run the plan-cache query. Count how many single-use Adhoc plans your application has created, then fix one call site and watch the number drop.
  3. Insert 100,000 rows three ways β€” a loop, a table-valued parameter, and SqlBulkCopy. Record all three timings.
  4. Batch-delete a million rows and watch blocking in a second session with sys.dm_exec_requests (Chapter 43).
  5. Force a deadlock from two connections and implement the retry with backoff and jitter. Verify the retry actually succeeds.
  6. Set CommandTimeout = 1, run WAITFOR DELAY '00:00:05', and confirm which error your driver raises.

🧭 In practice β€” SQL from the application layer

How to use it. Use parameterised commands, a connection pool, and short transactions. Map result sets to objects in one place. Set sensible command timeouts. Expected result: the database is used efficiently from code, and failures surface as handled errors rather than as exhausted pools.

When to use it. In every application that talks to a database β€” which is where most real-world database problems are actually created.

Where to use it. The data-access layer. Scenario: a page lists 50 orders and then queries the customer for each one β€” the N+1 problem: 51 round trips where one join would do. It is invisible in development with 5 rows and is the most common cause of a slow page in production.

When not to use it. Do not open a connection per query and leave pooling disabled β€” establishing a connection is expensive, and a pool exists precisely to avoid it. Do not hold a transaction open while waiting for the user, an HTTP call, or a file. Do not build SQL by string concatenation, ever. And do not let an ORM’s lazy loading run inside a loop without knowing that it is doing so.

Best practices. Log the SQL your ORM generates during development β€” most N+1 problems are visible in one glance at a query log and invisible in the code. Always use parameters, always dispose connections (using/with), and set explicit timeouts so a stuck query fails rather than accumulating. The Repository and Unit of Work patterns from the Python and C# guides are the object-side counterpart to this chapter.


βœ… Checkpoint β€” after Chapter 65 Β· you can run it in production

[!IMPORTANT] The last part is the one that decides whether a working database stays working. Most of it is about habits rather than syntax.

πŸ—£οΈ Teach it back

What is it? Why does it matter? How does it work? Can I give an example? β€” for each of:

  • Least privilege (Ch 54)
  • SQL injection and parameterisation (Ch 55)
  • RPO and RTO, and why a backup is not a recovery plan (Ch 56)
  • UTC storage and time zones (Ch 61)
  • Migrations in source control (Ch 64)
  • The N+1 problem (Ch 65)
πŸ§ͺ Self-check questions
  1. What is the single rule that prevents SQL injection, and why is escaping not enough?
  2. Why is an untested backup not a backup?
  3. Why store timestamps in UTC rather than local time?
  4. A page lists 50 orders and issues 51 queries. What is this called and how do you find it?
  5. Why should you never edit a migration that has already been applied?
  6. Your application connects as sa. Name two concrete things that go wrong.
πŸ“ Sample answers
  1. Parameterise every value β€” pass input as a parameter, never concatenate it into the SQL string. Escaping is an incomplete defence: it depends on getting every character class, every encoding, and every context right, and attackers are better at finding the gap than defenders are at closing it. Parameterisation removes the category of bug, because the value is never parsed as code. Note that identifiers cannot be parameterised, so those need an allow-list.

  2. Because the thing you need is the restore, and you have never proved it works. Backups fail silently, get written to the failing disk, omit a filegroup, or turn out to be unreadable. Rehearse a restore onto different hardware, on a schedule, and time it β€” that time is your RTO.

  3. Because local time is ambiguous and non-monotonic. At the end of daylight saving, one local hour occurs twice, so two events can carry the same timestamp and no query can order them. UTC instants are always distinct and always comparable. Convert to local time only for display, and store the IANA zone name rather than a fixed offset.

  4. The N+1 problem β€” one query for the list, then one per row. You find it by logging the SQL your ORM actually generates during development; it is obvious in a query log and invisible in the code. The fix is a join or an eager-load, turning 51 round trips into one.

  5. Because other environments have already run it, so changing it makes them silently diverge from yours. Migrations are an ordered, immutable history. When something is wrong, you add a new migration that corrects it β€” which also leaves an honest record of what happened.

  6. The blast radius of any compromise is the whole server, and a bug can do unlimited damage β€” an accidental DROP or an injected statement is not stopped by anything. A least-privilege account that holds only SELECT, INSERT, and UPDATE on the tables it needs turns a catastrophe into an error message.

🎯 Give a simple example

Describe your deployment process for a schema change, from writing it to it being live β€” and say where a human reads the script before it touches production.


Part index Prerequisites Previous Next Full course