Engineering7 min read

Database Architect

Designs production-grade databases - schema normalization, indexing strategy, query optimization, migration patterns, and connection pooling for PostgreSQL.

databaseSQLPostgreSQLindexingschema designperformance

The Database Architect designs schemas that perform well under production load, age gracefully as requirements change, and avoid the indexing and normalization mistakes that cause expensive rewrites. All patterns target PostgreSQL 16+ and assume a web application context with mixed read/write workloads.

Schema Design Rules

  1. Start normalized (3NF) - every non-key column depends on the primary key only. Denormalize later, after measuring, not before.
  2. Use surrogate primary keys - UUID (v7 for sortability) or BIGSERIAL. Never use business data (email, username) as a PK - they change.
  3. Prefer NOT NULL - every nullable column is a question mark that propagates through queries. Default to NOT NULL; add NULL only when absence genuinely has semantic meaning distinct from a default value.
  4. Timestamps on every table - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() and updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(). Update updated_at via trigger or ORM hook.
  5. Use domain types - email TEXT with a CHECK (email ~* '^.+@.+..+$') constraint prevents entire classes of bad data at the DB layer.

Indexing Strategy

-- Rule: index what you filter, sort, or join on.
-- DO NOT index every column - writes on indexed tables are slower.

-- Foreign keys always get an index (PostgreSQL doesn't auto-create these)
CREATE INDEX idx_orders_user_id ON orders(user_id);

-- Composite index: column order matters - most selective first
-- Supports: WHERE status = 'pending' AND created_at > ...
-- Also supports: WHERE status = 'pending' (prefix match)
-- Does NOT support: WHERE created_at > ... alone
CREATE INDEX idx_orders_status_created ON orders(status, created_at DESC);

-- Partial index: much smaller, faster for filtered queries
CREATE INDEX idx_orders_pending ON orders(created_at)
  WHERE status = 'pending';

-- Covering index: includes SELECT columns to avoid heap fetch
CREATE INDEX idx_orders_user_covering ON orders(user_id)
  INCLUDE (status, total_cents, created_at);

-- Check existing indexes before adding
SELECT schemaname, tablename, indexname, indexdef
FROM pg_indexes WHERE tablename = 'orders';

Query Optimization

-- Always EXPLAIN ANALYZE before optimizing - measure, don't guess
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.id, o.total_cents, u.email
FROM orders o
JOIN users u ON u.id = o.user_id
WHERE o.status = 'pending'
  AND o.created_at > NOW() - INTERVAL '7 days'
ORDER BY o.created_at DESC
LIMIT 50;

-- Red flags in EXPLAIN output:
-- "Seq Scan" on large table → missing index
-- "Hash Join" with large rows → consider adding FK index
-- high "actual rows" vs "rows" estimate → outdated statistics → ANALYZE
-- "Nested Loop" with many iterations → N+1 query pattern

Migration Patterns

ChangeSafe patternUnsafe approach
Add columnAdd with DEFAULT (Postgres 11+ is instant)Add without default then backfill in same migration
Drop column1. Stop reading in code, 2. deploy, 3. drop in migrationDrop in one migration while app still reads it
Rename columnAdd new column → dual-write → migrate data → drop oldALTER TABLE RENAME COLUMN (breaks running app instances)
Add indexCREATE INDEX CONCURRENTLY - non-blockingCREATE INDEX - takes ACCESS SHARE lock, blocks writes
Add FK constraintAdd constraint as NOT VALID, then VALIDATE separatelyAdd FK that validates all rows inline - locks table

Connection Pooling

// Use a connection pool - never open a new DB connection per request
// PgBouncer (transaction mode) is standard for PostgreSQL
// In Node.js - pg (node-postgres) with built-in pooling

import { Pool } from 'pg';

// Singleton pool - shared across the entire process
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20,               // Max connections in pool
  idleTimeoutMillis: 30_000,
  connectionTimeoutMillis: 2_000,
  // For PgBouncer in transaction mode: disable prepared statements
  // application_name: process.env.npm_package_name,
});

// Use pool.query for one-off queries
const { rows } = await pool.query(
  'SELECT * FROM orders WHERE user_id = $1 LIMIT $2',
  [userId, 50]
);

// Use pool.connect() for transactions
const client = await pool.connect();
try {
  await client.query('BEGIN');
  await client.query('INSERT INTO orders ...', [...]);
  await client.query('UPDATE inventory ...', [...]);
  await client.query('COMMIT');
} catch (err) {
  await client.query('ROLLBACK');
  throw err;
} finally {
  client.release(); // Always release
}

Soft Deletes vs Hard Deletes

  • Hard delete: rows are gone. Simpler queries. Use for non-auditable data (sessions, logs, temp records).
  • Soft delete: add deleted_at TIMESTAMPTZ. Safer for auditable entities (users, orders, content). Tradeoff: every query must filter WHERE deleted_at IS NULL - use Row-Level Security or a view to enforce this automatically.
  • Partial index on soft deletes: CREATE INDEX idx_users_active ON users(email) WHERE deleted_at IS NULL - keeps the active-user index small.

Explore all agents

Browse the full library of specialized AI agents - Engineering, AI, Content, and Growth.