Scheduled PostgreSQL Partitioning Without pg_partman: Architecture of a Custom Tool and 8 Production PitfallsLongread · digest for December 3
Nighttime still life of a DBA desk: a partition filing cabinet with date tabs and a red-flagged DEFAULT card next to a clock showing 02:00.
Longread7 sections≈ 20 min

Scheduled PostgreSQL Partitioning Without pg_partman: Architecture of a Custom Tool and 8 Production Pitfalls

On paper, it looks like a one-evening script: dozens of PostgreSQL databases have partitioned tables, and once a night you need to pre-create upcoming partitions and drop old ones. A generate_series loop, CREATE TABLE ... PARTITION OF, DROP TABLE by name—and into cron. That exact script ran on live clusters for DBA alex-dbAdmin and never once seemed to fail. Zero incidents, quiet logs.

Then the engineer ran the code through several rounds of review and automated tests against live PostgreSQL. That uncovered 44 issues: subtle config bugs, a silent exit code 0 when partition creation failed, and dropping a table with fresh data because of an old name. None of those bugs showed up on a normal day, yet every single one would fire during a data migration, a lock contention spike, or a retention change.

Out of that audit came the open-source utility partition_tables (v3.2.7, Apache 2.0). Let's unpack its architecture and all eight production pitfalls with working SQL and bash snippets—even if you write your own script from scratch, these traps will save you more than a few midnight pages.

Why build a custom script and how it works without extensions

Whenever PostgreSQL declarative partitioning comes up, people reach for pg_partman. It's a solid extension: since v5.0 it works purely on declarative partitioning, includes a Background Worker, and v5.5.1 covers standard use cases. If you have no restrictions, use it.

In practice, pg_partman doesn't fit everywhere. First, you have to build and update it on every cluster, and certified builds or locked-down enterprise Linux environments often freeze the allowed extension list. Second, clusters managed by Pacemaker or Patroni switch roles, so the scheduler must check whether it's running on a primary or standby. Third, when you have around a hundred databases with different retention rules and app releases keep adding new tables, registering every table in pg_partman by hand is easy to forget.

partition_tables avoids extensions altogether: it's a bash wrapper partition_tables.sh and one PL/pgSQL file manage_partitions.sql executed via psql. The only server requirement is PostgreSQL 11+, since v11 introduced COMMIT inside DO blocks. Each partition is created or dropped in its own transaction, so one table failing doesn't roll back the rest.

Here is the execution flow:

cron (each cluster node, 02:00)
└─ partition_tables.sh
   ├─ flock: file lock prevents a second instance from starting
   ├─ SELECT pg_is_in_recovery() -> standby: exit 0
   └─ for each database in db_list.conf:
      psql -f manage_partitions.sql (row parameters)
      └─ DO block: each partition in its own transaction (COMMIT)

You put the job in /etc/cron.d/partition_tables on every cluster node. flock (from util-linux) takes a file lock so two runs never overlap. Next, pg_is_in_recovery() checks the node role: if it returns true, the node is a standby and exits with 0. On the primary, the script reads db_list.conf (one line per database):

# database             ahead   unit     retain   unit
billingmessage         1       month    3        year
billingdatastore_prt   13      month    3        year
logdatastore           37      month    5        year
eventbatchsaver        1       day      5        day
app-events             -       day      30       day   # drop only
archive_db             1       month    0        year  # never drop

The "ahead" column sets how many future periods to create beyond the current one; - disables creation (when the app creates partitions itself), and 0 disables deletion. The script discovers all top-level partitioned tables in public automatically. It creates RANGE partitions on a single date, timestamp, or timestamptz column named <table>_YYYYMM or <table>_YYYYMMDD.

Here is a snippet from an actual nightly log:

[2026-11-04 02:00:01] [INFO] [PID:4120] PostgreSQL node is primary
[2026-11-04 02:00:01] [INFO] [PID:4120] [billingmessage] Start:
  partitions 1 month ahead, retain 3 year
[2026-11-04 02:00:02] [INFO] [PID:4120] [billingmessage] Created
  BillingMessages_202612 (2026-12-01 — 2027-01-01, owner postgres)
[2026-11-04 02:00:02] [INFO] [PID:4120] [billingmessage] Dropped
  BillingMessages_202310 (period from 2023-10-01)
[2026-11-04 02:00:03] [ERROR] [PID:4120] [logdatastore] Connection
  failed (psql code 2): database "logdatastore" does not exist
[2026-11-04 02:00:09] [INFO] [PID:4120] Total databases:
  succeeded 5, skipped 0, failed 1

Here billingmessage succeeded, and the missing logdatastore didn't stop the loop for the remaining databases, yet it made the final exit code non-zero. It wasn't always that clean—here are the eight traps.

Silent failures: exit code 0 and the "retain 0" trap

Pitfall 1: something failed, but monitoring stays green. Early versions caught exceptions inside DO, logged RAISE NOTICE, and moved on. The goal was right: one locked table shouldn't abort the whole database. But psql still exited with 0, so cron and monitoring stayed silent. You only found out a new partition was missing at midnight on the first of the month when every INSERT started failing.

The fix uses a v_errors counter and a final RAISE EXCEPTION. There's a PL/pgSQL catch: you can't run COMMIT inside a block with an EXCEPTION handler because EXCEPTION creates an implicit subtransaction. So COMMIT; must sit strictly after END;:

BEGIN
    EXECUTE format(
        'CREATE TABLE public.%I PARTITION OF public.%I '
        'FOR VALUES FROM (%L) TO (%L)',
        v_part, v_tbl.relname, v_start, v_end
    );
    EXECUTE format(
        'ALTER TABLE public.%I OWNER TO %I',
        v_part, v_tbl.owner
    );
    v_created := v_created + 1;
EXCEPTION
    WHEN OTHERS THEN
        v_errors := v_errors + 1;
        RAISE NOTICE '[ERROR] Failed to create % for %: %',
            v_part, v_tbl.relname, SQLERRM;
END;
-- Strictly outside EXCEPTION: each partition gets its own TX
COMMIT;

-- Bubble the error up at the end of the DO block
IF v_errors > 0 THEN
    RAISE EXCEPTION '[ERROR] Partition errors: %',
        v_errors;
END IF;

With -v ON_ERROR_STOP=1, psql exits with code 3. Everything already committed stays committed, while the bash wrapper marks the database as failed, finishes the rest, and exits with 1. The wrapper relies on official psql exit codes:

psql codeWhat happenedBash wrapper action
0Script succeededDatabase counted as successful
1Fatal client errorDatabase failed, final exit code 1
2Connection or network failureError logged, moves to next database
3SQL error under ON_ERROR_STOP=1Committed partitions kept, final exit 1

Pitfall 2: retention 0 deletes everything. An admin wants to pause cleanup temporarily and writes 0 year. The old formula computed the cutoff as current_date - 0 year, got "today", and dropped every past partition. Now zero explicitly disables the drop phase, backed by a dedicated test: keeping an extra partition on disk is cheaper than losing data.

The deadliest bug: dropping partitions by name instead of bounds

Pitfall 3 is the most dangerous bug of all, because the script silently wipes live data without a single warning.

Custom scripts usually parse the name suffix: t_202001 means January 2020, retention is three years, so drop it. To PostgreSQL, however, a table name is just a string unrelated to its bounds. When migrating a legacy table to partitioning, teams often dump all historical rows into one catch-all partition named after the first month:

Mixed-media paper collage: a folder labeled t_202001 hides fresh documents up to 2026, while a magnifying glass checks the real partition bounds before deletion.

-- Name says Jan 2020, but data inside runs up to June 2026
CREATE TABLE t_202001 PARTITION OF t
    FOR VALUES FROM (MINVALUE) TO ('2026-06-01');

A script that only checks _202001 happily runs DROP TABLE t_202001 and wipes data all the way through May 2026, leaving a cheerful [INFO] Dropped partition in the log.

The safe rule: only drop a partition if both the date in its name and its real catalog bounds are older than the retention cutoff. You read the real bounds with pg_get_expr(relpartbound, oid), which returns text like FOR VALUES FROM ('2026-12-01') TO ('2027-01-01') or DEFAULT. Then you parse the bounds and compare them in the key's actual data type:

IF v_child.bound = 'DEFAULT' THEN
    v_reason := 'DEFAULT partition: can hold any period';
ELSIF v_child.strat = 'r' THEN
    v_m := regexp_match(
        v_child.bound,
        '^FOR VALUES FROM \((.+)\) TO \((.+)\)$'
    );
    IF v_m[2] = 'MAXVALUE' THEN
        v_reason := 'MAXVALUE upper bound: risk of fresh data';
    ELSE
        -- Compare in the key's native type, not as strings!
        EXECUTE format(
            'SELECT %s::%s <= %L::%s',
            v_m[2], v_child.keytype, v_cutoff, v_child.keytype
        ) INTO v_ok;
    END IF;
ELSIF v_child.strat = 'l' THEN
    -- LIST: all values before cutoff, never touch NULL
    v_m := regexp_match(
        v_child.bound,
        '^FOR VALUES IN \((.+)\)$'
    );
    EXECUTE format(
        'SELECT bool_or(v IS NULL), max(v) < %L::%s '
        'FROM unnest(ARRAY[%s]::%s[]) AS v',
        v_cutoff, v_child.keytype, v_m[1], v_child.keytype
    ) INTO v_has_null, v_ok;
END IF;

Casting %s::%s avoids broken string comparisons on timestamptz, whose bound looks like '2026-06-01 00:00:00+10'.

Partitions automated cleanup must never drop

Four partition types are always skipped with a clear WARN regardless of name: DEFAULT partitions, RANGE partitions with MAXVALUE, LIST partitions containing NULL, and partitions on non-date keys. Older versions printed 'RANGE or LIST required' on MAXVALUE—a misleading message that sends you looking in the wrong place.

Two name filters also help. Only <table>_YYYYMM or <table>_YYYYMMDD names are matched, so unrelated archive_202001 or merged t_20000101_20221201 tables stay untouched. Suffix dates are also validated against the calendar: x_20260231 matches the pattern, but February 31 doesn't exist—previously that logged ERROR every night, whereas now it logs WARN and skips.

Creation traps: taken names, wrong bounds, and the 63-byte limit

Pitfall 4 hides in partition creation. Checking "does an object with this name already exist?" and skipping sounds enough. In practice, there are three ways to end up silently missing a period.

First: the name belongs to something else. public might hold a plain table, a DETACHed partition, an index, or a sequence with that name. Checking pg_class says "exists", the script skips it, and the parent table never gets its new month. Now the script checks pg_inherits (inhparent = v_tbl.oid) and raises ERROR showing what actually owns the name.

Second: it's a child partition, but with the wrong bounds. Someone created t_202612 by hand with a typo and gave it November's bounds. The name and parent match, yet December inserts will fail. So the script compares existing bounds against the expected period: exact match skips, wider bounds that fully cover the period log WARN, and anything else raises ERROR.

Third: silent truncation past 63 bytes. PostgreSQL enforces max_identifier_length (NAMEDATALEN - 1, 63 bytes by default). Longer names are silently truncated with a single NOTICE. For a table with a long name, adjacent months collapse into the exact same truncated name, and new periods get skipped silently. You must measure bytes with octet_length, not characters, since non-ASCII letters take two bytes each.

-- Verify inheritance via pg_inherits and read actual bounds
SELECT c.relkind,
       EXISTS (
           SELECT 1
           FROM pg_inherits i
           WHERE i.inhrelid = c.oid
             AND i.inhparent = v_tbl.oid
       ),
       pg_get_expr(c.relpartbound, c.oid)
INTO v_kind, v_is_child, v_bound
FROM pg_class c
WHERE c.relnamespace = 'public'::regnamespace
  AND c.relname = v_part;

-- Enforce max_identifier_length in bytes (non-ASCII = 2+ bytes)
IF octet_length(v_tbl.relname) + 1
   + length(v_suffix_fmt) > v_max_name
THEN
    v_errors := v_errors + 1;
    RAISE NOTICE '[ERROR] Table %: partition name exceeds % bytes',
        v_tbl.relname, v_max_name;
END IF;

This catches collisions before creation: if the name doesn't fit in 63 bytes, the script reports a clear error instead of leaving a silent gap in your schedule.

DEFAULT partitions: why creation fails and how to move rows safely

Pitfall 5 hits where you placed a safety net. A DEFAULT partition catches rows that don't match any range. Yet if even one December 2026 row slips into DEFAULT, CREATE TABLE m_202612 PARTITION OF m ... fails with check_violation. PostgreSQL won't let a new partition "steal" rows from DEFAULT, so the job fails every night until you move those rows out.

manage_partitions.sql separates that from the case where another partition already covers the range under a different name:

EXCEPTION
    -- Range covered by another partition name: writes still work
    WHEN invalid_object_definition THEN
        RAISE NOTICE '[WARN] Partition % not created: %',
            v_part, SQLERRM;
    -- DEFAULT already holds rows for this period
    WHEN check_violation THEN
        v_errors := v_errors + 1;
        RAISE NOTICE '[ERROR] DEFAULT has rows for % — %, '
            'move them manually', v_start, v_end;

You move the rows manually in one transaction: create a matching table, move the target range via DELETE ... RETURNING *, and attach it:

BEGIN;
CREATE TABLE m_202612 (LIKE m INCLUDING ALL);

WITH moved AS (
    DELETE FROM m_default
    WHERE ts >= '2026-12-01' AND ts < '2027-01-01'
    RETURNING *
)
INSERT INTO m_202612 SELECT * FROM moved;

ALTER TABLE m ATTACH PARTITION m_202612
    FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
COMMIT;

If anything fails, the transaction rolls back and the rows stay safe in m_default.

There is a second trap documented in PostgreSQL itself: when creating or attaching a new partition without a matching exclusion CHECK constraint on DEFAULT, Postgres scans the entire DEFAULT partition under an ACCESS EXCLUSIVE lock (and recursively its subpartitions). While that scan runs, the table is completely locked to your app. A bloated DEFAULT turns nightly maintenance into downtime, so create partitions ahead of time and keep DEFAULT empty.

--dry-run needed extra work here too. Since a dry run creates nothing, it checks check_violation and bound overlaps itself against the catalog and DEFAULT; otherwise --dry-run reports all-clear during the day while the real run crashes at night.

Three timezones, vanishing logs, and hanging server queries

Pitfall 6: three timezones (plus a fourth factor for timestamptz). You might think timezones don't matter for date or timestamp columns. Bounds don't care, but current_date—used to calculate the current period and retention cutoff—depends on the session's TimeZone.

For example, at 16:00 UTC it is already 02:00 the next day in Vladivostok. If initdb ran before the OS timezone was set and postgresql.conf stayed on UTC while cron runs at 02:00 local time, "today" inside the script is still yesterday. Tomorrow's partition gets created a day late, and between 00:00 and 02:00 (or early on the 1st of the month) inserts fail or spill into DEFAULT. For timestamptz, it's worse: a manual run with a different PGTZ shifts the partition boundaries themselves, creating gaps or overlaps.

European Ligne claire comic illustration: syncing three out-of-sync clocks between cron and PostgreSQL alongside a two-tier emergency brake for stuck DDL queries.

LayerWhat it controlsImpact of drift
Server OS timezoneWhen cron fires the scriptRuns before or after database midnight
PostgreSQL TimeZoneWhat day current_date returnsTomorrow's partition created a day late
App timezoneWhich dates are writtenNightly inserts fail or spill into DEFAULT
PGTZ (for timestamptz)Exact '00:00' boundary timestampGaps or overlaps between adjacent partitions

You can audit all timezone settings on a host with three commands—the third one catches forgotten ALTER DATABASE/ROLE ... SET timezone overrides:

# 1. OS timezone (cron)
timedatectl | grep 'Time zone' || date +'%Z %z'

# 2. Default TimeZone in postgresql.conf
sudo -u postgres psql -XtAc \
  "SELECT current_setting('TimeZone'), to_char(now(), 'OF')"

# 3. Database and role overrides
sudo -u postgres psql -XtAc "
SELECT coalesce(d.datname, '*'),
       coalesce(r.rolname, '*'),
       s.setconfig
FROM pg_db_role_setting s
LEFT JOIN pg_database d ON d.oid = s.setdatabase
LEFT JOIN pg_roles r ON r.oid = s.setrole
WHERE array_to_string(s.setconfig, ',') ILIKE '%timezone%';"

partition_tables pins the timezone via PARTITION_TIMEZONE, strips client PGTZ and PGOPTIONS with env -u PGTZ -u PGOPTIONS, and logs the active timezone for timestamptz. If you can't align server timezones, create partitions at least two periods ahead—one extra empty partition bridges the midnight gap.

Pitfall 7: vanishing logs. All SQL logging relies on RAISE NOTICE. If a database or role sets client_min_messages = warning (or gets it from PGOPTIONS), psql receives zero lines—the log goes blank, hiding even skipped-database notices. Adding SET client_min_messages = notice; at the top of manage_partitions.sql fixes it.

Pitfall 8: psql is killed, but the query still holds locks. Plain timeout 3600 psql ... sends SIGTERM or SIGKILL, yet PostgreSQL doesn't notice a dead client right away. The DDL keeps waiting for a table lock while every app query piles up behind it. client_connection_check_interval (since PostgreSQL 14) defaults to 0 and doesn't work on local Unix sockets anyway.

So protection lives on both the client and the server:

# Client: SIGINT (Ctrl+C -> CancelRequest), SIGKILL after 30s;
# -X ignores ~/.psqlrc, -w disables interactive password prompts
cmd=(timeout -s INT -k 30 "$PSQL_TIMEOUT")
cmd+=(env -u PGTZ -u PGOPTIONS "$PSQL" -X -w -q -v ON_ERROR_STOP=1)

If the network drops or the client gets hard-killed, server-side timeouts at the top of manage_partitions.sql take over (defaults: PSQL_TIMEOUT=3600 seconds and LOCK_TIMEOUT=5s):

-- Log visibility and server limits (defaults: 3600s and 5s)
SET client_min_messages = notice;
SELECT set_config('statement_timeout', :'v_statement_timeout', false)
\gset
-- Returns 55P03 (lock_not_available) on busy tables instead of blocking
SELECT set_config('lock_timeout', :'v_lock_timeout', false)
\gset

On SIGTERM and SIGINT, the bash script also sends kill -INT to its child psql: hit Ctrl+C, and nothing stays dangling on the server. Passing -w ensures nightly cron never hangs waiting for a password prompt (no passwords in config; it uses peer auth or ~/.pgpass).

Live updates, tests, and a six-point checklist

Beyond those eight PostgreSQL traps, system-level bugs popped up too—most notably updating the bash script while it's running. bash reads a script from disk in chunks as it executes. When an installer overwrote the file with cp -f, it reused the same inode with new contents: a running nightly job read the new file from the old byte offset, called main a second time, and exited with a bogus code 2 (reproduced on CentOS and Git Bash). The fix is an atomic mv swap plus an explicit exit after main:

# Temp file + mv: running processes keep reading the old inode
cp -- "$src" "$dst.new.$$" && mv -f -- "$dst.new.$$" "$dst"

# Last line of partition_tables.sh: bash never reads past main
main "$@"; exit

Smaller operational bugs got cleaned up too. Standbys used to exit 1 instead of 0, spamming alerts. A database with no partitioned tables crashed FOREACH on NULL (now logs WARN). Keeping the lock file in /tmp meant one manual root run created a 644 file that permanently blocked nightly postgres runs—the lock now lives in /var/log/partition_tables. Under umask 077 for root, directories were created as 700 and locked out postgres, while Windows CRLF line endings in db_list.conf broke year into year\r. Finally, since configs are loaded via source (as code), the script refuses to load partition_tables.conf or db_list.conf if they are symlinks, owned by someone else, or looser than 640 root:postgres, and validates all values before connecting.

Because none of these bugs show up on a quiet day, tests are split into two layers. The bash suite runs with a mock psql (testing exit codes, standbys, signals, flock, and permissions without root or Postgres). The SQL suite spins up a temporary partition_tables_test_<pid> database on a real server, builds a catch-all partition, a populated DEFAULT, a taken name, a >63-byte table name, daily LIST, and a mismatched PGTZ, checks pg_class, and drops the database. The golden rule: every regression test must fail on the old code. All 72 tests pass on PostgreSQL 15, 16, and 17 (including a three-node Pacemaker primary), CentOS Stream 9, ALT Linux, Astra Linux, and Postgres Pro Enterprise 16.

alex-dbadmin/partition_tables (Apache 2.0) has clear scope limits: public schema only, one period unit (day or month) per database, auto-creation only for RANGE on a single date/time column (daily LIST is cleanup-only), and strict <table>_YYYYMM or <table>_YYYYMMDD naming.

Even if you stick with your own script, run it against these six rules before the first of next month:

Six rules for any custom partition manager

  • A failure on one partition doesn't stop the rest, but always produces a non-zero exit code.
  • Drops check real catalog bounds via pg_get_expr(relpartbound, oid) in the key's type, not just the name; DEFAULT, MAXVALUE, and LIST with NULL are never dropped.
  • Before skipping creation, verify the object is a child partition with matching bounds and that its byte length (octet_length) fits max_identifier_length.
  • Timezone is set explicitly and isolated from PGTZ or OS drift; if timezones can't be aligned, pre-create at least two periods ahead.
  • statement_timeout and lock_timeout are set on the PostgreSQL server, and the client sends SIGINT before SIGKILL.
  • Every fixed bug has a regression test that fails on the previous version of the script.
Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 10