@vstlmkh/designing-databases 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,123 @@
1
+ -- PostgreSQL read-only snapshot pack.
2
+ -- Usage: psql "$DATABASE_URL" -X -f assets/pg_snapshot.sql > snapshot.txt
3
+ -- Safe on a replica. Every statement is read-only.
4
+
5
+ \set ON_ERROR_STOP off
6
+ \timing off
7
+ \pset pager off
8
+
9
+ SET default_transaction_read_only = on;
10
+ SET statement_timeout = '60s';
11
+ SET lock_timeout = '2s';
12
+
13
+ \echo '===== 1. VERSION AND KEY SETTINGS ====='
14
+ SELECT version();
15
+ SELECT name, setting, unit
16
+ FROM pg_settings
17
+ WHERE name IN ('shared_buffers','work_mem','maintenance_work_mem','effective_cache_size',
18
+ 'random_page_cost','seq_page_cost','max_connections','max_parallel_workers_per_gather',
19
+ 'default_statistics_target','autovacuum','autovacuum_vacuum_scale_factor',
20
+ 'autovacuum_analyze_scale_factor','synchronous_commit','wal_level')
21
+ ORDER BY name;
22
+
23
+ \echo '===== 2. DATABASE AND TABLE SIZES ====='
24
+ SELECT pg_size_pretty(pg_database_size(current_database())) AS database_size;
25
+
26
+ SELECT schemaname || '.' || relname AS table_name,
27
+ to_char(n_live_tup, 'FM999,999,999') AS live_rows,
28
+ pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
29
+ pg_size_pretty(pg_relation_size(relid)) AS heap_size,
30
+ pg_size_pretty(pg_indexes_size(relid)) AS index_size
31
+ FROM pg_stat_user_tables
32
+ ORDER BY pg_total_relation_size(relid) DESC
33
+ LIMIT 25;
34
+
35
+ \echo '===== 3. DEAD TUPLES / VACUUM HEALTH ====='
36
+ SELECT schemaname || '.' || relname AS table_name,
37
+ n_live_tup, n_dead_tup,
38
+ CASE WHEN n_live_tup > 0
39
+ THEN round(100.0 * n_dead_tup / n_live_tup, 1) END AS dead_pct,
40
+ last_autovacuum, last_autoanalyze
41
+ FROM pg_stat_user_tables
42
+ WHERE n_dead_tup > 1000
43
+ ORDER BY n_dead_tup DESC
44
+ LIMIT 20;
45
+
46
+ \echo '===== 4. INDEX INVENTORY (largest first) ====='
47
+ SELECT s.schemaname || '.' || s.relname AS table_name,
48
+ s.indexrelname AS index_name,
49
+ i.indisunique AS is_unique,
50
+ s.idx_scan AS scans,
51
+ pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
52
+ FROM pg_stat_user_indexes s
53
+ JOIN pg_index i USING (indexrelid)
54
+ ORDER BY pg_relation_size(s.indexrelid) DESC
55
+ LIMIT 30;
56
+
57
+ \echo '===== 5. NEVER-SCANNED NON-UNIQUE INDEXES (check replicas before dropping) ====='
58
+ SELECT s.schemaname || '.' || s.relname AS table_name,
59
+ s.indexrelname AS index_name,
60
+ pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
61
+ FROM pg_stat_user_indexes s
62
+ JOIN pg_index i USING (indexrelid)
63
+ WHERE i.indisunique IS FALSE AND s.idx_scan = 0
64
+ ORDER BY pg_relation_size(s.indexrelid) DESC
65
+ LIMIT 20;
66
+
67
+ \echo '===== 6. INVALID INDEXES (failed CONCURRENTLY builds) ====='
68
+ SELECT c.relname AS index_name
69
+ FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
70
+ WHERE NOT i.indisvalid;
71
+
72
+ \echo '===== 7. FOREIGN KEYS WITHOUT AN INDEX ON THE CHILD COLUMN ====='
73
+ SELECT conrelid::regclass AS child_table,
74
+ conname AS constraint_name,
75
+ (SELECT string_agg(attname, ', ' ORDER BY ord)
76
+ FROM unnest(conkey) WITH ORDINALITY AS u(attnum, ord)
77
+ JOIN pg_attribute a ON a.attrelid = conrelid AND a.attnum = u.attnum) AS child_columns
78
+ FROM pg_constraint c
79
+ WHERE contype = 'f'
80
+ -- no index whose LEFTMOST column is the first FK column (indkey is 0-based)
81
+ AND NOT EXISTS (
82
+ SELECT 1 FROM pg_index i
83
+ WHERE i.indrelid = c.conrelid
84
+ AND i.indisvalid
85
+ AND i.indkey[0] = c.conkey[1]
86
+ )
87
+ ORDER BY 1;
88
+
89
+ \echo '===== 8. LONG-RUNNING AND IDLE-IN-TRANSACTION SESSIONS ====='
90
+ SELECT pid, state, now() - xact_start AS xact_age, now() - query_start AS query_age,
91
+ wait_event_type, left(query, 100) AS query
92
+ FROM pg_stat_activity
93
+ WHERE state <> 'idle' AND pid <> pg_backend_pid()
94
+ ORDER BY xact_start NULLS LAST
95
+ LIMIT 20;
96
+
97
+ \echo '===== 9. BLOCKING CHAINS ====='
98
+ SELECT blocked.pid AS blocked_pid, left(blocked.query, 60) AS blocked_query,
99
+ blocking.pid AS blocking_pid, left(blocking.query, 60) AS blocking_query
100
+ FROM pg_stat_activity blocked
101
+ JOIN pg_stat_activity blocking ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
102
+ WHERE cardinality(pg_blocking_pids(blocked.pid)) > 0;
103
+
104
+ \echo '===== 10. TOP STATEMENTS BY TOTAL TIME (needs pg_stat_statements) ====='
105
+ SELECT round(total_exec_time::numeric, 1) AS total_ms,
106
+ calls,
107
+ round(mean_exec_time::numeric, 2) AS mean_ms,
108
+ rows,
109
+ left(regexp_replace(query, '\s+', ' ', 'g'), 120) AS query
110
+ FROM pg_stat_statements
111
+ ORDER BY total_exec_time DESC
112
+ LIMIT 20;
113
+
114
+ \echo '===== 11. CACHE HIT RATIO AND SEQ-SCAN-HEAVY TABLES ====='
115
+ SELECT round(100.0 * sum(blks_hit) / nullif(sum(blks_hit) + sum(blks_read), 0), 2) AS cache_hit_pct
116
+ FROM pg_stat_database WHERE datname = current_database();
117
+
118
+ SELECT schemaname || '.' || relname AS table_name, seq_scan, idx_scan,
119
+ seq_tup_read, n_live_tup
120
+ FROM pg_stat_user_tables
121
+ WHERE seq_scan > 0 AND n_live_tup > 100000
122
+ ORDER BY seq_tup_read DESC
123
+ LIMIT 15;
@@ -0,0 +1,76 @@
1
+ # Report template
2
+
3
+ Use when the deliverable is a written schema or performance review. Keep the
4
+ order: what was examined → what is wrong → what to do → what it costs. Every
5
+ claim carries its evidence; every recommendation carries its risk.
6
+
7
+ ---
8
+
9
+ # <Database / service> — <schema audit | performance review>
10
+
11
+ **Engine**: PostgreSQL 16.3 · **Source**: read-only replica `db-r2`, 2026-10-20
12
+ **Scope**: `orders`, `payments`, `customers` (the checkout path)
13
+ **Evidence**: `pg_snapshot.sql` output, `pg_stat_statements` top 20,
14
+ `EXPLAIN (ANALYZE, BUFFERS)` for the three slowest statements
15
+
16
+ ## Summary
17
+
18
+ Two sentences: the headline problem and the expected effect of fixing it.
19
+ Example: "Checkout reads scan `orders` end to end because the composite index
20
+ puts the range column first; p95 is 4.8 s. A reordered index plus an `ANALYZE`
21
+ on `orders` should bring it under 50 ms."
22
+
23
+ ## Findings
24
+
25
+ Ranked by impact, not by discovery order. One table row per finding.
26
+
27
+ | # | Severity | Object | Finding | Evidence |
28
+ |---|---|---|---|---|
29
+ | 1 | Critical | `orders` | Sequential scan over 5M rows per checkout read | plan node `Seq Scan on orders`, 182k rows returned, 4.8M removed by filter |
30
+ | 2 | High | `payments.order_id` | Foreign key with no index | `pg_snapshot` §7 |
31
+ | 3 | Medium | `idx_orders_customer` | Redundant: leftmost prefix of `idx_orders_customer_status` | `schema_audit.py` IDX002 |
32
+
33
+ For each finding worth more than a table row:
34
+
35
+ ### 1. `orders` is scanned sequentially on every checkout read
36
+
37
+ **What happens.** <mechanism, in engine terms — not "it is slow">
38
+ **Evidence.**
39
+ ```
40
+ -> Seq Scan on orders (cost=0.00..980.00 rows=95) (actual rows=182440 loops=1)
41
+ Filter: (date_trunc('day', created_at) >= '2026-01-01')
42
+ Rows Removed by Filter: 4817560
43
+ ```
44
+ **Why it is this way.** <the predicate is non-sargable / the index violates ESR / statistics are stale>
45
+ **Fix.**
46
+ ```sql
47
+ CREATE INDEX CONCURRENTLY idx_orders_tenant_created ON orders (tenant_id, created_at);
48
+ -- and rewrite the predicate as a half-open range:
49
+ WHERE created_at >= '2026-01-01' AND created_at < '2026-01-02'
50
+ ```
51
+ **Cost and risk.** ~4 min build on 52M rows, +1.8 GB disk, writes continue;
52
+ adds ~3% to insert latency on `orders`. Rollback: `DROP INDEX CONCURRENTLY …`.
53
+ **Verification.** Re-run the plan; expect `Index Scan`, `shared read` under 200
54
+ blocks, p95 under 50 ms.
55
+
56
+ ## Recommended sequence
57
+
58
+ Ordered so each step is independently shippable and reversible.
59
+
60
+ 1. `ANALYZE orders;` — free, may alone fix the plan shape. Verify before step 2.
61
+ 2. Add `idx_orders_tenant_created` concurrently.
62
+ 3. Deploy the predicate rewrite.
63
+ 4. After one week of telemetry, drop `idx_orders_customer` (confirm zero scans
64
+ on the primary **and** every replica first).
65
+
66
+ ## Not changed, and why
67
+
68
+ State what you deliberately left alone — a denormalization that is load-bearing,
69
+ an index that looks redundant but serves a replica report, a type that cannot be
70
+ widened without an expand/contract cycle. This section prevents the next reviewer
71
+ from "fixing" something on purpose.
72
+
73
+ ## Open questions
74
+
75
+ Facts you could not establish and who can answer them (row growth rate, whether
76
+ a replica serves reporting, retention policy, peak concurrency).
package/bin/cli.js ADDED
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+
8
+ const SKILL_NAME = 'designing-databases';
9
+ const PKG_ROOT = path.resolve(__dirname, '..');
10
+ const PAYLOAD = ['SKILL.md', 'references', 'scripts', 'assets'];
11
+
12
+ function usage() {
13
+ console.log(`designing-databases — install the Agent Skill into a skills directory
14
+
15
+ Usage:
16
+ npx @vstlmkh/designing-databases install [options]
17
+ npx @vstlmkh/designing-databases uninstall [options]
18
+ npx @vstlmkh/designing-databases where [options]
19
+
20
+ Options:
21
+ --agent <name> target agent: claude (default) or kimi
22
+ --user install into the agent's user skills directory (default)
23
+ --project install into the agent's project skills directory
24
+ --dir <path> install into <path>/${SKILL_NAME}
25
+ --force overwrite an existing installation
26
+ -h, --help show this help
27
+ `);
28
+ }
29
+
30
+ function parseArgs(argv) {
31
+ const opts = { command: null, agent: 'claude', scope: 'user', dir: null, force: false, help: false };
32
+ for (let i = 0; i < argv.length; i++) {
33
+ const a = argv[i];
34
+ if (a === '-h' || a === '--help') opts.help = true;
35
+ else if (a === '--agent') {
36
+ opts.agent = argv[++i];
37
+ if (!['claude', 'kimi'].includes(opts.agent)) throw new Error('--agent must be claude or kimi');
38
+ } else if (a === '--user') opts.scope = 'user';
39
+ else if (a === '--project') opts.scope = 'project';
40
+ else if (a === '--force') opts.force = true;
41
+ else if (a === '--dir') {
42
+ opts.dir = argv[++i];
43
+ if (!opts.dir) throw new Error('--dir requires a path');
44
+ } else if (a.startsWith('-')) throw new Error(`unknown option: ${a}`);
45
+ else if (!opts.command) opts.command = a;
46
+ else throw new Error(`unexpected argument: ${a}`);
47
+ }
48
+ return opts;
49
+ }
50
+
51
+ function skillsRoot(opts) {
52
+ if (opts.dir) return path.resolve(opts.dir);
53
+ if (opts.agent === 'kimi') {
54
+ if (opts.scope === 'project') return path.resolve(process.cwd(), '.kimi-code', 'skills');
55
+ const kimiHome = process.env.KIMI_CODE_HOME || path.join(os.homedir(), '.kimi-code');
56
+ return path.resolve(kimiHome, 'skills');
57
+ }
58
+ if (opts.scope === 'project') return path.resolve(process.cwd(), '.claude', 'skills');
59
+ return path.join(os.homedir(), '.claude', 'skills');
60
+ }
61
+
62
+ function copy(src, dest) {
63
+ const stat = fs.statSync(src);
64
+ if (stat.isDirectory()) {
65
+ fs.mkdirSync(dest, { recursive: true });
66
+ for (const entry of fs.readdirSync(src)) {
67
+ if (entry === '__pycache__' || entry.endsWith('.pyc')) continue;
68
+ copy(path.join(src, entry), path.join(dest, entry));
69
+ }
70
+ } else {
71
+ fs.copyFileSync(src, dest);
72
+ }
73
+ }
74
+
75
+ function install(opts) {
76
+ const target = path.join(skillsRoot(opts), SKILL_NAME);
77
+ if (fs.existsSync(target) && !opts.force) {
78
+ console.error(`${target} already exists. Re-run with --force to overwrite.`);
79
+ process.exit(1);
80
+ }
81
+ if (fs.existsSync(target)) fs.rmSync(target, { recursive: true, force: true });
82
+ fs.mkdirSync(target, { recursive: true });
83
+ for (const item of PAYLOAD) {
84
+ const src = path.join(PKG_ROOT, item);
85
+ if (fs.existsSync(src)) copy(src, path.join(target, item));
86
+ }
87
+ console.log(`Installed ${SKILL_NAME} to ${target}`);
88
+ console.log('Kimi Code reloads its skill catalog automatically; restart Claude Code if the skill does not appear.');
89
+ }
90
+
91
+ function uninstall(opts) {
92
+ const target = path.join(skillsRoot(opts), SKILL_NAME);
93
+ if (!fs.existsSync(target)) {
94
+ console.log(`Nothing to remove at ${target}`);
95
+ return;
96
+ }
97
+ fs.rmSync(target, { recursive: true, force: true });
98
+ console.log(`Removed ${target}`);
99
+ }
100
+
101
+ function main() {
102
+ let opts;
103
+ try {
104
+ opts = parseArgs(process.argv.slice(2));
105
+ } catch (err) {
106
+ console.error(String(err.message));
107
+ usage();
108
+ process.exit(2);
109
+ }
110
+ if (opts.help || !opts.command) return usage();
111
+
112
+ switch (opts.command) {
113
+ case 'install': return install(opts);
114
+ case 'uninstall':
115
+ case 'remove': return uninstall(opts);
116
+ case 'where':
117
+ console.log(path.join(skillsRoot(opts), SKILL_NAME));
118
+ return;
119
+ default:
120
+ console.error(`unknown command: ${opts.command}`);
121
+ usage();
122
+ process.exit(2);
123
+ }
124
+ }
125
+
126
+ main();
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@vstlmkh/designing-databases",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.3.0",
4
+ "description": "Agent Skill for Claude Code and Kimi Code: design, audit and tune PostgreSQL and MySQL/InnoDB schemas, indexes, EXPLAIN plans, locking, and zero-downtime migrations.",
5
+ "keywords": [
6
+ "agent-skill",
7
+ "claude",
8
+ "claude-code",
9
+ "kimi",
10
+ "kimi-code",
11
+ "skill",
12
+ "postgresql",
13
+ "mysql",
14
+ "innodb",
15
+ "database",
16
+ "schema-design",
17
+ "index",
18
+ "explain",
19
+ "query-tuning",
20
+ "migrations"
21
+ ],
22
+ "license": "MIT",
23
+ "author": "Vladislav Stelmakh (vstlmkh)",
24
+ "homepage": "https://github.com/vstlmkh/designing-databases#readme",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/vstlmkh/designing-databases.git"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/vstlmkh/designing-databases/issues"
31
+ },
32
+ "type": "commonjs",
33
+ "bin": {
34
+ "designing-databases": "bin/cli.js"
35
+ },
36
+ "files": [
37
+ "bin/",
38
+ "SKILL.md",
39
+ "references/",
40
+ "scripts/",
41
+ "!scripts/__pycache__/",
42
+ "!**/*.pyc",
43
+ "assets/",
44
+ "README.md",
45
+ "LICENSE.md"
46
+ ],
47
+ "engines": {
48
+ "node": ">=18"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }
@@ -0,0 +1,261 @@
1
+ # Engine internals, transactions and locking
2
+
3
+ Load for any question about transactions, isolation, deadlocks, lock waits,
4
+ bloat, or "why does this behave differently on MySQL".
5
+
6
+ ## Contents
7
+
8
+ - Why the engine matters
9
+ - The physical write path (ACID)
10
+ - MVCC: heap versions vs undo log
11
+ - Bloat, vacuum, and the idle-transaction hazard
12
+ - The five concurrency anomalies
13
+ - Isolation levels in practice
14
+ - Locking mechanics per engine
15
+ - Lost updates
16
+ - Write skew and SSI
17
+ - Deadlocks
18
+ - Queue patterns: SKIP LOCKED
19
+ - Connection pools and lock-holding
20
+
21
+ ## Why the engine matters
22
+
23
+ PostgreSQL and MySQL/InnoDB share SQL syntax and make opposite choices
24
+ underneath: heap vs clustered storage, in-heap row versions vs undo log,
25
+ snapshot isolation vs gap locking. Advice that ignores the engine is wrong for
26
+ one of them roughly half the time. Establish the engine first, every time.
27
+
28
+ ## The physical write path (ACID)
29
+
30
+ 1. **Atomicity via logging.** The engine never writes the data file first. It
31
+ modifies the page in the buffer pool (marking it dirty) and appends a log
32
+ record — the WAL (PostgreSQL) or redo log (InnoDB) — before acknowledging the
33
+ commit. Recovery replays the log forward and undoes partial transactions via
34
+ the undo log (InnoDB) or commit status bits in `pg_xact` (PostgreSQL).
35
+ 2. **Consistency via invariants.** `NOT NULL`, foreign keys, unique indexes and
36
+ `CHECK` are the only guarantees that survive concurrency bugs. PostgreSQL
37
+ deferred constraints move the check to `COMMIT`, which is what makes transient
38
+ violations inside a batch legal.
39
+ 3. **Isolation via snapshots.** Under MVCC a reader takes no shared locks; it
40
+ reads the row version matching its snapshot. Writers do not block readers;
41
+ readers do not block writers.
42
+ 4. **Durability via fsync.** A commit is durable only once the log record is
43
+ `fsync`'d to non-volatile storage. (PostgreSQL `synchronous_commit`,
44
+ InnoDB `innodb_flush_log_at_trx_commit` — both trade durability for throughput
45
+ when relaxed.)
46
+
47
+ ## MVCC: heap versions vs undo log
48
+
49
+ **PostgreSQL — in-heap versioning.** Every `UPDATE` is physically an `INSERT` of
50
+ a new tuple plus marking the old one expired. Both versions live in the table's
51
+ heap pages; each row header carries `xmin` (inserting transaction) and `xmax`
52
+ (deleting/replacing transaction). Dead tuples are reclaimed later by autovacuum.
53
+ Consequence: updates bloat the table *and every index on it*, and an index entry
54
+ exists per row version (HOT updates avoid this only when no indexed column
55
+ changed and the page has room).
56
+
57
+ **MySQL InnoDB — undo log segments.** An `UPDATE` modifies the row in place in
58
+ the clustered leaf page; the previous image goes to the undo log, and the row
59
+ keeps a 7-byte `roll_ptr` back to it. Secondary indexes point at the primary key,
60
+ so they are untouched unless the indexed column itself changed. Consequence:
61
+ updates are cheaper for secondary indexes, but readers of old snapshots must walk
62
+ undo chains.
63
+
64
+ ## Bloat, vacuum, and the idle-transaction hazard
65
+
66
+ PostgreSQL cannot remove any tuple that might still be visible to the oldest open
67
+ snapshot. One connection sitting `idle in transaction` therefore freezes cleanup
68
+ for the whole database: tables and indexes grow, plans degrade, disk fills.
69
+
70
+ ```sql
71
+ -- PostgreSQL: who is holding the horizon open
72
+ SELECT pid, now() - xact_start AS duration, state, wait_event_type, left(query, 80)
73
+ FROM pg_stat_activity
74
+ WHERE state <> 'idle'
75
+ ORDER BY duration DESC;
76
+
77
+ -- and the dead-tuple picture
78
+ SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
79
+ FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 20;
80
+ ```
81
+
82
+ ```sql
83
+ -- MySQL: look for "History list length" — >100,000 means purge is far behind
84
+ SHOW ENGINE INNODB STATUS\G
85
+ SELECT * FROM information_schema.innodb_trx ORDER BY trx_started LIMIT 10;
86
+ ```
87
+
88
+ Fixes: set `idle_in_transaction_session_timeout`, never hold a transaction open
89
+ across an HTTP call or a user think-time, tune autovacuum per hot table
90
+ (`autovacuum_vacuum_scale_factor` down to 0.01–0.05 on large churning tables),
91
+ and never let an ORM open a transaction at request start "just in case".
92
+
93
+ ## The five concurrency anomalies
94
+
95
+ 1. **Dirty read** — reading another transaction's uncommitted write.
96
+ 2. **Non-repeatable read** — the same row read twice returns different values.
97
+ 3. **Phantom read** — a range query re-run returns extra rows.
98
+ 4. **Lost update** — two transactions read a value, compute, and write back;
99
+ one write is silently overwritten.
100
+ 5. **Write skew** — two transactions read an overlapping set, each checks an
101
+ invariant, each modifies *different* rows, and together they break the
102
+ invariant (the "at least one doctor on call" case).
103
+
104
+ The ANSI levels only speak about the first three. Lost updates and write skew are
105
+ where production bugs actually live.
106
+
107
+ ## Isolation levels in practice
108
+
109
+ | Level | PostgreSQL | MySQL InnoDB | Prevents |
110
+ |---|---|---|---|
111
+ | Read Committed | statement-level snapshot; fresh view per query (**default**) | statement-level read view per query | dirty reads |
112
+ | Repeatable Read | transaction-level snapshot at the first non-DML statement; no gap locks | transaction-level snapshot at first read + gap/next-key locks on writes (**default**) | + non-repeatable and phantom reads |
113
+ | Serializable | Serializable Snapshot Isolation (SSI): SIREAD tracking, no read blocking, aborts on dependency cycles | strict 2PL: implicit shared locks on plain `SELECT` | + write skew |
114
+
115
+ Note the default differs: Read Committed in PostgreSQL, Repeatable Read in MySQL.
116
+ Code ported between them changes behaviour silently.
117
+
118
+ ## Locking mechanics per engine
119
+
120
+ **InnoDB** uses record, gap and next-key locks. A *record lock* locks an index
121
+ record; a *gap lock* locks the space between records; a *next-key lock* is the
122
+ union `(previous_key, current_key]`.
123
+
124
+ ```sql
125
+ -- InnoDB, REPEATABLE READ
126
+ SELECT * FROM inventory WHERE item_id BETWEEN 10 AND 20 FOR UPDATE;
127
+ -- Another session inserting item_id = 15 now WAITS until this commits.
128
+ ```
129
+
130
+ **PostgreSQL** has no gap locks. Under Repeatable Read the second transaction's
131
+ insert succeeds and simply is not visible to the first. But if the first tries to
132
+ update a row that another committed after its snapshot began:
133
+
134
+ ```
135
+ ERROR: could not serialize access due to concurrent update
136
+ ```
137
+
138
+ The application must catch this and retry. Same isolation name, completely
139
+ different failure mode — plan the retry logic for the engine you actually run.
140
+
141
+ Useful lock introspection:
142
+
143
+ ```sql
144
+ -- PostgreSQL: who blocks whom
145
+ SELECT blocked.pid AS blocked_pid, blocked.query AS blocked_query,
146
+ blocking.pid AS blocking_pid, blocking.query AS blocking_query
147
+ FROM pg_stat_activity blocked
148
+ JOIN pg_stat_activity blocking ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
149
+ WHERE cardinality(pg_blocking_pids(blocked.pid)) > 0;
150
+ ```
151
+
152
+ ```sql
153
+ -- MySQL 8
154
+ SELECT * FROM performance_schema.data_lock_waits;
155
+ SELECT * FROM sys.innodb_lock_waits;
156
+ ```
157
+
158
+ ## Lost updates
159
+
160
+ ```sql
161
+ -- Anti-pattern under Read Committed
162
+ SELECT stock FROM items WHERE id = 1; -- both sessions read 10
163
+ UPDATE items SET stock = 8 WHERE id = 1; -- computed in the application
164
+ -- the second write overwrites the first; inventory silently drifts
165
+ ```
166
+
167
+ Two correct patterns:
168
+
169
+ ```sql
170
+ -- 1. Atomic single statement (preferred: smallest lock footprint)
171
+ UPDATE items SET stock = stock - 2 WHERE id = 1 AND stock >= 2;
172
+ -- check affected rows: 0 means insufficient stock, not success
173
+
174
+ -- 2. Pessimistic lock, when cross-table validation must happen in between
175
+ BEGIN;
176
+ SELECT stock FROM items WHERE id = 1 FOR UPDATE;
177
+ -- business validation here (no network calls!)
178
+ UPDATE items SET stock = stock - 2 WHERE id = 1;
179
+ COMMIT;
180
+ ```
181
+
182
+ Optimistic locking (a `version` column, `UPDATE … WHERE version = :v`) is the
183
+ third option and the right one for long user-facing edit flows.
184
+
185
+ ## Write skew and SSI
186
+
187
+ ```sql
188
+ -- Both transactions see 2 doctors on call; both commit; zero remain.
189
+ BEGIN;
190
+ SELECT count(*) FROM shift WHERE on_call = true; -- 2
191
+ UPDATE shift SET on_call = false WHERE doctor_id = 'Alice';
192
+ COMMIT;
193
+ ```
194
+
195
+ - **PostgreSQL**: `SET TRANSACTION ISOLATION LEVEL SERIALIZABLE`. SSI tracks
196
+ read-write dependencies via SIREAD locks and aborts one transaction with
197
+ `could not serialize access due to read/write dependencies among transactions`.
198
+ - **MySQL**: elevate to `SERIALIZABLE` (which takes shared locks on plain
199
+ `SELECT`), or take explicit locks covering the predicate — which in practice
200
+ means locking the rows *and* the gaps.
201
+ - **Either engine**: materialize the invariant into a row you can lock (a
202
+ `on_call_count` row, a unique partial index, an `EXCLUDE` constraint).
203
+
204
+ **Never recommend `SERIALIZABLE` without a retry loop.** Serialization failures
205
+ are the mechanism, not an error: catch the SQLSTATE (`40001`, and `40P01` for
206
+ deadlocks), retry with exponential backoff and a cap, and make the transaction
207
+ body idempotent.
208
+
209
+ ## Deadlocks
210
+
211
+ Two transactions each hold what the other needs; the engine's wait-for graph
212
+ detects the cycle and kills a victim (`40P01` / `ERROR 1213`).
213
+
214
+ The fix is deterministic lock ordering — always acquire in the same order,
215
+ everywhere:
216
+
217
+ ```sql
218
+ BEGIN;
219
+ SELECT * FROM inventory WHERE item_id IN (14, 52) ORDER BY item_id FOR UPDATE;
220
+ UPDATE inventory SET stock = stock - 1 WHERE item_id = 14;
221
+ UPDATE inventory SET stock = stock - 1 WHERE item_id = 52;
222
+ COMMIT;
223
+ ```
224
+
225
+ Also: keep transactions short, touch tables in a fixed order across the codebase,
226
+ avoid upgrading a shared lock to exclusive mid-transaction, and read
227
+ `SHOW ENGINE INNODB STATUS` → "LATEST DETECTED DEADLOCK" / the PostgreSQL log
228
+ entry to see the real cycle rather than guessing.
229
+
230
+ ## Queue patterns: SKIP LOCKED
231
+
232
+ For worker queues, never poll with a plain `SELECT … FOR UPDATE` — workers
233
+ serialize behind each other.
234
+
235
+ ```sql
236
+ -- PostgreSQL / MySQL 8
237
+ BEGIN;
238
+ SELECT id, payload FROM task_queue
239
+ WHERE status = 'QUEUED'
240
+ ORDER BY created_at
241
+ LIMIT 10
242
+ FOR UPDATE SKIP LOCKED;
243
+ -- … process, then mark done in the same transaction
244
+ COMMIT;
245
+ ```
246
+
247
+ `NOWAIT` is the other variant: fail immediately rather than wait. Pair either
248
+ with a partial index on the queued states.
249
+
250
+ ## Connection pools and lock-holding
251
+
252
+ A transaction holding row locks while waiting on an external HTTP call converts
253
+ one slow dependency into total lock contention and pool exhaustion. Rules:
254
+
255
+ - No network calls inside a transaction. Ever.
256
+ - Keep transactions to the smallest set of statements that must be atomic.
257
+ - Size the pool below what the database can actually serve concurrently
258
+ (`max_connections` is not a target; use PgBouncer/ProxySQL for high counts).
259
+ - Set `statement_timeout`, `idle_in_transaction_session_timeout` and
260
+ `lock_timeout` at the role level so a forgotten transaction cannot wedge the
261
+ system.