S
Supanote
Sign in Sign up

PostgreSQL 18 Native uuidv7() Time-Ordered Primary Keys

plain (sql) 1 day ago · 46 lines · 4 views
Verified Blueprint PostgreSQL 18

Eliminate B-tree page splits and WAL bloat in PostgreSQL 18 using native DEFAULT uuidv7() primary keys and timestamp extraction.

  • ✓ Uses built-in PostgreSQL 18 uuidv7() without pgcrypto or third-party C extensions
  • ✓ Keeps B-tree right-leaning append locality like BIGSERIAL while preserving globally unique 128-bit IDs
  • ✓ Extracts embedded millisecond creation timestamps via uuid_extract_timestamp() without extra index columns
Quick Fetch
1-- PostgreSQL 18+ Native Time-Ordered UUIDv7 Primary Key Blueprint
2-- Solves random UUIDv4 B-tree index fragmentation, buffer churn, and WAL write amplification
3
4-- 1. Core Table Using Built-In uuidv7() Default (RFC 9562)
5CREATE TABLE IF NOT EXISTS tenant_events (
6 id uuid PRIMARY KEY DEFAULT uuidv7(),
7 tenant_id uuid NOT NULL,
8 event_type text NOT NULL,
9 payload jsonb NOT NULL DEFAULT '{}'::jsonb,
10 -- Optional: PG 18 virtual generated column (zero disk overhead) exposing embedded timestamp
11 recorded_at timestamptz GENERATED ALWAYS AS (uuid_extract_timestamp(id)) VIRTUAL
12);
14-- 2. Composite Index Leveraging Monotonic ID Ordering
15-- Prefix by tenant_id; trailing id is naturally chronological (no separate created_at needed)
16CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tenant_events_tenant_id_desc
17 ON tenant_events (tenant_id, id DESC);
19-- 3. Backfill / Historical Seed Helper Using uuidv7(interval_offset)
20-- PostgreSQL 18 uuidv7() accepts an optional interval shift for backdated event imports:
21INSERT INTO tenant_events (id, tenant_id, event_type, payload)
22VALUES (
23 uuidv7('-1 hour'::interval),
24 '0195f3a0-7c00-7000-8000-000000000001'::uuid,
25 'invoice.paid',
26 '{"amount_cents": 4900, "currency": "USD"}'::jsonb
27);
29-- 4. Keyset (Cursor) Pagination Without OFFSET Slowdowns
30-- Uses monotonic UUIDv7 ordering to fetch the next 50 events in < 1ms
31SELECT
32 id,
33 uuid_extract_timestamp(id) AS occurred_at,
34 uuid_extract_version(id) AS uuid_ver,
35 event_type,
36 payload
37FROM tenant_events
38WHERE tenant_id = '0195f3a0-7c00-7000-8000-000000000001'::uuid
39 AND id < '0195f3e8-0000-7000-8000-ffffffffffff'::uuid
40ORDER BY id DESC
41LIMIT 50;
43-- 5. Inspect Index Leaf Density (Compare ~90% fill on UUIDv7 vs ~50-65% on UUIDv4)
44-- CREATE EXTENSION IF NOT EXISTS pgstattuple;
45-- SELECT avg_leaf_density, leaf_fragmentation FROM pgstatindex('tenant_events_pkey');

No replies yet

Every reply is a note. Start a discussion, ask a question, or attach a code snippet.

Related PostgreSQL 18 & Database, Cache & SQL Blueprints

Production-ready configurations and diagnostics from the verified Supanote library.

All Database, Cache & SQL →
Interactive Developer Workbench: .env, Log & API Key Secret Scanner

Detect and redact leaked AWS keys, JWTs, database URIs, private keys, and Bearer tokens before sharing.

Open Secret Scanner →

Share Note

Open
Download SVG
Social Card Preview
Open on mobile
Point your phone camera to open this note directly

Report this note

Notification