{"data":{"slug":"discovered-b0f694b4edcf5a079e40166507bb3737ab38f7bba9a8500d","title":"Postgres Patterns","summary":"Design, secure, and tune PostgreSQL schemas and operations with best practices for role separation, Row-Level Security (RLS), connection security, JSONB, partitioning, indexing strategies, and performance tuning. Supports PostgreSQL 17 and 18 features like uuidv7(), virtual generated columns, and asynchronous I\/O.","url":"https:\/\/skillshunter.net\/skills\/discovered-b0f694b4edcf5a079e40166507bb3737ab38f7bba9a8500d","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-b0f694b4edcf5a079e40166507bb3737ab38f7bba9a8500d","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-b0f694b4edcf5a079e40166507bb3737ab38f7bba9a8500d.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-b0f694b4edcf5a079e40166507bb3737ab38f7bba9a8500d\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Use `uuidv7()` as the default for primary keys in PostgreSQL 18 to ensure time-ordered UUIDs with better B-tree locality. For PostgreSQL 17, use the `pg_uuidv7` extension to emulate uuidv7 behavior. Ensure connection strings are stored in environment variables (`DATABASE_URL`) and never in source code. Avoid using the `SUPERUSER` role; instead, use at least three distinct roles for security.","instructions":"---\nname: postgres-patterns\nversion: 2.0.0\ndescription: \"PostgreSQL design, security, and tuning at the SQL\/operations layer \u2014 role separation, Row-Level Security (RLS), connection security, JSONB, partitioning, indexing strategy (BTREE\/GIN\/BRIN\/skip-scan\/partial\/expression), EXPLAIN ANALYZE, isolation levels, locking, advisory locks, connection pool sizing, plus PG 18 (Sept 2025) features: uuidv7(), virtual generated columns (now default), temporal constraints, asynchronous I\/O, OAuth 2.0 auth. Stack-agnostic. Invoke when designing Postgres schemas, hardening database access, or debugging Postgres query performance. Complements per-stack ORM skills (Drizzle, SQLAlchemy, Eloquent, Mongoose) and the database-migrations skill.\"\n---\n\n# PostgreSQL \u2014 Design, Security, and Tuning (PG 17 \/ 18-aware)\n\n**Invoke when designing a Postgres schema, granting database access, picking an index, debugging a slow query, or hardening prod connection settings.**\n\n> Postgres is the same on every stack. The application code differs. This skill covers the database side \u2014 what to ask of it, how to lock it down, and how to read its performance signals. For schema **deployment** (concurrent indexes, lock timeouts, backfills, parallel change), see `database-migrations`.\n\nThis skill assumes Postgres \u2265 16. **PG 18 (released Sept 25, 2025) is the recommended target for new projects** \u2014 see \u00a70 for headline features. PG 17 (Sept 2024) is the safe LTS-style choice for production today; PG 14\/15 are still supported but missing features called out below.\n\n---\n\n## 0. PG 18 \u2014 What changed (Sept 25, 2025)\n\nThe most consequential release for application code in years. Adopt for greenfield; plan migration for prod.\n\n| Feature | Why it matters |\n|---|---|\n| **`uuidv7()`** built-in function | Time-ordered UUIDs \u2192 drastically better B-tree locality than `gen_random_uuid()` (uuidv4). Use as PK default. |\n| **Virtual generated columns** (now the **default** for `GENERATED ... AS (...)` without `STORED`) | Computed at read time, no write amplification. PG 17 only had `STORED`. |\n| **Temporal constraints** on PK \/ UNIQUE \/ FK (`PERIOD`) | Native bitemporal modelling \u2014 no more manual `tstzrange` + EXCLUDE workarounds for \"valid history\" tables. |\n| **Asynchronous I\/O (AIO) subsystem** | Up to **3\u00d7** sequential-scan \/ bitmap-heap \/ vacuum perf. Tunable via `io_method` GUC. |\n| **Skip-scan on multicolumn B-tree indexes** | Index `(a, b)` is now usable to filter by `b` alone (with `a`-cardinality penalty). Reduces \"wrong-prefix\" index proliferation. |\n| **OAuth 2.0 authentication** | Native SSO at the wire protocol \u2014 no PAM\/LDAP gymnastics. |\n| **`pg_upgrade` keeps optimizer stats** | Post-upgrade slow-down on first day eliminated. |\n| **OLD \/ NEW in `RETURNING`** | `UPDATE ... RETURNING OLD.balance, NEW.balance` \u2014 audit trails without triggers. |\n\n### `uuidv7()` as PK default *(PG 18 idiom)*\n\n```sql\n-- PG 18+\nCREATE TABLE orders (\n  id   uuid PRIMARY KEY DEFAULT uuidv7(),\n  ...\n);\n\n-- PG \u2264 17 \u2014 emulate via extension\nCREATE EXTENSION IF NOT EXISTS pg_uuidv7;   -- third-party\n```\n\nUUIDv7 layout: 48-bit unix-ms timestamp + random tail. Inserts hit the *right* edge of the B-tree \u2192 no random-IO write amplification (the well-known v4 problem).\n\n### Virtual generated columns\n\n```sql\n-- PG 18 \u2014 default is VIRTUAL (computed at read)\nCREATE TABLE invoices (\n  amount_cents int  NOT NULL,\n  tax_cents    int  GENERATED ALWAYS AS (amount_cents * 0.1) NOT STORED,    -- still works; explicit NOT STORED\n  total_cents  int  GENERATED ALWAYS AS (amount_cents + (amount_cents * 0.1))  -- DEFAULT virtual in PG 18\n);\n```\n\nUse VIRTUAL for cheap derivations; STORED when the value is read >> written or indexed.\n\n### Temporal constraints\n\n```sql\n-- PG 18 \u2014 native bitemporal PK\nCREATE TABLE employee_salary (\n  employee_id int NOT NULL,\n  salary      numeric NOT NULL,\n  valid       tstzrange NOT NULL,\n  PRIMARY KEY (employee_id, valid WITHOUT OVERLAPS)\n);\n-- INSERTs that overlap on `valid` for the same employee are rejected \u2014 no EXCLUDE-with-gist hack.\n```\n\n### Tuning AIO\n\n```\n# postgresql.conf \u2014 PG 18\nio_method = 'io_uring'    # Linux \u2265 5.x recommended; 'worker' fallback on others\nio_workers = 3            # tune to NVMe queue depth\n```\n\n---\n\n## PG 17 \u2014 Still excellent (Sept 2024)\n\nIf you're not yet on 18, prioritize these PG 17 features:\n\n- **VACUUM** memory cut up to 20\u00d7 \u2192 much shorter maintenance windows.\n- **WAL throughput** up to 2\u00d7 under heavy write concurrency.\n- **`pg_createsubscriber`** \u2014 promote a physical standby to a logical subscriber in minutes (cuts initial-sync time).\n- **`JSON_TABLE()`** \u2014 SQL-standard way to flatten JSONB into rows; avoid hand-written `jsonb_to_recordset` plumbing.\n- **`COPY ... ON_ERROR ignore`** \u2014 bulk loads tolerate single bad rows without aborting.\n- **BRIN parallel build** \u2014 finally usable for big append-only tables.\n\n---\n\n---\n\n## 1. Connection Security (do this on day 1)\n\n### TLS \u2014 non-negotiable in production\n\n```\n# Connection string\npostgresql:\/\/app_user:****@db.example.com:5432\/app_db?sslmode=verify-full&sslrootcert=\/etc\/ssl\/certs\/postgres-ca.pem\n```\n\n| `sslmode` | Use |\n|---|---|\n| `disable` | Local dev only |\n| `require` | Encryption only \u2014 does NOT verify cert (vulnerable to MITM) |\n| `verify-ca` | Verifies cert is signed by trusted CA |\n| `verify-full` | + verifies hostname matches cert. **Production minimum.** |\n\nServer: set `ssl = on` and require TLS in `pg_hba.conf` with `hostssl` lines (not `host`). Reject plaintext.\n\n### Credentials in env, never in code\n\nConnection strings live in environment variables (`DATABASE_URL`), never in source. See `secrets-management`.\n\nConnection strings should not appear in:\n- application logs (mask before logging)\n- error messages returned to clients\n- crash dumps \/ Sentry breadcrumbs\n\n---\n\n## 2. Role Separation (least privilege)\n\n**Never** connect the application as a `SUPERUSER` or as the database owner. Three roles minimum:\n\n```sql\n-- Owner: created tables. Used only by migrations.\nCREATE ROLE app_owner LOGIN PASSWORD '...';\n\n-- Application: runtime. SELECT\/INSERT\/UPDATE\/DELETE on data tables, no DDL.\nCREATE ROLE app_runtime LOGIN PASSWORD '...';\n\n-- Read-only: analytics, BI, on-call investigation.\nCREATE ROLE app_readonly LOGIN PASSWORD '...';\n\n-- Schema, owned by the migration role\nCREATE SCHEMA app AUTHORIZATION app_owner;\nALTER ROLE app_owner SET search_path = app, public;\n\n-- Grants\nGRANT USAGE ON SCHEMA app TO app_runtime, app_readonly;\nGRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA app TO app_runtime;\nGRANT SELECT ON ALL TABLES IN SCHEMA app TO app_readonly;\n\n-- Apply to future tables (created by migrations)\nALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app\n  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_runtime;\nALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app\n  GRANT SELECT ON TABLES TO app_readonly;\n```\n\nOutcomes:\n- An RCE in the app cannot `DROP TABLE` (no DDL grant)\n- A leaked read-only credential cannot mutate\n- Migrations get their own audit trail\n\n**Lock down `public`:** remove the default `CREATE` privilege on the `public` schema (PG 15 already revokes it for non-owners \u2014 verify with `\\dn+`). Untrusted users with table-creation rights in `public` enable function-search-path attacks.\n\n---\n\n## 3. Row-Level Security (RLS) \u2014 multi-tenant default\n\nFor any multi-tenant or per-user data, enable RLS so even a buggy `WHERE` clause can't leak across tenants.\n\n```sql\n-- Schema\nCREATE TABLE app.documents (\n  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n  tenant_id   uuid NOT NULL,\n  owner_id    uuid NOT NULL,\n  title       text NOT NULL,\n  body        text,\n  created_at  timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX ON app.documents (tenant_id, created_at DESC);\n\n-- Enable RLS\nALTER TABLE app.documents ENABLE ROW LEVEL SECURITY;\nALTER TABLE app.documents FORCE ROW LEVEL SECURITY;  -- applies to table owner too\n\n-- App-level policy: tenant set per session\nCREATE POLICY tenant_isolation ON app.documents\n  USING (tenant_id = current_setting('app.tenant_id', true)::uuid);\n\n-- App connects, then SETs the tenant from session-trusted context (JWT, cookie):\nSET LOCAL app.tenant_id = '01HZ...';\nSELECT * FROM app.documents;   -- automatically filtered\n```\n\n**Critical:** the `SET LOCAL` value comes from your **server-side authn**, never from a request header you didn't validate. RLS is enforced by the database; the trust boundary is whoever owns the connection setting.\n\nWith PgBouncer transaction pooling, use `SET LOCAL` (transaction-scoped), never `SET` (session-scoped \u2014 leaks to next pooled user).\n\n---\n\n## 4. Schema Design\n\n### IDs\n\n| Choice | When |\n|---|---|\n| `bigserial` \/ `bigint generated always as identity` | Internal, single-region; fastest |\n| `uuid` (v4 random) | Distributed, public IDs; trades index locality for non-guessability |\n| **`uuid` v7** (RFC 9562) | **2025 best practice** \u2014 time-ordered UUIDs; preserve insert locality + non-guessability |\n\nPostgres 18 ships native `uuidv7()`. On older versions, use the `pg_uuidv7` extension or generate in app code (Drizzle's `uuid().defaultRandom()`, Python's `uuid_utils`).\n\nAvoid `serial`\/`integer` IDs for anything in URLs (4-byte counter exhausts at 2.1B; no privacy).\n\n### Timestamps\n\n```sql\ncreated_at timestamptz NOT NULL DEFAULT now(),\nupdated_at timestamptz NOT NULL DEFAULT now()\n```\n\n`timestamptz` (= `timestamp with time zone`) \u2014 always. It stores UTC; the \"with time zone\" is misleading. `timestamp` (without) is a foot-gun: no offset info, time-zone-conversion bugs at every boundary.\n\n### Constraints \u2014 push correctness into the DB\n\n```sql\nCREATE TABLE app.orders (\n  id          uuid PRIMARY KEY,\n  user_id     uuid NOT NULL REFERENCES app.users(id) ON DELETE RESTRICT,\n  status      text NOT NULL,\n  total_cents bigint NOT NULL,\n  currency    text NOT NULL DEFAULT 'USD',\n  created_at  timestamptz NOT NULL DEFAULT now(),\n\n  CONSTRAINT chk_status CHECK (status IN ('pending','paid','shipped','cancelled')),\n  CONSTRAINT chk_total_positive CHECK (total_cents > 0),\n  CONSTRAINT chk_currency CHECK (currency ~ '^[A-Z]{3}$')\n);\n```\n\nCHECK constraints catch bad data the application failed to. They cost almost nothing on insert.\n\n### Money\n\n**Always** integer cents (`bigint`) or `numeric(precision, scale)`. **Never** `float`\/`double` for money \u2014 IEEE 754 rounding errors compound.\n\n### Enums vs lookup tables\n\n- **Postgres `ENUM`**: cheaper, rigid (adding values is `ALTER TYPE`, ordering matters)\n- **Lookup table** (`status_codes (code text PK, label text)` + FK): flexible, joins required\n\nLookup tables age better for any value users might reorder\/rename\/translate.\n\n### JSONB \u2014 when to use it\n\nUse `jsonb` (not `json`) when:\n- Truly heterogeneous attributes per row (settings blobs, audit details, integration payloads)\n- Sparse fields where >80% of rows wouldn't have them\n- External payloads stored as-is (Stripe events, webhook bodies)\n\n**Don't** use JSONB for:\n- Fields you'll filter or order on regularly (worse than indexed columns)\n- Anything with a stable shape (use real columns + CHECK)\n- Multi-row data (use a child table)\n\n```sql\n-- Indexing JSONB\nCREATE INDEX ON app.events USING GIN (payload jsonb_path_ops);     -- good for @>, ?\nCREATE INDEX ON app.events ((payload->>'user_id'));                -- expression index for one path\n```\n\n### Generated columns\n\n```sql\nCREATE TABLE app.users (\n  id    uuid PRIMARY KEY,\n  email citext NOT NULL UNIQUE,\n  search_tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', email)) STORED\n);\nCREATE INDEX ON app.users USING GIN (search_tsv);\n```\n\nThe DB keeps it consistent. Saves an UPDATE trigger or app-side maintenance.\n\n---\n\n## 5. Indexing Strategy\n\n### Index types \u2014 choose by workload\n\n| Type | Use For |\n|---|---|\n| **BTREE** (default) | Equality, range, ORDER BY |\n| **GIN** | `@>`, `?`, `?|`, `?&` on JSONB; full-text search; arrays |\n| **GIST** | Geometry (PostGIS), exclusion constraints, range types |\n| **BRIN** | Huge append-only tables (events, logs) ordered by insertion time. Tiny index, range-scan focus |\n| **HASH** | Equality only on large keys; rare \u2014 BTREE usually wins |\n\n### Partial indexes \u2014 index only what you query\n\n```sql\n-- 90% of rows are status='inactive' \u2014 don't index them\nCREATE INDEX idx_active_users_email ON app.users (email) WHERE status = 'active';\n\n-- Soft-delete pattern\nCREATE INDEX idx_orders_user ON app.orders (user_id) WHERE deleted_at IS NULL;\n```\n\nPartial indexes are smaller, faster to maintain, and the planner uses them when the query's `WHERE` matches.\n\n### Expression indexes \u2014 index computed values\n\n```sql\n-- Case-insensitive email lookup without citext\nCREATE UNIQUE INDEX idx_users_email_lower ON app.users (lower(email));\nSELECT * FROM app.users WHERE lower(email) = lower($1);\n```\n\n### Composite ordering matters\n\n```sql\n-- Used by:  WHERE tenant_id=? ORDER BY created_at DESC\nCREATE INDEX ON app.documents (tenant_id, created_at DESC);\n\n-- DOES NOT serve:  WHERE created_at >= ?  (leftmost prefix rule)\n```\n\nLeftmost prefix rule: a composite index `(a, b, c)` serves queries on `(a)`, `(a, b)`, `(a, b, c)` \u2014 never on `(b)` alone.\n\n### Unique constraints\n\n```sql\n-- One active subscription per user (partial UNIQUE)\nCREATE UNIQUE INDEX one_active_sub_per_user\n  ON app.subscriptions (user_id) WHERE status = 'active';\n```\n\n---\n\n## 6. Reading Performance \u2014 `EXPLAIN ANALYZE`\n\n```sql\nEXPLAIN (ANALYZE, BUFFERS, VERBOSE, FORMAT TEXT)\nSELECT u.id, count(o.id)\nFROM app.users u\nLEFT JOIN app.orders o ON o.user_id = u.id\nWHERE u.created_at > now() - interval '7 days'\nGROUP BY u.id;\n```\n\nWhat to look for:\n\n| Signal | Meaning |\n|---|---|\n| `Seq Scan` on a big table | Missing or unusable index; or planner thinks scan is cheaper |\n| `rows=10000 vs actual rows=10` | Planner stats are stale \u2192 `ANALYZE table_name` |\n| `Buffers: shared read=...` huge | Cold cache or genuinely large scan |\n| `Sort Method: external merge Disk: ...kB` | `work_mem` too small; bumps to disk |\n| `Rows Removed by Filter: 99000` | Index is wrong shape; fetching too much |\n| `Heap Fetches: 100000` | Index-only scan turned into heap fetch \u2014 visibility map stale, run `VACUUM` |\n\nAlways test with `ANALYZE` (real execution); plain `EXPLAIN` shows estimated plan, not actuals.\n\n`pg_stat_statements` extension: enable in production. Sort by `total_exec_time DESC` to find the queries actually consuming the database.\n\n---\n\n## 7. Transactions and Locking\n\n### Isolation levels\n\n| Level | Postgres default | Phenomena prevented |\n|---|---|---|\n| `READ COMMITTED` | yes (default) | Dirty reads |\n| `REPEATABLE READ` | | + non-repeatable reads, phantom reads |\n| `SERIALIZABLE` | | + write skew (Serializable Snapshot Isolation) |\n\n`SERIALIZABLE` is the safest and well-implemented in Postgres (SSI). The cost is occasional `40001` serialization-failure errors \u2014 your application **must** retry them. Worth it for financial\/balance logic.\n\n### Locking selects\n\n```sql\n-- Block other transactions from updating this row\nSELECT * FROM app.invoices WHERE id = $1 FOR UPDATE;\n\n-- Wait at most 5 seconds for the lock\nSET LOCAL lock_timeout = '5s';\nSELECT * FROM app.invoices WHERE id = $1 FOR UPDATE;\n\n-- Job queue pattern: pick + lock + skip already-locked\nSELECT * FROM app.jobs\nWHERE status = 'pending'\nORDER BY priority, created_at\nLIMIT 1\nFOR UPDATE SKIP LOCKED;\n```\n\n`FOR UPDATE SKIP LOCKED` is the classic correct way to build a worker queue on top of Postgres. No external broker needed for many use cases.\n\n### Advisory locks \u2014 coordinate without rows\n\n```sql\n-- App-level mutex, e.g. \"only one cron at a time\"\nSELECT pg_try_advisory_lock(42);   -- returns true if got it\n-- ... do work ...\nSELECT pg_advisory_unlock(42);\n```\n\nSurvives across rows; cheap. Useful for cross-instance leadership without Redis.\n\n### Idempotent upsert\n\n```sql\nINSERT INTO app.users (id, email, name)\nVALUES ($1, $2, $3)\nON CONFLICT (email) DO UPDATE\n  SET name = EXCLUDED.name,\n      updated_at = now()\nRETURNING *;\n```\n\nAtomic. Use this everywhere you'd otherwise SELECT-then-INSERT.\n\n---\n\n## 8. Connection Pooling\n\nPostgres connections are heavyweight (each fork = ~10MB + planner state). Pool, but understand the modes.\n\n| Tool | Modes |\n|---|---|\n| **PgBouncer** | session, transaction, statement |\n| **Pgpool-II** | similar; also load-balancing |\n| In-app pool (drizzle\/pg-pool, SQLAlchemy, etc.) | session |\n\n### Sizing\n\n```\ntotal_pool_size \u2248 (cores * 2) + spindle_count\n```\n\nReal-world starting point per Postgres instance: 50\u2013200. **Never** size your app pool * replica count > server `max_connections` \u2014 you'll get `too many clients already` outages.\n\nRun multiple app instances? Use PgBouncer. Each app's local pool = ~5\u201310 connections to PgBouncer; PgBouncer multiplexes onto fewer real connections.\n\n### PgBouncer transaction-mode caveats\n\nIn transaction-pooling mode, a single backend connection serves many clients across transactions. Things that break:\n\n| Feature | Why it breaks | Workaround |\n|---|---|---|\n| `SET` (session-scope) | Leaks to next user | Use `SET LOCAL` inside a tx |\n| Prepared statements (server-side) | Cached on the wrong backend | `pgbouncer.ini`: `max_prepared_statements`; PG \u2265 16 + PgBouncer \u2265 1.21 supports protocol-level prepared in transaction mode |\n| `LISTEN`\/`NOTIFY` | Notification listeners survive across pooling | Use a dedicated connection outside PgBouncer |\n| Temporary tables | Live for the connection, not your transaction | Don't, or use `ON COMMIT DROP` |\n| Advisory **session** locks | Leak | Use `pg_advisory_xact_lock` (transaction-scoped) |\n\nIf your stack uses a lot of session state, run PgBouncer in **session** mode and accept fewer connection-multiplexing wins, or rely on the in-app pool only.\n\n---\n\n## 9. Timeouts (set everywhere)\n\nIn every connection or session:\n\n```sql\nSET statement_timeout      = '15s';   -- kill any single statement past 15s\nSET lock_timeout           = '5s';    -- kill any wait-on-lock past 5s\nSET idle_in_transaction_session_timeout = '60s';   -- kill stuck transactions\n```\n\nWithout these, one slow query holding a lock cascades into a database-wide stall. Set per-role defaults so nobody forgets:\n\n```sql\nALTER ROLE app_runtime SET statement_timeout = '15s';\nALTER ROLE app_runtime SET lock_timeout = '5s';\nALTER ROLE app_runtime SET idle_in_transaction_session_timeout = '60s';\n```\n\nMigrations need different timeouts (longer; less concurrent traffic). Set them in the migration role only.\n\n---\n\n## 10. Maintenance\n\n### Autovacuum \u2014 leave it on, tune for hot tables\n\nAutovacuum is enabled by default and good. But hot-write tables (`>10k upserts\/min`) often need:\n\n```sql\nALTER TABLE app.events SET (\n  autovacuum_vacuum_scale_factor = 0.05,   -- vacuum at 5% dead tuples (default 20%)\n  autovacuum_analyze_scale_factor = 0.02,\n  autovacuum_vacuum_cost_limit = 1000      -- vacuum more aggressively\n);\n```\n\nWithout this, dead tuples accumulate, indexes bloat, planner stats stale, queries slow.\n\n### `VACUUM ANALYZE` after large data change\n\nAfter a big migration, backfill, or import, run `VACUUM ANALYZE table_name;` so the planner re-stats the table.\n\n### Bloat monitoring\n\n`pgstattuple` extension or `pg_repack` to repack tables online without taking write locks. See `database-migrations` \u00a78.\n\n---\n\n## 11. Encryption at Rest (column-level)\n\nFor specific PII fields, use `pgcrypto`:\n\n```sql\nCREATE EXTENSION IF NOT EXISTS pgcrypto;\n\n-- Symmetric: stores ciphertext in column; key stays in app\nINSERT INTO app.kyc_documents (user_id, ssn_enc)\nVALUES ($1, pgp_sym_encrypt($2, current_setting('app.encryption_key')));\n\nSELECT pgp_sym_decrypt(ssn_enc, current_setting('app.encryption_key'))\nFROM app.kyc_documents WHERE user_id = $1;\n```\n\nDisk-level encryption (LUKS, EBS, RDS-default) protects against backup theft and disposal. Column encryption protects against DB-admin access and SQL injection. They are **not** substitutes \u2014 use both for sensitive PII.\n\nFor audit trails, prefer storage in a separate, write-only-by-app schema with `app_runtime` having only `INSERT` (not `UPDATE`\/`DELETE`).\n\n---\n\n## 12. SQL Injection \u2014 Postgres specifics\n\nGeneric SQL injection defense lives in `security-baseline` \u00a7A03. Postgres-specific gotchas:\n\n| Gotcha | Defense |\n|---|---|\n| String concat in dynamic SQL (`EXECUTE 'SELECT ' || user_input`) | Use `EXECUTE ... USING ($1, $2)` with bindings \u2014 even in `plpgsql` |\n| `quote_ident()` \/ `quote_literal()` | Use **only** when truly building dynamic identifiers; never for user data |\n| `search_path` hijacking \u2014 function calls resolve via search_path | Schema-qualify everywhere in functions: `SELECT app.users.id`; set `SET search_path = pg_catalog, app` at function definition |\n| `LIKE` patterns | Escape `%` and `_` in user input: `replace(replace(input, '%', '\\\\%'), '_', '\\\\_')` then bind |\n| ORM \"raw\" escape hatches | Audit every call site; treat as guilty until proven safe |\n\n---\n\n## 13. Backups\n\n| Tool | Use |\n|---|---|\n| `pg_basebackup` + WAL archiving | Point-in-time recovery (PITR), production standard |\n| `pg_dump --format=custom` | Logical, portable across versions; use for schema migration \/ small DBs |\n| Cloud provider (RDS, Cloud SQL, Neon, Supabase) snapshots | Convenient, verify retention\/region |\n\nThree rules:\n1. **Test restores monthly.** A backup nobody has restored is not a backup.\n2. **Store off-region.** A region failure that takes the DB also takes co-located backups.\n3. **Encrypt and rotate** the backup encryption keys; treat them as production secrets.\n\n---\n\n## 14. Pre-Deploy Checklist\n\n- [ ] App connects as a non-superuser role with only the privileges it needs\n- [ ] `sslmode=verify-full` against a known CA\n- [ ] `statement_timeout`, `lock_timeout`, `idle_in_transaction_session_timeout` set per role\n- [ ] RLS enabled on every multi-tenant table; `FORCE ROW LEVEL SECURITY` on\n- [ ] Multi-tenant policies tested with a non-bypass role\n- [ ] PgBouncer mode matches what the ORM\/driver expects (transaction vs session)\n- [ ] Autovacuum tuned for known hot tables\n- [ ] `pg_stat_statements` enabled with retention configured\n- [ ] Backup + restore drill within last 30 days\n- [ ] Slow-query log threshold set (`log_min_duration_statement = '500ms'`)\n\n---\n\n## FORBIDDEN\n\n| Pattern | Reason |\n|---|---|\n| App connects as `postgres` superuser | RCE = `DROP DATABASE`; no audit boundary |\n| `sslmode=require` (no `verify-full`) | MITM-vulnerable |\n| Multi-tenant table without RLS | One bad WHERE \u2192 cross-tenant leak |\n| Tenant ID derived from request header app didn't authenticate | RLS becomes attacker-controlled |\n| `float`\/`double precision` for money | Rounding errors |\n| `timestamp` (no time zone) for events | DST\/UTC bugs |\n| Sequential `serial` IDs in public URLs | Enumeration; existence leaks |\n| Connection pool sized > server `max_connections` | Outage on traffic spike |\n| `SET` (session) on PgBouncer transaction-mode | Leaks to next pooled user |\n| No `statement_timeout` | One runaway query can stall the cluster |\n| String concat for dynamic SQL in `plpgsql` functions | SQL injection inside the database |\n| Column encryption keys in the same DB \/ same secret | Defeats the purpose |\n| Untested backups | Not backups |\n\n---\n\n## See Also\n\n- `database-migrations` \u2014 safe DDL: concurrent indexes, parallel-change pattern, lock-aware migrations\n- `security-baseline` \u2014 A01 (authz), A03 (SQL injection generic), A09 (audit logging)\n- `secrets-management` \u2014 DATABASE_URL hygiene, key rotation\n- `observability` \u2014 slow-query log shipping, `pg_stat_statements` to APM\n- `performance-patterns` \u2014 generic perf: caching, N+1, response compression\n- per-stack ORM skill \u2014 Drizzle (Node), SQLAlchemy\/asyncpg (Python), Eloquent (PHP), Mongoose (only if you accidentally added Postgres to a Mongo project \u2014 don't)\n","use_cases":["Designing secure and scalable PostgreSQL schemas","Implementing Row-Level Security (RLS) in PostgreSQL","Optimizing PostgreSQL query performance with indexing and EXPLAIN ANALYZE","Migrating to PostgreSQL 18 and leveraging new features like uuidv7() and virtual generated columns","Hardening database access with proper role separation and connection security"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/0x57-1\/start-vibing-stacks\/blob\/6e398b34c4dfe73ac8f809216b218856b8e02ff4\/stacks\/_shared\/skills\/postgres-patterns\/SKILL.md","source_commit":"6e398b34c4dfe73ac8f809216b218856b8e02ff4","license":null,"version":null,"listing_approved_at":"2026-12-03","created_at":"2026-12-02T09:11:40.000000Z","updated_at":"2026-12-03T16:20:08.000000Z","seo_title":"PostgreSQL Design, Security, and Tuning Patterns","seo_description":"Learn best practices for PostgreSQL schema design, security, and performance tuning, including role separation, RLS, indexing strategies, and PostgreSQL 18 features like`","seo_keywords":["PostgreSQL design patterns","PostgreSQL security best practices","PostgreSQL performance tuning","Row-Level Security (RLS) in PostgreSQL","PostgreSQL 18 features","uuidv7() in PostgreSQL","virtual generated columns PostgreSQL","asynchronous I\/O PostgreSQL"]}}