An event table had grown to 2 billion rows, was taking 10 million new rows a day, and had never been purged. Every consumer poll scanned the whole table, and a classic DELETE-based clean-up would have meant days of WAL, dead tuples and VACUUM pressure on a production system that could not stop. This post shows how I converted that live table into daily range partitions with a cutover lock of a few milliseconds and zero application errors, and replaced DELETE with automated DETACH + DROP. Every script is included, tested on PostgreSQL 16, 17 and 18, and runs on Aurora, RDS, self-managed PostgreSQL or a container.
DROP.1. The problem
The table (I'll call it EVENT_QUEUE) is a classic outbox: the application inserts an event, consumers poll for unprocessed rows, publish them, then set processedtime.
CREATE TABLE public."EVENT_QUEUE" (
event_id varchar(255) NOT NULL,
payload jsonb NULL,
traceid varchar(255) NULL,
createdtime timestamp DEFAULT CURRENT_TIMESTAMP NULL,
processedtime timestamp NULL,
worker_id numeric(3) DEFAULT 1 NULL, -- set by a BEFORE INSERT trigger (1..32)
CONSTRAINT "EVENT_QUEUE_pkey" PRIMARY KEY (event_id)
);
-- consumer poll
SELECT * FROM "EVENT_QUEUE" WHERE processedtime IS NULL AND worker_id = 1 LIMIT 100;
-- after publishing
UPDATE "EVENT_QUEUE" SET processedtime = now() WHERE event_id IN ('…', '…', '…');| Fact | Consequence |
|---|---|
| 2 billion rows, +10 M per day, no purge | Grows ~2 GB per day, forever |
No index on processedtime | Every poll is a full sequential scan (49–73 ms on just 1–2 M rows in the lab) |
Purge with DELETE | Row-by-row WAL, index maintenance, dead tuples, long VACUUM, I/O on a busy system |
| Production, 24×7 | No downtime window, no application change allowed |
2. The idea: attach, don't copy
PostgreSQL can attach an existing table as a partition. If the table already carries a validated CHECK constraint that proves every row fits the partition range, ATTACH PARTITION skips its validation scan and becomes a pure catalog change. So the 2 billion rows never move: they become the partition EVENT_QUEUE_LEGACY covering everything before a boundary (the next midnight). From the boundary on, new rows land in small daily partitions.
Prepare online, cutover in milliseconds, then purge with DETACH + DROP
3. Architecture
A small framework in schema partmaint drives everything from one config row per table: partition size, retention, buffer of future partitions, purge on/off, archive mode. A pg_cron job calls partmaint.run_maintenance() every 30 minutes; it is idempotent, so a missed run is simply caught up by the next one.
4. Design decisions (and the traps)
4.1 Lock levels decide everything
I measured the locks each DDL takes on the parent (PostgreSQL 16):
| Operation | Lock on parent | Consequence |
|---|---|---|
CREATE TABLE … PARTITION OF | ACCESS EXCLUSIVE | Blocks inserts while waiting: avoided |
CREATE TABLE standalone + ATTACH PARTITION | SHARE UPDATE EXCLUSIVE | Does not block DML: used to create partitions |
DETACH PARTITION | ACCESS EXCLUSIVE (milliseconds) | Used with a 1 s lock_timeout and retries |
DETACH … CONCURRENTLY | weaker, two transactions | Cannot run inside a function or procedure, so it cannot be automated in-database |
Any statement that needs ACCESS EXCLUSIVE is dangerous not because of how long it holds the lock, but because of how long it waits: while it waits behind a long query, every new insert queues behind it. That's why every DDL in the kit runs with a short lock_timeout and a retry loop.
4.2 Primary key: no global unique index in PostgreSQL
A primary key on a partitioned table must include the partition column. PRIMARY KEY (event_id, createdtime) looks fine but silently accepts the same event_id twice with two timestamps; my test proved it. Instead, the parent has no primary key and every partition gets its own PRIMARY KEY (event_id); LEGACY keeps its original one. For random-UUID keys that's uniqueness in practice. The one statement this breaks is INSERT … ON CONFLICT (event_id), so the prechecks look for it in pg_stat_statements.
4.3 The trigger trap
The table has a BEFORE INSERT trigger. Row triggers on a partitioned parent are cloned to every partition, but ATTACH fails with trigger already exists if the old table still has its own copy. Prepare copies the trigger to the new parent; cutover drops LEGACY's copy in the same transaction just before ATTACH, so no insert ever misses it. Rollback recreates it, because DETACH removes cloned triggers.
4.4 The time zone trap (found in testing)
createdtime is timestamp without time zone, written in the application session's time zone. My first version computed "midnight" in UTC; on a server whose time zone runs ahead of UTC, the first daily partition overlapped LEGACY by the UTC offset and the cutover failed (safely: the transaction rolled back). Now the boundaries use the application time zone, stored in the config, and prepare refuses to continue if the newest row disagrees with the session clock.
4.5 The partial index is the biggest single win
CREATE INDEX CONCURRENTLY event_queue_unprocessed_ix
ON public."EVENT_QUEUE" (worker_id) WHERE processedtime IS NULL;It only holds the backlog, so it stays tiny (32 kB on 2 M rows). The poll went from 101 to 141,153 transactions per second. It is also what makes the time zone guard and the purge guard instant, so prepare requires it.
4.6 How many future partitions?
The UPDATE … WHERE event_id IN (…) has no createdtime, so it probes every partition, including empty future ones:
| Partitions | UPDATE by event_id (tps) | vs. plain table |
|---|---|---|
| 1 (plain table) | 10,853 | – |
| 4 (3-day buffer) | 7,967 | −27% |
| 8 (7-day buffer) | 6,627 | −39% |
| 16 (15-day buffer) | 4,605 | −58% |
The buffer only matters if the scheduler stops, and the health check raises CRITICAL when fewer than 2 future days remain. So: 3 days of buffer, steady state of 5 partitions.
4.7 Never drop unprocessed events
Each config row has a retire_guard predicate (processedtime IS NULL). A partition with any matching row is not retired; it is logged as BLOCKED and the health check warns. With a separate purge_enabled flag you can pause purging entirely while partitions keep being created.
5. Step-by-step deployment
export PGHOST=<writer endpoint> PGPORT=5432 PGDATABASE=<db> PGUSER=<table owner>
export PGPASSWORD='<password>' # or ~/.pgpass
export PGTZ='<application time zone>' # e.g. Asia/Kolkata: MUST match the application sessions
export SCH=public TBL=EVENT_QUEUE PCOL=createdtime- Prechecks (read-only).
psql -v sch=$SCH -v tbl=$TBL -v pcol=$PCOL -f 00_prechecks.sql. Pass: noON CONFLICT (event_id), no foreign keys into the table, partition column is a timestamp, xid age far from the freeze limit. - Phase 1 index, off-peak: the
CREATE INDEX CONCURRENTLYabove. Hours on billions of rows; it never blocks DML. Checkindisvalid. - Install the framework:
psql -v ON_ERROR_STOP=1 -f 01_partmaint_framework.sql - Prepare (early on cutover day, inside
screen):psql -v sch=$SCH -v tbl=$TBL -v pcol=$PCOL -f 02_prepare_online.sql. Boundary = next midnight automatically; VALIDATE reads the table once (hours), without blocking DML. - Go / no-go: all guards OK, boundary > 30 min away, no long transactions, rollback script at hand.
- Cutover:
psql -v sch=$SCH -v tbl=$TBL -f 03_cutover.sql. ExpectCUTOVER COMPLETE … DDL under lock x ms. - Schedule:
CALL partmaint.run_maintenance();once by hand, thenpsql -f 06_schedule.sql(pg_cron). No pg_cron? Run the same CALL from Linux cron, a Kubernetes CronJob or EventBridge.
createdtime >= boundary. Cut over the same day, or run 04_abort_before_cutover.sql. The cutover script refuses to run within 30 minutes of the boundary.6. Configuration and operations
| Column | Example | Meaning |
|---|---|---|
part_interval | 1 day | Partition size |
retention | 1 day | Retire partitions whose whole range is older than this |
premake / min_future | 3 / 2 | Future partitions kept / CRITICAL below |
purge_enabled | true | false = nothing is detached, archived or dropped |
archive_mode | NONE | NONE drop · KEEP move to an archive schema · S3 export (aws_s3), verify, drop |
retire_guard | processedtime IS NULL | Never retire a partition with matching rows |
time_zone | Asia/Kolkata | Boundary arithmetic (locked once partitions exist) |
UPDATE partmaint.part_config SET purge_enabled = false WHERE parent_table = 'EVENT_QUEUE'; -- pause purge
UPDATE partmaint.part_config SET retention = '2 days' WHERE parent_table = 'EVENT_QUEUE';
SELECT * FROM partmaint.health_check() WHERE status <> 'OK'; -- alerting
SELECT * FROM partmaint.part_log ORDER BY log_id DESC LIMIT 50; -- every action + config changeEvery config change is validated by a CHECK constraint and written to the log with who changed what, old to new.
6.1 Scheduling with pg_cron
Automation is three pg_cron jobs created by 06_schedule.sql: partmaint_run does the partition work, while partmaint_log_purge (keeps 90 days of framework log) and cron_history_purge (keeps 14 days of pg_cron history) are housekeeping. Every 30 minutes partmaint_run calls CALL partmaint.run_maintenance();, which for every table in partmaint.part_config:
- Creates future partitions so that
premakedays (3) are always ready. - Retires old partitions older than
retention(1 day): DETACH, then DROP (or archive perarchive_mode). It skips partitions that still hold unprocessed events and does nothing whilepurge_enabled = false. - Runs ANALYZE on the parent once a day (autovacuum never analyzes a partitioned parent).
- Logs every action to
partmaint.part_log.
The procedure is idempotent and protected by an advisory lock: a missed run is caught up by the next one, and two runs never overlap.
SELECT cron.schedule('partmaint_run', '*/30 * * * *', $$CALL partmaint.run_maintenance()$$);Enable pg_cron once (on managed services this needs a restart, so plan it in a maintenance window well before the cutover):
| Environment | How |
|---|---|
| Aurora PostgreSQL / Amazon RDS | Parameter group: add pg_cron to shared_preload_libraries, set cron.database_name to your database, reboot the writer, then CREATE EXTENSION pg_cron; |
| Self-managed (RHEL / Ubuntu) | Install the pg_cron package for your PostgreSQL version, set the same two parameters in postgresql.conf, restart, then CREATE EXTENSION pg_cron; |
| No pg_cron available | Run psql -c "CALL partmaint.run_maintenance()" every 30 minutes from Linux cron, a Kubernetes CronJob or AWS EventBridge |
Check that it is running:
SELECT jobid, jobname, schedule FROM cron.job; -- scheduled jobs
SELECT jobid, status, return_message, start_time FROM cron.job_run_details
ORDER BY start_time DESC LIMIT 5; -- recent runs
SELECT * FROM partmaint.health_check() WHERE status <> 'OK'; -- no rows = all good7. Abort and rollback
| Situation | Script | Effect |
|---|---|---|
| Cutover cannot happen before the boundary | 04_abort_before_cutover.sql | Live table exactly as before prepare |
| Application misbehaves after cutover | 05_rollback_after_cutover.sql | Detach LEGACY, copy back new rows, swap names, recreate triggers: back to one table with its original PK |
8. Test results
8 concurrent sessions ran insert / read-by-event_id / update-processedtime the whole time, with a long-running query deliberately blocking the first cutover attempt.
| Version | Cutover lock | App errors | Consumer poll (tps), without → with partial index | Mixed workload vs. plain |
|---|---|---|---|---|
| PostgreSQL 16.15 | 2–5 ms | 0 | 11 → 17,960 | – |
| PostgreSQL 17.12 | 3.3–4.4 ms | 0 | 101 → 141,153 | −9% to −12% |
| PostgreSQL 18.1 | 2.7–3.9 ms | 0 | – | −11% |
Also verified: duplicates rejected per partition, trigger present on every partition, retention DETACH 0.5 ms / DROP 0.4 ms, purge flag, purge guard, config validation and audit, rollback under load with 0 errors, and four time zones.
9. Try it yourself in 5 minutes
The demo builds the whole scenario (trigger included) in a throwaway database evq_demo, runs prepare and cutover under live load and prints the results. It never touches other databases.
mkdir -p ~/evq && cd ~/evq # save all scripts from section 10 here
chmod +x *.sh
docker run -d --name pgtest -p 5434:5432 -e POSTGRES_PASSWORD=demo \
-e TZ=Asia/Kolkata -e PGTZ=Asia/Kolkata -v ~/evq:/evq:Z postgres:17 # podman works the same
until docker exec pgtest pg_isready -U postgres; do sleep 2; done
docker exec -it -e PGUSER=postgres -e ROWS=300000 pgtest bash -c "cd /evq && ./run_demo.sh && ./collect_evidence.sh"
docker rm -f -v pgtest # -v removes the data volume too10. All scripts
Click a file to expand it; each has Copy and Download buttons. Save them in one folder.
00_prechecks.sqlRead-only gate checks (version, extensions, DDL, indexes, triggers, publications, grants, SQL patterns, xid age).
/* =============================================================================
00_prechecks.sql - READ-ONLY. Run in PROD (and PERF) before any change.
Usage: psql -v tbl=EVENT_QUEUE -v sch=public -v pcol=createdtime -f 00_prechecks.sql
Every section marked [GATE] must pass or the design must change.
============================================================================= */
\set ON_ERROR_STOP off
\pset pager off
\echo '== 1. Engine / extensions available (need pg_cron for in-DB scheduling, aws_s3 for S3 archive)'
SELECT version();
SELECT name, default_version, installed_version
FROM pg_available_extensions WHERE name IN ('pg_cron','aws_s3','aws_commons','pg_partman','pg_stat_statements');
SHOW shared_preload_libraries;
\echo '== 2. Table definition (column order matters: the new parent is built LIKE this table)'
SELECT ordinal_position, column_name, data_type, character_maximum_length, numeric_precision,
is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = :'sch' AND table_name = :'tbl' ORDER BY ordinal_position;
\echo '== 3. [GATE] Partition column type must be timestamp / timestamptz / date'
SELECT format_type(a.atttypid, a.atttypmod) AS pcol_type, a.attnotnull
FROM pg_attribute a WHERE a.attrelid = format('%I.%I', :'sch', :'tbl')::regclass AND a.attname = :'pcol';
\echo '== 4. Size (catalog only, no scan) + transaction-ID age (VALIDATE blocks autovacuum for hours)'
SELECT age(relfrozenxid) AS xid_age, current_setting('autovacuum_freeze_max_age') AS freeze_max_age
FROM pg_class WHERE oid = format('%I.%I', :'sch', :'tbl')::regclass;
SELECT pg_size_pretty(pg_total_relation_size(format('%I.%I', :'sch', :'tbl')::regclass)) AS total_size,
pg_size_pretty(pg_relation_size(format('%I.%I', :'sch', :'tbl')::regclass)) AS heap_size,
(SELECT reltuples::bigint FROM pg_class WHERE oid = format('%I.%I', :'sch', :'tbl')::regclass) AS est_rows;
\echo '== 5. Indexes. PK is recreated per partition automatically. [GATE] any OTHER unique index'
\echo '-- becomes partition-local only and is not replicated by the framework -> handle manually'
SELECT i.indexrelid::regclass AS index_name, i.indisprimary, i.indisunique,
pg_get_indexdef(i.indexrelid) AS ddl,
pg_size_pretty(pg_relation_size(i.indexrelid)) AS size
FROM pg_index i WHERE i.indrelid = format('%I.%I', :'sch', :'tbl')::regclass;
\echo '== 6. [GATE] Objects that break or need rework under partitioning'
\echo '-- 6a. Foreign keys pointing TO this table'
SELECT conname, conrelid::regclass AS from_table FROM pg_constraint
WHERE confrelid = format('%I.%I', :'sch', :'tbl')::regclass;
\echo '-- 6b. Triggers / rules'
SELECT tgname, pg_get_triggerdef(oid) FROM pg_trigger
WHERE tgrelid = format('%I.%I', :'sch', :'tbl')::regclass AND NOT tgisinternal;
\echo '-- 6c. Dependent views / matviews (must be recreated against the new parent)'
SELECT DISTINCT dv.oid::regclass AS dependent_view
FROM pg_depend d JOIN pg_rewrite rw ON rw.oid = d.objid JOIN pg_class dv ON dv.oid = rw.ev_class
WHERE d.refobjid = format('%I.%I', :'sch', :'tbl')::regclass AND dv.oid <> d.refobjid;
\echo '-- 6d. Logical replication publications (DMS / Debezium / CDC to Kafka?) -> need publish_via_partition_root'
SELECT p.pubname, p.pubviaroot FROM pg_publication p
JOIN pg_publication_tables pt ON pt.pubname = p.pubname
WHERE pt.schemaname = :'sch' AND pt.tablename = :'tbl';
SELECT slot_name, plugin, slot_type, active FROM pg_replication_slots;
\echo '-- 6e. Owner and grants (replicated onto the new parent)'
SELECT pg_get_userbyid(relowner) AS owner, relacl FROM pg_class
WHERE oid = format('%I.%I', :'sch', :'tbl')::regclass;
\echo '== 7. [GATE] How does the application touch the table? (needs pg_stat_statements)'
\echo '-- Look for: ON CONFLICT (event_id) -> FAILS on a partitioned table (no global unique index)'
\echo '-- (plain INSERT and ON CONFLICT DO NOTHING without a target are fine)'
\echo '-- UPDATE ... SET <partition column> -> row movement between partitions'
\echo '-- WHERE event_id = ... without partition column -> probes EVERY partition'
\echo '-- (measured: 4 partitions -19%, 12 -55%, 30 -79% select TPS) -> keep partition count low'
\echo '-- INSERT without createdtime / NULL createdtime -> "no partition found" error'
SELECT calls, round(mean_exec_time::numeric, 3) AS mean_ms, rows,
left(regexp_replace(query, '\s+', ' ', 'g'), 300) AS query
FROM pg_stat_statements
WHERE query ILIKE '%' || :'tbl' || '%'
ORDER BY calls DESC LIMIT 50;
\echo '== 8. Partition column data quality (FULL SCAN - run on a replica / reader, or in PERF copy)'
\echo '-- [GATE] nulls must be 0; max must be < chosen cutover boundary'
-- SELECT count(*) FILTER (WHERE createdtime IS NULL) AS nulls,
-- min(createdtime), max(createdtime) FROM public."EVENT_QUEUE";
\echo '== 9. Daily volume (sizes the partition interval; target 1-50 GB per partition)'
-- SELECT date_trunc('day', createdtime) d, count(*) FROM public."EVENT_QUEUE"
-- WHERE createdtime > now() - interval '14 days' GROUP BY 1 ORDER BY 1;
\echo '== 9b. [GATE] Time zone: createdtime is timestamp WITHOUT tz, written in the APP session TZ.'
\echo '-- newest createdtime should be ~ localtimestamp. If off by whole hours, run 02 with PGTZ=<app tz>'
SELECT current_setting('TimeZone') AS session_tz, localtimestamp(0) AS session_local_now;
-- SELECT max(createdtime) FROM public."EVENT_QUEUE" WHERE createdtime > now() - interval '2 days';
\echo '== 10. Long-running transactions right now (these block every DDL lock)'
SELECT pid, now() - xact_start AS xact_age, state, left(query, 120) AS query
FROM pg_stat_activity WHERE xact_start < now() - interval '1 minute' ORDER BY xact_start;
01_partmaint_framework.sqlThe framework: config table, log, procedures, health check, config validation and audit.
/* =============================================================================
01_partmaint_framework.sql
Generic RANGE-partition maintenance framework for PostgreSQL / Aurora PostgreSQL
(PG 13+). Table-agnostic and config driven (one row per partitioned table).
Design rules (verified on PG16):
* No PRIMARY KEY on the parent (it would have to include the partition
column, i.e. (event_id, createdtime), which silently allows duplicate event_ids).
Instead EVERY partition gets its own PRIMARY KEY (event_id) -> local_pk_cols.
* New partitions are created as STANDALONE tables and then ATTACHed.
CREATE TABLE ... PARTITION OF takes ACCESS EXCLUSIVE on the parent;
ATTACH PARTITION takes only SHARE UPDATE EXCLUSIVE -> inserts keep flowing.
* Old partitions are removed with plain DETACH (ACCESS EXCLUSIVE, metadata
only, milliseconds) under a short lock_timeout with retries, so we never
queue behind a long query and block the application's INSERTs.
DETACH ... CONCURRENTLY cannot be executed from a function/procedure, so it
is not usable for in-database automation (pg_cron -> CALL procedure).
* No DEFAULT partition: it blocks DETACH CONCURRENTLY and forces a scan on
every ATTACH. Instead we pre-create partitions ahead and health-check them.
* Time zone: for a timestamp-WITHOUT-time-zone column, "midnight" means midnight
in the TZ the application writes in. All bound arithmetic runs in
part_config.time_zone, whatever TZ the scheduler session (pg_cron) uses.
* Every step is logged in partmaint.part_log; each partition is its own
transaction (COMMIT per step), so a failure never rolls back earlier work.
* purge_enabled (per table): false = nothing is ever detached/archived/dropped;
future partitions are still created. Every config change is validated and
audited in part_log (action CONFIG).
* retire_guard: a partition still holding rows that match it (e.g. unprocessed
events) is never retired - logged as BLOCKED and raised by health_check.
* Retire = DETACH -> (optional archive) -> DROP. If the archive fails the
detached table is kept and flagged; data is never dropped unverified.
============================================================================= */
CREATE SCHEMA IF NOT EXISTS partmaint;
CREATE SCHEMA IF NOT EXISTS partmaint_archive; -- used by archive_mode = 'KEEP'
-- -----------------------------------------------------------------------------
-- Configuration: one row per partitioned table
-- -----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS partmaint.part_config (
parent_schema text NOT NULL DEFAULT 'public',
parent_table text NOT NULL,
part_column text NOT NULL,
part_prefix text, -- partition name prefix (default = parent_table)
local_pk_cols text[], -- PRIMARY KEY created on EACH partition (e.g. {event_id})
part_interval interval NOT NULL DEFAULT '1 day',
premake int NOT NULL DEFAULT 14, -- partitions kept ahead of now()
min_future int NOT NULL DEFAULT 7, -- health_check CRITICAL below this
retention interval NOT NULL, -- partition dropped when upper bound <= now() - retention
retire_guard text, -- SQL predicate; a partition with ANY row matching it
-- is NOT retired (e.g. 'processedtime IS NULL')
archive_mode text NOT NULL DEFAULT 'NONE'
CHECK (archive_mode IN ('NONE','KEEP','S3')),
s3_bucket text,
s3_prefix text,
s3_region text,
lock_timeout_ms int NOT NULL DEFAULT 1000, -- DETACH stalls DML while waiting: keep short
max_retries int NOT NULL DEFAULT 30,
retry_sleep_s numeric NOT NULL DEFAULT 5,
time_zone text NOT NULL DEFAULT current_setting('TimeZone'),
-- TZ in which part_column (timestamp WITHOUT tz) values are written by the
-- application sessions. Partition bounds are computed in this TZ.
-- Defaults to the TZ of the session that registers the table.
analyze_parent boolean NOT NULL DEFAULT true, -- autovacuum never ANALYZEs a partitioned parent
purge_enabled boolean NOT NULL DEFAULT true, -- true: retire = DETACH -> archive_mode -> DROP
-- false: nothing is detached/archived/dropped (kept)
enabled boolean NOT NULL DEFAULT true, -- false: NO maintenance at all (also no new partitions!)
PRIMARY KEY (parent_schema, parent_table),
CHECK (archive_mode <> 'S3' OR (s3_bucket IS NOT NULL AND s3_region IS NOT NULL))
);
CREATE TABLE IF NOT EXISTS partmaint.part_log (
log_id bigserial PRIMARY KEY,
log_time timestamptz NOT NULL DEFAULT clock_timestamp(),
parent_table text,
partition_name text,
action text, -- CREATE | DETACH | ARCHIVE | DROP | ANALYZE | RUN
status text, -- OK | SKIPPED | ERROR | ARCHIVE_FAILED | KEPT
attempts int,
duration_ms numeric,
rows_affected bigint,
detail text
);
CREATE INDEX IF NOT EXISTS part_log_time_ix ON partmaint.part_log (log_time);
-- upgrade path for installs created by an earlier version of this script
ALTER TABLE partmaint.part_config ADD COLUMN IF NOT EXISTS retire_guard text;
ALTER TABLE partmaint.part_config ADD COLUMN IF NOT EXISTS purge_enabled boolean NOT NULL DEFAULT true;
-- validation rules: a bad UPDATE on the config is rejected, the running config stays intact
DO $v$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'part_config_values_chk') THEN
ALTER TABLE partmaint.part_config ADD CONSTRAINT part_config_values_chk CHECK (
part_interval > interval '0'
AND retention >= interval '0'
AND min_future >= 1
AND premake >= min_future
AND premake <= 60
AND lock_timeout_ms BETWEEN 100 AND 60000
AND max_retries BETWEEN 1 AND 1000
AND retry_sleep_s BETWEEN 0 AND 600);
END IF;
END $v$;
-- audit + protection of config changes (who / what / old -> new) in part_log
CREATE OR REPLACE FUNCTION partmaint.part_config_audit()
RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE v_diff text; v_has_parts boolean;
BEGIN
IF TG_OP = 'UPDATE' THEN
-- part_column / time_zone define where existing boundaries are: block once partitions exist
IF (NEW.part_column IS DISTINCT FROM OLD.part_column OR NEW.time_zone IS DISTINCT FROM OLD.time_zone) THEN
SELECT EXISTS (SELECT 1 FROM pg_inherits
WHERE inhparent = to_regclass(format('%I.%I', OLD.parent_schema, OLD.parent_table)))
INTO v_has_parts;
IF v_has_parts THEN
RAISE EXCEPTION 'part_column / time_zone cannot be changed while %.% has partitions (boundaries would shift)',
OLD.parent_schema, OLD.parent_table;
END IF;
END IF;
SELECT string_agg(format('%s: %s -> %s', n.key, o.value, n.value), '; ' ORDER BY n.key)
INTO v_diff
FROM jsonb_each_text(to_jsonb(NEW)) n
JOIN jsonb_each_text(to_jsonb(OLD)) o USING (key)
WHERE n.value IS DISTINCT FROM o.value;
IF v_diff IS NOT NULL THEN
PERFORM partmaint.log(NEW.parent_table, NULL, 'CONFIG', 'OK', NULL, NULL, NULL,
'by ' || current_user || ': ' || v_diff);
END IF;
RETURN NEW;
ELSIF TG_OP = 'INSERT' THEN
PERFORM partmaint.log(NEW.parent_table, NULL, 'CONFIG', 'OK', NULL, NULL, NULL,
'registered by ' || current_user || ': retention=' || NEW.retention ||
', interval=' || NEW.part_interval || ', premake=' || NEW.premake ||
', purge_enabled=' || NEW.purge_enabled || ', tz=' || NEW.time_zone);
RETURN NEW;
ELSE
PERFORM partmaint.log(OLD.parent_table, NULL, 'CONFIG', 'OK', NULL, NULL, NULL,
'unregistered by ' || current_user);
RETURN OLD;
END IF;
END $$;
-- -----------------------------------------------------------------------------
-- Helpers
-- -----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION partmaint.log(p_parent text, p_part text, p_action text, p_status text,
p_attempts int DEFAULT NULL, p_t0 timestamptz DEFAULT NULL,
p_rows bigint DEFAULT NULL, p_detail text DEFAULT NULL)
RETURNS void LANGUAGE sql AS $$
INSERT INTO partmaint.part_log(parent_table, partition_name, action, status, attempts,
duration_ms, rows_affected, detail)
VALUES (p_parent, p_part, p_action, p_status, p_attempts,
CASE WHEN p_t0 IS NOT NULL
THEN round(extract(epoch FROM clock_timestamp() - p_t0) * 1000, 1) END,
p_rows, p_detail);
$$;
DROP TRIGGER IF EXISTS part_config_audit_trg ON partmaint.part_config;
CREATE TRIGGER part_config_audit_trg
AFTER INSERT OR UPDATE OR DELETE ON partmaint.part_config
FOR EACH ROW EXECUTE FUNCTION partmaint.part_config_audit();
-- Lists the RANGE partitions of a parent with parsed bounds (DEFAULT excluded)
CREATE OR REPLACE FUNCTION partmaint.partitions(p_schema text, p_table text)
RETURNS TABLE(part_schema text, part_name text, lower_bound timestamptz, upper_bound timestamptz, bound_expr text)
LANGUAGE sql STABLE AS $$
SELECT n.nspname::text, c.relname::text,
CASE WHEN b ~ 'FROM \(MINVALUE\)' THEN '-infinity'::timestamptz
ELSE substring(b FROM 'FROM \(''([^'']+)''\)')::timestamptz END,
CASE WHEN b ~ 'TO \(MAXVALUE\)' THEN 'infinity'::timestamptz
ELSE substring(b FROM 'TO \(''([^'']+)''\)')::timestamptz END,
b
FROM pg_inherits i
JOIN pg_class c ON c.oid = i.inhrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
CROSS JOIN LATERAL pg_get_expr(c.relpartbound, c.oid) AS b
WHERE i.inhparent = format('%I.%I', p_schema, p_table)::regclass
AND b <> 'DEFAULT';
$$;
-- Executes one DDL statement with a short lock_timeout, retrying on lock waits.
-- Locks taken by a failed attempt are released (sub-transaction rollback).
CREATE OR REPLACE FUNCTION partmaint.exec_with_retry(p_sql text, p_lock_timeout_ms int,
p_max_retries int, p_sleep_s numeric)
RETURNS int LANGUAGE plpgsql AS $$
DECLARE n int := 0;
BEGIN
PERFORM set_config('lock_timeout', p_lock_timeout_ms || 'ms', true);
LOOP
n := n + 1;
BEGIN
EXECUTE p_sql;
PERFORM set_config('lock_timeout', '0', true);
RETURN n;
EXCEPTION WHEN lock_not_available OR deadlock_detected THEN
IF n >= p_max_retries THEN
RAISE EXCEPTION 'gave up after % attempts (lock_timeout %ms): %',
n, p_lock_timeout_ms, p_sql USING ERRCODE = 'lock_not_available';
END IF;
PERFORM pg_sleep(p_sleep_s);
END;
END LOOP;
END $$;
-- -----------------------------------------------------------------------------
-- Single-partition workers (functions: they trap their own errors and log;
-- the calling procedures COMMIT after each one)
-- -----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION partmaint._create_one(cfg partmaint.part_config, p_from timestamptz,
p_to timestamptz, p_name text)
RETURNS text LANGUAGE plpgsql AS $$
DECLARE t0 timestamptz := clock_timestamp(); n int;
BEGIN
IF to_regclass(format('%I.%I', cfg.parent_schema, p_name)) IS NOT NULL THEN
PERFORM partmaint.log(cfg.parent_table, p_name, 'CREATE', 'SKIPPED', 0, t0, NULL, 'already exists');
RETURN 'SKIPPED';
END IF;
-- standalone table with identical column layout; parent indexes are created by ATTACH (empty -> instant)
EXECUTE format('CREATE TABLE %I.%I (LIKE %I.%I INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING STORAGE INCLUDING COMMENTS)',
cfg.parent_schema, p_name, cfg.parent_schema, cfg.parent_table);
-- partition-local primary key (business-key uniqueness within the partition)
IF cfg.local_pk_cols IS NOT NULL THEN
EXECUTE format('ALTER TABLE %I.%I ADD CONSTRAINT %I PRIMARY KEY (%s)',
cfg.parent_schema, p_name, lower(p_name) || '_pk',
(SELECT string_agg(quote_ident(c), ', ') FROM unnest(cfg.local_pk_cols) c));
END IF;
n := partmaint.exec_with_retry(
format('ALTER TABLE %I.%I ATTACH PARTITION %I.%I FOR VALUES FROM (%L) TO (%L)',
cfg.parent_schema, cfg.parent_table, cfg.parent_schema, p_name, p_from, p_to),
cfg.lock_timeout_ms, cfg.max_retries, cfg.retry_sleep_s);
PERFORM partmaint.log(cfg.parent_table, p_name, 'CREATE', 'OK', n, t0, NULL,
format('[%s, %s)', p_from, p_to));
RETURN 'OK';
EXCEPTION WHEN OTHERS THEN
PERFORM partmaint.log(cfg.parent_table, p_name, 'CREATE', 'ERROR', NULL, t0, NULL, SQLERRM);
RETURN 'ERROR';
END $$;
CREATE OR REPLACE FUNCTION partmaint._detach_one(cfg partmaint.part_config, p_name text)
RETURNS text LANGUAGE plpgsql AS $$
DECLARE t0 timestamptz := clock_timestamp(); n int;
BEGIN
n := partmaint.exec_with_retry(
format('ALTER TABLE %I.%I DETACH PARTITION %I.%I',
cfg.parent_schema, cfg.parent_table, cfg.parent_schema, p_name),
cfg.lock_timeout_ms, cfg.max_retries, cfg.retry_sleep_s);
PERFORM partmaint.log(cfg.parent_table, p_name, 'DETACH', 'OK', n, t0);
RETURN 'OK';
EXCEPTION WHEN OTHERS THEN
PERFORM partmaint.log(cfg.parent_table, p_name, 'DETACH', 'ERROR', NULL, t0, NULL, SQLERRM);
RETURN 'ERROR';
END $$;
-- Archive (per archive_mode) then DROP. Data is dropped only after a verified archive.
CREATE OR REPLACE FUNCTION partmaint._archive_drop_one(cfg partmaint.part_config, p_name text)
RETURNS text LANGUAGE plpgsql AS $$
DECLARE t0 timestamptz := clock_timestamp(); v_rows bigint; v_up bigint; v_key text;
BEGIN
IF cfg.archive_mode = 'KEEP' THEN
EXECUTE format('ALTER TABLE %I.%I SET SCHEMA partmaint_archive', cfg.parent_schema, p_name);
PERFORM partmaint.log(cfg.parent_table, p_name, 'ARCHIVE', 'KEPT', 1, t0, NULL,
'moved to schema partmaint_archive');
RETURN 'KEPT';
END IF;
IF cfg.archive_mode = 'S3' THEN
EXECUTE format('SELECT count(*) FROM %I.%I', cfg.parent_schema, p_name) INTO v_rows;
v_key := coalesce(cfg.s3_prefix || '/', '') || p_name || '.csv';
-- aws_s3 extension (Aurora/RDS). Called dynamically so this file compiles without it.
EXECUTE format($q$SELECT rows_uploaded FROM aws_s3.query_export_to_s3(%L,
aws_commons.create_s3_uri(%L, %L, %L), options := 'format csv, header true')$q$,
format('SELECT * FROM %I.%I', cfg.parent_schema, p_name),
cfg.s3_bucket, v_key, cfg.s3_region)
INTO v_up;
IF v_up IS DISTINCT FROM v_rows THEN
PERFORM partmaint.log(cfg.parent_table, p_name, 'ARCHIVE', 'ARCHIVE_FAILED', 1, t0, v_up,
format('row count mismatch: table=%s uploaded=%s; table kept', v_rows, v_up));
RETURN 'ARCHIVE_FAILED';
END IF;
PERFORM partmaint.log(cfg.parent_table, p_name, 'ARCHIVE', 'OK', 1, t0, v_up,
format('s3://%s/%s', cfg.s3_bucket, v_key));
t0 := clock_timestamp();
END IF;
EXECUTE format('DROP TABLE %I.%I', cfg.parent_schema, p_name);
PERFORM partmaint.log(cfg.parent_table, p_name, 'DROP', 'OK', 1, t0);
RETURN 'OK';
EXCEPTION WHEN OTHERS THEN
PERFORM partmaint.log(cfg.parent_table, p_name, 'ARCHIVE', 'ARCHIVE_FAILED', NULL, t0, NULL,
SQLERRM || ' ; detached table kept');
RETURN 'ARCHIVE_FAILED';
END $$;
-- -----------------------------------------------------------------------------
-- Procedures (COMMIT per partition). Run as the table owner.
-- -----------------------------------------------------------------------------
CREATE OR REPLACE PROCEDURE partmaint.create_future_partitions(p_schema text, p_table text,
p_start timestamptz DEFAULT NULL)
LANGUAGE plpgsql AS $$
DECLARE cfg partmaint.part_config; v_from timestamptz; v_until timestamptz; v_fmt text; v_max timestamptz;
BEGIN
SELECT * INTO STRICT cfg FROM partmaint.part_config
WHERE parent_schema = p_schema AND parent_table = p_table;
PERFORM set_config('timezone', cfg.time_zone, false);
v_fmt := CASE WHEN cfg.part_interval < interval '1 day' THEN 'YYYYMMDD"_"HH24MI' ELSE 'YYYYMMDD' END;
SELECT max(upper_bound) INTO v_max FROM partmaint.partitions(p_schema, p_table)
WHERE upper_bound < 'infinity';
v_from := coalesce(greatest(v_max, p_start), v_max, p_start,
date_trunc('day', now()));
v_until := now() + cfg.part_interval * cfg.premake;
WHILE v_from < v_until LOOP
IF partmaint._create_one(cfg, v_from, v_from + cfg.part_interval,
coalesce(cfg.part_prefix, p_table) || '_P' || to_char(v_from, v_fmt)) = 'ERROR' THEN
COMMIT;
EXIT; -- stop on error; health_check will surface it
END IF;
COMMIT;
v_from := v_from + cfg.part_interval;
END LOOP;
END $$;
CREATE OR REPLACE PROCEDURE partmaint.retire_partitions(p_schema text, p_table text)
LANGUAGE plpgsql AS $$
DECLARE cfg partmaint.part_config; r record; v_blocked boolean;
BEGIN
SELECT * INTO STRICT cfg FROM partmaint.part_config
WHERE parent_schema = p_schema AND parent_table = p_table;
IF NOT cfg.purge_enabled THEN
RETURN; -- purge switched off: keep everything (health_check reports it)
END IF;
PERFORM set_config('timezone', cfg.time_zone, false);
FOR r IN SELECT part_name FROM partmaint.partitions(p_schema, p_table)
WHERE upper_bound <= now() - cfg.retention
ORDER BY upper_bound
LOOP
-- safety: never drop a partition that still holds unprocessed events
IF cfg.retire_guard IS NOT NULL THEN
EXECUTE format('SELECT EXISTS (SELECT 1 FROM %I.%I WHERE %s)',
cfg.parent_schema, r.part_name, cfg.retire_guard) INTO v_blocked;
IF v_blocked THEN
PERFORM partmaint.log(cfg.parent_table, r.part_name, 'RETIRE', 'BLOCKED', 0, NULL, NULL,
'rows match retire_guard: ' || cfg.retire_guard || ' -> kept');
CONTINUE;
END IF;
END IF;
IF partmaint._detach_one(cfg, r.part_name) = 'OK' THEN
COMMIT;
PERFORM partmaint._archive_drop_one(cfg, r.part_name);
END IF;
COMMIT;
END LOOP;
END $$;
-- Entry point for the scheduler. Serialised with an advisory lock.
CREATE OR REPLACE PROCEDURE partmaint.run_maintenance()
LANGUAGE plpgsql AS $$
DECLARE r record; t0 timestamptz; v_ta timestamptz; v_last timestamptz;
BEGIN
IF NOT pg_try_advisory_lock(hashtext('partmaint.run_maintenance')) THEN
RAISE NOTICE 'partmaint: another run is active, skipping';
RETURN;
END IF;
FOR r IN SELECT * FROM partmaint.part_config WHERE enabled ORDER BY 1, 2 LOOP
t0 := clock_timestamp();
CALL partmaint.create_future_partitions(r.parent_schema, r.parent_table);
CALL partmaint.retire_partitions(r.parent_schema, r.parent_table);
IF r.analyze_parent THEN -- once a day is enough
SELECT max(log_time) INTO v_last FROM partmaint.part_log
WHERE parent_table = r.parent_table AND action = 'ANALYZE' AND status = 'OK';
IF v_last IS NULL OR v_last < now() - interval '1 day' THEN
v_ta := clock_timestamp();
EXECUTE format('ANALYZE %I.%I', r.parent_schema, r.parent_table);
PERFORM partmaint.log(r.parent_table, NULL, 'ANALYZE', 'OK', 1, v_ta);
END IF;
END IF;
PERFORM partmaint.log(r.parent_table, NULL, 'RUN', 'OK', NULL, t0);
COMMIT;
END LOOP;
PERFORM pg_advisory_unlock(hashtext('partmaint.run_maintenance'));
END $$;
-- -----------------------------------------------------------------------------
-- Health check: poll from monitoring (CloudWatch / Grafana / Nagios)
-- Any CRITICAL row = page someone. "no current partition" means INSERTs will fail.
-- -----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION partmaint.health_check()
RETURNS TABLE(parent_table text, check_name text, status text, detail text)
LANGUAGE plpgsql STABLE AS $$
DECLARE c partmaint.part_config; v_n int; v_t timestamptz;
BEGIN
FOR c IN SELECT * FROM partmaint.part_config ORDER BY parent_schema, parent_table LOOP
PERFORM set_config('timezone', c.time_zone, true);
RETURN QUERY SELECT c.parent_table, 'maintenance_enabled'::text,
CASE WHEN c.enabled THEN 'OK' ELSE 'CRITICAL' END,
CASE WHEN c.enabled THEN 'scheduler maintains this table'
ELSE 'enabled=false: NO new partitions are being created' END;
RETURN QUERY SELECT c.parent_table, 'purge_enabled'::text,
CASE WHEN c.purge_enabled THEN 'OK' ELSE 'WARNING' END,
CASE WHEN c.purge_enabled THEN format('retention %s, archive_mode %s', c.retention, c.archive_mode)
ELSE 'purge_enabled=false: old partitions are kept, nothing detached/archived/dropped' END;
SELECT count(*) INTO v_n FROM partmaint.partitions(c.parent_schema, c.parent_table)
WHERE now() >= lower_bound AND now() < upper_bound;
RETURN QUERY SELECT c.parent_table, 'current_partition'::text,
CASE WHEN v_n = 1 THEN 'OK' ELSE 'CRITICAL' END,
CASE WHEN v_n = 1 THEN 'partition covering now() exists'
ELSE 'NO partition covers now(): inserts will fail' END;
SELECT count(*) INTO v_n FROM partmaint.partitions(c.parent_schema, c.parent_table)
WHERE lower_bound > now();
RETURN QUERY SELECT c.parent_table, 'future_partitions'::text,
CASE WHEN v_n >= c.min_future THEN 'OK' ELSE 'CRITICAL' END,
format('%s future partitions (min %s, premake %s)', v_n, c.min_future, c.premake);
SELECT count(*) INTO v_n FROM partmaint.partitions(c.parent_schema, c.parent_table)
WHERE upper_bound <= now() - c.retention - c.part_interval * 2;
RETURN QUERY SELECT c.parent_table, 'retention_overdue'::text,
CASE WHEN v_n = 0 THEN 'OK' ELSE 'WARNING' END,
format('%s partitions past retention not yet retired%s', v_n,
CASE WHEN NOT c.purge_enabled AND v_n > 0 THEN ' (purge disabled)' ELSE '' END);
SELECT count(*) INTO v_n FROM pg_class pc JOIN pg_namespace pn ON pn.oid = pc.relnamespace
WHERE pn.nspname = c.parent_schema AND pc.relkind = 'r' AND NOT pc.relispartition
AND pc.relname LIKE coalesce(c.part_prefix, c.parent_table) || '\_P%';
RETURN QUERY SELECT c.parent_table, 'orphan_detached_tables'::text,
CASE WHEN v_n = 0 THEN 'OK' ELSE 'WARNING' END,
format('%s detached-but-not-dropped tables (archive failure?)', v_n);
SELECT count(*) INTO v_n FROM pg_inherits i JOIN pg_class pc ON pc.oid = i.inhrelid
WHERE i.inhparent = format('%I.%I', c.parent_schema, c.parent_table)::regclass
AND pg_get_expr(pc.relpartbound, pc.oid) = 'DEFAULT';
RETURN QUERY SELECT c.parent_table, 'default_partition'::text,
CASE WHEN v_n = 0 THEN 'OK' ELSE 'WARNING' END,
CASE WHEN v_n = 0 THEN 'none (by design)' ELSE 'DEFAULT partition present' END;
SELECT count(*) INTO v_n FROM partmaint.part_log l
WHERE l.parent_table = c.parent_table AND l.status IN ('ERROR','ARCHIVE_FAILED','BLOCKED')
AND l.log_time > now() - interval '24 hours';
RETURN QUERY SELECT c.parent_table, 'errors_24h'::text,
CASE WHEN v_n = 0 THEN 'OK' ELSE 'WARNING' END,
format('%s errors / blocked retirements in part_log (24h)', v_n);
SELECT max(log_time) INTO v_t FROM partmaint.part_log l
WHERE l.parent_table = c.parent_table AND l.action = 'RUN' AND l.status = 'OK';
RETURN QUERY SELECT c.parent_table, 'last_successful_run'::text,
CASE WHEN v_t > now() - interval '3 hours' THEN 'OK' ELSE 'WARNING' END,
coalesce(v_t::text, 'never');
END LOOP;
END $$;
02_prepare_online.sqlOnline preparation: guards, validated boundary CHECK, new partitioned parent, indexes, triggers, grants, first partitions.
/* =============================================================================
02_prepare_online.sql - ONLINE preparation. No application stop.
Strategy: "attach the existing table as the first partition".
- No data copy, no index rebuild on the big table, no WAL/IO burst,
no double storage. The live table's PRIMARY KEY (event_id) is untouched.
- At cutover the current table becomes partition EVENT_QUEUE_LEGACY
covering (MINVALUE .. :boundary). Rows from :boundary onwards go to
new partitions, each with its own PRIMARY KEY (event_id).
- LEGACY is dropped by the framework once all its rows are past retention.
Usage (as the TABLE OWNER, with PGTZ = the application's time zone):
psql -v sch=public -v tbl=EVENT_QUEUE -v pcol=createdtime -f 02_prepare_online.sql
Optional: -v boundary='2026-11-25 00:00:00' (default: next midnight, or the one after
if the next is < min_hours away) -v min_hours=12
-v retention='1 day' -v interval='1 day' -v purge=true|false
!!! :boundary MUST be a future instant AFTER the planned cutover time.
!!! Step 1 adds CHECK (pcol < :boundary) which is enforced immediately for new rows.
!!! If cutover does not happen before :boundary, run 04_abort_before_cutover.sql
!!! or INSERTs into EVENT_QUEUE will start failing at :boundary.
============================================================================= */
\set ON_ERROR_STOP on
-- ---- defaults: every -v parameter except sch / tbl / pcol is optional ----------------------
\if :{?retention} \else \set retention '1 day' \endif
\if :{?interval} \else \set interval '1 day' \endif
\if :{?purge} \else \set purge true \endif
\if :{?min_hours} \else \set min_hours 12 \endif
\if :{?boundary}
\echo 'boundary (given):' :boundary
\else
-- next midnight in this session's TimeZone; if it is less than :min_hours away
-- (VALIDATE on billions of rows takes hours), take the midnight after that
SELECT to_char(date_trunc('day', localtimestamp)
+ CASE WHEN date_trunc('day', localtimestamp) + interval '1 day' - localtimestamp
>= make_interval(hours => :min_hours)
THEN interval '1 day' ELSE interval '2 days' END,
'YYYY-MM-DD HH24:MI:SS') AS boundary \gset
\echo 'boundary (auto = next midnight, session TimeZone):' :boundary
\endif
SET lock_timeout = '1s'; -- never queue behind long transactions and block the app
SET statement_timeout = 0;
\echo '== Guard: boundary must be at least 2 hours in the future'
SELECT (:'boundary'::timestamptz > now() + interval '2 hours') AS boundary_ok \gset
\if :boundary_ok
\echo 'boundary OK'
\else
\echo 'ABORT: boundary is less than 2 hours away - choose a later boundary'
\quit
\endif
\echo '== Guard: Phase-1 partial index (processedtime IS NULL) must exist'
-- Needed by: the consumer poll, this time zone check, and the retire guard on LEGACY.
-- Without it each of those is a FULL SCAN of the (billions of rows) table.
SELECT EXISTS (SELECT 1 FROM pg_index i
WHERE i.indrelid = format('%I.%I', :'sch', :'tbl')::regclass
AND i.indisvalid
AND pg_get_expr(i.indpred, i.indrelid) ILIKE '%processedtime IS NULL%') AS pidx_ok \gset
\if :pidx_ok
\echo 'partial index present and valid'
\else
\echo 'ABORT: create the Phase-1 index first (off-peak):'
\echo ' CREATE INDEX CONCURRENTLY event_queue_unprocessed_ix ON <tbl> (worker_id) WHERE processedtime IS NULL;'
\quit
\endif
\echo '== Guard: session TimeZone must match the TZ the application writes createdtime in'
-- createdtime is "timestamp WITHOUT time zone" filled by CURRENT_TIMESTAMP in the APP session.
-- Partition bounds (midnight) are computed in THIS session's TimeZone, so they must agree.
-- Cheap check via the partial index: the newest UNPROCESSED row is recent, so it should be
-- close to localtimestamp (not off by whole hours). No full scan.
SELECT current_setting('TimeZone') AS session_tz, localtimestamp(0) AS session_local_now,
(SELECT max(:"pcol") FROM :"sch".:"tbl" WHERE processedtime IS NULL) AS newest_unprocessed_row;
SELECT coalesce(abs(extract(epoch FROM localtimestamp -
(SELECT max(:"pcol") FROM :"sch".:"tbl" WHERE processedtime IS NULL))) < 1800, true) AS tz_ok \gset
\if :tz_ok
\echo 'TimeZone OK (or no unprocessed rows to compare - then confirm the app TZ manually)'
\else
\echo 'ABORT: newest unprocessed createdtime is >30 min away from this session''s local time.'
\echo ' Either the consumer backlog is >30 min old, or the TimeZone differs from the app.'
\echo ' Set PGTZ / SET TimeZone to the application''s time zone and re-run (or confirm the backlog).'
\quit
\endif
\echo '== 1. Range-bound CHECK so ATTACH PARTITION can skip its full-table validation scan'
-- NOT VALID = instant (brief lock); VALIDATE = full scan under SHARE UPDATE EXCLUSIVE,
-- which does NOT block INSERT/UPDATE/DELETE/SELECT. It is I/O: run it in a quiet hour.
-- On billions of rows this takes HOURS (measure on the Aurora clone) and autovacuum
-- cannot run on the table meanwhile -> check age(relfrozenxid) first (00_prechecks).
-- On lock timeout, run 04_abort_before_cutover.sql and start again.
ALTER TABLE :"sch".:"tbl" ADD CONSTRAINT evq_legacy_bound
CHECK (:"pcol" IS NOT NULL AND :"pcol" < :'boundary') NOT VALID;
ALTER TABLE :"sch".:"tbl" VALIDATE CONSTRAINT evq_legacy_bound;
\echo '== 2. New partitioned parent with identical column layout (no PK on parent, by design)'
SELECT format('%s_NEW', :'tbl') AS newtbl \gset
CREATE TABLE :"sch".:"newtbl"
(LIKE :"sch".:"tbl" INCLUDING DEFAULTS INCLUDING STORAGE INCLUDING COMMENTS)
PARTITION BY RANGE (:"pcol");
\echo '== 3. Replicate secondary (non-unique) indexes onto the new parent'
-- Same definition => ATTACH adopts the existing LEGACY index instead of building one.
SELECT format('CREATE INDEX %I ON %I.%I %s', c.relname || '_p', :'sch', :'newtbl',
substring(pg_get_indexdef(i.indexrelid) FROM ' USING .*$')) AS ddl
FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
WHERE i.indrelid = format('%I.%I', :'sch', :'tbl')::regclass
AND NOT i.indisunique \gexec
\echo '== 3b. Replicate triggers (e.g. an application BEFORE INSERT trigger) onto the new parent'
-- Row triggers on a partitioned parent are cloned to every partition (PG13+).
-- The LEGACY copy is dropped inside 03_cutover.sql (ATTACH fails on a same-name trigger).
SELECT replace(pg_get_triggerdef(t.oid),
format(' ON %I.%I ', :'sch', :'tbl'), format(' ON %I.%I ', :'sch', :'newtbl')) AS ddl
FROM pg_trigger t
WHERE t.tgrelid = format('%I.%I', :'sch', :'tbl')::regclass AND NOT t.tgisinternal \gexec
\echo '== 4. Owner and grants copied from the current table'
SELECT format('ALTER TABLE %I.%I OWNER TO %I', :'sch', :'newtbl', pg_get_userbyid(relowner))
FROM pg_class WHERE oid = format('%I.%I', :'sch', :'tbl')::regclass \gexec
SELECT format('GRANT %s ON %I.%I TO %s', a.privilege_type, :'sch', :'newtbl',
CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(a.grantee)) END)
FROM pg_class c, aclexplode(c.relacl) a
WHERE c.oid = format('%I.%I', :'sch', :'tbl')::regclass
AND a.grantee <> c.relowner \gexec
\echo '== 5. Register in framework (disabled until cutover) and pre-create partitions from :boundary'
-- local_pk_cols is read from the live table's PRIMARY KEY, so every new partition
-- gets exactly the same PK (event_id) as today.
INSERT INTO partmaint.part_config (parent_schema, parent_table, part_column, part_prefix, local_pk_cols,
part_interval, premake, min_future, retention, archive_mode, enabled, time_zone,
retire_guard, purge_enabled)
SELECT :'sch', :'newtbl', :'pcol', :'tbl',
(SELECT array_agg(a.attname::text ORDER BY k.ord)
FROM pg_index i
CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY k(attnum, ord)
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
WHERE i.indrelid = format('%I.%I', :'sch', :'tbl')::regclass AND i.indisprimary),
:'interval'::interval, 3, 2, :'retention'::interval, 'NONE', false, current_setting('TimeZone'),
'processedtime IS NULL', -- never drop partitions holding unprocessed events
:'purge'::boolean
ON CONFLICT (parent_schema, parent_table) DO NOTHING;
CALL partmaint.create_future_partitions(:'sch', :'newtbl', :'boundary'::timestamptz);
\echo '== 6. Result'
SELECT parent_table, part_prefix, local_pk_cols, part_interval, premake, retention, time_zone, purge_enabled
FROM partmaint.part_config WHERE parent_schema = :'sch' AND parent_table = :'newtbl';
SELECT part_name, pg_get_expr(c.relpartbound, c.oid) AS bound
FROM partmaint.partitions(:'sch', :'newtbl') p JOIN pg_class c ON c.relname = p.part_name
ORDER BY p.lower_bound;
\echo '== Guard: first new partition must start exactly at :boundary'
SELECT EXISTS (SELECT 1 FROM pg_inherits i JOIN pg_class c ON c.oid = i.inhrelid
WHERE i.inhparent = format('%I.%I', :'sch', :'newtbl')::regclass
AND pg_get_expr(c.relpartbound, c.oid) LIKE format('FOR VALUES FROM (%L)%%', :'boundary'))
AS first_ok \gset
\if :first_ok
\echo 'first partition starts at boundary: OK'
\else
\echo 'ERROR: first partition does not start at :boundary (time zone mismatch?). Run 04_abort_before_cutover.sql.'
\quit
\endif
SELECT conname, convalidated FROM pg_constraint WHERE conrelid = format('%I.%I', :'sch', :'tbl')::regclass;
03_cutover.sqlThe switch: rename + ATTACH in one transaction with lock_timeout and retry.
/* =============================================================================
03_cutover.sql - THE SWITCH. Application stays up.
One transaction, metadata only (no data movement, no index build, PK untouched):
EVENT_QUEUE -> EVENT_QUEUE_LEGACY
EVENT_QUEUE_NEW -> EVENT_QUEUE (partitioned parent)
DROP LEGACY's own copy of its triggers; parent's copy is cloned in
ATTACH EVENT_QUEUE_LEGACY FOR VALUES FROM (MINVALUE) TO (:boundary)
Locks: ACCESS EXCLUSIVE on the old table for milliseconds. Requested with a
500ms lock_timeout and retried, so a long-running query can stall the app for
at most ~0.5s per attempt instead of piling up INSERTs indefinitely.
The application keeps using the name EVENT_QUEUE; server-side prepared
statements re-resolve the name automatically (tested: pgbench -M prepared, 0 errors).
Usage: psql -v sch=public -v tbl=EVENT_QUEUE -f 03_cutover.sql
(boundary is read from the evq_legacy_bound constraint created by prepare;
-v boundary='...' only to override)
============================================================================= */
\set ON_ERROR_STOP on
\if :{?boundary} \else \set boundary '' \endif -- default: read from evq_legacy_bound (set by prepare)
SELECT set_config('evq.sch', :'sch', false), set_config('evq.tbl', :'tbl', false),
set_config('evq.boundary', :'boundary', false) \gset
DO $cutover$
DECLARE
sch text := current_setting('evq.sch');
tbl text := current_setting('evq.tbl');
bnd text := current_setting('evq.boundary');
attempts int := 0;
t0 timestamptz;
t_lock timestamptz;
v_trg name;
BEGIN
IF coalesce(bnd, '') = '' THEN
SELECT substring(pg_get_constraintdef(oid) FROM '< ''([^'']+)''') INTO bnd
FROM pg_constraint
WHERE conrelid = format('%I.%I', sch, tbl)::regclass AND conname = 'evq_legacy_bound';
IF bnd IS NULL THEN
RAISE EXCEPTION 'ABORT: evq_legacy_bound not found - run 02_prepare_online.sql first';
END IF;
RAISE NOTICE 'boundary read from evq_legacy_bound: %', bnd;
END IF;
IF now() > bnd::timestamptz - interval '30 minutes' THEN
RAISE EXCEPTION 'ABORT: less than 30 min before boundary %. Run 04_abort_before_cutover.sql and re-prepare with a later boundary.', bnd;
END IF;
IF to_regclass(format('%I.%I', sch, tbl || '_NEW')) IS NULL THEN
RAISE EXCEPTION 'ABORT: %_NEW not found - run 02_prepare_online.sql first', tbl;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_constraint
WHERE conrelid = format('%I.%I', sch, tbl)::regclass
AND conname = 'evq_legacy_bound' AND convalidated) THEN
RAISE EXCEPTION 'ABORT: validated evq_legacy_bound not found - ATTACH would scan the whole table under lock';
END IF;
IF EXISTS (SELECT 1 FROM pg_inherits i JOIN pg_class c ON c.oid = i.inhrelid
WHERE i.inhparent = format('%I.%I', sch, tbl || '_NEW')::regclass
AND substring(pg_get_expr(c.relpartbound, c.oid) FROM 'FROM \(''([^'']+)''\)') < bnd) THEN
RAISE EXCEPTION 'ABORT: a partition of %_NEW starts before boundary % (time zone mismatch at prepare?). Run 04_abort_before_cutover.sql and re-prepare.', tbl, bnd;
END IF;
PERFORM set_config('lock_timeout', '500ms', true);
t0 := clock_timestamp();
LOOP
attempts := attempts + 1;
BEGIN
EXECUTE format('LOCK TABLE %I.%I IN ACCESS EXCLUSIVE MODE', sch, tbl);
t_lock := clock_timestamp();
EXECUTE format('ALTER TABLE %I.%I RENAME TO %I', sch, tbl, tbl || '_LEGACY');
EXECUTE format('ALTER TABLE %I.%I RENAME TO %I', sch, tbl || '_NEW', tbl);
-- drop LEGACY's own triggers that the new parent also has; the parent's
-- copy is cloned onto LEGACY by ATTACH (same txn => no insert misses it)
FOR v_trg IN SELECT t.tgname FROM pg_trigger t
WHERE t.tgrelid = format('%I.%I', sch, tbl || '_LEGACY')::regclass
AND NOT t.tgisinternal
AND t.tgname IN (SELECT tgname FROM pg_trigger
WHERE tgrelid = format('%I.%I', sch, tbl)::regclass)
LOOP
EXECUTE format('DROP TRIGGER %I ON %I.%I', v_trg, sch, tbl || '_LEGACY');
END LOOP;
EXECUTE format('ALTER TABLE %I.%I ATTACH PARTITION %I.%I FOR VALUES FROM (MINVALUE) TO (%L)',
sch, tbl, sch, tbl || '_LEGACY', bnd);
UPDATE partmaint.part_config SET parent_table = tbl, enabled = true
WHERE parent_schema = sch AND parent_table = tbl || '_NEW';
PERFORM partmaint.log(tbl, tbl || '_LEGACY', 'CUTOVER', 'OK', attempts, t_lock, NULL,
'legacy attached FROM (MINVALUE) TO (' || bnd || ')');
EXIT;
EXCEPTION WHEN lock_not_available OR deadlock_detected THEN
RAISE NOTICE 'attempt %: lock not available within 500ms, retrying in 2s', attempts;
IF attempts >= 60 THEN
RAISE EXCEPTION 'ABORT: no lock after % attempts - check pg_stat_activity for long transactions', attempts;
END IF;
PERFORM pg_sleep(2);
END;
END LOOP;
RAISE NOTICE 'CUTOVER COMPLETE: % attempt(s), total % ms, DDL under lock % ms (+ commit)',
attempts, round(extract(epoch FROM clock_timestamp() - t0) * 1000, 1),
round(extract(epoch FROM clock_timestamp() - t_lock) * 1000, 1);
END
$cutover$;
\echo '== Post-cutover verification'
SELECT c.relkind AS kind /* p = partitioned */, c.relname
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = :'sch' AND c.relname = :'tbl';
SELECT part_name, lower_bound, upper_bound FROM partmaint.partitions(:'sch', :'tbl') ORDER BY lower_bound;
SELECT * FROM partmaint.health_check();
\echo '-- Where are new rows landing? (expect LEGACY until :boundary, then _PYYYYMMDD)'
-- SELECT tableoid::regclass, count(*) FROM public."EVENT_QUEUE"
-- WHERE createdtime > now() - interval '5 minutes' GROUP BY 1;
\echo '-- Next: enable the scheduler (06_schedule.sql) and run once by hand: CALL partmaint.run_maintenance();'
04_abort_before_cutover.sqlUndo prepare if the cutover does not happen before the boundary.
/* =============================================================================
04_abort_before_cutover.sql - Undo 02_prepare_online.sql if cutover is NOT done.
MANDATORY if cutover slips past (:boundary - 30 min): the CHECK (pcol < :boundary)
on the live table would otherwise reject INSERTs from :boundary onwards.
Usage: psql -v sch=public -v tbl=EVENT_QUEUE -f 04_abort_before_cutover.sql
============================================================================= */
\set ON_ERROR_STOP on
SET lock_timeout = '1s'; -- if it times out, re-run immediately
-- 1. Most urgent: remove the boundary check from the live table
ALTER TABLE :"sch".:"tbl" DROP CONSTRAINT IF EXISTS evq_legacy_bound;
-- 2. Remove the unused new parent, its empty partitions and its config
SELECT format('%s_NEW', :'tbl') AS newtbl \gset
DROP TABLE IF EXISTS :"sch".:"newtbl" CASCADE;
DELETE FROM partmaint.part_config WHERE parent_schema = :'sch' AND parent_table = :'newtbl';
SELECT conname FROM pg_constraint WHERE conrelid = format('%I.%I', :'sch', :'tbl')::regclass;
\echo 'Aborted. Live table is exactly as before 02_prepare_online.sql.'
05_rollback_after_cutover.sqlReturn to the single, non-partitioned table after cutover.
/* =============================================================================
05_rollback_after_cutover.sql - Go back to the single (non-partitioned) table.
Use if the application misbehaves after cutover. Cheapest before :boundary:
until then every new row lands in LEGACY anyway, so the copy-back is ~0 rows.
LEGACY still has its original PRIMARY KEY (event_id), so nothing to rebuild.
Holds ACCESS EXCLUSIVE on EVENT_QUEUE during the copy (inserts wait).
Check the volume first:
SELECT tableoid::regclass, count(*) FROM public."EVENT_QUEUE"
WHERE tableoid <> 'public."EVENT_QUEUE_LEGACY"'::regclass GROUP BY 1;
Usage: psql -v sch=public -v tbl=EVENT_QUEUE -f 05_rollback_after_cutover.sql
============================================================================= */
\set ON_ERROR_STOP on
SELECT format('%s_LEGACY', :'tbl') AS legacy, format('%s_PARTED_ROLLEDBACK', :'tbl') AS parked \gset
-- stop the scheduler touching this table
UPDATE partmaint.part_config SET enabled = false WHERE parent_schema = :'sch' AND parent_table = :'tbl';
SET lock_timeout = '1s'; -- if this times out, simply re-run the script
BEGIN;
LOCK TABLE :"sch".:"tbl" IN ACCESS EXCLUSIVE MODE;
ALTER TABLE :"sch".:"tbl" DETACH PARTITION :"sch".:"legacy";
ALTER TABLE :"sch".:"legacy" DROP CONSTRAINT IF EXISTS evq_legacy_bound;
-- DETACH removes the triggers cloned from the parent: recreate them on LEGACY
SELECT replace(pg_get_triggerdef(t.oid),
format(' ON %I.%I ', :'sch', :'tbl'), format(' ON %I.%I ', :'sch', :'legacy')) AS ddl
FROM pg_trigger t
WHERE t.tgrelid = format('%I.%I', :'sch', :'tbl')::regclass AND NOT t.tgisinternal
AND t.tgname NOT IN (SELECT tgname FROM pg_trigger
WHERE tgrelid = format('%I.%I', :'sch', :'legacy')::regclass) \gexec
INSERT INTO :"sch".:"legacy" SELECT * FROM :"sch".:"tbl"; -- rows from the new partitions
ALTER TABLE :"sch".:"tbl" RENAME TO :"parked";
ALTER TABLE :"sch".:"legacy" RENAME TO :"tbl";
DELETE FROM partmaint.part_config WHERE parent_schema = :'sch' AND parent_table = :'tbl';
SELECT partmaint.log(:'tbl', :'parked', 'ROLLBACK', 'OK');
COMMIT;
\echo 'Rolled back. Verify the application, then drop the parked parent and its partitions:'
\echo ' DROP TABLE <schema>."<tbl>_PARTED_ROLLEDBACK" CASCADE;'
SELECT relkind, relname FROM pg_class WHERE oid = format('%I.%I', :'sch', :'tbl')::regclass;
06_schedule.sqlpg_cron jobs: maintenance every 30 minutes plus log housekeeping.
/* =============================================================================
06_schedule.sql - Automation.
OPTION A (preferred): pg_cron inside Aurora PostgreSQL
Prerequisite (one-time, needs a REBOOT of the writer -> do it in an existing
maintenance window, weeks BEFORE the cutover, not on cutover day):
DB cluster parameter group: shared_preload_libraries += pg_cron
cron.database_name = <application database>
Then, as rds_superuser in that database: CREATE EXTENSION pg_cron;
Jobs run as the user who schedules them -> schedule as the TABLE OWNER
(or use cron.schedule_in_database with that username).
OPTION B (no reboot possible): EventBridge Scheduler -> Lambda / ECS task, or
an existing ops host cron, running:
psql "$CONN" -c "CALL partmaint.run_maintenance()"
============================================================================= */
-- every 30 min: idempotent (creates what's missing, retires what's due)
SELECT cron.schedule('partmaint_run', '*/30 * * * *', $$CALL partmaint.run_maintenance()$$);
-- housekeeping of the framework's own log (keep 90 days)
SELECT cron.schedule('partmaint_log_purge', '15 3 * * *',
$$DELETE FROM partmaint.part_log WHERE log_time < now() - interval '90 days'$$);
-- pg_cron's run history also grows; keep 14 days
SELECT cron.schedule('cron_history_purge', '20 3 * * *',
$$DELETE FROM cron.job_run_details WHERE end_time < now() - interval '14 days'$$);
/* Monitoring - wire into CloudWatch / Grafana / existing DB alerting:
SELECT * FROM partmaint.health_check() WHERE status <> 'OK';
CRITICAL rows (no current partition / too few future partitions) = page on-call.
Useful views:
SELECT * FROM partmaint.part_log ORDER BY log_id DESC LIMIT 50;
SELECT jobid, status, return_message, start_time FROM cron.job_run_details
ORDER BY start_time DESC LIMIT 20;
*/
run_demo.shEnd-to-end rehearsal in a throwaway database under live pgbench load.
#!/usr/bin/env bash
# =============================================================================
# run_demo.sh - End-to-end demo of the EVENT_QUEUE online partitioning framework
# on ANY PostgreSQL 13+ (local Linux / RHEL / Aurora test instance).
#
# Creates a SEPARATE database (default: evq_demo). Existing databases are not touched.
#
# Usage (from the folder containing the 0x_*.sql scripts):
# export PGHOST=localhost PGPORT=5432 PGUSER=postgres # PGPASSWORD or ~/.pgpass if needed
# ./run_demo.sh # 1M rows, 30s load phases
# ROWS=5000000 LOAD_SECS=60 ./run_demo.sh
# ROLLBACK_DEMO=1 ./run_demo.sh # also demonstrate rollback at the end
# DEMO_DB=evq_demo2 ./run_demo.sh # different demo database name
# KEEP=1 ./run_demo.sh # re-use an existing demo DB name by dropping it first
#
# Needs: psql. Optional: pgbench (RHEL: postgresqlNN-contrib / Ubuntu: postgresql-client)
# for the "under live load" parts; without it, the DDL steps still run.
# =============================================================================
set -uo pipefail
cd "$(dirname "$0")"
DEMO_DB=${DEMO_DB:-evq_demo}
ROWS=${ROWS:-1000000}
LOAD_SECS=${LOAD_SECS:-30}
CLIENTS=${CLIENTS:-8}
ROLLBACK_DEMO=${ROLLBACK_DEMO:-0}
LOG=demo_$(date +%Y%m%d_%H%M%S).log
Q() { psql -X -q -v ON_ERROR_STOP=1 -d "$DEMO_DB" "$@"; }
QT() { psql -X -qtA -v ON_ERROR_STOP=1 -d "$DEMO_DB" "$@"; }
hdr() { printf '\n\033[1;36m==== %s ====\033[0m\n' "$*" | tee -a "$LOG"; }
ok() { printf '\033[1;32m OK\033[0m %s\n' "$*" | tee -a "$LOG"; }
bad() { printf '\033[1;31m FAIL\033[0m %s\n' "$*" | tee -a "$LOG"; }
die() { bad "$*"; exit 1; }
command -v psql >/dev/null || die "psql not found in PATH"
HAVE_PGBENCH=1; command -v pgbench >/dev/null || { HAVE_PGBENCH=0; echo "pgbench not found: load phases will be skipped"; }
hdr "0. Connection / demo database"
psql -X -w -qtA -d postgres -c "select 1" >/dev/null 2>&1 || die "cannot connect without a password prompt. export PGPASSWORD=... or use ~/.pgpass"
psql -X -qtA -d postgres -c "select 'server: '||version()||' | session TimeZone: '||current_setting('TimeZone')" || die "cannot connect (set PGHOST/PGPORT/PGUSER)"
EXISTS=$(psql -X -qtA -d postgres -c "select 1 from pg_database where datname='$DEMO_DB'")
if [[ "$EXISTS" == "1" && "${KEEP:-0}" != "1" ]]; then
die "database $DEMO_DB already exists. Use KEEP=1 to drop & recreate it, or DEMO_DB=<other name>"
fi
psql -X -q -d postgres -c "drop database if exists \"$DEMO_DB\"" -c "create database \"$DEMO_DB\"" || die "create database failed"
ok "created database $DEMO_DB (log: $LOG)"
hdr "1. Simulate the application: EVENT_QUEUE with a round-robin worker trigger ($ROWS rows over 10 days)"
Q <<SQL || die "setup failed"
CREATE SEQUENCE evq_worker_seq CYCLE;
-- spreads events round-robin over 32 consumer workers (a typical outbox pattern)
CREATE OR REPLACE FUNCTION evq_assign_worker() RETURNS trigger LANGUAGE plpgsql AS \$\$
BEGIN
NEW.worker_id := (nextval('evq_worker_seq') % 32) + 1;
RETURN NEW;
END \$\$;
CREATE TABLE public."EVENT_QUEUE" (
event_id varchar(255) NOT NULL,
payload jsonb NULL,
traceid varchar(255) NULL,
createdtime timestamp DEFAULT CURRENT_TIMESTAMP NULL,
processedtime timestamp NULL,
worker_id numeric(3) DEFAULT 1 NULL,
CONSTRAINT "EVENT_QUEUE_pkey" PRIMARY KEY (event_id));
CREATE TRIGGER evq_assign_worker_trg BEFORE INSERT ON public."EVENT_QUEUE"
FOR EACH ROW EXECUTE FUNCTION evq_assign_worker();
INSERT INTO public."EVENT_QUEUE"(event_id, payload, traceid, createdtime, processedtime)
SELECT 'EVT'||g, jsonb_build_object('event', g, 'payload', md5(g::text)), md5(g::text),
ts, ts + interval '1 second'
FROM (SELECT g, now() - random() * interval '10 days' AS ts FROM generate_series(1, $ROWS) g) s;
ANALYZE public."EVENT_QUEUE";
SQL
QT -c "select 'EVENT_QUEUE: '||count(*)||' rows, '||pg_size_pretty(pg_total_relation_size('public.\"EVENT_QUEUE\"'))||', worker ids: '||count(distinct worker_id) from public.\"EVENT_QUEUE\"" | tee -a "$LOG"
hdr "2. Install framework (schema partmaint) + run prechecks"
Q -f 01_partmaint_framework.sql 2>&1 | grep -v NOTICE | tee -a "$LOG"
Q -v tbl=EVENT_QUEUE -v sch=public -v pcol=createdtime -f 00_prechecks.sql 2>&1 \
| grep -vE "pg_stat_statements|^LINE|^ +\^" >> "$LOG"
ok "framework installed; full precheck output in $LOG"
# app-like workload: insert (trigger assigns worker_id), read by event_id, mark processed
cat > /tmp/evq_app.sql <<'EOF'
\set id random(1, 9000000000000000000)
\set rid random(1, 1000000)
INSERT INTO public."EVENT_QUEUE"(event_id, payload, traceid) VALUES ('N' || :id, '{"k":1}', 'demo');
SELECT * FROM public."EVENT_QUEUE" WHERE event_id = 'EVT' || :rid;
UPDATE public."EVENT_QUEUE" SET processedtime = now() WHERE event_id = 'N' || :id;
EOF
bench() { # $1 = label, $2 = seconds -> prints tps and failures
pgbench -n -M prepared -c "$CLIENTS" -j 4 -T "$2" -f /tmp/evq_app.sql "$DEMO_DB" > /tmp/evq_bench.out 2>&1
local tps fail errs
tps=$(awk '/tps =/ {printf "%.0f", $3}' /tmp/evq_bench.out)
fail=$(awk '/failed transactions/ {print $5}' /tmp/evq_bench.out)
errs=$(grep -c "error" /tmp/evq_bench.out)
[[ -n "$tps" ]] || { bad "pgbench did not run:"; head -3 /tmp/evq_bench.out | tee -a "$LOG"; return; }
printf ' %-34s tps=%-8s failed=%-4s client_errors=%s\n' "$1" "$tps" "${fail:-?}" "$errs" | tee -a "$LOG"
[[ "$errs" == "0" ]] || grep error /tmp/evq_bench.out | head -3 | tee -a "$LOG"
}
if [[ $HAVE_PGBENCH == 1 ]]; then
hdr "3. Baseline workload on the NON-partitioned table"
bench "baseline (plain table)" 15
fi
BOUNDARY=$(QT -c "select to_char(date_trunc('day', now()) + CASE WHEN now() > date_trunc('day', now()) + interval '21 hours' THEN interval '2 days' ELSE interval '1 day' END, 'YYYY-MM-DD HH24:MI:SS')")
hdr "3b. PHASE 1: partial index on unprocessed rows (prerequisite for prepare)"
Q -c 'CREATE INDEX CONCURRENTLY IF NOT EXISTS event_queue_unprocessed_ix ON public."EVENT_QUEUE" (worker_id) WHERE processedtime IS NULL' || die "partial index failed"
ok "event_queue_unprocessed_ix created"
hdr "4. PREPARE online (boundary = $BOUNDARY) while the application workload is running"
[[ $HAVE_PGBENCH == 1 ]] && { pgbench -n -M prepared -c "$CLIENTS" -j 4 -T "$LOAD_SECS" -f /tmp/evq_app.sql "$DEMO_DB" > /tmp/evq_bench_live.out 2>&1 & BPID=$!; sleep 3; }
T0=$(date +%s)
Q -v sch=public -v tbl=EVENT_QUEUE -v pcol=createdtime -v boundary="$BOUNDARY" \
-v retention='1 day' -v interval='1 day' -f 02_prepare_online.sql >> "$LOG" 2>&1 || die "prepare failed - see $LOG"
ok "prepare done in $(( $(date +%s) - T0 ))s: boundary CHECK validated, EVENT_QUEUE_NEW + partitions + trigger created"
hdr "5. CUTOVER under load, with a long-running query holding a lock (to show lock_timeout + retry)"
psql -X -q -d "$DEMO_DB" -c "begin; select count(*) from public.\"EVENT_QUEUE\" where event_id='EVT1'; select pg_sleep(3); commit;" >/dev/null 2>&1 &
RPID=$!; sleep 0.5
Q -v sch=public -v tbl=EVENT_QUEUE -v boundary="$BOUNDARY" -f 03_cutover.sql 2>&1 | tee -a "$LOG" \
| grep -E "NOTICE|ERROR" | sed 's/^psql:[^:]*:[0-9]*: //'
wait $RPID 2>/dev/null
CUT_OK=$(QT -c "select relkind = 'p' from pg_class where oid = 'public.\"EVENT_QUEUE\"'::regclass")
if [[ $HAVE_PGBENCH == 1 ]]; then
wait $BPID 2>/dev/null
tps=$(awk '/tps =/ {printf "%.0f", $3}' /tmp/evq_bench_live.out); fail=$(awk '/failed transactions/ {print $5}' /tmp/evq_bench_live.out)
errs=$(grep -c "error" /tmp/evq_bench_live.out)
printf ' %-34s tps=%-8s failed=%-4s client_errors=%s\n' "workload during prepare+cutover" "$tps" "$fail" "$errs" | tee -a "$LOG"
[[ -n "$tps" ]] || { bad "pgbench did not run:"; head -3 /tmp/evq_bench_live.out; }
[[ -n "$tps" && "$errs" == "0" ]] && ok "application saw ZERO errors through prepare + cutover" || bad "client errors during cutover - see /tmp/evq_bench_live.out"
fi
if [[ "$CUT_OK" != "t" ]]; then
bad "CUTOVER DID NOT HAPPEN (transaction rolled back, table unchanged). Running 04_abort_before_cutover.sql"
Q -v sch=public -v tbl=EVENT_QUEUE -f 04_abort_before_cutover.sql >> "$LOG" 2>&1 && ok "aborted cleanly: boundary CHECK removed, EVENT_QUEUE_NEW dropped"
die "stopping demo. Send: tail -n 60 $LOG"
fi
ok "cutover complete: EVENT_QUEUE is now partitioned"
hdr "6. Result: what the application now sees"
QT <<SQL | tee -a "$LOG"
SELECT ' EVENT_QUEUE relkind = '||relkind::text||' (p = partitioned)' FROM pg_class WHERE oid = 'public."EVENT_QUEUE"'::regclass;
SELECT format(' %-26s %-22s -> %s', part_name, lower_bound, upper_bound) FROM partmaint.partitions('public','EVENT_QUEUE') ORDER BY lower_bound;
INSERT INTO public."EVENT_QUEUE"(event_id, traceid) VALUES ('DEMO_NOW','demo');
INSERT INTO public."EVENT_QUEUE"(event_id, traceid, createdtime) VALUES ('DEMO_AFTER_BOUNDARY','demo', '$BOUNDARY'::timestamp + interval '3 hours');
SELECT format(' row %-20s landed in %-26s worker_id=%s (trigger fired)', event_id, tableoid::regclass, worker_id)
FROM public."EVENT_QUEUE" WHERE event_id IN ('DEMO_NOW','DEMO_AFTER_BOUNDARY') ORDER BY event_id DESC;
SQL
echo " duplicate event_id test:" | tee -a "$LOG"
QT -c "INSERT INTO public.\"EVENT_QUEUE\"(event_id) VALUES ('EVT5')" 2>&1 | sed 's/^/ legacy range: /' | head -1 | tee -a "$LOG"
QT -c "INSERT INTO public.\"EVENT_QUEUE\"(event_id, createdtime) VALUES ('DEMO_AFTER_BOUNDARY', '$BOUNDARY'::timestamp + interval '4 hours')" 2>&1 | sed 's/^/ new partition: /' | head -1 | tee -a "$LOG"
echo " health check:" | tee -a "$LOG"
QT -c "select format(' %-24s %-8s %s', check_name, status, detail) from partmaint.health_check()" | tee -a "$LOG"
if [[ $HAVE_PGBENCH == 1 ]]; then
hdr "7. Workload on the PARTITIONED table (event_id-only lookups probe every partition)"
bench "partitioned (legacy + 3 daily)" 15
fi
hdr "8. Automated retention demo (separate table with 10 days of past partitions, retention 3 days)"
Q <<'SQL' 2>&1 | grep -v NOTICE | tee -a "$LOG"
CREATE TABLE public.ev_retention_demo (event_id varchar(255), createdtime timestamp, worker_id numeric(3)) PARTITION BY RANGE (createdtime);
INSERT INTO partmaint.part_config(parent_schema, parent_table, part_column, local_pk_cols, part_interval, premake, min_future, retention, archive_mode)
VALUES ('public','ev_retention_demo','createdtime','{event_id}','1 day',3,2,'3 days','NONE');
CALL partmaint.create_future_partitions('public','ev_retention_demo', date_trunc('day', now()) - interval '10 days');
INSERT INTO public.ev_retention_demo SELECT 'R'||g, now() - random() * interval '10 days', 1 FROM generate_series(1,200000) g;
SQL
echo " before: $(QT -c "select count(*)||' partitions, '||(select count(*) from public.ev_retention_demo)||' rows' from partmaint.partitions('public','ev_retention_demo')")" | tee -a "$LOG"
Q -c "UPDATE partmaint.part_config SET purge_enabled = false WHERE parent_table = 'ev_retention_demo'"
Q -c "CALL partmaint.run_maintenance()"
echo " purge_enabled=false -> after run: $(QT -c "select count(*)||' partitions (nothing detached/dropped)' from partmaint.partitions('public','ev_retention_demo')")" | tee -a "$LOG"
QT -c "select format(' health: %s %s - %s', check_name, status, detail) from partmaint.health_check() where parent_table='ev_retention_demo' and check_name in ('purge_enabled','retention_overdue')" | tee -a "$LOG"
Q -c "UPDATE partmaint.part_config SET purge_enabled = true WHERE parent_table = 'ev_retention_demo'"
echo " config change audit:" | tee -a "$LOG"
QT -c "select ' '||left(detail, 110) from partmaint.part_log where parent_table='ev_retention_demo' and action='CONFIG' order by log_id" | tee -a "$LOG"
echo -n " invalid change rejected? " | tee -a "$LOG"
QT -c "UPDATE partmaint.part_config SET premake = 1, min_future = 2 WHERE parent_table = 'ev_retention_demo'" 2>&1 | grep -o 'violates check constraint "[a-z_]*"' | tee -a "$LOG"
Q -c "CALL partmaint.run_maintenance()"
echo " purge_enabled=true -> after run: $(QT -c "select count(*)||' partitions, '||(select count(*) from public.ev_retention_demo)||' rows, oldest from '||min(lower_bound)::date from partmaint.partitions('public','ev_retention_demo')")" | tee -a "$LOG"
echo " framework log (partmaint.part_log):" | tee -a "$LOG"
QT -c "select format(' %-8s %-7s x%-3s avg %s ms', action, status, count(*), round(avg(duration_ms),1)) from partmaint.part_log where parent_table='ev_retention_demo' group by action, status order by action" | tee -a "$LOG"
ok "old data removed by DETACH + DROP: no DELETE, no dead tuples, no VACUUM debt"
if [[ "$ROLLBACK_DEMO" == "1" ]]; then
hdr "9. ROLLBACK to the non-partitioned table under load"
[[ $HAVE_PGBENCH == 1 ]] && { pgbench -n -M prepared -c "$CLIENTS" -j 4 -T 12 -f /tmp/evq_app.sql "$DEMO_DB" > /tmp/evq_bench_rb.out 2>&1 & BPID=$!; sleep 3; }
Q -v sch=public -v tbl=EVENT_QUEUE -f 05_rollback_after_cutover.sql >> "$LOG" 2>&1 || bad "rollback failed - see $LOG"
[[ $HAVE_PGBENCH == 1 ]] && { wait $BPID; echo " workload during rollback: $(grep -c error /tmp/evq_bench_rb.out) client errors" | tee -a "$LOG"; }
QT -c "select ' EVENT_QUEUE relkind = '||relkind::text||' (r = plain table again), PK: '||(select pg_get_constraintdef(oid) from pg_constraint where conrelid='public.\"EVENT_QUEUE\"'::regclass and contype='p') from pg_class where oid='public.\"EVENT_QUEUE\"'::regclass" | tee -a "$LOG"
QT -c "select ' trigger present: '||count(*) from pg_trigger where tgrelid='public.\"EVENT_QUEUE\"'::regclass and tgname='evq_assign_worker_trg'" | tee -a "$LOG"
fi
hdr "Done"
echo " Full log: $LOG"
echo " Explore: psql -d $DEMO_DB -> \\d+ \"EVENT_QUEUE\" ; select * from partmaint.part_log;"
echo " Cleanup: psql -d postgres -c 'drop database \"$DEMO_DB\"'"
collect_evidence.shCollects plans, throughput and logs from the demo into one archive.
#!/usr/bin/env bash
# =============================================================================
# collect_evidence.sh - Run AFTER run_demo.sh (without ROLLBACK_DEMO=1), against the
# demo database. Collects everything needed for the design decision into one archive.
# Read-only on the demo, except: it creates the Phase-1 partial index on the demo
# table to measure before/after. Never point it at production.
#
# Usage: DEMO_DB=evq_demo ./collect_evidence.sh -> evidence_<host>_<ts>.tar.gz
# =============================================================================
set -uo pipefail
cd "$(dirname "$0")"
DEMO_DB=${DEMO_DB:-evq_demo}
BENCH_SECS=${BENCH_SECS:-15}
TS=$(date +%Y%m%d_%H%M%S); OUT="evidence_$(hostname -s)_$TS"; mkdir -p "$OUT"
Q() { psql -X -q -v ON_ERROR_STOP=0 -d "$DEMO_DB" "$@"; }
[[ "$DEMO_DB" == evq_demo* ]] || { echo "refusing: DEMO_DB must be a demo database (evq_demo*)"; exit 1; }
psql -X -w -qtA -d "$DEMO_DB" -c "select 1" >/dev/null 2>&1 || { echo "cannot connect to $DEMO_DB (password? run run_demo.sh first)"; exit 1; }
[[ "$(psql -X -qtA -d "$DEMO_DB" -c "select relkind::text from pg_class where oid='public.\"EVENT_QUEUE\"'::regclass")" == "p" ]] \
|| { echo "EVENT_QUEUE is not partitioned: run run_demo.sh WITHOUT ROLLBACK_DEMO=1 first"; exit 1; }
echo "== 1. environment"
Q > "$OUT/01_environment.txt" <<'SQL'
SELECT version();
SELECT name, setting, unit FROM pg_settings
WHERE name IN ('TimeZone','shared_buffers','work_mem','max_parallel_workers_per_gather','enable_partition_pruning',
'plan_cache_mode','lock_timeout','autovacuum','max_connections','server_version')
ORDER BY name;
SELECT extname, extversion FROM pg_extension ORDER BY 1;
SELECT name, default_version FROM pg_available_extensions WHERE name IN ('pg_cron','pg_partman','aws_s3','pg_stat_statements');
SQL
{ echo "host: $(hostname)"; echo "os: $(cat /etc/redhat-release 2>/dev/null || uname -a)"; echo "cpus: $(nproc)"; free -g 2>/dev/null | head -2; } >> "$OUT/01_environment.txt"
echo "== 2. partition layout"
Q > "$OUT/02_partitions.txt" <<'SQL'
\pset pager off
SELECT c.relname AS partition, pg_get_expr(c.relpartbound, c.oid) AS bound,
pg_size_pretty(pg_total_relation_size(c.oid)) AS size, c.reltuples::bigint AS est_rows
FROM pg_inherits i JOIN pg_class c ON c.oid = i.inhrelid
WHERE i.inhparent = 'public."EVENT_QUEUE"'::regclass ORDER BY 2;
SELECT tableoid::regclass AS partition, count(*) AS rows, count(*) FILTER (WHERE processedtime IS NULL) AS unprocessed
FROM public."EVENT_QUEUE" GROUP BY 1 ORDER BY 1;
SELECT tablename, indexname, indexdef FROM pg_indexes WHERE tablename LIKE 'EVENT_QUEUE%' ORDER BY 1, 2;
SELECT tgrelid::regclass AS table_name, tgname FROM pg_trigger WHERE tgname = 'evq_assign_worker_trg' ORDER BY 1;
\d+ public."EVENT_QUEUE"
SQL
echo "== 3. real application statements: plans WITHOUT the partial index"
Q -c 'DROP INDEX IF EXISTS public.event_queue_unprocessed_ix' >/dev/null 2>&1
Q -c 'DROP INDEX IF EXISTS public."EVENT_QUEUE_NEW_unprocessed_ix"' >/dev/null 2>&1
for ix in $(psql -X -qtA -d "$DEMO_DB" -c "select format('%I.%I', n.nspname, c.relname) from pg_index i join pg_class c on c.oid=i.indexrelid join pg_namespace n on n.oid=c.relnamespace where i.indrelid='public.\"EVENT_QUEUE\"'::regclass and pg_get_expr(i.indpred,i.indrelid) ilike '%processedtime IS NULL%'"); do Q -c "DROP INDEX $ix" >/dev/null; done
POLL='SELECT * FROM "EVENT_QUEUE" WHERE PROCESSEDTIME IS NULL AND WORKER_ID = 1 LIMIT 100'
RIDS=$(psql -X -qtA -d "$DEMO_DB" -c "select string_agg(quote_literal(event_id), ',') from (select event_id from public.\"EVENT_QUEUE\" where processedtime is null limit 3) s")
[[ -n "$RIDS" ]] || RIDS="'EVT1','EVT2','EVT3'"
UPD="UPDATE \"EVENT_QUEUE\" SET PROCESSEDTIME = now() WHERE EVENT_ID IN ($RIDS)"
explain_both() {
echo "-- POLL: $POLL"; Q -c "EXPLAIN (ANALYZE, BUFFERS, SETTINGS) $POLL"
echo "-- UPDATE (rolled back): $UPD"; Q -c "BEGIN" -c "EXPLAIN (ANALYZE, BUFFERS) $UPD" -c "ROLLBACK"
}
explain_both > "$OUT/03_plans_without_partial_index.txt" 2>&1
cat > /tmp/evq_poll.sql <<EOF
$POLL;
EOF
cat > /tmp/evq_upd.sql <<'EOF'
\set n random(1, 1000000)
UPDATE "EVENT_QUEUE" SET PROCESSEDTIME = now() WHERE EVENT_ID IN ('EVT' || :n, 'EVT' || (:n + 1), 'EVT' || (:n + 2));
EOF
bench() { pgbench -n -M prepared -c 8 -j 4 -T "$BENCH_SECS" -f "$1" "$DEMO_DB" 2>&1 | awk '/tps =/{printf "%.0f", $3}'; }
{
echo "partitions: $(psql -X -qtA -d "$DEMO_DB" -c "select count(*) from partmaint.partitions('public','EVENT_QUEUE')")"
if command -v pgbench >/dev/null; then
echo "poll tps WITHOUT partial index: $(bench /tmp/evq_poll.sql)"
fi
} > "$OUT/05_throughput.txt"
echo "== 4. Phase 1: create partial index, plans again"
Q -c 'CREATE INDEX IF NOT EXISTS event_queue_unprocessed_ix ON public."EVENT_QUEUE" (worker_id) WHERE processedtime IS NULL' >/dev/null
Q -c 'ANALYZE public."EVENT_QUEUE"' >/dev/null
explain_both > "$OUT/04_plans_with_partial_index.txt" 2>&1
echo "== 5. throughput of the real statements (8 sessions, ${BENCH_SECS}s each)"
if command -v pgbench >/dev/null; then
{
echo "poll tps WITH partial index: $(bench /tmp/evq_poll.sql)"
echo "update tps (IN 3 event_ids): $(bench /tmp/evq_upd.sql)"
} >> "$OUT/05_throughput.txt"
else
echo "pgbench not found - throughput skipped" >> "$OUT/05_throughput.txt"
fi
cat "$OUT/05_throughput.txt"
echo "== 6. framework state"
Q > "$OUT/06_framework.txt" <<'SQL'
\pset pager off
SELECT * FROM partmaint.part_config;
SELECT * FROM partmaint.health_check();
SELECT log_time, parent_table, partition_name, action, status, attempts, duration_ms, left(detail, 120) AS detail
FROM partmaint.part_log ORDER BY log_id;
SQL
echo "== 7. demo log"
cp demo_*.log "$OUT/" 2>/dev/null || echo "no demo_*.log found next to this script" > "$OUT/07_no_demo_log.txt"
tar czf "$OUT.tar.gz" "$OUT" && rm -rf "$OUT"
echo
echo "Evidence collected: $(pwd)/$OUT.tar.gz"
11. FAQ
Why not pg_partman?
It's a good tool for new partitioned tables. Here I needed the online conversion of an existing 2-billion-row table, a trigger-aware cutover, a guard against dropping unprocessed events and time zone checks, so a small purpose-built framework was simpler to reason about.
Does the cutover really not block anything?
It takes an ACCESS EXCLUSIVE lock for a few milliseconds. The request waits at most 500 ms and retries, so a long query can delay the cutover but cannot pile up the application's inserts behind it.
What does VALIDATE cost on billions of rows?
One sequential read of the table, under SHARE UPDATE EXCLUSIVE: reads and writes continue, autovacuum waits. Measure it on a clone and check the transaction-ID age first.
Can I keep history?
Set archive_mode to KEEP (move to an archive schema) or S3 (aws_s3 export with row-count check). For a multi-billion-row LEGACY partition, a managed snapshot export is usually the better tool.
References: PostgreSQL: Table Partitioning · ALTER TABLE (ATTACH / DETACH PARTITION) · Explicit Locking · pg_cron. All numbers come from my own tests; verify in a rehearsal on your own environment before production.


