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 theWHEREclause did not hold, zero rows change and you know immediately β noSELECTfirst, 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_atas 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. UseROWVERSIONπ₯ 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
ROWVERSIONcolumn marked[Timestamp]and throwsDbUpdateConcurrencyException; Hibernate/JPA uses@Version; Django usesselect_for_updateor 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] β οΈ
UPDLOCKwithoutHOLDLOCKdoes 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 aUNIQUEconstraint 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 KEYis doing the real work. Even if theWHERE NOT EXISTSloses 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 usesREADCOMMITTEDLOCKso it also works atREAD COMMITTEDwhenREAD_COMMITTED_SNAPSHOTis 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 noOUTPUTorRETURNING, which is why its version selects the rowsFOR UPDATE SKIP LOCKEDinside a transaction and then updates them.
[!WARNING] β οΈ Always store
claimed_utcand reset stale claims. A worker that dies mid-job leaves rows stuck inProcessingforever. 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 ONis 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 withTRY β¦ 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
- Reproduce the lost update in two connections, step by step, and confirm no error is raised at any point.
- Add a
ROWVERSIONcolumn and fix it. Prove the second writer now gets@@ROWCOUNT = 0. - Rewrite the same logic as a single guarded
UPDATEand explain why it needs neither a version column nor a lock hint. - Build a two-row
job_queueand pull from it in two sessions β first withoutREADPAST/SKIP LOCKED, then with. Time both. - Take
sp_getapplockin one session and try to take it in another. Confirm you get-1, not a hang. - 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 UPDATEin 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 >= 1is 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_nameand 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
checksumcolumn 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_nameon 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
DOWNscript.
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__AB6E61648F1FC932is 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 checksmasterfirst for anything starting withsp_, so you pay a lookup penalty on every call. (This guideβs examples useusp_, which is also fine β the harmful one issp_.)
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
SELECTonce there are more than two - Every table gets a meaningful alias β
c,o,p, nota,b,t1 ONconditions immediately under theirJOIN, 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] π‘
EXCEPTin 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+ supportsEXCEPT; on older versions useLEFT 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 NOCHECKcan enforce new writes while leaving old data unvalidated and the constraint untrusted; validate existing rows withWITH CHECK CHECK CONSTRAINTwhen 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
- Build the
schema_migrationstable and a two-script runner. Run it twice and prove the second run is a no-op. - Take a column rename and write it out as three separate expandβcontract deploys.
- Write a constraint test for every
CHECKin ShopDB. Break one deliberately and confirm the test fails. - Rewrite one of the Chapter 26 reporting queries and prove set equality with
EXCEPTin both directions. - 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 COLUMNis 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 = 100is 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_recycleexist 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,ActiveRecordquery 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.
Includeon 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 anNVARCHAR(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 withusecounts = 1is the signature of unparameterized SQL. Every one of those cost a compilation.PreparedandProcentries with highusecountsare 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
WHEREclause 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] β οΈ
CommandTimeoutandConnectTimeoutare different things, and the defaultCommandTimeoutof 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, notOFFSET(Chapter 17) βOFFSET 900000makes 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-useAdhoc - β 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
- Write the N+1 version and the joined version of βcustomers with their ordersβ. Time both against 10,000 customers.
- Run the plan-cache query. Count how many single-use
Adhocplans your application has created, then fix one call site and watch the number drop. - Insert 100,000 rows three ways β a loop, a table-valued parameter, and
SqlBulkCopy. Record all three timings. - Batch-delete a million rows and watch blocking in a second session with
sys.dm_exec_requests(Chapter 43). - Force a deadlock from two connections and implement the retry with backoff and jitter. Verify the retry actually succeeds.
- Set
CommandTimeout = 1, runWAITFOR 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
- What is the single rule that prevents SQL injection, and why is escaping not enough?
- Why is an untested backup not a backup?
- Why store timestamps in UTC rather than local time?
- A page lists 50 orders and issues 51 queries. What is this called and how do you find it?
- Why should you never edit a migration that has already been applied?
- Your application connects as
sa. Name two concrete things that go wrong.
π Sample answers
-
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.
-
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.
-
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.
-
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.
-
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.
-
The blast radius of any compromise is the whole server, and a bug can do unlimited damage β an accidental
DROPor an injected statement is not stopped by anything. A least-privilege account that holds onlySELECT,INSERT, andUPDATEon 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 |