Prompting guidesDatabases

Database terms for AI prompting

Contents
  1. How to prompt with these
  2. 1. Choosing a data model
  3. 2. Schema design and constraints
  4. 3. Indexes
  5. 4. Query plans and performance
  6. 5. Application access patterns
  7. 6. Transactions and isolation
  8. 7. Locking and concurrency control
  9. 8. Durability and storage engines
  10. 9. Replication and high availability
  11. 10. Distributed consistency models
  12. 11. Partitioning and sharding
  13. 12. Backups and recovery
  14. 13. Schema migrations
  15. 14. Change data capture and events
  16. 15. Operations and maintenance
  17. 16. Security and access control
  18. 17. Words to avoid and what to say instead
  19. Sources

Each term below is an established database name with the system or paper it comes from and a prompt line you can paste. Every section opens with the vague ask it replaces. The databases overview explains the ideas behind these terms with whiteboard diagrams.

How to prompt with these

Name the engine, the version and the access pattern, then name the mechanism you want. A model asked to “make the query faster” guesses. A model asked for “a composite B-tree index on (tenant_id, created_at) to serve this keyset-paginated query, checked with EXPLAIN (ANALYZE, BUFFERS)” builds the thing you mean, and you can check the result.

  1. State the engine and version. PostgreSQL 17 and MySQL 8.4 differ in defaults that change correctness. PostgreSQL defaults to Read Committed and MySQL InnoDB defaults to Repeatable Read, and the two Repeatable Reads behave differently.
  2. Give the access patterns with numbers. Write “10,000 orders per day, read by customer and by date, 95% reads” instead of “an orders table”. The model picks keys, indexes and partitioning from the reads.
  3. Ask for the plan, not a promise. Ask the model to show EXPLAIN output or say which index each query uses. A claim that a query is “optimized” means nothing without the plan.
  4. Name the isolation level and the retry. Any transaction that must stay correct under concurrency needs a stated isolation level and a retry loop for serialization failures.
  5. Make migrations reversible and online. Ask for expand and contract steps, lock_timeout on every DDL statement, and a rollback for each step.
  6. One concern per prompt. Schema first, then indexes, then the transaction logic, then operations. End each prompt with checks you can run in a minute.
  7. Ask for the failure case. “What happens if two requests run this at once?” and “What happens if the primary dies mid-write?” catch most of what a model gets wrong.

A template to copy:

Engine: PostgreSQL 17. Table sizes: <rows now, rows in a year>.
Access patterns (with rates):
- <query shape>: <calls per second>, <latency target>
- <write shape>: <writes per second>
Task: <schema change | index | query | transaction | migration>.
Use these mechanisms: <term>: <one-line expectation>; <term>: <expectation>.
Constraints: no table rewrite while serving traffic; lock_timeout 2s on DDL.
Show: the DDL, EXPLAIN (ANALYZE, BUFFERS) for each query, and the rollback.
Acceptance: <2-3 checks I can run>.
Don't change unrelated tables or queries.

1. Choosing a data model

Instead of “which database should I use?”, list the reads and writes and name the model that serves them. The AWS DynamoDB guide says it directly: “you shouldn’t start designing your schema” until you know the questions it will need to answer.

Term What it means Seen in Prompt line
Access pattern A specific read or write the application performs, with its filter, sort and rate DynamoDB design guide “Before any schema, list every access pattern as filter, sort, rate per second and latency target.”
Relational model Data as relations of tuples, queried by value rather than by stored order or access path Codd 1970 “Use a relational schema with declared keys and constraints; queries must not depend on row order.”
Document model Each record is a nested document read and written as a unit MongoDB “Store each order as one document with its line items embedded, since they are read and written together.”
Embedding vs referencing Embed child data read with the parent; reference children that grow without bound or live on their own MongoDB data modeling docs “Embed addresses in the customer document; reference orders by id, because a customer’s orders grow without limit.”
Key-value store Values looked up by a single key, with no query on the value Redis “Use Redis as a key-value cache keyed by session:{id}, with a TTL of 30 minutes.”
Wide-column store Rows grouped by a partition key and sorted by clustering columns, modeled one table per query Apache Cassandra “Design one Cassandra table per query: partition by sensor_id and day, cluster by ts DESC.”
Graph database Nodes and typed, directed relationships stored natively, so traversals need no joins Neo4j “Model users and follows as a property graph and write the friends-of-friends query as a two-hop traversal.”
Time-series table Append-mostly data partitioned by time TimescaleDB hypertables “Store readings in a hypertable partitioned on ts, and drop chunks older than 90 days.”
Inverted index A map from each token to the documents that contain it, used for full-text search Elasticsearch, Lucene “Index product names in an inverted index with lowercase and stemming analyzers; rank with BM25.”
Vector index An approximate nearest-neighbour index over embeddings pgvector “Add an HNSW index on embedding with cosine distance; accept approximate results.”
Columnar storage Each column stored and compressed separately, so a query reads only the columns it uses ClickHouse “Put the event analytics in a columnar store; the dashboards aggregate 3 columns of 40.”
OLTP vs OLAP Many small transactional reads and writes versus large scans and aggregations Common usage “Keep OLTP in PostgreSQL and copy events to a columnar OLAP store for reporting; don’t run reports on the primary.”
Single-table design Storing several entity types in one DynamoDB table with composite keys, shaped by access patterns DynamoDB design guide “Use single-table design: PK CUSTOMER#{id}, SK ORDER#{date}, so one Query returns a customer and their recent orders.”

2. Schema design and constraints

Instead of “design a schema for this”, ask for keys, constraints and a normal form, and say where you accept duplication. William Kent’s summary of the normal forms is that every non-key field gives a fact about “the key, the whole key, and nothing but the key.”

Term What it means Seen in Prompt line
Primary key The column set that uniquely identifies a row; unique and not null, one per table PostgreSQL “Every table gets a primary key; no table without one.”
Surrogate key A system-generated key with no business meaning, such as an identity column Common usage “Use bigint GENERATED ALWAYS AS IDENTITY surrogate keys, and keep a separate UNIQUE constraint on the natural key.”
Natural key A key built from real-world attributes, such as an ISO country code Common usage “Use the natural key iso_code char(2) for countries, because it never changes.”
Foreign key A column whose values must match a key in another table Codd 1970, PostgreSQL “Declare foreign keys with ON DELETE RESTRICT, and index every referencing column.”
Index on the foreign key PostgreSQL doesn’t index the referencing column, so parent deletes scan the child PostgreSQL constraints docs “Add an index on every foreign key column; parent deletes must not seq-scan the child table.”
First normal form Each field holds one value; no repeating groups Kent 1983 “Keep the schema in 1NF: no comma-separated lists in a column; use a join table.”
Second normal form No non-key field depends on only part of a composite key Kent 1983 “Check 2NF on tables with composite keys; move partial-key facts to their own table.”
Third normal form No non-key field depends on another non-key field Kent 1983 “Normalize to 3NF; the customer’s address lives only in customers.”
Boyce-Codd normal form For every non-trivial dependency X to Y, X is a superkey Boyce and Codd 1974 “Check BCNF on the scheduling tables and list any dependency that breaks it.”
Denormalization Duplicating data on purpose to speed up reads, accepting update cost Kent 1983 “Denormalize order_total onto orders, keep it correct with a trigger, and write down why.”
Update anomaly A fact stored in several rows can be changed in one and missed in another Kent 1983 “Point out any column where the same fact is stored in more than one row.”
NOT NULL constraint The column can’t hold null; PostgreSQL’s docs say most columns should have it PostgreSQL “Mark every column NOT NULL unless null has a defined meaning; list the nullable ones and that meaning.”
CHECK constraint A per-row condition; it passes when the expression is true or null PostgreSQL “Add CHECK (quantity > 0) and CHECK (ends_at > starts_at); remember a null passes a CHECK.”
UNIQUE NULLS NOT DISTINCT By default nulls count as distinct in a unique constraint; this option treats them as equal PostgreSQL “Use UNIQUE NULLS NOT DISTINCT (tenant_id, email) so two null emails in one tenant conflict.”
Exclusion constraint No two rows may overlap on a given operator, such as a time range PostgreSQL “Prevent double bookings with an exclusion constraint on (room_id WITH =, during WITH &&).”
Generated column A column computed from other columns in the same row; virtual is the default since PostgreSQL 18 PostgreSQL, MySQL “Make search_name a STORED generated column of lower(name) so it can be indexed.”
UUIDv7 A UUID whose first 48 bits are a Unix millisecond timestamp, so new keys sort by time RFC 9562, PostgreSQL 18 uuidv7() “Use UUIDv7 primary keys, not random UUIDv4; RFC 9562 notes v4 has poor index locality.”
Soft delete Marking rows deleted with a flag or timestamp instead of removing them Common usage “Use soft delete with deleted_at, and a partial unique index on email WHERE deleted_at IS NULL.”

3. Indexes

Instead of “add indexes so it’s fast”, name the index type, the column order and the query it serves. The PostgreSQL docs list six index types, and B-tree is the default.

Term What it means Seen in Prompt line
B-tree index The default index; serves equality, ranges, sorting and left-anchored LIKE PostgreSQL “Create a B-tree index on orders (customer_id, created_at) for the order history query.”
Hash index Stores a 32-bit hash of the key; equality only PostgreSQL “Don’t use a hash index here; we also need range queries.”
GIN index An inverted index for values with many parts: arrays, jsonb, full-text PostgreSQL “Add a GIN index on attributes jsonb for @> containment queries.”
GiST index A framework index for geometry, ranges and nearest-neighbour ordering PostgreSQL “Use a GiST index on location and order by <-> for the 10 nearest stores.”
BRIN index Stores min and max per block range; tiny, and good when values follow physical order PostgreSQL “Use a BRIN index on created_at in this append-only log table instead of a B-tree.”
Composite index One index over several columns, ordered PostgreSQL, Winand “Order the composite index columns as equality columns first, then the range column.”
Leftmost prefix A B-tree on (a, b) serves queries on a, or a and b, but usually not b alone Use the Index, Luke “Check that every query’s filter uses a leftmost prefix of an existing index.”
Covering index An index that holds every column a query needs, so the table isn’t read PostgreSQL INCLUDE “Add INCLUDE (status, total) so the dashboard query becomes an index-only scan.”
Index-only scan A scan that answers from the index alone, skipping heap pages the visibility map marks all-visible PostgreSQL “Confirm an Index Only Scan with low Heap Fetches in EXPLAIN ANALYZE.”
Partial index An index over only the rows that match a WHERE predicate PostgreSQL “Create a partial index ON jobs (run_at) WHERE status = 'pending'; done jobs are 99% of rows.”
Expression index An index on a computed expression, such as lower(email) PostgreSQL “Index lower(email) and write the lookup as WHERE lower(email) = lower($1).”
Clustered index The index that stores the table rows; in InnoDB this is the primary key MySQL InnoDB “In InnoDB, keep the primary key short, because every secondary index stores a copy of it.”
Unique index An index that enforces uniqueness; constraints create one PostgreSQL “Back the idempotency key with a unique index so duplicate inserts fail.”
Selectivity The fraction of rows a predicate matches; low fractions make an index worthwhile Common usage “Skip an index on is_active; it matches 90% of rows.”
Write amplification of indexes Every index adds work to each insert and update PostgreSQL index docs “List every index on the table and the queries that use each; drop any that serve none.”

4. Query plans and performance

Instead of “why is this query slow?”, ask for the plan with real timings and compare estimated rows with actual rows. The PostgreSQL docs call that comparison the main check on the planner.

Term What it means Seen in Prompt line
EXPLAIN Shows the planner’s chosen plan with estimated costs and rows PostgreSQL “Show EXPLAIN for each new query before writing the code that calls it.”
EXPLAIN ANALYZE Runs the query and shows actual times and rows per node PostgreSQL “Use EXPLAIN (ANALYZE, BUFFERS), wrapping any write in BEGIN and ROLLBACK, because ANALYZE executes it.”
Estimated vs actual rows The planner’s guess per node against what the run produced PostgreSQL “Flag every plan node where actual rows differ from estimated rows by more than 10x.”
Sequential scan Reads every page of the table PostgreSQL “A Seq Scan on a table over 100,000 rows in a request path is a bug; explain or fix each one.”
Index scan Walks the index and fetches matching rows from the table PostgreSQL “This lookup should be an Index Scan on users_email_key; show it.”
Bitmap heap scan Builds a bitmap of matching row locations from an index, then reads those pages in order PostgreSQL “Explain why the planner chose a Bitmap Heap Scan and whether a better index exists.”
Nested loop join Runs the inner side once per outer row PostgreSQL “A nested loop with 50,000 loops on the inner side means a missing index; find it.”
Hash join Builds an in-memory hash table from one input and probes it with the other PostgreSQL “For the nightly report, a hash join of the two big tables is expected; check it fits in work_mem.”
Merge join Joins two inputs already sorted on the join key PostgreSQL “Note when a merge join needs an explicit Sort node.”
Planner statistics Per-column samples such as most common values and histograms, gathered by ANALYZE PostgreSQL “Run ANALYZE after the bulk load, then re-check the plan.”
Statistics target How many values ANALYZE samples per column; default 100 PostgreSQL “Raise the statistics target on tenant_id to 1000; its distribution is very skewed.”
Extended statistics Statistics on column combinations, for correlated columns PostgreSQL CREATE STATISTICS “Create dependencies statistics on (city, zip); the planner assumes they are independent.”
random_page_cost The planner’s cost for a non-sequential page read; default 4.0 against 1.0 for sequential PostgreSQL “Don’t change random_page_cost globally to fix one query; show the plan with and without.”
Sargable predicate A filter written so an index can be used; a function on the indexed column prevents it Use the Index, Luke “Rewrite WHERE date(created_at) = $1 as a range: created_at >= $1 AND created_at < $1 + 1 day.”
pg_stat_statements An extension that records normalized query text with call counts and total time PostgreSQL “Rank queries from pg_stat_statements by total_exec_time and fix the top 5 first.”
Slow query log MySQL’s log of statements over long_query_time, which defaults to 10 seconds MySQL “Turn on the slow query log with long_query_time = 0.2 in staging and summarize it with mysqldumpslow.”

5. Application access patterns

Instead of “the ORM code is slow”, name the pattern. Most slow application code issues too many queries or holds too many connections.

Term What it means Seen in Prompt line
N+1 query problem Loading a list, then one more query per item to load a relation Rails, Django docs “Remove the N+1 on the orders page: load authors with includes(:author), 2 queries total.”
Eager loading Fetching related rows up front with a join or one extra query Rails includes, Django select_related “Use select_related for the foreign key and prefetch_related for the many-to-many.”
Keyset pagination Paging with WHERE (sort_key, id) < (last values) instead of OFFSET Use the Index, Luke “Replace OFFSET paging with keyset pagination on (created_at, id), backed by a matching index.”
OFFSET pagination Skipping N rows; the database still reads and discards them Use the Index, Luke “Keep OFFSET only for the admin page, which never goes past page 5.”
Batching Grouping many writes into one statement or transaction Common usage “Insert the import in batches of 1,000 rows per statement, one transaction per batch.”
Upsert Insert, or update if the key exists, in one statement PostgreSQL ON CONFLICT “Write the counter as INSERT ... ON CONFLICT (key) DO UPDATE SET n = counters.n + 1.”
Connection pool A fixed set of open connections shared by many requests PgBouncer, app pools “Put PgBouncer in front of PostgreSQL; the app has 400 workers and the server allows 100 connections.”
Pool mode When a pooled server connection is released: per session, transaction or statement PgBouncer “Use PgBouncer transaction pooling, and remove session state: no SET, LISTEN or session advisory locks.”
max_connections The server’s connection limit, typically 100 in PostgreSQL PostgreSQL “Size the app pools so their sum stays under max_connections minus 10 for admin access.”
Parameterized query SQL sent with placeholders and values bound separately OWASP SQL injection cheat sheet “Use bound parameters for every value; never build SQL by string concatenation.”
Allow-list for identifiers Mapping user input to fixed column names or sort directions, because placeholders can’t bind identifiers OWASP “Map the sort parameter to an allow-list of column names; reject anything else.”
Prepared statement A statement parsed once and executed many times with new parameters PostgreSQL, PgBouncer “Use protocol-level prepared statements; with PgBouncer, set max_prepared_statements.”

6. Transactions and isolation

Instead of “make it safe when two users do this at once”, name the isolation level, the anomaly you are preventing and the retry. The PostgreSQL docs define the levels by the phenomena each one allows.

Term What it means Seen in Prompt line
Transaction A group of statements that commit or roll back as one SQL standard “Wrap the transfer in one transaction: debit, credit and ledger insert commit together or not at all.”
ACID Atomicity, consistency, isolation and durability PostgreSQL glossary “Say which ACID property each part of this design relies on.”
Atomicity All of a transaction’s changes happen or none do, including across a crash PostgreSQL glossary “If the process dies between the two inserts, neither row may exist.”
Isolation level How much a transaction can see of concurrent transactions SQL standard, PostgreSQL “Run the booking transaction at SERIALIZABLE and say why Read Committed isn’t enough.”
Read Committed Each statement sees data committed before it began; PostgreSQL’s default PostgreSQL “Assume Read Committed and show what a concurrent update can do between our SELECT and UPDATE.”
Repeatable Read In PostgreSQL, snapshot isolation: the transaction sees one snapshot throughout PostgreSQL “Use REPEATABLE READ for the report so all its queries see one snapshot.”
Serializable Results match some one-at-a-time order of the transactions PostgreSQL SSI “Use SERIALIZABLE and retry on SQLSTATE 40001 up to 5 times with jittered backoff.”
Snapshot isolation Each transaction reads a consistent snapshot; the first committer wins on a write-write conflict Berenson et al. 1995 “Explain which anomalies snapshot isolation still allows in this flow.”
Serializable snapshot isolation Snapshot isolation plus detection of dangerous read-write dependency patterns, aborting one transaction Ports and Grittner 2012 “Rely on PostgreSQL’s SSI rather than explicit locks for the on-call rule.”
Dirty read Reading another transaction’s uncommitted write PostgreSQL “Confirm no code path depends on reading uncommitted data.”
Non-repeatable read Re-reading a row shows a change another transaction committed meanwhile PostgreSQL “This function reads the balance twice; make it read once or use REPEATABLE READ.”
Phantom read Re-running a query returns a different set of rows PostgreSQL “The capacity check counts rows; protect it against phantoms.”
Lost update Two read-modify-write cycles interleave and one write overwrites the other Berenson et al. 1995 “Fix the lost update on stock: use UPDATE ... SET stock = stock - 1 WHERE stock > 0.”
Read skew A transaction sees part of another transaction’s changes Berenson et al. 1995 “Show how read skew could make the totals page disagree with itself.”
Write skew Two transactions read overlapping data, write different rows, and together break a rule Berenson et al. 1995, Jepsen “Two doctors can both go off call; prevent this write skew with SERIALIZABLE or by locking the rows read.”
Serialization failure The error a database raises to abort a transaction that would break isolation; SQLSTATE 40001 PostgreSQL “Catch 40001 and 40P01 and retry the whole transaction, including the reads that chose the values.”
Idempotency key A client-chosen unique key that makes a retried request return the first result Stripe API “Accept an Idempotency-Key header, store it with a unique index and the response, and replay the response on retry.”

7. Locking and concurrency control

Instead of “add a lock so they don’t collide”, name the lock, its scope and the timeout. PostgreSQL’s MVCC means “reading never blocks writing and writing never blocks reading”, so locks matter only between writers and around DDL.

Term What it means Seen in Prompt line
MVCC Multi-version concurrency control: updates write new row versions, and each reader sees a snapshot PostgreSQL “Explain which row version each of the two sessions sees in this sequence.”
Row lock A lock on specific rows taken by UPDATE, DELETE or SELECT FOR UPDATE PostgreSQL “Lock the account rows with SELECT … FOR UPDATE, always in ascending id order.”
SELECT FOR UPDATE Reads rows and locks them against concurrent writes until commit PostgreSQL, MySQL “Use SELECT … FOR UPDATE on the seat row before marking it sold.”
SKIP LOCKED Skips rows another transaction has locked; meant for queue tables PostgreSQL “Workers claim jobs with FOR UPDATE SKIP LOCKED LIMIT 10.”
NOWAIT Fails at once instead of waiting for a row lock PostgreSQL “Use NOWAIT on the admin edit lock and show ‘someone else is editing’ on failure.”
Gap lock / next-key lock InnoDB’s lock on the range between index records, which blocks inserts into it MySQL InnoDB “In InnoDB at REPEATABLE READ, explain which gap locks this range UPDATE takes.”
Advisory lock An application-defined lock the database tracks but doesn’t tie to any row PostgreSQL “Take pg_advisory_xact_lock(hashtext(tenant_id)) so one tenant’s billing run executes at a time; it releases at commit.”
Optimistic concurrency control Read a version number, then update only if it hasn’t changed, and check the row count Common usage “Add a version column; update with WHERE id = $1 AND version = $2 and return 409 if 0 rows changed.”
Pessimistic locking Lock first, then read and modify Common usage “Use pessimistic locking only on the inventory row; everything else is optimistic.”
Deadlock Two transactions each wait for a lock the other holds; the database aborts one PostgreSQL “Prevent deadlocks by locking rows in a consistent order, and retry on 40P01.”
deadlock_timeout How long PostgreSQL waits on a lock before running the deadlock check; default 1 second PostgreSQL “Leave deadlock_timeout at 1s; fix the lock order instead.”
lock_timeout Aborts a statement that waits longer than this for any lock; default off PostgreSQL “Set lock_timeout = '2s' for the migration session.”
statement_timeout Aborts any statement that runs longer than this; default off PostgreSQL “Set statement_timeout = '5s' on the web role, not in postgresql.conf.”
idle_in_transaction_session_timeout Ends sessions that sit idle inside an open transaction; default off PostgreSQL “Set idle_in_transaction_session_timeout = '60s'; idle transactions hold locks and block cleanup.”
Two-phase commit PREPARE TRANSACTION, then COMMIT PREPARED from any session; off by default in PostgreSQL PostgreSQL “Don’t use two-phase commit; use the outbox pattern for the cross-service write.”

8. Durability and storage engines

Instead of “make sure we don’t lose data”, say what a commit must have done before it returns, and name the storage engine’s trade-offs.

Term What it means Seen in Prompt line
Write-ahead log Changes are logged and flushed before data files change, so recovery can replay them PostgreSQL WAL “Explain what is on disk when COMMIT returns, in terms of the WAL.”
fsync Forcing written data from OS buffers to stable storage PostgreSQL “Never set fsync = off; the docs warn it can cause arbitrary corruption.”
synchronous_commit Whether COMMIT waits for the WAL flush; off risks losing recent commits but not corrupting data PostgreSQL “Use SET LOCAL synchronous_commit = off only for the analytics event insert.”
Checkpoint The point where dirty pages are written to data files so older WAL isn’t needed for recovery PostgreSQL “Keep checkpoint_timeout at 5min unless checkpoints show up in latency; show the evidence.”
Full-page writes Writing the whole page to WAL on its first change after a checkpoint, to recover torn pages PostgreSQL “Keep full_page_writes on.”
Redo log InnoDB’s append-only log of changes, replayed from the last checkpoint after a crash MySQL InnoDB “Size innodb_redo_log_capacity from the measured write rate.”
Doublewrite buffer InnoDB writes pages to a separate area first, so a torn page can be restored MySQL InnoDB “Keep the doublewrite buffer on.”
innodb_flush_log_at_trx_commit Whether InnoDB flushes the redo log at every commit; 1, the default, is the durable setting MySQL InnoDB “Keep innodb_flush_log_at_trx_commit = 1 and sync_binlog = 1 on the primary.”
B-tree storage engine Rows stored in pages of a balanced tree, updated in place InnoDB, PostgreSQL indexes “We have heavy random updates; explain the page-write cost in a B-tree engine.”
LSM-tree Writes buffered in memory and flushed as sorted immutable files that are merged later O’Neil et al. 1996, RocksDB “For 50,000 inserts per second, compare an LSM engine against InnoDB on write cost.”
Memtable The in-memory sorted buffer of an LSM engine RocksDB, Cassandra “Explain when the memtable flushes and what the WAL protects until then.”
SSTable A sorted, immutable file written by an LSM flush or compaction RocksDB, Cassandra “Report how many SSTables a point read touches in this table.”
Compaction Merging SSTables to drop overwritten and deleted data RocksDB, Cassandra “Use leveled compaction for this read-heavy table and universal for the write-heavy log.”
Write, read and space amplification Bytes written per byte stored, reads per query, and disk size per data size RocksDB tuning guide “State the write, read and space amplification you expect from each compaction choice.”
Bloom filter A per-file filter that says a key is definitely absent or may be present RocksDB, Cassandra “Enable bloom filters at about 10 bits per key, roughly 1% false positives.”
Tombstone A marker for a deleted key in an LSM engine, removed only by compaction Cassandra, RocksDB “Avoid delete-heavy queue patterns in Cassandra; tombstones slow reads until compaction.”

9. Replication and high availability

Instead of “make it highly available”, name the replication type, sync or async, and what the application does about lag. PostgreSQL streaming replication is asynchronous by default.

Term What it means Seen in Prompt line
Primary and replica One node takes writes; replicas apply its changes and can serve reads PostgreSQL, MySQL “Send writes to the primary and read-only report queries to a replica.”
Streaming replication Physical replication that ships WAL to standbys as it is generated PostgreSQL “Set up one streaming replica and monitor lag from pg_stat_replication.”
Logical replication Replicating row changes through publications and subscriptions; works across major versions PostgreSQL “Use logical replication to upgrade from 15 to 17 with a short cutover.”
Asynchronous replication The primary commits without waiting for replicas; a failover can lose recent commits PostgreSQL “We accept async replication with up to 1s of loss at failover; write that in the runbook.”
Synchronous replication Commit waits for one or more standbys; adds at least one network round trip PostgreSQL “Use synchronous_standby_names = 'ANY 1 (s1, s2)' so commits survive one node loss.”
Replication lag How far a replica is behind the primary PostgreSQL “Alert when replay lag exceeds 30s, and stop routing reads to that replica.”
Read-your-writes A client always sees its own earlier writes Jepsen “After a user writes, route their reads to the primary for 5 seconds.”
Hot standby A replica that serves read-only queries while it replays WAL PostgreSQL “Explain which long replica queries get cancelled once replay waits past max_standby_streaming_delay, 30s by default.”
Replication slot Makes the primary keep WAL until a consumer has received it, even while disconnected PostgreSQL “Set max_slot_wal_keep_size so an abandoned slot can’t fill the disk.”
Binary log and GTID MySQL’s change log for replication; GTIDs identify each transaction across servers MySQL “Use GTID-based replication with SOURCE_AUTO_POSITION = 1.”
Failover Promoting a replica to primary when the primary fails PostgreSQL pg_promote “Write the failover runbook: fence the old primary, promote, repoint the app.”
Split brain Two nodes both accept writes as primary after a partition Common usage “Explain how the failover tool prevents split brain, and what fences the old primary.”
Quorum A majority of nodes; Raft commits once a majority has an entry Raft paper “Run 3 nodes so the cluster survives 1 failure; 5 nodes survive 2.”
Consensus Agreement on one ordered log across nodes despite failures Raft paper “Use a Raft-based store for the leader lock, not a timestamp in a table.”
RPO and RTO Recovery point objective is the data loss you accept; recovery time objective is the downtime you accept AWS disaster recovery whitepaper “Design for RPO 1 minute and RTO 15 minutes, and say which part delivers each.”

10. Distributed consistency models

Instead of “is this consistent?”, name the model. Jepsen’s map of consistency models is the reference most engineers use, and its definitions are precise.

Term What it means Seen in Prompt line
Linearizability Every operation appears to happen at one instant, in real-time order, on one object Jepsen “The lock service must be linearizable; a read after a write returns that write.”
Sequential consistency Operations appear in one total order that respects each process’s order Jepsen “Explain whether sequential consistency is enough for this counter.”
Serializability Transactions appear to run in some one-at-a-time order, with no real-time constraint Jepsen “Serializability alone allows a stale order; say if that matters here.”
Strict serializability Serializable and consistent with real-time order Jepsen, Spanner “We need strict serializability for balances across regions.”
Causal consistency Causally related operations appear in the same order everywhere Jepsen “Comments must never appear before the post they reply to; causal consistency is enough.”
Monotonic reads A client’s reads never go backwards in time Jepsen “Pin each session to one replica so reads stay monotonic.”
Eventual consistency If writes stop, all replicas eventually return the last value Vogels 2008 “The view counter may be eventually consistent; the inventory count may not.”
CAP theorem During a partition, a system can’t be both linearizable and available on every node Gilbert and Lynch 2002 “During a partition, choose: reject writes or accept them and reconcile. Say which and why.”
PACELC With a partition, trade availability against consistency; else, trade latency against consistency Abadi 2012 “Classify this database under PACELC and say what that costs us in normal operation.”
Tunable consistency Choosing per request how many replicas must answer Cassandra “Use LOCAL_QUORUM for reads and writes so W + R > RF within the region.”
Last-write-wins Conflicting writes resolved by timestamp, discarding the older Cassandra “We can’t accept last-write-wins on cart contents; merge them instead.”

11. Partitioning and sharding

Instead of “make it scale”, say what the partition key is, how rows map to partitions, and what happens to a hot key. The PostgreSQL docs suggest partitioning when a table grows larger than memory, and warn “never just assume that more partitions are better than fewer.”

Term What it means Seen in Prompt line
Partitioning Splitting one table into child tables on one server PostgreSQL “Partition events by month so old months can be detached instead of deleted.”
Range partitioning Each partition holds a key range; lower bound inclusive, upper exclusive PostgreSQL “Range-partition on created_at, one partition per month, created 3 months ahead.”
List partitioning Each partition holds listed key values PostgreSQL “List-partition orders by region.”
Hash partitioning Rows assigned by hash modulus PostgreSQL “Hash-partition sessions into 16 partitions on user_id.”
Partition pruning The planner skips partitions the query can’t touch PostgreSQL “Show that this query prunes to one partition in EXPLAIN.”
Sharding Splitting data across separate servers by a shard key Common usage “Shard by tenant_id; every request must carry it and touch one shard.”
Shard key The column that decides where a row lives Common usage “Choose the shard key that keeps each request on one shard and spreads load evenly.”
Consistent hashing Keys and nodes placed on a ring, so adding a node moves only a share of keys Cassandra “Use consistent hashing with virtual nodes so adding a node moves about 1/N of keys.”
Hot partition One partition getting far more traffic than the rest DynamoDB “Find hot partitions: a DynamoDB partition handles 3,000 reads and 1,000 writes per second.”
Write sharding Adding a random or computed suffix to a hot key to spread its writes DynamoDB “Write-shard the daily_total key into 10 suffixes and sum them on read.”
Rebalancing Moving data when shards are added or uneven Common usage “Plan how data moves when we go from 4 to 8 shards, without downtime.”
Global secondary index An index in DynamoDB with its own partition key, updated asynchronously DynamoDB “Add a GSI on email for login lookups; its reads are eventually consistent.”

12. Backups and recovery

Instead of “set up backups”, say the recovery point you need, the method and how a restore is tested. PostgreSQL’s docs state that pg_dump “cannot be used for continuous archiving or PITR.”

Term What it means Seen in Prompt line
Logical backup An export of schema and data as SQL or an archive pg_dump “Take a nightly pg_dump -Fd -j 4 of the app database as a second backup type.”
Physical backup A copy of the data files pg_basebackup “Take a weekly pg_basebackup as the base for PITR.”
Continuous archiving Copying every completed WAL segment to separate storage PostgreSQL “Archive WAL to object storage, and make archive_command exit non-zero on any failure.”
Point-in-time recovery Restoring a base backup and replaying WAL to a chosen moment PostgreSQL “Write the PITR runbook to recover to 1 minute before a bad DELETE, using recovery_target_time.”
Incremental backup A backup of only the blocks changed since an earlier one PostgreSQL pg_combinebackup “Use incremental base backups daily and a full one weekly.”
Restore test Restoring a backup to a scratch server and checking it PostgreSQL docs “Add a weekly job that restores the latest backup to a scratch instance and runs row-count checks.”
Binlog point-in-time recovery Replaying MySQL binary log events recorded after a backup MySQL “Keep binlogs for 7 days so we can recover to any point after the last full backup.”
Backup retention How long backups are kept and how many Common usage “Keep daily backups for 14 days and monthly ones for a year; delete the rest automatically.”
Replication is not a backup Replicas copy a bad write or a DROP at once AWS disaster recovery whitepaper “Don’t count the replica as a backup; it replays the mistake within seconds.”

13. Schema migrations

Instead of “add this column”, ask for an online migration in expand and contract steps, with a lock timeout on each. Danilo Sato’s parallel change article on martinfowler.com describes the pattern.

Term What it means Seen in Prompt line
Expand and contract Add the new shape, move clients, then remove the old shape, each as its own deploy martinfowler.com parallel change “Rename the column with expand and contract: add, dual-write, backfill, switch reads, drop. Four deploys.”
Backfill Filling a new column for existing rows Common usage “Backfill in batches of 5,000 rows with a 100 ms pause, resumable by id.”
Dual write Writing both the old and new column during a migration Common usage “Dual-write in the app code until the backfill finishes and reads move over.”
ACCESS EXCLUSIVE lock The lock most ALTER TABLE forms take; it blocks even plain SELECT PostgreSQL “List which statements in this migration take ACCESS EXCLUSIVE and for how long.”
lock_timeout for DDL Making a DDL statement give up quickly instead of queueing behind a long query PostgreSQL “Run each DDL with SET lock_timeout = '2s' and retry in a loop.”
Fast column default Adding a column with a constant default stores it in the catalog without rewriting the table, since PostgreSQL 11 PostgreSQL 11 “Add the column with a constant default; a volatile default like random() rewrites the table.”
CREATE INDEX CONCURRENTLY Builds an index without blocking writes; a failed build leaves an INVALID index PostgreSQL “Use CREATE INDEX CONCURRENTLY outside a transaction, and drop any INVALID index before retrying.”
NOT VALID constraint Adding a constraint that applies to new rows now and is checked on old rows later PostgreSQL “Add the foreign key NOT VALID, then VALIDATE CONSTRAINT in a separate step.”
Online schema change tool A tool that copies the table in the background and swaps it in gh-ost, pt-online-schema-change “Run the MySQL ALTER through gh-ost with throttling and a postponed cut-over.”
Migration version table A table that records which migrations have run Common usage “Each migration has a version and a down step; refuse to run out of order.”

14. Change data capture and events

Instead of “also send an event when the order changes”, name how the event leaves the database. Writing to the database and a message broker in two separate steps loses one when the process dies between them.

Term What it means Seen in Prompt line
Change data capture Reading committed changes from the database log and publishing them Debezium “Stream orders changes with Debezium from the PostgreSQL WAL using pgoutput.”
Logical decoding PostgreSQL’s interface for reading row changes from the WAL PostgreSQL “Create a logical replication slot for the CDC connector and alert on its lag.”
Transactional outbox Writing the event to an outbox table in the same transaction as the data, then relaying it microservices.io, Debezium “Use a transactional outbox: insert into outbox in the same transaction, and relay with Debezium’s outbox router.”
At-least-once delivery Every event is delivered, and some may be delivered twice microservices.io “Assume at-least-once delivery and make consumers idempotent by event id.”
Dual-write problem Writing to two systems without a shared transaction, so they can disagree Common usage “Remove the dual write to the database and the queue; use the outbox.”

15. Operations and maintenance

Instead of “keep the database healthy”, name the background work and the numbers to watch. In PostgreSQL, most incidents that aren’t slow queries come from vacuum, connections or disk.

Term What it means Seen in Prompt line
Dead tuple An old row version left behind by an UPDATE or DELETE PostgreSQL “Report dead tuples per table from pg_stat_user_tables.”
VACUUM Marks dead row space as reusable; doesn’t usually shrink the file PostgreSQL “Run VACUUM ANALYZE after the bulk delete.”
Autovacuum The background process that runs VACUUM and ANALYZE; on by default PostgreSQL “Tune autovacuum on events: scale factor 0.01, because the default 0.2 waits for 20% of rows to change.”
Table bloat Space held by dead tuples that vacuum hasn’t reclaimed PostgreSQL “Measure bloat on the top 10 tables and fix the cause before rewriting any table.”
VACUUM FULL Rewrites the table to shrink it, under an ACCESS EXCLUSIVE lock PostgreSQL “Don’t run VACUUM FULL on a live table; it blocks all reads and writes.”
Transaction ID wraparound PostgreSQL’s 32-bit transaction IDs require each table to be frozen at least every 2 billion transactions PostgreSQL “Alert when age(datfrozenxid) passes 1 billion.”
Freezing Marking old rows as visible to all future transactions so their IDs can be reused PostgreSQL “Explain why this table’s freeze age keeps growing.”
Long-running transaction A transaction open for minutes, which stops vacuum from removing newer dead rows PostgreSQL “Find transactions open longer than 5 minutes in pg_stat_activity and say what they block.”
Connection saturation Running out of server connections PostgreSQL “Graph active connections against max_connections and alert at 80%.”
Disk and WAL growth Data, indexes and retained WAL growing toward the volume size PostgreSQL “Alert when pg_wal grows past 3x max_wal_size; that means archiving or a slot is stuck.”
Runbook Written steps for a known failure Common usage “Write runbooks for disk full, replica lag, failover and restore, each with the exact commands.”

16. Security and access control

Instead of “make the database secure”, name who can connect, what each role can do and which rows it sees.

Term What it means Seen in Prompt line
Least privilege Each role gets only the permissions it needs OWASP “Create an app role with SELECT, INSERT, UPDATE, DELETE on its tables only; no DDL, no superuser.”
Role separation Separate roles for migrations, the app and read-only access Common usage “Use three roles: migrator owns the schema, app reads and writes, readonly for analysts.”
Row-level security Policies that filter which rows a role can see or change; table owners and superusers bypass them unless FORCE is set PostgreSQL “Enable row-level security on invoices with a policy tenant_id = current_setting('app.tenant_id')::uuid.”
SQL injection Untrusted input changing the structure of a SQL statement OWASP “Audit every query builder call for string concatenation of user input.”
Encryption in transit TLS between clients and the server PostgreSQL, MySQL “Require TLS for every connection and verify the server certificate.”
Secrets management Keeping credentials out of code and config files Common usage “Read the database password from the secrets manager at startup; never commit it.”
Audit logging Recording who ran which statements PostgreSQL, MySQL “Log DDL and role changes to a separate audit log.”

17. Words to avoid and what to say instead

These words in a prompt let the model pick whatever it defaults to. Replace each with the mechanism you want.

Vague word Say instead
“Optimize the query” “Get this query under 20 ms at p95 on 10 million rows; show EXPLAIN (ANALYZE, BUFFERS) before and after.”
“Make it scalable” “Handle 5,000 writes per second; say whether that needs partitioning, an LSM engine or more hardware.”
“Make it safe” “Name the isolation level, the anomaly prevented and the retry on 40001.”
“Make it consistent” “Name the consistency model: linearizable, read-your-writes or eventual.”
“Highly available” “RPO 1 minute, RTO 15 minutes, survive one node or one zone failing.”
“NoSQL” “Key-value, document, wide-column or graph, chosen from these access patterns.”
“Add caching” “Cache-aside in Redis with a 60 s TTL, invalidated on write; say what staleness the user can see.”
“Run the migration” “Expand and contract, lock_timeout 2s on each DDL, batched backfill, a rollback per step.”

Sources